will
will

Reputation: 17

Prove this PHP Eval of Function Dangerous

I am looking at the following block of code and cannot find a working example of how eval would be dangerous in this specific case.

I realize eval is dangerous, never to be used, there are always better ways to do it, etc but for my own curiosity want to define how this code block is dangerous.

In the case below $z's value is controlled by the user but is single quoted (and -as far as I know- therefore cannot explode another variable). Applying a single quote inside of $z to break the string is not possible.

function bar($x) {
    echo $x;
}

$z = 'USER CONTROLLED INPUT';
eval("bar(\$z);");

Upvotes: 0

Views: 169

Answers (2)

Gumbo
Gumbo

Reputation: 655269

This all is about the separation of code and data: The programmer writes the program code to instruct the interpreter how to behave and how the data is to be processed. The code is the active party, the data is the passive party.

Now functions like eval build a bridge between these two banks and allow data to be evaluated like program code.

This is not a problem until the data, that is supposed to be interpreted as code, can be manipulated by someone other than the programmer, e. g., a user who is not supposed to change the program’s behavior. Because in that case the user would have the same powers as the programmer.

Your code may be secure right now. But a slight change may turn it into a severe security flaw, allowing any user of your web site to execute arbitrary PHP code on your server:

Caution  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.

The edge you’re walking on when you use eval is just too narrow that you shouldn’t try walking on it.

Upvotes: 0

Petro
Petro

Reputation: 3652

Well if you forgot to escape $z then you someone could always do something like:

$z = '); unlink('/files/importantfile.data');

In your case, there is nothing wrong with it other than the potential to forgot escaping!

Upvotes: 1

Related Questions