Preventing XSS Attacks Using Content Security Policy
Cross-site scripting (XSS) attacks are one of the more insidious types of Internet malicious activities because customers of a legitimate website may become victims without any direct compromise of the website, and often even without the site operator’s knowledge. Defending against such attacks can be difficult, but a function incorporated into newer web browsers adds a significant defensive tool against XSS.
A quick review: an XSS attack occurs when an attacker is able to insert malicious content into a legitimate website’s pages. The goal is to use the legitimacy of the targeted site to deliver this malicious content to other visitors. Areas of a web site most often targeted are discussion forums and comment sections, areas specifically intended to receive content from one visitor and display that content to many visitors.
One recommendation for defending against XSS is simply to avoid entirely inserting any visitor-provided content into your web pages. While this is a strong defense, it is also impractical in the era of maximum interactivity with site visitors.
Another recommendation is to sanitize and HTML-escape any visitor-provided content. This method seems straightforward in principle, and is the approach many sites use. However, attackers can be extremely clever in obfuscating and encoding their data to circumvent any filtering techniques. It can also lead to a false sense of security for the site owners, and doesn’t provide any data or feedback about attacks that may slip through.
Content Security Policy (CSP) is the latest defensive weapon in the XSS battle. A new technology built into the latest versions of the most popular web browsers, CSP lies dormant until “switched on” by a specific HTTP header from the web site being visited.
In addition to blocking of content, CSP includes a reporting capability. This can be used simultaneously with blocking, or in report-only mode with no blocking. Activating the reporting function causes the browser to send a JSON-formatted report to a URL specified by the originating site. Report-only mode would be useful for testing a proposed policy or for gathering intelligence when the content cannot be modified for some reason.
CSP polices apply to individual pages, so refactoring could be minimized by applying strict polices to only high-risk pages.
CSP is not a silver bullet because of the dependence on newer browser versions. Many older browsers will continue to be in use for a long time, and these cannot be protected. However CSP effectiveness will improve over time as more browsers are updated.
For more information, see the following references:
Content Security Policy Reference
An Introduction to Content Security Policy
Cross Site Scripting Prevention Cheat Sheet