Is it safe to handle the equation this way?

I take a user-provided string, such as 'm * 0.2', where 'm' is $value and evaluates the string. The user is allowed to use 4 basic math operators, decimal numbers and negative numbers. Any attempt to use anything is not yet specified.

 $equation = $metric['formatter']; $equation = preg_replace("/[^0-9*m.\/\+\-]/", "", $equation); //strips extra params if (strlen($equation) > 1) { $equation = str_replace("m", ' $value ', $equation); $code = '$newValue = '.$equation.';'; if (validExec($code)) { //validates syntax eval($code); $newValue = (int) $newValue; //unnecessary security step? if ($newValue != 0) { $value = $newValue; } } } function validExec($code) { $code = escapeshellarg('<?php ' . $code . ' ?>'); $lint = 'echo $code | php -l'; // command-line PHP // maybe there are other messages for good code? return (preg_match('/No syntax errors detected in -/', $lint)); } 

I want to know if my method is 100% protected by allowing the execution of the above.

+5
source share
1 answer

I was looking for a patch code that also took into account user-entered formulas.

What you are doing seems to prevent any malicious user code from running on your server, since they will only be allowed letters m, numbers, and mathematical operators.

However, this requires only one bright spark to find a way around it to compromise your system, and I think most will agree that letting the user enter the rating is probably not good practice, no matter how you make it check.

When I studied my problem, I started looking for formula processing libraries, such as those used in spreadsheets. An Excel library, like a library, will accept mathematical expressions and be able to evaluate them safely.

I never went around to verify this, but hopefully if you can find the right option, you can even get backward compatibility with your existing formulas.

Good luck.

+1
source

Source: https://habr.com/ru/post/1232372/


All Articles