0

Why is PHP 7 eval() still not safe after strict preg_match?

So I have a code that strictly filters so that only operators, parenthesis, and numbers are allowed. People still seem to be against using it, but no one has explained to me specifically why, other than "Oh it is dangerous."

So how can one exploit the below code for example?

The following program 1. grabs query string from the URL 2. Filters it through preg_match 3. eval()

<?php
    $exp =  $_SERVER["QUERY_STRING"];
    if(preg_match('~^[0-9()+\-*\/]+$~', $exp)){
      eval("echo $exp;");
    } else {
      echo "ERROR";
    }
?>

Edit: https://www.exakat.io/land-where-php-uses-eval/

This website also talks about how eval() could be used for Evaluating math or logical expression Is this wrong?

Leonard
  • 2,978
  • 6
  • 21
  • 42
  • 1
    I won't go into why `eval` might be bad, enough has been written about that. However, your question all depends on how you define 'exploit'. Every time this code gets executed, it will throw a Fatal Error due to lack of quotes in the `echo` argument. If you define a DoS to be an exploit, then this might open up a vector. – Ro Achterberg Jul 18 '19 at 16:08
  • I still say that learning how to actually build a functional calculator and learning how to make a simple expression parser and stack-based arithmetic will be far more useful to you in the long run than spending your time justifying and safeguarding against the kludge that is `eval()`. https://www.php.net/manual/en/function.eval.php#44008 – Sammitch Jul 18 '19 at 16:15
  • 1
    I can make it crash, does that count? Send it `(` or `1+` or anything else that's not valid PHP code. How about `1/0` for a divide by zero? Or `(123)()` for attempting to invoke a function? – Alex Howansky Jul 18 '19 at 16:17
  • I've updated the marked duplicate(s), since the chosen question was itself marked as a duplicate. – IMSoP Jul 18 '19 at 17:23
  • @RoAchterberg I'm not sure what you mean by "lack of quotes". If you set `$exp = '1+1';`, the result is `eval("echo 1+1;");` which echoes `2`. – IMSoP Jul 18 '19 at 17:28

0 Answers0