Fixing Cross-site Scripting (XSS)

Published: 25 October 2020

This issue comes about where user supplied input is included within server responses without filtration or encoding.

One very effective method of preventing this attack is to use an allow-list (sometimes called a whitelist) which will allow only known good content. For example if your expected input is an integer and the user supplies anything other than an integer you can simply reject that input – and perhaps supply a message to inform the user what the issue is, without including the original payload.

The opposite approach to this would be to use a blocklist (sometimes called a blacklist) which attempts to block known-bad content, which requires a complete list of all possible bad inputs and is therefore commonly ineffective, as it opens up the possibility for filter evasion.

However, encoding is often an option – for example in the example case, if output was HTML Entity encoded (Many languages have a built-in function for this, for example PHP has htmlentities(), then the JavaScript execution would be blocked by the browser.

In short this is because required characters such as the less-than and greater-than (< and >) would be replaced with their entity versions, < and >. These entities render correctly in the browser but the browser will not interpret them as tags, thereby blocking access to JavaScript or the ability to craft HTML tags.

It’s also worth considering Content Security Policy (CSP), which is a browser feature that allows you to specify an allow-list of locations where JavaScript (and other resources) can be loaded from – allowing you to block attacks of this nature across a whole site.

That's it!

Read More