阻止eval &&新功能

Mar*_*ahn 12 javascript node.js

我只是在codewars.com上编写一些随机的谜题,我很好奇是否有人在下面的代码运行后可以想到一种方法来评估代码:

eval = function(){};
delete Function.prototype.constructor;
Function = undefined;

// the following are to block require('vm') -- if anyone wants to run this
// in production it may be better to block that one module (others?)
require = undefined;
module.__proto__.require = undefined; // added this due to alexpod's answer, modified due to Fabrício Matté's :)
module.constructor = undefined; // added this due to alexpod's answer
Run Code Online (Sandbox Code Playgroud)

这是在node.js中,所以setTimeout( "string" )不起作用.

ale*_*ods 9

好吧,你也有 module变数node.所以你可以vm使用它的require方法来要求包和运行代码:

var vm = module.require('vm');
vm.runInThisContext(' console.log("hello") ');
Run Code Online (Sandbox Code Playgroud)

UPD 嗯,你更新了这个问题,但我们可以再次破解它:

var vm = module.constructor.prototype.require('vm');
vm.runInThisContext(' console.log("hello") ');
Run Code Online (Sandbox Code Playgroud)

UPD2 另一种变体:

var vm = module.constructor._load('vm');
vm.runInThisContext(' console.log("hello") ');
Run Code Online (Sandbox Code Playgroud)

UPD3 再次改变条件,以便下一个变体:

module.constructor.prototype._compile(' console.log("again hacked") ');
// or
module.__proto__._compile(' console.log("again hacked") ');
// or
Object.getPrototypeOf(module)._compile(' console.log("again hacked") ');
Run Code Online (Sandbox Code Playgroud)

我认为更好的设置module = undefined让问题更复杂:)

UPD4 还有另一个变种没有module:)

process.stdin.push(' console.log("here we are") \n ');
Run Code Online (Sandbox Code Playgroud)

但它只适用于CLI("repl")

UPD5 此外,在iojsnode与版本> = 0.11.x您可以使用contextify绑定:

var contextify = process.binding('contextify');
var script = new contextify.ContextifyScript(' console.log("im here, buddy") ');
script.runInThisContext();
Run Code Online (Sandbox Code Playgroud)

node版本<0.11.x中,您可以使用evals绑定:

var evals = process.binding('evals');
var script = new evals.NodeScript(' console.log("here I am") ')
script.runInThisContext();
Run Code Online (Sandbox Code Playgroud)


Fab*_*tté 5

module.require = undefined;require从Module原型继承的是不够的:

module.require = undefined;

var vm = module.__proto__.require('vm');
vm.runInThisContext('console.log(1)');
Run Code Online (Sandbox Code Playgroud)

相反,你应该:

module.__proto__.require = undefined;
// now this fails and you can't use the __proto__ trick:
var vm = module.require('vm');
Run Code Online (Sandbox Code Playgroud)