Content Security Policy (CSP)

The Content Security Policy (CSP) is an essential security feature implemented in modern web development to prevent various forms of attacks, especially Cross-Site Scripting (XSS), data injection, and other code execution vulnerabilities. By using CSP, developers can control which resources can be loaded by the browser, creating a "white-list" of safe resources and reducing the risk of malicious code execution. This chapter will guide you through the entire concept of CSP, from its basics to advanced topics, with practical examples.

Content Security Policy (CSP)?

CSP is a security mechanism enforced by browsers to restrict and control the resources (like JavaScript, CSS, images, etc.) that a website can load. This is done by setting rules, usually in the HTTP headers or HTML <meta> tags, that specify the sources from which content can be loaded.

Key Objectives of CSP

  • Prevent execution of unauthorized scripts.
  • Block loading of resources from unsafe domains.
  • Restrict data exfiltration attempts.
  • Enhance website security against cross-site scripting (XSS) attacks and other code injections.

Why Use CSP?

CSP helps prevent:

  1. Cross-Site Scripting (XSS) Attacks: These attacks inject malicious scripts that can steal data or perform harmful actions.
  2. Data Theft: CSP blocks attempts to exfiltrate data to unauthorized domains.
  3. Clickjacking Protection: CSP can be used to prevent clickjacking by controlling framing options.

Example of an XSS Attack

To understand the importance of CSP, let’s consider a basic example:

				
					<input type="text" placeholder="Enter your name" id="userInput"> <script type="litespeed/javascript">document.getElementById("userInput").value="<script>alert('XSS')</script>";
</script>

				
			

In this example, an XSS vulnerability exists because an attacker could inject a script that shows an alert. CSP helps block such unauthorized scripts.

Setting Up CSP

CSP can be set in two main ways:

  • HTTP Headers: By setting a Content-Security-Policy header on the server.
  • Meta Tags: By adding a <meta> tag within the HTML <head>.

Example: Basic CSP Setup in HTTP Header

An example of setting a basic CSP policy in an HTTP header:

				
					Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-scripts.com

				
			

This CSP:

  • Allows resources (like images, fonts) only from the same origin ('self').
  • Allows scripts only from the same origin and https://trusted-scripts.com.

Example: Basic CSP Setup in Meta Tag

Alternatively, we can add this policy in the <meta> tag:

				
					<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-scripts.com">

				
			

Explanation

  • default-src 'self': Only load resources from the same origin.
  • script-src: Limits script loading to the same origin and a specific trusted domain.

Output: With this CSP in place, any attempt to load scripts from untrusted sources will be blocked by the browser.

CSP Directives

CSP offers several directives to define specific content sources:

  1. default-src: Specifies the default policy for loading resources (e.g., images, scripts).
  2. script-src: Restricts JavaScript sources.
  3. style-src: Controls CSS stylesheets.
  4. img-src: Limits image sources.
  5. font-src: Defines allowed font sources.
  6. connect-src: Controls which URIs can be connected to (e.g., APIs).
  7. media-src: Restricts audio and video sources.
  8. frame-src: Limits framing (iframes).
  9. object-src: Restricts plugin-based content (e.g., Flash).

Example: Using Multiple CSP Directives

				
					<meta http-equiv="Content-Security-Policy" content="
    default-src 'self'; 
    script-src 'self' https://trusted-scripts.com;
    img-src 'self' https://images.com;
    style-src 'self' https://trusted-styles.com;
    font-src https://fonts.com;
">

				
			

Explanation

  • The policy restricts each content type to specific sources, enhancing security by narrowing down potential attack points.

Output: Only resources from defined sources will load. Any other sources will be blocked, helping prevent code injection.

Advanced CSP Features

Nonce-Based Policies

To allow inline scripts selectively, CSP supports nonces (numbers used only once).

Example of Nonce Usage

				
					<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-abc123' 'self';"> <script nonce="abc123">// This inline script is allowed due to matching nonce</script> 
				
			

Explanation

  • script-src 'nonce-abc123': Allows inline scripts with the specific nonce.
  • <script nonce="abc123">: Script tag includes matching nonce, so it is allowed to execute.

Content Security Policy Report

You can set CSP to report violations by adding a report-uri directive. This way, you can track attempted violations.

				
					Content-Security-Policy: default-src 'self'; report-uri /csp-report-endpoint

				
			

Explanation

  • report-uri: Logs violations to a specified endpoint without blocking them (report-only mode).

Implementing CSP Policies with Examples

Example 1: Strict CSP Policy

				
					<meta http-equiv="Content-Security-Policy" content="
    default-src 'self';
    script-src 'self';
    style-src 'self';
    img-src 'self';
    frame-ancestors 'none';
">

				
			

Explanation

  • Only content from the same origin ('self') is allowed for scripts, styles, and images.
  • frame-ancestors 'none' prevents the page from being framed, adding anti-clickjacking protection.

Example 2: Allowing External Resources

				
					<meta http-equiv="Content-Security-Policy" content="
    default-src 'self';
    script-src 'self' https://cdn.scripts.com;
    style-src 'self' https://cdn.styles.com;
    img-src 'self' data:;
">

				
			

Explanation

  • Scripts and styles are allowed from trusted external sources.
  • img-src 'self' data: allows images from the same origin and inline base64-encoded images.

Common Challenges and Best Practices

  • Testing CSP Policies: Start in report-only mode to monitor violations without blocking resources.
  • Nonce-Based Inline Script Control: For pages with inline scripts, use nonce-based policies.
  • Use Minimum Permissions: Limit CSP to only the domains necessary for the functionality of your website.

Example: Testing CSP in Report-Only Mode

				
					<meta http-equiv="Content-Security-Policy-Report-Only" content="default-src 'self'; report-uri /csp-report-endpoint">

				
			

The Content Security Policy (CSP) is a critical security feature that can significantly reduce the risk of XSS attacks, data exfiltration, and unauthorized resource usage on a webpage. By defining strict policies, developers can control the sources from which content is loaded, ensuring that only trusted scripts, styles, images, and other resources are used. Happy coding !❤️

Table of Contents