2

I was updating some PHP code following the advice of not using $_GET and $_POST anymore but instead to switch to the safer filter_input() functions.

I was thinking that function would save me in this stupid case:

<?php 

eval($_GET["var"]);

?>

which when called as localhost/test.php?var=phpinfo(); spits the whole PHP info page. So I changed it to:

<?php 

eval(filter_input(INPUT_GET, "var", FILTER_SANITIZE_STRING));

?>

However it seems that the above is still vulnerable to the same attack. Which should be the correct way of securing the eval() in the case above?

2
  • The current case doesn't make much sense: it's contradictory. Eval is used to evaluate code and yet you want it not be evaluated. If you could provide the real/whole case we might be able to give you a workaround or a suitable solution.
    – HamZa
    Mar 2, 2016 at 12:43
  • It doesn't make sense hardening eval against code execution. This is because the purpose of eval is code execution.
    – Bacon Brad
    Apr 19, 2016 at 22:35

2 Answers 2

6

filter_input is designed to filter out things that may cause issues with HTML output: from the PHP manual "Strip tags, optionally strip or encode special characters."

phpinfo() doesn't include any special characters, or tags, so is passed through exactly as provided, then eval executes it. In fact, this is the case for a lot of PHP code - you're using a filter designed for a different purpose.

As @SteffanUllrich says, you can't secure eval - it executes PHP, which is almost exactly what you want to prevent. Your best option at this point is to rewrite your code to avoid using the eval function.

Ways to do this could include passing an indirect reference to a function (e.g. if you get a parameter of 1, use a switch block to execute function_one()), or just hardcoding each PHP file to do a specific thing. If you provide any way for an end user to provide PHP code which is executed, you're likely to have problems.

7

Which should be the correct way of securing the eval() in the case above?

There is no way to secure input to eval. Just don't use eval on any user-generated data.

3
  • so the only case of code injection possible with filter_input() is when it is coupled with the eval() function? I won't ever use eval() however it was the most stupid test I came up to check the filter_input() function and it miserably failed :( Mar 1, 2016 at 15:49
  • @sarah.ferguson: That's not what I said. For instance it would also be unsafe to write user input (even filtered) into a file and then include this file as PHP code. And there are probably more ways. Mar 1, 2016 at 15:51
  • No. Code injection can also occur via preg_replace(), create_function(), include/require (and probably others). filter_input() is not a magic fix - far from it.
    – symcbean
    Mar 1, 2016 at 15:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .