...

/

Content Security Policy

Content Security Policy

In this lesson, we'll learn about one of the most powerful security features that browsers have introduced in recent years in mitigating Cross-site Scripting vulnerabilities and how it helps create a content trust policy.

As we discussed in the X-Frame-Options section, there are many attacks related to content injection in the user’s browser. These include Clickjacking attacks as well as another form of attacks known as Cross-Site-Scripting (XSS).

XSSXSS

Another improvement to the previous set of headers we reviewed so far is a header that can tell the browser which content to trust. This allows the browser to prevent attempts at content injection that is not trusted in the policy defined by the application owner.

With a Content Security Policy (CSP) it is possible to prevent a wide range of attacks, including Cross-site scripting and other content injections. The implementation of a CSP renders the use of the X-Frame-Options header obsolete.

The Risk

Using a Content Security Policy header will prevent and mitigate XSS and other injection attacks. Examples of some of the issues that can be prevented by setting a CSP policy include:

  • Inline JavaScript code specified with <script> tags, and any DOM events which trigger JavaScript execution such as onClick() etc.
  • Inline CSS code specified via a <style> tag or attribute elements.

The Solution

With CSP allowlists, we can allow many configurations for trusted content. As such, the initial setup can grow to a set of complex directives.

Let’s review one directive called connect-src. It is used to control which remote servers the browser is allowed to connect to via XMLHttpRequest (XHR), or ...