Parsing and dealing with the eval function in PHP
<p>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. </p>
<p>I have the following PHP script: </p>
<pre class="brush:php;toolbar:false;"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Example script</title>
</head>
<body>
<h1>Example page</h1>
<p>Now for the math. Please enter a formula to calculate. For example: 1 1. </p>
<form method="get">
<p>Formula: <input type="text" name="maths" /></p>
<p><input type="submit" value="calculate" /></p>
</form>
<?
if (( isset($_REQUEST["maths"])) && ($_REQUEST["maths"] != "") )
{
echo "<p>The result is:";
eval("echo (".$_REQUEST["maths"].");");
echo "</p>";
}
?>
</body>
</html></pre>
<p>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): </p>
<pre class="brush:php;toolbar:false;">$a='1');phpinfo();echo($a</pre>
<p>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. </p>
<p>I thought code like this would work:</p>
<pre class="brush:php;toolbar:false;">");phpinfo();echo("</pre>
<p>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. </p>
<p>Question:</p>
<ul>
<li>What is the correct way to inject code here? </li>
<li>Why does<code>$a='1');phpinfo();echo($a</code> work?</li>
</ul><p><br /></p>