In a large project of mine, I've run into a situation where a client might need to run evaluated JavaScript code. I know, it makes me cringe too. One option is to manually parse it, but for future flexibility, I would like to evaluate the code safely.
Everything I've seen and researched says, NO. Ah, the nay-sayers.
This is my attempt to sandbox the eval:
Can you shoot holes in it and try and break it? I should wrap it in a try so it doesn't throw ugly errors, but beyond that, tell me where I have gone awry.
/***************************************
* Senica Gonzalez ([email protected])
* This is an attempt to sandbox an eval
* in javascript using an iframe.
* Test it and let me know if you
* can break it.
***************************************/
window.addEventListener("message", function(event){
$('#result').text(event.data.eval);
console.log(event.data.scope1);
console.log(event.data.scope2);
}, false);
test = 'do I exist in the window?';
var input = $('[name=toeval]');
input.on('change', function(){
var val = $(this).val();
var code = btoa('<html>\
<head><\/head>\
<body>\
<' + 'script>\
var party_size = 10;\
window.parent.postMessage({\
eval: eval('+val+'),\
}, "*");\
<\/script' + '>\
<\/body>\
<\/html>');
var frame = $('<iframe sandbox="allow-scripts" src="data:text/html;base64,'+code+'"></iframe>');
var sandbox = $('#sandbox');
sandbox.html(frame);
});
I have been unsuccessful at accessing the parent document variables, or being able to do anything obnoxious other than to my self within the sandbox.
"</script>"
should be escaped using"<\/script>"
(and so should all other closing tags in string literals), the way you have it does nothing useful. \$\endgroup\$allow-same-origin
is all the security hole you need, isn't it? Also what about browsers that don't understand thesandbox
attribute? \$\endgroup\$/
as suggested certainly does not stop the inserted script from running. See Why split the <script> tag when writing it with document.write()?. \$\endgroup\$