PHP EVAL - Fixing an Insecurity

2019-05-16 22:57发布

问题:

We have a system that has to perform calculations that user input provides.

The easiest way I have found to do one of those calculations is eval -- trying to figure out a parser for:

(3 + 6 ) / 2 + 27 * 5 / 2

Just seems difficult. If anyone has a solution to this -- I would be happy to hear it.

Assuming you are going with EVAL (I know its the dreaded function) it would be a major insecurity to allow them to type whatever they want in that box.

So, I pose the question, if I did a regex removing everything besides numbers, standard operators (+ - / *) and parentheses, something like

$equation = preg_replace( '/[^0-9+-\/*()]/', '', $input_equation );
$result = eval( $equation );

Is there any harm that could possibly happen to a system?

回答1:

I recently coded a PEDMAS compliant interpreter that uses BCMath functions:

function BC($string, $precision = 32)
{
    if (extension_loaded('bcmath') === true)
    {
        if (is_array($string) === true)
        {
            if ((count($string = array_slice($string, 1)) == 3) && (bcscale($precision) === true))
            {
                $callback = array('^' => 'pow', '*' => 'mul', '/' => 'div', '%' => 'mod', '+' => 'add', '-' => 'sub');

                if (array_key_exists($operator = current(array_splice($string, 1, 1)), $callback) === true)
                {
                    $x = 1;
                    $result = @call_user_func_array('bc' . $callback[$operator], $string);

                    if ((strcmp('^', $operator) === 0) && (($i = fmod(array_pop($string), 1)) > 0))
                    {
                        $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string = array_shift($string), $x, $i = pow($i, -1)));

                        do
                        {
                            $x = $y;
                            $y = BC(sprintf('((%1$s * %2$s ^ (1 - %3$s)) / %3$s) - (%2$s / %3$s) + %2$s', $string, $x, $i));
                        }

                        while (BC(sprintf('%s > %s', $x, $y)));
                    }

                    if (strpos($result = bcmul($x, $result), '.') !== false)
                    {
                        $result = rtrim(rtrim($result, '0'), '.');

                        if (preg_match(sprintf('~[.][9]{%u}$~', $precision), $result) > 0)
                        {
                            $result = (strncmp('-', $result, 1) === 0) ? bcsub($result, 1, 0) : bcadd($result, 1, 0);
                        }

                        else if (preg_match(sprintf('~[.][0]{%u}[1]$~', $precision - 1), $result) > 0)
                        {
                            $result = bcmul($result, 1, 0);
                        }
                    }

                    return $result;
                }

                return intval(version_compare(call_user_func_array('bccomp', $string), 0, $operator));
            }

            $string = array_shift($string);
        }

        $string = str_replace(' ', '', str_ireplace('e', ' * 10 ^ ', $string));

        while (preg_match('~[(]([^()]++)[)]~', $string) > 0)
        {
            $string = preg_replace_callback('~[(]([^()]++)[)]~', __METHOD__, $string);
        }

        foreach (array('\^', '[\*/%]', '[\+-]', '[<>]=?|={1,2}') as $operator)
        {
            while (preg_match(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), $string) > 0)
            {
                $string = preg_replace_callback(sprintf('~(?<![0-9])(%1$s)(%2$s)(%1$s)~', '[+-]?(?:[0-9]++(?:[.][0-9]*+)?|[.][0-9]++)', $operator), __METHOD__, $string, 1);
            }
        }
    }

    return (preg_match('~^[+-]?[0-9]++(?:[.][0-9]++)?$~', $string) > 0) ? $string : false;
}

It supports the following operators:

  • ^ (pow)
  • *
  • /
  • % (modulus)
  • +
  • -
  • =, ==, <, <=, >, >= (comparison)

And you call it like this:

echo BC('(3 + 6 ) / 2 + 27 * 5 / 2');

I did this so I had an easy way to perform arbitrary length calculations but, in your case, you might as well just strip all whitespace and validate the characters using the following regular expression:

if (preg_match('~^(?:[0-9()*/%+-<>=]+)$~', $expression) > 0) {
    // safe to eval()
}


回答2:

This seemed simpler to me, but I haven't searched for a native PHP solution. I'll post it just for the kicks.

Instead of using eval, the first thing I thought to use is exec to call bc and have bc do all the work for me (assuming you're on a Linux machine).

So, you'd do something like (very untested):

$user_input = '(3 + 6 ) / 2 + 27 * 5 / 2';
$return = exec( 'echo "scale=1; ' . escapeshellarg( $user_input) . '" | bc', $output, $retval);

$calculation = $output[0];
if( !is_numeric( $calculation)) {
    echo "Invalid input!";
}
echo $calculation; // Outputs 72


标签: php eval