我在使用vm
的应用程序上工作时遇到一些问题:
无限while (true) {}
循环内的外部方法调用不会超时:
var context = {
externalMethod: function(str) {console.log(str)}
};
vm.runInNewContext("while (true) {externalMethod('test')}", context, {}, 100);
上面的代码即使在100ms超时结束后也可以无限运行;
vm.runInNewContext("for (;;) {}", {}, {}, 100)
也是这样。即使不运行外部方法,也不会超时。
最后一个问题:
vm2
中将运行不受信任的代码的外部方法调用的安全性如何:var context = {
method: (str) => {
createMessage("id", str) // some external (non-sandbox) method that sends an authenticated POST request to a chat app...
}
}
因此,可以使用该方法检索外部
global
或this
吗? 最佳答案
上面的代码即使在100ms超时完成后也可以无限运行timeout
应该是options
对象的属性,而不是单独的参数:
vm.runInNewContext("while (true) {externalMethod('test')}", context, { timeout : 100 })
最后一个问题:在
vm2
中具有将运行不受信任的代码的外部方法调用有多安全?我假设您的意思是
vm
(内置的Node模块),而不是vm2
。在这种情况下,当您在VM外部调用代码时,它可能会访问“外部”代码的全局变量,局部变量和this
:const vm = require('vm');
let SECRET = 'this is a secret';
let context = {
console, // to allow `console.log()` calls inside the sandboxed code
externalMethod() {
console.log('Secret outside:', SECRET)
}
};
vm.runInNewContext(`
console.log('Secret inside: ', typeof SECRET);
externalMethod();
`, context);
您不能直接从“内部”代码访问
SECRET
,但是外部方法可以访问它。因此,如果externalMethod
有可能运行不受信任的代码,那将是不安全的。关于javascript - node.js vm和外部方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40327557/