Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In this restricted setting, could eval() cause security problems?

I am writing a site that will include some math exercises. I don't care much if users try to cheat, so I am correcting the answers via Javascript

In my specific case, I have a field in a form. I'd like to allow the user to enter a mathematical expression (say 3/2) and use its result to tell if the user got it right. For that, i'd use eval.

My javascript would never read directly from a URL, just from the form. No results from this page would ever be stored for display to any user (maybe we'll keep the results for statistical analysys later on, storing then in a database via PHP, but then again, I probably need to sanitize any input on PHP itself, for fear of users using POST directly)

Whatever could go wrong ? =P

like image 669
josinalvo Avatar asked Aug 06 '12 20:08

josinalvo


2 Answers

You would want to be sure that nothing illegal will be going into the eval that could potentially break the script (this could be intentional or unintentional - not an attack but rather a user mistake). I would say either validate the field before eval to make sure it is arithmetic and only so.

Regardless of the use case, eval in general is universally regarded as a poor practice in any programming language. Sure, there is no real security concern here, but there is value in clean and solid code.

I would suggest taking a look at the Javascript Expression Evaluator to use in place of eval

like image 130
Austin Avatar answered Nov 03 '22 21:11

Austin


Whatever could go wrong?

Since Javascript is all client side, and you're not sending or persisting anything to the server, nothing really. A clever user could amuse themselves by breaking their own page or causing alerts to pop up by putting scripts into the box, but they could do that through a developer console as well. As long as everything stays Javascript side, you should be pretty safe, and any damage done can be fixed by a simple refresh of the page.

Nonetheless, upon thinking about it more, it just seems like a good idea and good practice to validate the input by at least a basic means, to avoid side effects. While the OP asked whether or not it was safe, and not whether or not it was professional, it seems seems worth mentioning that a solid, professional feeling page should ensure the inputs have only the expected effects.

like image 27
Nick Avatar answered Nov 03 '22 21:11

Nick