2015-02-07 50 views
12

我只是努力在codewars.com寫一些隨機的難題,並很好奇,如果任何人都可以想辦法給eval代碼下面的代碼已運行後:座EVAL &&新功能

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 

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

+1

你可能是一個編碼的挑戰網站更成功發佈此。 – Barmar 2015-02-07 01:17:32

+0

我認爲這是爲了安全措施?在這種情況下,它是一個黑名單,正如你的問題所暗示的那樣。 – Timmerz 2015-02-07 01:32:12

+1

@Barmar我認爲這是一個編碼挑戰網站? – Timmerz 2015-02-07 01:36:34

回答

9

那麼,你也有module變量在node。所以,你可以要求vm包,並使用其require方法運行代碼:

var vm = module.require('vm'); 
vm.runInThisContext(' console.log("hello") '); 

UPD 嗯,你更新的問題,但我們可以再次破解它:

var vm = module.constructor.prototype.require('vm'); 
vm.runInThisContext(' console.log("hello") '); 

UPD2 另一種變體:

var vm = module.constructor._load('vm'); 
vm.runInThisContext(' console.log("hello") '); 

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") '); 

我認爲最好設置module = undefined,使問題更加複雜:)

UPD4 有另一種變體,而不module: )

process.stdin.push(' console.log("here we are") \n '); 

但它起作用僅在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(); 

node與< 0.11.x版本您可以使用evals結合:

var evals = process.binding('evals'); 
var script = new evals.NodeScript(' console.log("here I am") ') 
script.runInThisContext(); 
+0

Upvoting,並將在晚些時候接受,因爲這是第一個正確答案:)儘管等待更多的答案:D – 2015-02-07 02:36:58

+0

@zyklus你改變了問題的條件:) – alexpods 2015-02-07 02:39:09

+0

是的,因爲我想盡可能多的答案。你的答案是正確的,我不是爭議:) – 2015-02-07 02:41:56

5

module.require = undefined;是不夠的爲require從模塊原型繼承:

module.require = undefined; 

var vm = module.__proto__.require('vm'); 
vm.runInThisContext('console.log(1)'); 

相反,你應該:

module.__proto__.require = undefined; 
// now this fails and you can't use the __proto__ trick: 
var vm = module.require('vm'); 
+0

真棒,謝謝:)我應該已經意識到 – 2015-02-07 02:43:55