Is it safe to declare critical literals in "c (...) {...}" to run sandbox code?

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 = {
   // list incomplete ;)
   console: true, XMLHttpRequest: true, document: true, window: true, addEventListener: true, removeEventListener: true, parent: true, top: true, history: true, ..., 

   // actual data
   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.

+4
source share
3 answers

, .

, with, - "" , :

var window = (function(){ return this }).call(undefined);

, Function.call this, undefined null.

+7

...

alert([1, window, document]);

var obj = {
    document: true, window: true
};

with (obj) {
  alert([2, window, document]);
  
  delete window;
  delete document;
  
  alert([3, window, document]); //restored
}

, - DOM, document/window ownerDocument/defaultView.

+4

( "" ) , / (.. ).

-, , , duskwuff Alex K. - :

function exec(e)
{
    e = e.replace(/new/, "new_", "g")
         .replace(/delete/, "delete_", "g")
         .replace(/function/, "function_", "g")
         .replace(/throw/, "throw_", "g")
         .replace(/this/, "this_", "g")
         .replace(/var/, "var_", "g")
         .replace(/eval/, "eval_", "g");
    obj = { ... };
    with(obj)
    {
        eval(e);
    }
}

, . Bergi , obj , .

replace() ... , . , , ( true false null). . eval.

, anew new, \b . , .

e.replace(/\bnew\b/, "new_", "g");

This will fit new, but not anew.

0
source

Source: https://habr.com/ru/post/1568477/


All Articles