I'm taking a user provided string like 'm*0.2' where 'm' is $value
and evaluating the string. The user is allowed to use the 4 basic math operators, decimals, and negative numbers. Any attempt to use anything else is omitted.
$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% secure in allowing the above to run.
I was looking at fixing code that eval'ed user inputted formulae as well.
What you are doing seems to prevent any user malicious code from being run on your server, as they would only be allowed the letter m, numbers and maths operators.
However, it just requires one bright spark to find a way around it, to compromise your system and I think most will agree that allowing user input to be eval'ed is probably not good practice, no matter how much you validate it.
When I was looking into my issue, I started looking for formulae processing libraries, such as those used in spreadsheets. An Excel like library would take mathematical expressions and be able to safely evaluate them.
I never got around to testing that, but hopefully, if you can find the right one, you can even get backwards compatibility with your existing formulae.
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With