views:

30

answers:

4

I want to let visitors of my web pages to access a textarea where they can write a tiny bit of javascript to configure certain features.

Imagine the javascript to be something like this:

{
max:100;
allowFeedback:false;
filterEnabled:true ;
}

I would want to eval what they write and then my javascript would do something depending on your choices:

so this would be:

var userCode = document.getElementById("textarea").value;
var result = eval(userCode);
.. if (result.filterEnabled) { ... }
if (result.allowFeedback) { ... } ...

The question is: the user could really type any javascript in there ? something malicious, something wrong what can I do to validate its code before executing ?

Many thanks

A: 

If you eval what they write, they could indeed write and run any javascript that you could write at the place of the eval call. I would suggest only allowing a very limited syntax (e.g. variable=value, with a limited set of allowed variables and values), and then parse that.

Edit: If available, you could also use a JSON parser for JavaScript instead of eval, e.g. JSON.parse.

Arkku
how do I allow a very limited syntax ?
Chez
Write a small parser in JavaScript that only recognises e.g. `variable=value` pairs and only the variables you define, and checks the values before assigning them to the variables. No `eval`. Or use regexps to remove everything even potentially dangerous (all special characters, etc) before `eval` - better specify a very limited set of what to allow rather than try to anticipate every possible “bad” input separately.
Arkku
(Or you can use `JSON.parse` or similar, if available, to parse the JSON subset of JavaScript. Just don't `eval` arbitrary input.)
Arkku
A: 

Read this on CSRF ... not a good idea to eval any user input, trust me.

Simone Margaritelli
is there anything I can do before evaling
Chez
Remove every "dangerous" character ... just like Arkku said, you have to limit the freedom of the user to be safe.
Simone Margaritelli
-1 this has nothing to do with csrf. This is DOM based xss.
Rook
A: 

The code you have posted is vulnerable to DOM Based XSS and all of the rules for exploiting XSS still apply. Its not often that vulnerabilities can be found in JavaScript, but this is a good case of it. I would avoid using this code. If you really want this feature then you should put it on its own domain which doesn't have sessions/authentication/anything of value.

Rook
A: 

Read this article about JSON and security. Code and example are also present there - Parse JSON using JSON Parser or eval()! . That should be helpful for you.

Satya Prakash