Mix

Understanding Content Security Policy (CSP)


Learn about Content Security Policy (CSP), its importance, how it works, and how it enhances web security.

What is Content Security Policy (CSP)?

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, particularly Cross-Site Scripting (XSS) and data injection attacks, by controlling the resources a web page is allowed to load.

CSP is implemented via an HTTP header, allowing web developers to explicitly specify which origins the browser should consider as trusted sources of content. This helps prevent malicious scripts or other harmful content from being executed in the user’s browser.

Why is CSP Important?

Modern web applications often use scripts, stylesheets, images, and media files from various sources. This complexity provides opportunities for attackers to inject malicious code, with XSS being one of the most common attack vectors. XSS attacks can compromise user sessions, sensitive information, or the website itself.

CSP plays a crucial role in mitigating these threats in several ways:

  • Prevents XSS Attacks: By specifying trusted script sources, CSP blocks malicious scripts from being injected and executed.
  • Prevents Data Exfiltration: It can restrict data transmission to specific domains, preventing sensitive information from being leaked.
  • Prevents Clickjacking: The frame-ancestors directive controls how other sites can frame the page, thus preventing clickjacking attacks.
  • Prevents Mixed Content: It helps maintain a secure connection by preventing HTTP content from being loaded on HTTPS pages.

How Does CSP Work?

The web server sends the Content-Security-Policy HTTP header to the client (browser). This header contains a set of policy directives, which are rules for the resources the page is allowed to load.

For example, the following CSP header allows scripts to be loaded only from the current domain ('self') and blocks scripts from all other origins:

Content-Security-Policy: script-src 'self';

When the browser receives this header, it enforces the policy for all resource requests on the page. If an attempt is made to load a resource that violates the policy, the browser blocks that resource and can send a violation report to a specified endpoint.

Key CSP Directives

CSP offers various directives for fine-grained control over resource types. Some key directives include: