Ora

What is 'self' in Content Security Policy (CSP)?

Published in Content Security Policy 5 mins read

In Content Security Policy (CSP), 'self' is a fundamental source expression that refers to the origin site from which the current document is being served, specifically matching the same scheme (protocol) and port number. It acts as a powerful whitelist entry, ensuring that your web application primarily loads resources only from its own domain.

Understanding the 'self' Origin

When you include 'self' in a CSP directive, you are instructing the browser to trust resources (like scripts, stylesheets, images, fonts, etc.) that originate from the same location as the HTML document itself. This "origin" is determined by three key components:

  • Scheme (Protocol): Whether the connection is secure (https://) or insecure (http://). A document served over https will only consider https resources from its own domain as 'self'.
  • Host (Domain Name): The specific domain, e.g., www.example.com or app.example.com.
  • Port Number: The port used for the connection (e.g., 80 for HTTP, 443 for HTTPS, or any custom port).

For example, if your web page is loaded from https://www.example.com:443/index.html, then 'self' would refer to any resource loaded from https://www.example.com:443/. Resources from http://www.example.com, https://sub.example.com, or https://www.example.com:8080 would not be considered 'self'.

Why 'self' is Crucial for Web Security

The judicious use of 'self' is a cornerstone of a robust Content Security Policy, significantly bolstering a website's defense against various attacks, particularly Cross-Site Scripting (XSS).

  1. XSS Prevention: By default, 'self' restricts the loading of scripts, styles, and other potentially malicious content to your own trusted domain. This prevents attackers from injecting and executing arbitrary scripts from external, untrusted sources.
  2. Defined Trust Boundaries: It clearly establishes what your application considers its own, local content, making it easier to identify and block unauthorized resource requests.
  3. Reduced Attack Surface: Limiting the origins from which content can be loaded drastically reduces the avenues for attackers to exploit vulnerabilities or compromise user data.

How to Use 'self' in CSP Directives

'self' is used within various CSP directives to specify allowed sources for different types of content. Below are common directives where 'self' is frequently applied:

CSP Directive Description Example Usage
default-src Fallback for any fetch directive not explicitly defined. default-src 'self';
script-src Specifies valid sources for JavaScript. script-src 'self' https://cdn.jsdelivr.net;
style-src Specifies valid sources for stylesheets. style-src 'self' 'unsafe-inline';
img-src Specifies valid sources for images. img-src 'self' data: https://user-content.com;
connect-src Applies to XMLHttpRequest (XHR), WebSockets, and EventSource. connect-src 'self' wss://api.example.com;
font-src Specifies valid sources for web fonts. font-src 'self' https://fonts.gstatic.com;
frame-src / child-src Specifies valid sources for frames, iframes, and web workers. frame-src 'self' https://www.youtube.com;

Example CSP Header:

A common and secure starting point for a CSP might look like this:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:;

In this example:

  • default-src 'self' means all resources (unless overridden by another directive) must come from the same origin.
  • script-src 'self' https://cdnjs.cloudflare.com allows JavaScript from the current origin and from cdnjs.cloudflare.com.
  • style-src 'self' 'unsafe-inline' allows stylesheets from the current origin and permits inline styles (though 'unsafe-inline' should be used with caution).
  • img-src 'self' data: allows images from the current origin and images embedded directly as data URIs.

'self' vs. Other CSP Source Expressions

It's important to understand how 'self' compares to other common source expressions used in CSP:

  • 'none': This directive explicitly forbids resources from any source. For instance, object-src 'none' would prevent embedding <object>, <embed>, or <applet> elements, regardless of their origin.
  • 'unsafe-inline': This keyword allows the use of inline scripts or styles directly embedded within the HTML document (e.g., <script>alert('hi')</script> or <style>body{color:red;}</style>). While sometimes necessary for legacy applications or specific framework integrations, it significantly weakens CSP's XSS protection and should be avoided if possible.
  • 'unsafe-eval': This keyword permits the use of dynamic code evaluation mechanisms such as eval(), setTimeout("...", 200), and new Function(). Like 'unsafe-inline', it bypasses some of CSP's core protections and should be used with extreme caution or avoided entirely.
  • Specific Hosts/Domains: You can whitelist specific external domains, like https://api.example.com or *.cloudfront.net, to fetch resources from them.
  • Wildcards: *.example.com allows all subdomains of example.com.
  • Data Schemes: data: allows resources embedded directly in the HTML using data URIs (e.g., <img> tags with data:image/png;base64,...).

Best Practices for Using 'self'

  • Start with 'self': Always include 'self' in most of your source directives unless you have a specific reason not to (e.g., if a directive like object-src should allow absolutely nothing).
  • Be Specific with External Sources: When external resources are needed, list them explicitly rather than relying on broad wildcards.
  • Minimize 'unsafe-inline' and 'unsafe-eval': These keywords compromise CSP's security benefits. Strive to refactor code to eliminate their necessity by using nonces or hashes for inline scripts/styles, or by avoiding eval()-like functions.
  • Continuously Test and Refine: Deploy your CSP in reporting mode (Content-Security-Policy-Report-Only) first to identify violations without blocking content, then iteratively refine it to achieve optimal security without breaking functionality.

By effectively utilizing 'self' within your Content Security Policy, you establish a strong baseline for your web application's security, ensuring that content primarily originates from your trusted environment.

[[Content Security Policy]]