Content Security Policy (CSP) - HTTP | MDN (original) (raw)

CSP overview

A CSP should be delivered to the browser in the Content-Security-Policy response header. It should be set on all responses to all requests, not just the main document.

You can also specify it using the http-equiv attribute of your document's element, and this is a useful option for some use cases, such as a client-side-rendered single page app which has only static resources, because you can then avoid relying on any server infrastructure. However, this option does not support all CSP features.

The policy is specified as a series of directives, separated by semi-colons. Each directive controls a different aspect of the security policy. Each directive has a name, followed by a space, followed by a value. Different directives can have different syntaxes.

For example, consider the following CSP:

Content-Security-Policy: default-src 'self'; img-src 'self' example.com

It sets two directives:

A CSP broken into its directives.

The first directive, default-src, tells the browser to load only resources that are same-origin with the document, unless other more specific directives set a different policy for other resource types. The second, img-src, tells the browser to load images that are same-origin or that are served from example.com.

In the next section, we'll look at the tools available to control resource loads, which is the main function of a CSP.

Controlling resource loading

A CSP can be used to control the resources that a document is allowed to load. This is primarily used for protection against cross-site scripting (XSS) attacks.

In this section we'll first see how controlling resource loads can help protect against XSS, then at the tools CSP provides to control what resources are loaded. Finally we'll describe one particular recommended strategy, which is called a "Strict CSP".

XSS and resource loading

A cross-site scripting (XSS) attack is one in which an attacker is able to execute their code in the context of the target website. This code is then able to do anything that the website's own code could do, including, for example:

An XSS attack is possible when a website accepts some input which might have been crafted by an attacker (for example, URL parameters, or a comment on a blog post) and then includes it in the page without sanitizing it: that is, without ensuring that it can't be executed as JavaScript.

Websites should protect themselves against XSS by sanitizing this input before including it in the page. A CSP provides a complementary protection, which can protect the website even if sanitization fails.

If sanitization does fail, there are various forms the injected malicious code can take in the document, including: