Question

I want to use eval()to resolve simple equations and logical expressions, e.g. 12*(4+3).

How safe is client side eval when the input (possibly untrusted) gets sanitized and only allows digits, +-*/()<>|&! and the words 'true' and 'false'?

Available JS parsers for equations are too big and featureful for me. I threw one together myself, however it's a lot of lines of code compared to eval'ing and it's not yet perfect.

EDIT: So yeah, I guess what I'm specifically asking is can somebody execute malicious code with nothing but digits and +-*/()<>|&! ? (I guess 'true' and 'false' are harmless)

Was it helpful?

Solution

I think it's completely safe, I don't think that eval is evil. Just use it with judice, and double check your sanitize function.

Since you're not allowing unicode letters neither _ or $ to pass sanitization, and javascript identifier must contains letter, it won't be possible to pollute the global scope, not to call functions.

from MDN page on identifiers :

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

Remember to catch for exception thrown by eval calls, because it's always possible to enter wrong expression, e.g. 4><5.

Also, be sure that you check for characters you allow, not for these that you deny, so that characters you didn't think about are denied by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top