I have a form field on my page, which if the user types a simple math equation into it, I would like to replace the value with the solution. So if the user types 1 + 2
into the field and hits enter I replace the input value with 3
.
Currently I only evaluate the equation if it matches this regex:
/^[\d. \+/\*-]+$/
That is, if the entire string is made up of digits, spaces, plus, minus, multiply, or divide characters.
I then eval the value like such:
(new Function('try {var a = ' + val + '; return a;} catch(e) {return -1;}'))()
This form field can be pre-populated by a query string param and the client will attempt to execute it. AKA a potential atack would be mysite.com?inputVal=cookieStealingProgram. I don't want users to be able to link to exploiting code.
I would like to add parenthesis and exponents to the regex so the user could put in (1 + 2) / 3 ^ 5
for example. While I'm fairly certain no exploits are possible with just numbers and operators, I'm not sure about a case with parenthesis.
I am aware that using only combinations of the characters ! [ ] + ( )
you can create a fully executable javascript program. I have also tried searching for "javascript exploit characters" and various combinations in Google but it's not a straightforward thing to find.
My specific question is can an arbitrary javascript program be written using only 0-9 . + - / * ( ) ^
(space character allowed)? Since it is a bit open ended, if no example can be provided after a few days, I'm fine closing this question.
I am NOT implementing nor making a parser to do this. That is irrelevant to the question
The answer to the question is no, it is impossible to create an arbirtary program using the given inputs, including parenthesis. In order to create a program, you must be able to create strings. The closest you can get with these restrictions is NaN
and Infinity
however it is impossible to cast either of those to a string without allowing for quotes or braces.
tl;dr you are blocked because you can't make strings.