Use eval without XSS threat

I was making (not now, but still interesting to me) a game using HTML5 and JS, and I wanted people to be able to insert a custom script, but safe.

function executeCustomJS(code){ eval(code);//bad } 

Of course, this code is very bad, because if the code is something like document.location.href='http://meatspn.com' , then the result will be very ... (...)

One of the solutions I found is to escape (for example, eval___eval___ ) all keywords and exclude keywords in the white list, such as "while", "for", "if", "var", true ',' false ', ... and 'func0', 'func1', .... which are a bit of an API and safe.

For example,

 function executeCustomJS(code){ code = code.replace(/(Keyword RegEx)/g,'___$1___'); /*unescape keywords in whitelist*/ eval(code); } 

I did not do RegEx and things in the comments, but that is not a question.

Suppose that the lines in the code are not escaped, there is no function that can be performed by escaping the lines, and "eval", "window", "document", "alert", "location" are NOT whitelisted. Nevertheless, some people can execute code like while(true){} , they cannot execute any code, for example document.location.href='http://meatspn.com' .

Is this method safe? Or, is there a better way or not?

+1
javascript security eval xss
source share
3 answers

I recommend that you expose your limited scripting language to JSON. So document a scripting engine that requires you to create a JSON object as your code.

This has the big advantage that it is not possible to embed bad code in JSON because it is just data.

So you can create some kind of declarative syntax for your scripting code. for example

 { "0": { "Action": "move", "X": 10, "Y": -5 }, "1": { "Action": "emote", "type": "dance" } } 

Now, what is a good design for a tiny declarative scripting language is a completely different matter.

+4
source share

To expose everything that the user may wish to do as combinators , for example. sublanguage.

0
source share

https://developers.google.com/caja/

The Caja Compiler is a tool to safely embed third-party HTML, CSS and JavaScript into your website. It provides rich interaction between the implementation page and embedded applications. Caja uses an object security model that allows you to use a wide range of flexible security policies so that your site can effectively control what embedded third-party code can do with user data.

0
source share

All Articles