I avoid using eval()or functions created from a string. But when I need to run some subset of Javascript that can be entered by the user, I am tempted to use it only because it will save me a lot of work by writing a lexer / parser and interpreter.
Let's say I would like to run this code:
a.toLowerCase() === 'xyz' || b == 1 || /pqr/.test(c)
own approach would be to pass it in eval()as follows:
with({a: ..., b: ..., c: ...}) {
ret = eval(code);
}
I cannot be sure that it codealways contains non-critical code, as mentioned above. This opens up the possibility of running malicious code.
I was thinking of passing an object overriding critical browser objects to, in withaddition to the actual data like:
var obj = {
console: true, XMLHttpRequest: true, document: true, window: true, addEventListener: true, removeEventListener: true, parent: true, top: true, history: true, ...,
a: ..., b: ..., c: ...
};
with (obj) {
...
}
When running the code inside, withaccess to objects / methods is impossible.
I know that you can still indirectly access these methods if they are indirectly available, although there is another object / function that is not overridden. Suppose I redefine them too.
Is it protected by sandbox code with a limited list of objects and functions as a content object?
What will remain as attack vectors in this case?
Change 1:
The code should work in Firefox, Chrome, IE (10+), Opera, Safari.