Content Security Policy (CSP) is a security feature designed to prevent malicious content from being executed on websites by controlling which resources can be loaded and executed. By specifying approved sources for content such as JavaScript, CSS, images, and other media, CSP helps mitigate security risks such as Cross-Site Scripting (XSS) attacks, code injection, and other content-based threats. Implemented through HTTP headers, CSP allows website administrators to define rules that govern content access and execution across web applications.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com; img-src 'self' https://images.example.com
CSP restrictions can be formulated by mapping resource requests to allowable sources. Let `R` be a set of resource requests and `S` a set of allowable sources. The function `f(r)` defines whether a resource `r` in `R` complies with CSP:
Thus, if `Σ f(r) = n` for `n` requests, then all requests are CSP-compliant. Any result where `Σ f(r) < n` signals that certain resources are blocked due to non-compliance with CSP.
The strength of CSP depends on the specific directives and source expressions used. Policies that restrict external sources, avoid `unsafe-inline`, and enforce strict rules on JavaScript and CSS sourcing provide robust protection. Adding `'nonce-'` (random tokens) or `'sha-'` (hashes) to CSP policies for inline scripts and styles adds another layer of control, allowing inline content only if it matches a pre-defined cryptographic hash or nonce value, mitigating XSS risks even further.
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:
This policy only permits content from the same origin (`'self'`) and embedded image data (`data:`), blocking all external content by default.
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *; connect-src https://api.example.com
This policy allows inline JavaScript (`'unsafe-inline'`) and permits images from any source (`*`), though this weaker policy increases vulnerability to XSS attacks.
CSP is essential in modern web application security, addressing common vulnerabilities related to content loading and execution. By defining strict content sources and limiting the use of inline scripts and dynamic code evaluation, CSP reduces the attack surface of web applications. Implementing CSP effectively involves balancing security with functionality, as overly restrictive policies can block legitimate content, while overly permissive policies may reduce protection. As a security control, CSP plays a critical role in safeguarding user data and application integrity against XSS and other injection-based attacks.