tags:

views:

299

answers:

3

Is htmlspcialchars($user_data) in PHP or h(user_data) in Ruby on Rails good enough for defending all cases of XSS (Cross-site scripting) attacks? What about encoding used or any other possible considerations?

+1  A: 

In general there are three different types of XSS: the DOM-based, the Non-Persistent and the Persistent.

Now server-side languages can only prevent the latter two (Non-Persistent and Persistent) as the first only takes place on the client-side.

Gumbo
A: 

You can also try to use strip_tags if you don't allow HTML tags in postings. Also check out the html purifier

marknt15
I wouldn't recommend strip_tags at all. The user could simply type something like <scr<script>ipt> and have the middle "script" stripped and have the outside "script" left untouched. You're best to use html purifier or htmlentities with ENT_QUOTES.
Ty
+2  A: 

Both htmlspecialchars and h escape all characters that may have special meaning in HTML, there is no way that literal HTML may be injected into the target page.

However, there are ways to execute (dangerous) Javascript that do not require HTML injection. For example, if you have an application that converts [img http://example.com/img.jpg] to <img src="http://example.com/img.jpg/&gt;, imagine what may happen if a user enters [img javascript:alert(document.cookies);]. Escaping HTML characters will not save you here, you have to sanitise the given URLs. This is a fairly comprehensive list of possible XSS vulnerability examples.

If you always use htmlspecialchars/h and you always completely sanitise user input that is used as attribute values in any HTML elements, then you have a proper XSS defence.

molf