executing a php command inside an `echo("");` comman - php

I was wondering if it was possible to make a php command echo a whole new php set.
<?php
$phpcmd=$_POST["phpcmd"];
echo "<?".$phpcmd."?>";
?>
<form action="" method="post">
<input type="text" value="<?echo($phpcmd)?>" name="phpcmd">
<input type="submit">
</form>

You could do this using:
eval($phpcmd);
BUT...
I would strongly advise you don't, think about the security risks of something like this, a malicious user could cause an awful lot of damage with a script like this.
As the PHP docs state:
The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.
Check out this article for more info on the eval() function.

Related

$_POST Form advanced security

I wanted to ask how can i secure my form from hackers who try to edit the input name? I mean... What i am trying to ask is the following:
<form action="?page=forumpost&action=posttopic">
<input type="hidden" name="parrentID" value="1">
<input type="text" name="post_name">
<input type="submit">
</form>
You see that form? Lets say i open the inspect element option, and i decide to change the
<input name="">
When i click the submit button after i edit the input name, i get redirected to the other page ?page=forumpost&action=posttopic where my form is proceeded. Of course, i get a PHP error "Undefined index: post_name". The server is searching for post_name, instead of that, a blank name was send to the server which resulted that error. This is the code that throws error.
if($_GET['action'] === "posttopic"){
posttopic($_POST['parrentID'],$_POST['postname']);
}
function posttopic($parrentID,$postname){
// Form code here
}
How can i prevent this from happening? Of course, i am using prepared statements, htmlspecialchars(), stripslashes(), strip_tags(), and additionally checking the min/max length of the input. But that doesn't prevent the user from making my server throw error. I can disable the errors but i don't find that as a good solution. A few security tips about forms will be welcome. Also is there a way for the user to somehow hack my website trough playing with fake forms or something... ?
Just check that all values are set before processing the data.
if (isset($_GET['action'], $_POST['parrentID'], $_POST['postname']) && $_GET['action'] === "posttopic") {
posttopic($_POST['parrentID'], $_POST['postname']);
}
http://php.net/isset
Also, you mention using htmlspecialchars(), stripslashes(), strip_tags() - are you aware what these functions are doing? You risk mangling the data in ways you didn't intend to.
htmlspecialchars() should only be called on output and not input. Storing values in the database with that function will make it a nightmare to search. Store clean text in the database, and instead do echo htmlspecialchars($myValue); when printing text around the website.
stripslashes() is not needed if you are using a prepared statement (this function that "could help" if you are not using a prepared statement (alternative, escape the input)). Just keep your prepared statement and ditch this function.
strip_tags() strips HTML tags, which could be useful - depends on your approach, but if you're using htmlspecialchars() on your output (again, not input!), it's redundant.

Allow a user to edit a php code and submit the results securely

Is there a way to allow user to edit a php code securely, for example this is a basic php code to echo
Hello World! onto the page.
The idea is not to allow full coding changes just things like the array or they could edit a date in mktime things like that. I thought there maybe a way to echo form input fields into a php code which will then display the results.
How could i go about allowing a user to edit the code changing (Hello World!) to something else and then click submit to display there edit.
<?php
echo "Hello World!";
?>
or another example would be how can the user edit the words in the array
<?php
$words = array("the ", "quick ", "brown ", "fox ",
"jumped ", "over ", "the ", "lazy ", "dog ");
shuffle($words);
foreach ($words as $word) {
echo $word;
};
unset($word);
?>
I presume that i would have to create a form which gets the php code and somehow get it to display the edited results?
<form name="form" method ="get" action="a.php">
<input type="text" id="edit" name="edit" size="30" />
<input type="submit" value="Submit" >
</form>
For anyone that is viewing this and would like to know what you can create using a form and php see here Form that edits php script
What you are trying to accomplish is what variables are for.
Taking this example:
echo "Hello World!";
You could change that to
echo $_POST["data"];
and in your html
<form type='post'>
<input type='text' name='data'/>
<input type='submit'/>
</form>
See it in action
Eval should be avoided at all costs, there is a very narrow set of problems where using eval is a sane solution.
You want people to run arbitrary PHP code, but not all arbitrary PHP code. Tough thing to get right.
First off do not just eval() form data. Only bad* can come of this.
<form method="POST">
<textarea name="php"></textarea>
<button type="submit">Run</button>
</form>
<pre>
<?= eval($_POST['php']) ?>
</pre>
One option that comes to mind is to use https://github.com/nikic/PHP-Parser.
Basically, the parser does nothing more than turn some PHP code into an abstract syntax tree. ("nothing more" is kind of sarcastic here as PHP has a ... uhm, let's just say "not nice" ... grammar, which makes parsing PHP very hard.)
You can then walk the AST and remove suspect expressions, reconstitute the tree to code, and then call eval() on it.
Outside of that, configuring a sandbox environment would be critical here, as nothing is foolproof. That way, when someone inevitably bricks the box, you can recover it.
php.ini configuration changes can make for a "safer" environment to execute arbitrary code by imposing restrictions. disable_functions and disable_classes can help limit the possible abuse. Setting a low memory_limit will prevent help reduce excessive resource slurping.
* Unless this is a social experiment to see how long it takes for someone to turn your machine into pudding
in THEORY you can do something like this, but PLEASE PLEASE PLEASE don't do it because it is extremely UNSECURE
<?php
if (isset($_REQUEST['do_eval'])){
eval($_REQUEST['to_eval']);
}
?>
<form action="eval.php">
<textarea name="to_eval" rows="20" cols="80"><?php if (isset($_REQUEST['eval'])) print($_REQUEST['eval']); ?></textarea>
<br />
<input type="submit" name="do_eval" value="Submit" />
</form>
if I get you right, then eval function is what you need (http://php.net/manual/en/function.eval.php)
Evaluates the given code as PHP.
Although it is very dangerous as a user can execute a destructive code or output some private data.
<?
if(isset($_POST['submit'])
{
eval($_POST['code']);
}
else
{
?>
<form method="POST">
<textarea name="code"></textarea>
<input type="submit" value="Submit"></form>
</form>
<?
}
This sounds extremely dangerous to me; since PHP code runs on the server, you are basically letting anyone and everyone tell your server what code to run, and telling it to run harmful code would be very easy. Unfortunately, I can't think of a trivial way to sanitize this type of input.
Having said that... you can have a form that submits the user's code to a page that can write that code into a .php file on your server, then redirects to the newly created .php file. But, again, I would not advise you to do this sort of thing.
I think I understand what you're trying to accomplish. The actual task I believe will require a large amount of javascript in association with your PHP.
So, let's run it down theoretically.
Let's say this is your start code:
$array = array('one', 'two', 'three');
var_dump($array);
Ok - so now you want to define that the user can modify the array. Your HTML now looks something like that code above - all escaped of course.
However, you put form element around the escaped content, and put each array element as an input field.
So, you'll end up with something like this: (Note this is HTML not PHP)
<form action="self.php">
<div>$array = array(</div>
<span>'<input name="arrayValue[]">, +</span>
<div>);<br>var_dump($array);</div>
<input type="submit" value="Process this code">
</form>
Now, you'll need to write some javascript that watches for the class 'addAnother' to be clicked. If so, it goes up to its parent element and clones it (see - that's the span) and adds it after the parent. This way you'll have another whole line that is that span - with another input.
If you style the inputs to look nice, you can make it look like the user is typing inline.
Once the submit is pressed, the values are sent to the PHP. Then, the PHP will create a new array from all of $_POST['arrayValue'];
Your actual code will do this:
$array = $_POST['arrayValue'];
var_dump($array);
And then, you'll rerender the HTML again.
I know this is all 'theory' - there's a bit more code to actually be written.
I honestly would re-think if you really want to take on this task - this is a LOT of work to do it in an interactive, secure way. Perhaps there are other ways to accomplish your core task. Best of luck!

How to make $_POST more secured?

This is a sample code that i got from Facebook Engineering page.
<?php
if ($_POST['name']) {
?>
<span>Hello, <?=$_POST['name']?>.</span>
<?php
} else {
?>
<form method="post">
What is your name?<br>
<input type="text" name="name">
<input type="submit">
</form>
<?php
}
It says that the above code is not secured because it is open to cross site scripting. the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.
Is always passing $_POST variable via a htmlspecialchars() inefficient?
I can't thought of any way to make it secure. They introduce XHP which i am reluctant to use.
Reference: https://www.facebook.com/notes/facebook-engineering/xhp-a-new-way-to-write-php/294003943919
the correct way is to pass the $_POST['name'] via htmlspecialchars(). However, they stated that it is poor programming practice.
It's not poor practice in itself. The problem is that when you have to type htmlspecialchars every single time you drop text content into HTML, you are quite likely to forget one, leaving a vulnerability.
What that page is saying, correctly, is that it's better to have a templating language that HTML-escapes by default, so that you don't have to think about it. This is a lesson most web frameworks have learned by now, but raw PHP still doesn't have a convenient way to do that.

PHP_SELF and XSS

I've found an article claiming that $_SERVER['PHP_SELF'] is vulnerable to XSS.
I'm not sure if I have understood it correctly, but I'm almost sure that it's wrong.
How can this be vulnerable to XSS attacks!?
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<!-- form contents -->
</form>
To make it safe to use you need to use htmlspecialchars().
<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>
See A XSS Vulnerability in Almost Every PHP Form I’ve Ever Written for how $_SERVER["PHP_SELF"] can be attacked.
It is indeed a XSS vulnerability. I do understand that you believe it may not harm your website, but this doesn't mean it is not real.
If you do not believe it, try the following:
We assume you have a page such as "registration.php".
We assume you have a form where action is:
<?php echo $_SERVER['PHP_SELF']; ?>
as you put it down indeed:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<!-- form contents -->
</form>
Now simply append the string below
%27%22/%3E%3Cscript%3Ealert(1)%3C/script%3E
It is not actually hard to understand, because PHP_SELF is a reflection of the URL, your application will read whatever you put in the URL and echo it. It is simple as that.
htmlspecialchars should take care of the matter, no reason to dispute the evidence.
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<!-- form contents -->
</form>
However, even this is a first step in stealing a cookie, it's not that it take place automatically. Even if it's quite easy to craft the attack (as the attacker will register on your site and will see how the cookie looks...etc.), a series of other factors must be true to get to the point of having a cookie stealing situation. For instance, the cookie must not be expired. Than it depends of how complex the cookie is. Than maybe you have other precautions in placed on server, it doesn't have to be all authentication based on the presence of cookie!
While I do believe it is rather difficult and really bad programming for all conditions to met (even if yahoo.mail for example had such a vulnerability and if you look on internet you will find even the exploit and the cookie decoder), the XSS is real and who knows what a crafty attacker may do if your site suffer of it. The cure is simple...
The very article you linked gives you:
http://www.example.com/form.php/%22%3E%3Cscript%3Ealert(‘xss attack’)%3C/script%3E%3Cbr%20class=%22irrelevant
what's not clear?
Edit: this is an XSS attack because I can hide a link from my site to yours with some JS added to the URL which sends me your cookies so the moment you click that link, you are pwnd.
You should be using filter_input() to access superglobals in PHP. If you set the filter to FILTER_SANITIZE_FULL_SPECIAL_CHARS it will strip the unsafe characters typically used in XSS. Given your example:
<form method="post"
action="<?php filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_FULL_SPECIAL_CHARS); ?>">
<!-- form contents -->
</form>
The vulnerability is that a user can enter malicious JavaScript codes in the form. To prevent this, htmlspecialchars function is used.
Predefined characters (like >, <, ", ') are converted into entities(> < etc)
htmlspecialchars($_SERVER["PHP_SELF"]) ensures that all submitted form variables are converted into entities.
To read more about this vulnerability, visit: https://www.w3schools.com/php/php_form_validation.asp
Another link that can help you: https://www.google.com/amp/s/www.bitdegree.org/learn/php-form-validation/amp
I am studying this issue about the PHP_SELF variable and the XSS attack. There is something that I still can't understand: PHP_SELF variable is suposed to reference the name of the script file (the script that is running). Then, why does it take its value from the URL? (allowing the XSS problem).

is it right way( safe) to assign post data value directly by name attibute value to a variable in php

i m working in PHP since one year, but now a days i got this way to assign post data value directly using name attribute . i m really curious to know the documentation about it.please refere me link regarding this .
i explain by example
here is my form
<form method="post" action="">
<input type="text" name="userName" id="userName">
<input type="submit" name="doit" value="submit">
</form>
to get the post data i always use
$somevar=mysql_real_escape_string($_POST['userName']);
but now i see another way
$somevar= "userName";
i just want to know that is it safe n easy way??
I think you're looking for the PHP ini directive register_globals. Take a look at Variables From External Sources. However, this directive defaults to "off" and you should probably leave it that way since it is deprecated in PHP 5.3. You would still have to mysql_real_escape_string() it anyway.
You can also use import_request_variables() to register the globals manually:
import_request_variables("p");
echo $userName;
Using Register Globals on the PHP website gives you a good idea as to how it can be unsafe to automatically register HTTP variables as globals.
Personally I like to use an escape function. So I would stick with mysql_real_escape_string()
I've never seen any code where a variable has been assigned from a quoted value. The way I understand it, all you'd be doing is making $somevar contain a string userName
you can better use the below one
$somevar= $userName;
OR
$somevar= $_POST[userName];

Categories