gray stainless steel armor
Tue Jun 13

Content Security Policy (CSP) Header With Example

If you are a web developer or a website owner, you might have heard of Content Security Policy (CSP) as a way to protect your site from malicious attacks. But what exactly is CSP and how does it work? In this article, we will explain everything you need to know about CSP, including its definition, how it works, why it is important, and how to implement it. Hopefully, by the end of this article, you will have a clear understanding of how CSP can help you improve your web security and performance.

What is Content Security Policy?

Content Security Policy is a web standard that allows you to control what resources can be loaded and executed on your web pages. It is a set of rules that you can specify in your HTML header or meta tag, which tells the browser how to handle different types of content, such as scripts, images, stylesheets, fonts, media, etc.

The main purpose of CSP is to prevent cross-site scripting (XSS) attacks, which are one of the most common and dangerous web security threats. XSS attacks occur when an attacker injects malicious code into your web page, which can then execute in the browser of your visitors. This can lead to data theft, identity theft, account hijacking, malware infection, and more. By using CSP, you can limit the sources and types of content that can run on your web page, thus reducing the risk of XSS attacks.

How does Content Security Policy work?

CSP works by using directives and policies. A directive is a keyword that represents a type of content or a feature that you want to control. For example, some common directives are:

  • default-src: This applies to all types of content that are not specified by other directives
  • script-src: This applies to scripts
  • img-src: This applies to images
  • style-src: This applies to stylesheets
  • font-src: This applies to fonts
  • media-src: This applies to audio and video
  • frame-src: This applies to frames and iframes
  • object-src: This applies to plugins and objects
  • connect-src: This applies to XMLHttpRequests, WebSocket connections, and EventSource connections
  • report-uri: This specifies a URL where violation reports will be sent

A policy is a set of directives and their values that define what sources are allowed or disallowed for each type of content. For example, a policy can look like this:

`default-src 'self'; script-src 'self' https://example.com; img-src *; report-uri https://example.com/csp-report`

This policy means that:

You can specify multiple policies by separating them with semicolons. The browser will enforce the most restrictive policy for each type of content. For example:

`default-src 'self'; script-src 'self' https://example.com; script-src 'none'`

This means that no scripts are allowed at all ('none'), even from the same origin or from https://example.com.

You can also use some special keywords or values in your policies, such as:

  • ‘none’: This means no sources are allowed
  • ‘self’: This means the same origin as the web page
  • ‘unsafe-inline’: This means inline scripts or styles are allowed
  • ‘unsafe-eval’: This means scripts that use eval() or similar functions are allowed
  • ‘nonce-value’: This means scripts or styles that have a matching nonce attribute are allowed
  • ‘sha256-value’: This means scripts or styles that have a matching hash value are allowed
  • data:: This means data URIs are allowed

Why is Content Security Policy important?

CSP is important because it can help you improve your web security and performance in several ways, such as:

Preventing XSS attacks :**** As mentioned earlier, CSP can prevent malicious code from running on your web page, which can protect your site and your visitors from data theft, identity theft, account hijacking, malware infection, and more.
Reducing the attack surface : By limiting the sources and types of content that can run on your web page, you can reduce the number of potential vulnerabilities and exploits that an attacker can use to compromise your site.
Improving the loading speed : By restricting unnecessary or unwanted content from loading on your web page, you can reduce the bandwidth and CPU usage, which can improve the loading speed and performance of your site.
**Enhancing the user experience** : By preventing unwanted content such as ads, pop-ups, trackers, or malware from loading on your web page, you can enhance the user experience and satisfaction of your visitors.

How to implement Content Security Policy?

To implement CSP, you need to create and apply a policy that suits your needs and goals. There are different ways to do this, depending on your scenario and platform. Here are some general steps to follow:

  1. Analyze your web page and identify what types of content you need and where they come from. You can use tools such as Chrome DevTools or Mozilla Observatory to help you with this.
  2. Create a policy that allows only the necessary and trusted sources for each type of content. You can use tools such as CSP Evaluator or CSP Builder to help you with this.
  3. Test your policy in a development or staging environment before applying it to your production site. You can use tools such as CSP Tester or Report URI to help you with this.
  4. Apply your policy to your web page by adding it to your HTML header or meta tag. For example: <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://example.com; img-src *; report-uri `[`https://example.com/csp-report">](https://example.com/csp-report”>`)
  5. Monitor and update your policy regularly to ensure that it is working properly and does not break any functionality or features of your site. You can use tools such as CSP Monitor or CSP Scanner to help you with this.

Additional information about Content Security Policy

Most modern browsers support CSP, including Chrome, Firefox, Safari, Edge, Opera, and Brave. However, some older browsers or versions may not support CSP or may support only some directives or features. You can check the browser compatibility of CSP here. If a browser does not support CSP, it will ignore the policy and load the web page normally. This means that the web page will not be protected by CSP and may be vulnerable to XSS attacks or other security threats. Despite that, Content Security Policy is supported by most modern websites, with the exception of Internet Explorer.

If you are a developer, you may also need to debug CSP. To do that you can use the browser’s developer tools or console to check for any errors or warnings related to CSP. You can also use the report-uri directive to send violation reports to a specified URL, where you can analyze them using tools such as Report URI or Sentry. Optimizing your CSP involves following some best practices and implementing effective strategies. Consider the following tips:

  1. Set a baseline policy using the default-src directive to define a default behavior for all types of content.
  2. Use specific directives for each content type to override the default policy when necessary.
  3. Utilize the 'self' keyword to allow content from the same origin as the web page.
  4. Implement hashes or nonces to permit inline scripts or styles securely.
  5. Prefer using HTTPS connections whenever possible to ensure the integrity and confidentiality of your content.
  6. Implement subresource integrity (SRI) to verify the integrity of external scripts or styles, preventing the injection of malicious content.
  7. Leverage content delivery networks (CDNs) or trusted domains to host your external content, reducing the risk of hosting malicious files on your own servers.
  8. Minimize the usage of 'unsafe-inline', 'unsafe-eval', or data: keywords, as they can weaken your CSP by allowing potentially dangerous content.
  9. Regularly test and update your CSP to ensure it doesn’t inadvertently break any functionality or features of your website. This includes verifying that all required domains, sources, and directives are correctly specified.

Conclusion

Content Security Policy is a powerful and effective way to protect your web site from XSS attacks and other security threats. By using CSP, you can control what resources can be loaded and executed on your web pages, thus reducing the attack surface and improving the loading speed and user experience of your site. However, implementing CSP can be challenging and complex, as you need to create and apply a policy that suits your needs and goals, without breaking any functionality or features of your site. Therefore, you need to use the right tools and best practices to help you with this process.