Content security policy (CSP)

The site has a policy that limits what external content can load on its pages.

On this page

Impact

ScanGov impact ratings

About

Content Security Policy (CSP) is a security standard that helps protect websites from attacks like cross-site scripting (XSS) by allowing website owners to declare trusted sources of content.

CSP is delivered using HTTP headers or HTML meta tags, and uses directives like default-src, script-src, and img-src to control resource loading. CSP can enforce policies, report violations, and is not a replacement for careful input validation, but a defense-in-depth measure. Strict CSP is more secure using nonces or hashes.

Note: It's an extra layer of protection, not the primary defense.

Risks

Hackers can inject bad code into your site.

Why it's important

Helps stop hackers by blocking harmful code from running on your website.

User stories

As a website owner, I want to define a Content Security Policy so that I can prevent malicious scripts from executing and protect users from XSS attacks.
As a site visitor, I want the website to load safely and securely without being exposed to malicious content or scripts so that my browsing experience is safe and my data is protected.

Code

Example header:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' https://example.gov;
  style-src 'self' 'unsafe-inline';
  img-src 'self' https://example.gov;
  font-src 'self' https://example.gov;
  object-src 'none';
  frame-ancestors 'none';
  upgrade-insecure-requests;

Example HTML code:

<!-- Content Security Policy example using meta tag -->
<meta http-equiv="Content-Security-Policy" content="
  default-src 'self';
  script-src 'self' https://example.gov;
  style-src 'self' 'unsafe-inline';
  img-src 'self' https://example.gov;
  font-src 'self' https://example.gov;
  object-src 'none';
  frame-ancestors 'none';
  upgrade-insecure-requests;
">

Error

ScanGov messaging when a site fails a standard:

Content Security Policy is missing or too permissive.

Example

A minimal but effective CSP for a government site that uses only its own assets:

Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'

Progressively tighten by switching from Content-Security-Policy to report-only mode first:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri https://example.gov/csp-report

Guidance

Indicators

On this page