I was making(not now, but still I’m curious about this one) a game using HTML5 and JS, and one I wanted was that people can insert custom script, but secure.
function executeCustomJS(code){
eval(code);//bad
}
Of course this code is very bad, because if code is something like document.location.href='http://meatspn.com', then the result will become very…(…)
One solution I found is escaping(like eval -> ___eval___) all keywords, and un-escape keywords in whitelist, such as ‘while’, ‘for’, ‘if’, ‘var’, ‘true’, ‘false’, … and ‘func0’, ‘func1’, …., which are something (like API) of the game and are secure.
For example,
function executeCustomJS(code){
code = code.replace(/(Keyword RegEx)/g,'___$1___');
/*unescape keywords in whitelist*/
eval(code);
}
I haven’t made RegEx and things in comment, but that’s not the question.
Let’s assume strings in code are not escaped, there’s no function which can be made by escaping a string, and ‘eval’, ‘window’, ‘document’, ‘alert’, ‘location’ are NOT in the whitelist. Still some people can execute code like while(true){}, they can’t execute any code like document.location.href='http://meatspn.com'.
Is this method secure? Or, is better way exists or not?
I recommend you expose a limited scripting language over JSON. So document a scripting engine that requires you to create a JSON object as your code.
This has the large advantage that it’s impossible to inject bad code into JSON because it’s just data.
So you can create some kind of declarative syntax for your scripting code. For example
Now what is a good design for a tiny declarative scripting language is a completely different question.