Skip to content Skip to sidebar Skip to footer

Is It Safe To Use Eval In Javascript When It Only Executes Server-side Data?

Yes, it's a kinda duplicate of this question, but the answer given by @apsillers is a super-answer as it points a new aspect of the problem that have not been told in the previous

Solution 1:

The security rule for eval is: a user should never eval a string that was generated or modified by another user. It is perfectly safe to eval strings created by the server. After all, the server is providing the actual code of the page, so if it chooses to provide that code as an eval string, there's not necessarily a security concern.

In terms of security, it's basically as dangerous (or basically as safe) to include a dynamically-created <script> element as it is to call eval. The only difference is that <script> code will always run in the global scope, while eval can run in the lexical scope in which the call is made, allowing it to access variables from its containing function(s). This may or may not be desirable, depending on what you expect the script to have access to.

functionf() {
    var a = 5;
    eval("alert(a);");
    // an injected <script> wouldn't have access to `a`
}

The insidious danger with eval is that is can be quite difficult to strictly verify that the contents of eval have never been generated or modified by another user. In your case, if Object.prototype has been supplied with any enumerable property (included in your for..in loop), the value of that property will be evaled:

Object.prototype.foo = "alert(1);";

You can get around this problem by enforcing an own-property check:

for(var s in o) {
    if(o.hasOwnProperty(s)) {
        eval(o[s]);
    }
}

eval also incurs a significant performance penalty and creates variable-scope situations that cannot be optimized, but that's not a security concern.

Post a Comment for "Is It Safe To Use Eval In Javascript When It Only Executes Server-side Data?"