Chez
Chez

Reputation: 507

input field to put javascript/json and security issues

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

Upvotes: 4

Views: 1334

Answers (5)

Praveen Kumar Patidar
Praveen Kumar Patidar

Reputation: 77

I had similar kind of usecase long ago. This may seems childish answer but before evaluating you can parse the characters like < > and . specially. SO that the content will no longer be a valid program. Mainly the scripting contains dots and < > and that can be filtered for the evaluation. or replaced by some other characters.

Upvotes: 0

Satya Prakash
Satya Prakash

Reputation: 3502

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.

Upvotes: 1

rook
rook

Reputation: 67039

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.

Upvotes: 0

Simone Margaritelli
Simone Margaritelli

Reputation: 4733

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

Upvotes: 0

Arkku
Arkku

Reputation: 42159

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.

Upvotes: 0

Related Questions