Semi-sandboxing Javascript eval

前端 未结 4 2045
-上瘾入骨i
-上瘾入骨i 2021-01-12 16:03

Background: I\'m working on a framework/library to be used for a specific site in coordination with greasemonkey/userscripts. This framework/library will al

4条回答
  •  暖寄归人
    2021-01-12 16:44

    There's no absolute way to prevent an end user or addon developer from executing specific code in JavaScript. That's why security measures in an open source language like JavaScript is said to be foolproof (as in it's only effective against fools).

    That being said however let's build a sandbox security layer to prevent inexperienced developers from breaking your site. Personally I prefer using the Function constructor over eval to execute user code for the following reasons:

    1. The code is wrapped in an anonymous function. Hence it may be stored in a variable and called as many times as needed.
    2. The function always exists in the global scope. Hence it doesn't have access to the local variables in the block which created the function.
    3. The function may be passed arbitrary named parameters. Hence you may exploit this feature to pass or import modules required by the user code (e.g. jQuery).
    4. Most importantly you may set a custom this pointer and create local variables named window and document to prevent access to the global scope and the DOM. This allows you to create your own version of the DOM and pass it to the user code.

    Note however that even this pattern has disadvantages. Most importantly it may only prevent direct access to the global scope. User code may still create global variables by simply declaring variables without var, and malicious code may use hacks like creating a function and using it's this pointer to access the global scope (the default behavior of JavaScript).

    So let's look at some code: http://jsfiddle.net/C3Kw7/

提交回复
热议问题