-
-
Save line-o/3852813 to your computer and use it in GitHub Desktop.
Is it possible to sandbox JS code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sandbox(script, context){ | |
context.window = {}; | |
for (var key in context){ | |
context.window[key] = context[key]; | |
} | |
context.global = context.window; | |
eval("with (context){ " + script + " }"); | |
} | |
var NOT_ALLOWED = function(name){ | |
return function(){ | |
console.warn(name + "(); is not allowed."); | |
return function(){}; | |
}; | |
}; | |
var scope = { | |
"alert": function(message){ console.log(message); }, | |
"eval": NOT_ALLOWED("eval"), | |
"Function": NOT_ALLOWED("Function") | |
}; | |
sandbox("alert('good try');", scope); | |
sandbox("global.alert('good try');", scope); | |
sandbox("window.alert('good try');", scope); | |
sandbox("eval('alert(1)');", scope); | |
sandbox("~new Function('alert(1)')();", scope); | |
// This will fail: | |
sandbox("(function(){this.eval('good try');}).apply(null)", scope); | |
// ~90 bytes: | |
// function(e,t,n,r){r={};for(n in t)r[n]=t[n];t.window=t.global=r,evil("with(t){"+e+"}")} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment