Search code examples
javascripteval

Can a javascript string be evaluated as a function without eval?


I'm doing a code audit and the toString method can be overwriten by an attacker due to an unwanted behavior. It is overwritting the toString method with a string rather than a method.

Take the following code :

let a = new Object();
a.toString = "function(){ return 'hello world' }"

a.toString is a string and not a function here. Thus, a.toString() won't work.

Is there any hack possible that would result in accidentally executing the toString string (considering the string can be anything and not considering eval) ?


Solution

  • From your clarifying comment:

    I'm doing a code audit and the toString method can be rewriten. Since the input is coming from a client, it's overwritting the toString method of the instance with a string sent by a client. I was wondering if there were any security risk here.

    Unless your code does something to turn that string into a function (eval(a.toString), new Function(a.toString), btn.onclick = a.toString;, ...), it won't become one, so in that sense it's not a security risk. Anything attempting to call toString on a (explicitly or implicitly) will get an error instead. For instance, here's an implicit use of toString:

    let a = new Object();
    a.toString = "function(){ return 'hello world' }"
    String(a); // TypeError: a.toString is not a function

    It's obviously not desirable, but you said it was a bug and you're trying to explore the degree to which it could be exploited. I'd say it's not particularly exploitable.