1

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
3
  • Please, add samples of strings to check. As I assume, strings like '54*4' or '5 - 7' must pass the regular expression test? Commented May 18, 2011 at 16:00
  • Not really an answer to your question, but your character class is wrong — you don't need the pipes, ^ at the beginning negates it, and you can't use repetition operators in a character class. Use [()^\d*/+-] instead. Commented May 19, 2011 at 5:47
  • 1
    If you add [, ] and ! to that set, we can start to do some damage! ([][1]+[])[2]+(![]+[])[4]+([][1]+[])[1]+([][1]+[])[5]+(![]+[])[4]+([][1]+[])[2] === 'denied' Commented May 19, 2011 at 6:17

1 Answer 1

1

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, that 2 ^ 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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.