I understand at a high level why one would not want to allow arbitrary code to execute in a web browser via the JS eval()
function.
But I wonder if there are any practical approaches to preventing attacks by parsing the code that is passed to eval()
to check that it is safe. For example:
- disallowing any flow control functions, e.g.
for
,while
. (Should stop infinite loops) - disallowing any variable names / function calls that don't match a whitelist. (Should stop any access to the DOM, built-in APIs, or malicious functions)
If you don't think this can be done safely, could you describe the predicted pitfalls? It's valuable to me if somebody says "this isn't practical because X" rather than just some blanket statement. Trust me - if I can't convince myself with certainty that it can be done safely, I won't do it.
I know that I can write my own my expression evaluator or use a 3rd-party library that does the same. And I may do that. But I remain interested in using eval()
because of certain advantages - native implementation performance and language consistency.