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:
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/>
, 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.
回答2:
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.
回答3:
You can also try to use strip_tags if you don't allow HTML tags in postings. Also check out the html purifier