node.js vm 和外部方法
node.js vm and external methods
我在使用 vm
:
的应用程序上工作时遇到了一些问题
无限 while (true) {}
循环内的外部方法调用不会超时:
var context = {
externalMethod: function(str) {console.log(str)}
};
vm.runInNewContext("while (true) {externalMethod('test')}", context, {}, 100);
上面的代码无限 运行s,即使在 100ms 超时完成后也是如此;
vm.runInNewContext("for (;;) {}", {}, {}, 100)
还有这个.. 即使没有 运行ning 外部方法,它也不会超时。
最后一个问题:在 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
?
Code above runs infinitely, even after 100ms timeout is finished
timeout
应该是 options
对象的 属性,而不是单独的参数:
vm.runInNewContext("while (true) {externalMethod('test')}", context, { timeout : 100 })
And one last question: how safe is it to have external method calls inside vm2
that will run untrusted code.
我假设你在这里指的是 vm
(内置 Node 模块)而不是 vm2
。在这种情况下,当您在 VM 外部调用代码时,它可能会访问 "outside" 代码的全局变量、局部变量和 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);
您不能直接从'inside'代码访问SECRET
,但外部方法可以访问它。因此,如果 externalMethod
有可能成为 运行 不受信任的代码,那将是不安全的。
我在使用 vm
:
无限 while (true) {}
循环内的外部方法调用不会超时:
var context = {
externalMethod: function(str) {console.log(str)}
};
vm.runInNewContext("while (true) {externalMethod('test')}", context, {}, 100);
上面的代码无限 运行s,即使在 100ms 超时完成后也是如此;
vm.runInNewContext("for (;;) {}", {}, {}, 100)
还有这个.. 即使没有 运行ning 外部方法,它也不会超时。
最后一个问题:在 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
?
Code above runs infinitely, even after 100ms timeout is finished
timeout
应该是 options
对象的 属性,而不是单独的参数:
vm.runInNewContext("while (true) {externalMethod('test')}", context, { timeout : 100 })
And one last question: how safe is it to have external method calls inside
vm2
that will run untrusted code.
我假设你在这里指的是 vm
(内置 Node 模块)而不是 vm2
。在这种情况下,当您在 VM 外部调用代码时,它可能会访问 "outside" 代码的全局变量、局部变量和 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);
您不能直接从'inside'代码访问SECRET
,但外部方法可以访问它。因此,如果 externalMethod
有可能成为 运行 不受信任的代码,那将是不安全的。