1. What is CSP?

Content Security Policy is a browser-enforced allowlist that tells the browser which sources of content (scripts, styles, images, frames, …) a page may load or execute.

  • Delivered via HTTP response header (preferred) or <meta http-equiv> (limited).
  • Defense in depth, mainly against XSS and data injection. Also helps with clickjacking (frame-ancestors) and mixed content.
  • It does not fix the underlying injection bug. It limits the damage.
  • Enforced by the browser, not the server. Non-supporting clients ignore it.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com

Headers

HeaderPurpose
Content-Security-PolicyEnforce: violations are blocked and reported
Content-Security-Policy-Report-OnlyMonitor: violations are only reported, nothing blocked. Use for rollout
  • Multiple policies are allowed. All must pass (the most restrictive wins).
  • Syntax: directives separated by ;, sources within a directive separated by spaces.

2. Common directives

Fetch directives (what can load)

DirectiveControls
default-srcFallback for most other fetch directives
script-srcJavaScript (also script-src-elem, script-src-attr)
style-srcCSS (also style-src-elem, style-src-attr)
img-srcImages and favicons
font-srcFonts
connect-srcfetch/XHR, WebSocket, EventSource, sendBeacon
media-src<audio>, <video>
object-src<object>, <embed> (set to 'none')
frame-srcSources for <iframe> / <frame> content you embed
child-srcFrames and workers (legacy-ish)
worker-srcWorkers and service workers
manifest-srcWeb app manifest

Document / navigation directives (no fallback to default-src)

DirectiveControls
base-uriAllowed <base> URLs. Set 'self' or 'none'
form-actionWhere forms may submit
frame-ancestorsWho may embed your page (replaces X-Frame-Options)
sandboxApplies iframe-sandbox-like restrictions to the page

Other

DirectivePurpose
upgrade-insecure-requestsRewrites http:// subresource URLs to https://
report-toReporting API group name (modern)
report-uriLegacy reporting endpoint (deprecated but still widely used)
require-trusted-types-for 'script' / trusted-typesDOM XSS sink protection (Trusted Types)

3. Source values

ValueMeaning
'none'Nothing allowed
'self'Same origin (scheme + host + port)
https:Any HTTPS URL (scheme source)
https://cdn.example.comSpecific host
*.example.comWildcard subdomain
data: / blob:Data / blob URIs (data: in script-src is dangerous)
'unsafe-inline'Allows inline scripts/styles. Defeats most XSS protection
'unsafe-eval'Allows eval() and similar. Avoid
'nonce-<base64>'Allows elements carrying a matching nonce attribute
'sha256-<base64>'Allows inline content with a matching hash (also sha384/sha512)
'strict-dynamic'Trust propagates to scripts loaded by already-trusted scripts. Host allowlist and 'unsafe-inline' are ignored
'unsafe-hashes'Allows hashed inline event handlers
'report-sample'Includes a code sample in violation reports

Rules to remember

  • If a nonce or hash is present in a directive, 'unsafe-inline' is ignored by modern browsers (intentional backward-compat trick).
  • Nonces must be unique per response, unguessable (≥128 bits random), never static.
  • Host allowlists are weak: JSONP endpoints and old Angular/CDN gadgets on allowed hosts can bypass them. Prefer nonce + 'strict-dynamic'.
  • default-src is only a fallback. A specific directive replaces it (no merging).

4. Example policies

Content-Security-Policy:
  script-src 'nonce-{RANDOM}' 'strict-dynamic' https: 'unsafe-inline';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'self';
  form-action 'self';
  report-to csp-endpoint

(https: and 'unsafe-inline' are only fallbacks for old browsers. Modern ones ignore them when nonce + strict-dynamic are present.)

Simple static site

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

Report-Only rollout

Content-Security-Policy-Report-Only: default-src 'self'; report-to csp-endpoint
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"

Nonce usage in HTML

<script nonce="rAnd0m123">/* allowed */</script>
<script>/* blocked without nonce */</script>

Meta tag (limited)

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

Meta cannot use: frame-ancestors, report-uri/report-to, sandbox. No Report-Only via meta.


5. Rollout workflow

  1. Start with Content-Security-Policy-Report-Only.
  2. Collect reports, find inline scripts/styles and third-party hosts.
  3. Move inline JS to files or add nonces. Remove inline event handlers (onclick=).
  4. Tighten: object-src 'none', base-uri, frame-ancestors, form-action.
  5. Switch to enforcing Content-Security-Policy.
  6. Keep reporting on, monitor, iterate.

Common pitfalls

  • 'unsafe-inline' in script-src without nonce/hash: practically no XSS protection.
  • Allowlisting whole CDNs (https://cdnjs.cloudflare.com, *.googleapis.com): bypass gadgets possible.
  • Forgetting base-uri: <base> injection can redirect relative script URLs.
  • Forgetting object-src 'none'.
  • Assuming default-src covers frame-ancestors, base-uri, form-action (it doesn’t).
  • Static nonces, or caching a page that contains a nonce.
  • Third-party scripts and browser extensions can cause noisy reports.

6. Session cookies

A session cookie (no Expires/Max-Age) lives until the browser session ends (the browser may restore it with session restore). Typically carries a session ID that maps to server-side state. It is the prize in session hijacking.

Note: “session cookie” (lifetime) is different from “authentication/session-ID cookie” (purpose). A persistent cookie can also hold a session ID.

Set-Cookie: __Host-sid=<random>; Path=/; Secure; HttpOnly; SameSite=Lax
AttributeEffectSecurity relevance
SecureSent only over HTTPSPrevents sniffing over HTTP
HttpOnlyNot readable via document.cookieBlocks cookie theft via XSS (does not stop XSS acting as the user)
SameSite=StrictNever sent on cross-site requestsStrongest CSRF mitigation, can break inbound links
SameSite=LaxSent on top-level GET navigations onlyGood default for session cookies
SameSite=NoneSent cross-site (requires Secure)Needed for embedded/3rd-party use
Domain=Scopes to domain and subdomainsOmit it to restrict to the exact host
Path=Scopes to pathNot a security boundary
Expires / Max-AgeMakes cookie persistentOmit both for a session cookie
Partitioned (CHIPS)Cookie keyed to top-level siteThird-party cookie partitioning
PrefixRequirements
__Secure-Must have Secure, set from a secure origin
__Host-Secure + Path=/ + no Domain (strongest: bound to exact host, resists subdomain overwrite)

Session management best practices

  • High-entropy random session IDs (≥64 bits entropy per OWASP guidance, CSPRNG).
  • Regenerate the session ID on login and privilege change (prevents session fixation).
  • Invalidate server-side on logout. Set idle and absolute timeouts.
  • Never put session IDs in URLs.
  • Use CSRF protection (SameSite + tokens for state-changing requests).
  • Browser default for missing SameSite: Chrome treats it as Lax. Firefox’s behavior has differed (verify for your version). Set it explicitly.
  • Cookie size limit is about 4096 bytes per cookie (browser-dependent).

How CSP and cookies relate

  • CSP reduces the chance injected script runs, so it protects the cookie indirectly.
  • HttpOnly protects the cookie directly from script read access.
  • CSP connect-src/form-action/img-src also limit exfiltration paths if XSS happens.
  • They complement each other. Neither replaces the other.

7. How to check in Firefox

A) Check the CSP of a page

Network tab (most reliable)

  1. F12 (or Ctrl+Shift+E) → Network
  2. Reload the page (F5)
  3. Click the main document request (first row, type html)
  4. Headers tab → Response Headers → look for Content-Security-Policy / Content-Security-Policy-Report-Only
  5. Check the filter box: content-security-policy also works in header search

Console tab (violations)

  • F12 → Console
  • Blocked loads appear as warnings/errors naming the violated directive, e.g. “Content-Security-Policy: The page’s settings blocked the loading of a resource … (script-src-elem)”.
  • Enable Warnings/Errors filters if you don’t see them.

Meta-tag CSP

  • F12 → Inspector → search (Ctrl+F) for Content-Security-Policy in the DOM.

Command line (cross-check)

curl -sI https://example.com | grep -i content-security-policy

B) Check cookies and their flags

Storage Inspector

  1. F12 → Storage (enable it under DevTools settings if the tab is missing)
  2. Cookies → select the site
  3. Columns: Name, Value, Domain, Path, Expires/Max-Age, Size, HttpOnly, Secure, SameSite, (Partition key if applicable)
  4. Right-click the column header to show or hide columns
  5. Session in the Expires column = session cookie
  6. Edit, add, or delete cookies directly (useful for testing)

Network tab (see how cookies are actually set/sent)

  1. Network → click a request
  2. Cookies tab: separate request cookies and response cookies, with parsed attributes
  3. Headers tab: raw Set-Cookie (response) and Cookie (request)

Quick JS check (Console)

document.cookie

Cookies flagged HttpOnly will not appear. That is a quick way to confirm HttpOnly works.

Browser settings UI

  • Padlock icon in the address bar → Connection secure → Clear cookies and site data (shows cookies per site)
  • about:preferences#privacy → Cookies and Site Data → Manage Data

C) Quick audit checklist

  • CSP header present on HTML responses?
  • No 'unsafe-inline' / 'unsafe-eval' in script-src (or neutralized by nonce + strict-dynamic)?
  • object-src 'none', base-uri, frame-ancestors, form-action set?
  • No overly broad hosts (*, https:, data: in script-src)?
  • Session cookie has Secure, HttpOnly, explicit SameSite?
  • Preferably __Host- prefix, Path=/, no Domain?
  • Cookie shows as Session (no expiry) if intended?
  • Session ID changes after login?
  • Console free of unexpected CSP violations?

8. Tools

9. Quick reference: reports

Violation report (legacy report-uri, application/csp-report) contains: document-uri, violated-directive, effective-directive, blocked-uri, original-policy, disposition (enforce/report), source-file, line-number, script-sample.