Chapter 28. Defending Against XSS Attacks

In Chapter 10, we discussed XSS attacks that took advantage of the browser’s ability to execute JavaScript code on user devices in depth. XSS vulnerabilities are widespread and capable of causing a significant amount of harm, as script execution vulnerabilities have a wide breadth of potential damage.

Fortunately, although XSS appears often on the web, it is quite easy to mitigate or prevent entirely via secure coding best practices and XSS-specific mitigation techniques. This chapter is all about protecting your codebase from XSS.

Anti-XSS Coding Best Practices

One major rule you can implement in your development team to dramatically mitigate the odds of running into XSS vulnerabilities is “don’t allow any user-supplied data to be passed into the DOM—except as strings.”

Such a rule is not applicable to all applications, as many applications have features that incorporate user-to-DOM data transfer. In this case, we can make this rule more specific: “never allow any unsanitized user-supplied data to be passed into the DOM.”

Allowing user-supplied data to populate the DOM should be a fallback, last-case option rather than a first option. Such functionality will accidentally lead to XSS vulnerabilities, so when other options are available, they should be chosen first.

When user-supplied data must be passed into the DOM, it should be done as a string, if possible. This means, in any case where HTML/DOM is NOT required and user-supplied data ...

Get Web Application Security, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.