将eval()限制在狭窄的范围内 [英] Restricting eval() to a narrow scope

查看:383
本文介绍了将eval()限制在狭窄的范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript文件读取另一个文件,其中可能包含需要eval()编辑的javascript片段。脚本片段应该符合javascript的严格子集,这限制了它们可以做什么以及它们可以更改哪些变量,但我想知道是否有某种方法可以通过阻止eval在全局范围内查看变量来强制执行此操作。如下所示:

I have a javascript file that reads another file which may contain javascript fragments that need to be eval()-ed. The script fragments are supposed to conform to a strict subset of javascript that limits what they can do and which variables they can change, but I want to know if there is some way to enforce this by preventing the eval from seeing variables in the global scope. Something like the following:

function safeEval( fragment )
{
    var localVariable = g_Variable;

    {
        // do magic scoping here so that the eval fragment can see localVariable
        // but not g_Variable or anything else outside function scope

        eval( fragment );
    }
}

实际代码不需要看起来像这样 - 我对任何和所有奇怪的技巧都有开放等等。但我确实想知道这是否是可能的

The actual code doesn't need to look like this--I'm open to any and all weird tricks with closures, etc. But I do want to know if this is even possible.

推荐答案

简短回答:不会。如果它在全球范围内,它可以用于任何事情。

Short answer: No. If it's in the global scope, it's available to anything.

长答案:如果您 eval()不受信任的代码真的想要阅读或搞乱你的执行环境,你被搞砸了。但是如果您拥有并信任所有正在执行的代码,包括 eval() ed,您可以通过覆盖执行上下文来伪造它:

Long answer: if you're eval()ing untrusted code that really wants to read or mess with your execution environment, you're screwed. But if you own and trust all code being executed, including that being eval()ed, you can fake it by overriding the execution context:

function maskedEval(scr)
{
    // set up an object to serve as the context for the code
    // being evaluated. 
    var mask = {};
    // mask global properties 
    for (p in this)
        mask[p] = undefined;

    // execute script in private context
    (new Function( "with(this) { " + scr + "}")).call(mask);
}

同样,我必须强调:


这仅用于保护可信代码不受其执行的上下文的影响。如果您不信任该代码,请不要 eval()它(或将其传递给新的函数() ,或以任何其他方式使用它,其行为类似于 eval())。

This will only serve to shield trusted code from the context in which it is executed. If you don't trust the code, DO NOT eval() it (or pass it to new Function(), or use it in any other way that behaves like eval()).

这篇关于将eval()限制在狭窄的范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆