Disclaimer: This is just an example for learning PHP code injection, not production code to be used in any way. I'm fully aware that this is not good coding practice.
I have the following PHP script:
if (( isset($_REQUEST["maths"])) && ($_REQUEST["maths"] != "") ) { echo "Example script Example page
Now for the math. Please enter a formula to calculate. For example: 1 1.
The result is:"; eval("echo (".$_REQUEST["maths"].");"); echo "
"; } ?>This script is vulnerable to PHP code injection, I was able to break it by doing the following (mostly found out by trial and error):
$a='1');phpinfo();echo($a
However, I don't fully understand the rationale. From what I understand, I need to complete the echo statement, insert my own code (e.g. phpinfo()), and then write another function (e.g. echo) to handle the closing bracket.
I thought code like this would work:
");phpinfo();echo("
However, this does not work because phpinfo is considered part of the string and is not evaluated by the eval function. I also tried escaping the quotes without success.
Question:
$a='1');phpinfo();echo($a
work?
The problem is that this statement is invalid:
It will cause parsing errors. So you need to inject something to avoid this error. For example:
When you use that input, the result of substituting the variable is:
So
$a='1'
is assigned here, and the result of the assignment is output (that is, the value assigned to$a
). Thenphpinfo()
was executed. Finally$a
is output again.If you try to use
);phpinfo();echo(
, it won't work because it's trying to doecho ()
. Butecho
At least one parameter is required.So to inject code here, you have to make sure the input starts with something valid after
echo (
) and ends with something valid before);
. Place any additional code you want to inject between these two parts.