javascript 字符串是否可以在没有 eval 的情况下作为函数求值?

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

我正在进行代码审计,toString 方法可能会由于不受欢迎的行为而被攻击者覆盖。它用字符串而不是方法覆盖 toString 方法。

取下面的代码:

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

a.toString 是字符串而不是函数。因此,a.toString() 将不起作用。

是否有任何可能导致意外执行 toString 字符串的黑客攻击(考虑到字符串可以是任何内容而不考虑 eval)?

来自您的澄清评论:

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.

除非您的代码执行某些操作将该字符串转换为函数(eval(a.toString)new Function(a.toString)btn.onclick = a.toString;、...),否则它不会变成一个函数,因此在从某种意义上说,这不是安全风险。任何试图在 a 上调用 toString 的东西(显式或隐式)都会得到一个错误。例如,这里隐式使用了 toString:

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

这显然是不可取的,但您说这是一个错误,并且您正在尝试探索它可以被利用的程度。我会说它不是特别容易被利用。