Skip to content

Instantly share code, notes, and snippets.

@line-o
Forked from aemkei/SandBox.js
Created October 8, 2012 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save line-o/3852813 to your computer and use it in GitHub Desktop.
Save line-o/3852813 to your computer and use it in GitHub Desktop.
Is it possible to sandbox JS code
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