Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inject php code via input fields?

I haven't found this question on here yet, and I have done some quick Google research on this but I couldn't really find a clear or good answer to this question.

Is it possible to inject a piece of php code in an input field. that would actually work.

//for instance.
//Ill fill in '"test()"' in the field.
<input type="text" name="input" value="'"test()"'">

$injection = $_POST/*(or $_GET)*/['input']; // coming from the input

public function test(){
    echo "injection successful";
}

So is this possible?

like image 966
kpp Avatar asked Feb 05 '26 11:02

kpp


2 Answers

It is possible, but not like that. If you do what you do in your script, then the code would just be assigned as-is (as a string) to the variable $injection.

You can however execute it like this:

$injection = $_POST/*(or $_GET)*/['input']; 
eval($injection);

There are other ways as well, but all have the same issue: you must actually evaluate the string as code to execute it. eval is the most obvious solution for that.

But be very careful when you implement this! If you open such a form for the outside world, everybody can execute any script, including ones that might destroy your server or steal your passwords.

like image 103
GolezTrol Avatar answered Feb 08 '26 05:02

GolezTrol


The snippet you posted is harmless, but depending on what you do with user-supplied data, it can be used in an code-injection attack. The linked wiki has some examples, here's a couple of them:

$posted = $_POST['user_input'];
eval($posted);//<--- NEVER DO THIS

However, after 10 years, I've never ever even gotten close to the point where I had to even worry about dreaming of having to maybe go down this route.
Another, slightly less unlikely possible vulnerability is impropper escaping when passing user-data to exec:

$cmdArgument = $_POST['flag'];
exec('ls '.$cmdArgument, $return, $status);

Could leave you vulnerable if I passed this as a "flag" value:

-lta && /usr/bin/env php -r 'echo __DIR__;'

And use that input to start messing around with your file-system.
To protect agains this, use the escapeshellarg and escapeshellcmd functions to sanitize the input.

More common, equally dangerous, but easier to overlook, would be this:

$requested = $_GET['page'];
require $requested.'.php';

Instead, if you want to require scripts like this, a safer, and just as easy approach is this:

switch ($_GET['page'])
{
    case 'admin':
        require 'admin.php';
        break;
    case 'user':
        require 'user.php';
        break;
    default:
        require 'error.php';
        break;
}
like image 41
Elias Van Ootegem Avatar answered Feb 08 '26 04:02

Elias Van Ootegem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!