CSP & Session Cookies Cheat Sheet
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
| Header | Purpose |
|---|---|
Content-Security-Policy | Enforce: violations are blocked and reported |
Content-Security-Policy-Report-Only | Monitor: 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)
| Directive | Controls |
|---|---|
default-src | Fallback for most other fetch directives |
script-src | JavaScript (also script-src-elem, script-src-attr) |
style-src | CSS (also style-src-elem, style-src-attr) |
img-src | Images and favicons |
font-src | Fonts |
connect-src | fetch/XHR, WebSocket, EventSource, sendBeacon |
media-src | <audio>, <video> |
object-src | <object>, <embed> (set to 'none') |
frame-src | Sources for <iframe> / <frame> content you embed |
child-src | Frames and workers (legacy-ish) |
worker-src | Workers and service workers |
manifest-src | Web app manifest |
Document / navigation directives (no fallback to default-src)
| Directive | Controls |
|---|---|
base-uri | Allowed <base> URLs. Set 'self' or 'none' |
form-action | Where forms may submit |
frame-ancestors | Who may embed your page (replaces X-Frame-Options) |
sandbox | Applies iframe-sandbox-like restrictions to the page |
Other
| Directive | Purpose |
|---|---|
upgrade-insecure-requests | Rewrites http:// subresource URLs to https:// |
report-to | Reporting API group name (modern) |
report-uri | Legacy reporting endpoint (deprecated but still widely used) |
require-trusted-types-for 'script' / trusted-types | DOM XSS sink protection (Trusted Types) |
3. Source values
| Value | Meaning |
|---|---|
'none' | Nothing allowed |
'self' | Same origin (scheme + host + port) |
https: | Any HTTPS URL (scheme source) |
https://cdn.example.com | Specific host |
*.example.com | Wildcard 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-srcis only a fallback. A specific directive replaces it (no merging).
4. Example policies
Strict, modern (recommended pattern)
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
- Start with
Content-Security-Policy-Report-Only. - Collect reports, find inline scripts/styles and third-party hosts.
- Move inline JS to files or add nonces. Remove inline event handlers (
onclick=). - Tighten:
object-src 'none',base-uri,frame-ancestors,form-action. - Switch to enforcing
Content-Security-Policy. - Keep reporting on, monitor, iterate.
Common pitfalls
'unsafe-inline'inscript-srcwithout 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-srccoversframe-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 attributes
Set-Cookie: __Host-sid=<random>; Path=/; Secure; HttpOnly; SameSite=Lax
| Attribute | Effect | Security relevance |
|---|---|---|
Secure | Sent only over HTTPS | Prevents sniffing over HTTP |
HttpOnly | Not readable via document.cookie | Blocks cookie theft via XSS (does not stop XSS acting as the user) |
SameSite=Strict | Never sent on cross-site requests | Strongest CSRF mitigation, can break inbound links |
SameSite=Lax | Sent on top-level GET navigations only | Good default for session cookies |
SameSite=None | Sent cross-site (requires Secure) | Needed for embedded/3rd-party use |
Domain= | Scopes to domain and subdomains | Omit it to restrict to the exact host |
Path= | Scopes to path | Not a security boundary |
Expires / Max-Age | Makes cookie persistent | Omit both for a session cookie |
Partitioned (CHIPS) | Cookie keyed to top-level site | Third-party cookie partitioning |
Cookie prefixes
| Prefix | Requirements |
|---|---|
__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 asLax. 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.
HttpOnlyprotects the cookie directly from script read access.- CSP
connect-src/form-action/img-srcalso 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)
F12(orCtrl+Shift+E) → Network- Reload the page (
F5) - Click the main document request (first row, type
html) - Headers tab → Response Headers → look for
Content-Security-Policy/Content-Security-Policy-Report-Only - Check the filter box:
content-security-policyalso 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) forContent-Security-Policyin the DOM.
Command line (cross-check)
curl -sI https://example.com | grep -i content-security-policy
B) Check cookies and their flags
Storage Inspector
F12→ Storage (enable it under DevTools settings if the tab is missing)- Cookies → select the site
- Columns: Name, Value, Domain, Path, Expires/Max-Age, Size, HttpOnly, Secure, SameSite, (Partition key if applicable)
- Right-click the column header to show or hide columns
Sessionin the Expires column = session cookie- Edit, add, or delete cookies directly (useful for testing)
Network tab (see how cookies are actually set/sent)
- Network → click a request
- Cookies tab: separate request cookies and response cookies, with parsed attributes
- Headers tab: raw
Set-Cookie(response) andCookie(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'inscript-src(or neutralized by nonce + strict-dynamic)? -
object-src 'none',base-uri,frame-ancestors,form-actionset? - No overly broad hosts (
*,https:,data:inscript-src)? - Session cookie has
Secure,HttpOnly, explicitSameSite? - Preferably
__Host-prefix,Path=/, noDomain? - Cookie shows as
Session(no expiry) if intended? - Session ID changes after login?
- Console free of unexpected CSP violations?
8. Tools
- CSP Evaluator (Google): spots weak policies and known bypasses
- Mozilla Observatory: header and cookie scoring
curl -I, Burp Suite / ZAP: inspect and modify headers- report-uri.com or a self-hosted endpoint: collect violation reports
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.