最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - How to hide global scope from eval'd script - Stack Overflow

programmeradmin1浏览0评论

I usually think of global scope as a namespace that always can be accessed from everywhere. I would like to know whether it is theoretically possible to completely hide global scope. For example, assume we have some code we would like to evaluate (in the console of a browser):

var code = 
  "console.log(this);   " + // access the global object directly
  "console.log(window); " + // access the global object as the window object
  "newGlobalVar = 42;   ";  // implicitly create global object
eval(code);

By wrapping the eval call, this and window can be hidden from code:

(function (window) { eval(code); }).call({});

But I can't stop the code implicitly create global variables. Is it possible somehow? I don't want to use this stuff, I'm just curious.

I usually think of global scope as a namespace that always can be accessed from everywhere. I would like to know whether it is theoretically possible to completely hide global scope. For example, assume we have some code we would like to evaluate (in the console of a browser):

var code = 
  "console.log(this);   " + // access the global object directly
  "console.log(window); " + // access the global object as the window object
  "newGlobalVar = 42;   ";  // implicitly create global object
eval(code);

By wrapping the eval call, this and window can be hidden from code:

(function (window) { eval(code); }).call({});

But I can't stop the code implicitly create global variables. Is it possible somehow? I don't want to use this stuff, I'm just curious.

Share Improve this question edited May 29, 2013 at 22:16 kol asked May 29, 2013 at 20:39 kolkol 28.7k13 gold badges91 silver badges124 bronze badges 7
  • 1 Are you trying to sandbox eval'd/arbitrary code? There's a better way around if that's your aim. – Fabrício Matté Commented May 29, 2013 at 20:42
  • No, I was just thinking about shielding global scope from user code. This led me to this question, it's about theory. – kol Commented May 29, 2013 at 20:48
  • 1 Then, in modern browsers, theoretically, you could freeze the window object. Though I've never tried that. – Fabrício Matté Commented May 29, 2013 at 20:51
  • @FabrícioMatté Interesting. I've just tried freeze and seal in Safari 5.1.9, and it worked on general objects, but did not work on the global object. – kol Commented May 29, 2013 at 21:00
  • 2 @Zorgatone Running arbitrary untrusted code is tough business, I'd do everything to avoid it. But if you really have to, these resources may be useful: vm.runInNewContext() (Node.js only), Aether (has incomplete sandboxing, ideally should be run inside a Web Worker), and Dr. SES (capability-based security). – Fabrício Matté Commented May 15, 2016 at 11:38
 |  Show 2 more comments

3 Answers 3

Reset to default 8

If you're running in fairly modern browsers, you can mostly block window access by making a function that shadows the window and self variables with parameters, and runs the code in strict mode.

var obj = {};

var func = new Function("self", "window", "'use strict';" + code);

func.call(obj, obj, obj);

console.log(obj); // see if there were any attempts to set global variables.

Any attempt to access window or self will merely access our obj object, and the value of this will also be our obj.

Because we're in strict mode, implicit globals aren't allowed. Also, the default this value of functions will be undefined instead of window.

I think there are a couple hacks that may get around this, but this should cover most scenarios.

Note: This is still a work in progress and partly inspired by squint's code snippet.

function quarantinedFunction(fnText){
    var exceptionKeys=[
        "eval","Object",  //need exceptions for this else error. (ie, 'Exception: redefining eval is deprecated')
        "Number","String","Boolean","RegExp","JSON","Date",
    ];
    var forbiddenKeys=[
        "fn","fnText","forbiddenKeys","exceptionKeys","empty","oForbiddenKeys",
    ];
    var oForbiddenKeys=Object.create(null);
    var empty=Object.create(null);
    Object.freeze(empty);
    forbiddenKeys.forEach(function(key){
        oForbiddenKeys[key]=null;
    });
    [this,self].forEach(function(obj){
        Object.getOwnPropertyNames(obj).forEach(function(key){
            if(!key.match(/^[\$\w]+$/))return;
            oForbiddenKeys[key]=null;
        });
    });
    exceptionKeys.forEach(function(key){
        delete oForbiddenKeys[key];
    });

    if(0){//debugging.
        return function(){
            return Object.keys(oForbiddenKeys);
            return Object.keys(empty);
        };
    }

    fnText=[
        '"use strict";',
        "var "+Object.keys(oForbiddenKeys).join(", ")+";",
        "{",
        fnText,
        "}"
    ].join("\n");

    var fn= (function(){
        with(empty)
        {
            return new Function("self","window",fnText);
        }
    })();

    return function(){
       return fn.call(Object.create(null));      //self,window undefined
       return fn.call(empty,empty,empty);  //self,window are objects w/o properties
    };
}

Output results (from Firefox scratchpad):

quarantinedFunction("return location.href;")();
/*
Exception: location is undefined
*/
quarantinedFunction("someGlobalVar=15;")();
/*
Exception: assignment to undeclared variable someGlobalVar
*/
quarantinedFunction("return 9*9;")();
/*
81
*/
quarantinedFunction("return console;")();
/*
undefined
*/

And a jsfiddle with some results.

Note: Some unexpected results show up in the fiddle but not in other tools (i.e. the location variable returns the page's url when the fiddle is viewed from firefox aurora, but not on chrome nor on the scratchpad devtool -- possibly the handiwork of Firefox's __noSuchMethod__ or similar 'late-binding' mechanism, resulting in properties being added only when accessed).

You can just append on beggning: "var window = null" in your eval string. As well, for each property, do a for loop appending to your string in start: for(var p in window) yourEvalString += "var "+p+"=null;"; and put this on a separated scope.

sorry, english ins't my first language, and i'm new logged in Stack Overflow.

发布评论

评论列表(0)

  1. 暂无评论