views:

100

answers:

3

ok, I start with a very simple method:

alert(someText);

"someText" is a variable, which users will pass a value in by a form. Will there a chance that the user pass following text, and inject some code in my Javascript? For example, can the user pass this in this method:

"anotherText"); alert("the nextText"

If so, how can I prevent it from happening? if not, can anyone mention some security concern about javascript?

+7  A: 

No, it doesn't work that way. String values are not substituted where they are used, they are just used as strings. So there is no security problem.

The only time you may have to worry about this is when you use eval:

eval("alert(\" + someText + "\");");

(Yes, I realize this is a contrived example...)

Zifre
+4  A: 

Basically, as long as you're not calling "eval" (or some function that does), and you're not injecting Javascript created from users directly in to pages (via the script tag), you shouldn't have anything to worry about.

Will Hartung
+2  A: 

Once you have a variable inside javascript it won't matter much unless you do an eval or set the innerHTML property of a DOM element with it.

Aside from that, whether there's a potential for injection depends on how you're getting the value from the form to the javascript.

If for example the form is being submitted to the server and the value of the variable is being set by writing the javascript on the server side you could potentially have a problem. Something like this would obviously leave the script open for injection.

var someText = "<?php echo $_POST["someText"]; ?>";

So it's hard to say whether you could have a security issue without knowing how you're getting the value from the form. In my experience the server side code is the cause of most XSS vectors. In terms of javascript you generally just have to watch for eval and innerHTML.

Kyle Jones