Question

Is this a possible solution for a pure javascript sandbox ? My willing is to execute an untrusted string of code without giving access to DOM, window, this, and so on but allowing the user to acces Math, JSON and other functionalities. I've tested it on Chrome.

UPDATE: I want to give the possibility to save on server user-defined code and make it available to other users. I'm looking for a way to deny access to the document ni order to make it safe.

function safe(code,args)
{
    if (!args)
        args=[];
    return (function(){
      for (i in window) 
        eval("var "+i+";");
      return function(){return eval(code);}.apply(0,args);
    })();
}



ff=function()
{
    return 3.14;
}

console.log(safe("this;"));//Number
console.log(safe("window;"));//undefined
console.log(safe("console;"));//undefined
console.log(safe("Math;"));//MathConstructor
console.log(safe("JSON;"));//JSON
console.log(safe("Element;"));//undefined
console.log(safe("document;"));//undefined
console.log(safe("Math.cos(arguments[0]);",[3.14]));//-0.9999987317275395
console.log(safe("arguments[0]();",[ff]));//3.14

I've proposed it on an old post : https://stackoverflow.com/a/11513690/76081

Thanks!

Was it helpful?

Solution

It's unsafe. The following construction will get the global window object from inside your sandbox:

(function(){return this;})()

At which point, you can extract anything you want from it, including goodies like document.

Hat tip to T.J. Crowder for his answer on https://stackoverflow.com/a/2673780/149341 in which he described this exploit.

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