I need to evaluate some simple user submitted math. Multiplication of 2 numbers for example.
This opens me up to injection attacks.
My plan is to whitelist a bunch of values [^|(|)|\d+|\*|\/|\+|-] and replace everything else with regex before evaluation.
Any problems with this?
Example strings:
324*32
(5+4-17) / 3
I can’t think of any particularly nasty way to mess up your server too much using just numbers and a handful of operators, however, there are some things you need to look out for:
Given that the
[^...]is a character class, you do not need to separate every value with|. This is probably what you really want:[^^()\d*\/+-]. This will match everything you do not want to allow.Additionally, it is important to remember that, in JavaScript,
^does not represent powers but rather “exclusive or”. This means, for example, that2 ^ 3 == 1. So you probably do not want to whitelist^:[^()\d*\/+-].You might encounter invalid syntax like
(1 * (2 + 3), so you should watch out for that as well. You can probably just have a try catch block and meaningfully deal with things like that (report the problem back to the user or something).