Skip to content

Interview PrepBrowser rules · Core

TLS and Security Headers ​

17. What is HTTPS, and how does TLS protect data in transit? ​

The short answer

HTTPS is plain HTTP sent inside a TLS connection. TLS gives three protections. Confidentiality: everything is encrypted, so someone on the café Wi-Fi sees only scrambled bytes. Integrity: every record carries a check value, so any change in transit is detected. Authentication: the server proves it really is shop.example with a certificate signed by a certificate authority the browser trusts. The handshake uses public-key cryptography to agree on fresh shared keys, then fast symmetric encryption carries the data.

Two kinds of encryption, and why TLS uses both. Symmetric encryption, such as AES, uses one shared key to lock and unlock. It is very fast, but both sides need the same key first. Asymmetric, or public-key, cryptography uses a key pair: anyone can use the public key, only the owner holds the private key. It is slow, but it lets two strangers agree on a secret over an open network. TLS uses the slow kind once, in the handshake, to agree on a key, then the fast kind for all the data.

browsershop.example① ClientHello · ciphers it supports · its key share② ServerHello · key share · certificate · signature③ certificate signed by a trusted CA?name matches shop.example? not expired?④ both sides derive the same session keys⑤ encrypted HTTP: GET /account, cookies, JSON
One round trip, then everything is private. ① and ② exchange key shares, a Diffie-Hellman exchange, so both sides can compute a secret nobody watching can. ③ The certificate proves who the server is. ④ Session keys are derived. ⑤ All HTTP traffic, headers and cookies included, is encrypted with them.

What the certificate proves, step by step:

  1. The server sends its certificate: its name and public key, signed by an intermediate certificate authority.
  2. The browser follows the chain up to a root authority already stored in the operating system or browser.
  3. It checks the name on the certificate matches the address bar, and that the dates are valid.
  4. The server signs part of the handshake with its private key. Only the real owner of the certificate can do that, so a copied certificate is useless to an impostor.

Forward secrecy. The key shares are fresh for every connection and thrown away afterwards. If the server's private key leaks next year, recorded traffic from today still cannot be decrypted. TLS 1.3 makes this mandatory.

What TLS does not hide: the server's IP address, the amount of data, timing, and usually the hostname in the handshake's Server Name Indication field. Once the data reaches the server, TLS is gone: protecting it at rest is a separate job.

18. What is the difference between SSL and TLS? ​

The short answer

SSL was the original protocol from Netscape in the 1990s. TLS is its renamed and redesigned successor, standardised by the IETF. Every SSL version, 2.0 and 3.0, is broken and disabled everywhere. TLS 1.0 and 1.1 were deprecated in 2021. Today you should allow only TLS 1.2 and TLS 1.3. People still say "SSL certificate" out of habit; the same certificate is used by TLS.

VersionYearStatus
SSL 2.0, 3.01995, 1996Broken, never use
TLS 1.0, 1.11999, 2006Deprecated in 2021
TLS 1.22008Fine with modern ciphers
TLS 1.32018Preferred

What TLS 1.3 improved over 1.2:

  1. Faster. The handshake takes one round trip instead of two.
  2. Simpler and safer. Old weak options, such as RSA key exchange, CBC-mode ciphers and SHA-1, were removed. There is less to misconfigure.
  3. Forward secrecy always, because every key exchange uses fresh keys.
  4. More of the handshake is encrypted, including the server's certificate.

Where TLS ends in a typical deployment is the load balancer or reverse proxy. It decrypts, then forwards plain HTTP inside the private network, or re-encrypts if your security model requires it (question 42).

19. What security headers should an Express application set? ​

The short answer

The core set: Strict-Transport-Security to force HTTPS; Content-Security-Policy to limit where scripts and other resources may load from; X-Content-Type-Options: nosniff so browsers do not guess file types; frame-ancestors in CSP, or X-Frame-Options, to stop clickjacking; Referrer-Policy to limit what URLs leak to other sites; and Permissions-Policy to switch off browser features you do not use. Also remove X-Powered-By, and set Cache-Control: no-store on private responses. In Express, Helmet sets most of these in one line.

HeaderStopsTypical value
Strict-Transport-SecurityDowngrade to HTTPmax-age=31536000; includeSubDomains
Content-Security-PolicyXSS, data theftdefault-src 'self' and more
X-Content-Type-OptionsMIME sniffingnosniff
X-Frame-OptionsClickjackingDENY or SAMEORIGIN
Referrer-PolicyURL leaksstrict-origin-when-cross-origin
Permissions-PolicyFeature abusecamera=(), geolocation=()
Cache-ControlPrivate data in shared cachesno-store on account pages

Where to set them. Either in Express with Helmet, or at the reverse proxy or CDN in front. Setting them at the edge covers static files too. Setting them in the app keeps them in version control beside the code. Many teams do both, but then must avoid two different values for the same header.

Which headers matter for a JSON API. A pure API returning JSON needs fewer: HSTS, nosniff, a strict CSP of default-src 'none', and Cache-Control. CSP and framing rules matter most on responses that render HTML.

20. What is Helmet, and why is it used? ​

The short answer

Helmet is a small Express middleware that sets a sensible group of security response headers with one call, app.use(helmet()). It exists because remembering and correctly writing about a dozen headers by hand is easy to get wrong. It does not fix code bugs like SQL injection or broken access control; it only tells the browser to apply extra protections. Its defaults are a good start, and you tune the Content Security Policy for your own app.

ts
import express from 'express'
import helmet from 'helmet'

const app = express()

app.use(helmet({                                                              // (1)
  contentSecurityPolicy: {
    directives: {
      'script-src': ["'self'", 'https://js.stripe.com'],                      // (2)
      'img-src': ["'self'", 'data:', 'https://images.shop.example'],
      'connect-src': ["'self'", 'https://api.stripe.com'],
    },
  },
}))
  1. One middleware, mounted before your routes, so every response gets the headers.
  2. Extend the default CSP with the outside sources your shop really uses: Stripe's payment script, your image CDN and Stripe's API. Helmet merges these with its other default directives.

Why it is used in practice: it is a cheap, reviewed baseline. Security scanners and penetration testers check for these headers first, and Helmet answers most of those findings in one line.

21. Which headers does Helmet configure? ​

The short answer

Helmet 8 sets, by default: Content-Security-Policy, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy, Origin-Agent-Cluster, Referrer-Policy: no-referrer, Strict-Transport-Security, X-Content-Type-Options: nosniff, X-DNS-Prefetch-Control: off, X-Download-Options, X-Frame-Options: SAMEORIGIN, X-Permitted-Cross-Domain-Policies: none and X-XSS-Protection: 0. It also removes X-Powered-By. Each one can be configured or turned off by name.

HeaderWhat it does
Content-Security-PolicyAllow-list of where resources may load from (question 22)
Cross-Origin-Opener-Policy: same-originPages opened from other sites cannot reach your window object
Cross-Origin-Resource-Policy: same-originOther sites cannot embed your responses
Origin-Agent-ClusterAsks the browser to isolate your origin in its own process
Referrer-Policy: no-referrerSends no referrer at all (question 26)
Strict-Transport-SecurityHTTPS only for a year (question 24)
X-Content-Type-Options: nosniffNo MIME guessing (question 25)
X-DNS-Prefetch-Control: offStops the browser looking up linked domains early
X-Download-Options: noopenOld Internet Explorer: do not open downloads in your site's context
X-Frame-Options: SAMEORIGINOnly your own pages may frame you (question 25)
X-Permitted-Cross-Domain-Policies: noneBlocks old Flash and PDF cross-domain policy files
X-XSS-Protection: 0Turns off the old browser XSS filter, which caused bugs

Why X-XSS-Protection: 0 and not 1? The old built-in filter in browsers could be tricked into removing good scripts from a page, which itself created leaks. Modern browsers removed it. CSP is the real protection now, so Helmet disables the old filter.

Turning one off:

ts
app.use(helmet({ crossOriginResourcePolicy: { policy: 'cross-origin' } }))   // a public image CDN

22. What is Content Security Policy (CSP)? ​

The short answer

CSP is a response header that gives the browser an allow-list of where scripts, styles, images, frames and connections may come from. If an attacker manages to inject <script> into your page, the browser refuses to run it because its source is not on the list. It is the strongest second line of defence against XSS. A strict modern policy allows scripts only with a per-request nonce or a hash, blocks inline event handlers and eval, and reports violations so you can find breakage.

<script nonce="r4nd0m">your own script<script>steal()</script>injected, no noncesrc="evil.example/x.js"source not allowedbrowser checks CSPscript-src 'self''nonce-r4nd0m'runsblockedviolation reported
The browser is the bouncer. Your HTML injection bug still exists, but the injected script never runs: it has no nonce and its source is not on the list. The violation is reported, which tells you the bug exists.

A strict policy for a server-rendered page:

http
Content-Security-Policy:
  default-src 'self';
  script-src 'nonce-4f9a2b' 'strict-dynamic';
  object-src 'none';
  base-uri 'none';
  frame-ancestors 'none';
  report-to csp-endpoint

Reading it line by line:

  1. default-src 'self': anything not listed below may load only from your own origin.
  2. script-src 'nonce-…' 'strict-dynamic': only scripts carrying this request's nonce run. Scripts those trusted scripts load are also trusted. Inline onclick= handlers are blocked.
  3. object-src 'none': no plug-ins such as Flash.
  4. base-uri 'none': an injected <base> tag cannot redirect your relative script URLs.
  5. frame-ancestors 'none': no site may put your page in a frame (question 25).
  6. report-to: send violation reports to an endpoint so you see attacks and breakage.

Rolling it out without breaking the site. Send it first as Content-Security-Policy-Report-Only. The browser reports what it would have blocked but blocks nothing. Fix the reports, then switch to the enforcing header.

What weakens a CSP: 'unsafe-inline' in script-src, which allows every inline script including injected ones; 'unsafe-eval'; and allowing a whole CDN host that also serves other people's files, since an attacker can load their own script from there.

23. What is the difference between a CSP nonce and a CSP hash? ​

The short answer

Both let specific inline or trusted scripts run while blocking injected ones. A nonce is a random value the server generates fresh for every response, puts in the CSP header, and adds to each of its own <script nonce="…"> tags. An attacker cannot guess it. A hash is the SHA-256 of a script's exact contents, listed in the header. The browser runs an inline script only if its hash matches. Use nonces for server-rendered pages, and hashes for static pages that cannot change per request.

NonceHash
ValueRandom per responseFingerprint of the script text
Needs a server per requestYesNo
Works on static hostingNoYes
Script can change freelyYesNo, hash must be updated
DangerReusing or caching one nonceNone special

A nonce in Express:

ts
import { randomBytes } from 'node:crypto'

app.use((req, res, next) => {
  res.locals.cspNonce = randomBytes(16).toString('base64')                    // (1)
  next()
})

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      'script-src': ["'self'", (req, res) => `'nonce-${(res as Response).locals.cspNonce}'`],   // (2)
    },
  },
}))

app.get('/checkout', (req, res) => {
  res.send(`<script nonce="${res.locals.cspNonce}">startCheckout()</script>`)   // (3)
})
  1. A fresh random value per request: 16 random bytes, about 128 bits, impossible to guess.
  2. The header names this request's nonce. Helmet accepts a function per directive value.
  3. Your own script tags carry the same nonce. An injected tag does not know it, so it is blocked.

The rule that keeps nonces safe: never cache an HTML page containing a nonce in a shared cache. If the same nonce is served to everyone, it stops being secret.

A hash looks like this: script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8='. Change one space in the script and the hash no longer matches.

24. What is HSTS, and how does it improve transport security? ​

The short answer

HSTS, HTTP Strict Transport Security, is the header Strict-Transport-Security: max-age=31536000; includeSubDomains. It tells the browser: for the next year, only ever talk to this site over HTTPS. After the first visit, the browser rewrites any http:// link or typed address to https:// itself, before sending anything. This stops an attacker on the network from catching that first plain-HTTP request and stripping the user down to an unencrypted connection. Adding the site to the browsers' preload list protects even the very first visit.

The attack HSTS stops, called SSL stripping:

  1. You type shop.example in a café. The browser tries http://shop.example first.
  2. An attacker on the same Wi-Fi intercepts that plain request.
  3. The attacker talks HTTPS to the real shop, but keeps talking plain HTTP to you, reading everything, including your password.

With HSTS remembered from an earlier visit, step 1 never happens: the browser goes straight to HTTPS. The browser also refuses to let you click through a certificate warning on that site.

The parts of the header:

PartMeaning
max-age=31536000Remember for one year, in seconds
includeSubDomainsApply to every subdomain too
preloadConsent to being on the built-in browser list

Roll out carefully. Start with a short max-age, such as 300 seconds. Check every subdomain works over HTTPS. Then raise it. Once preloaded, removing a domain from the list takes months, so an HTTP-only subdomain such as an old intranet tool would be unreachable.

HSTS is only honoured over HTTPS. The header sent on a plain-HTTP response is ignored, because an attacker could have added it. Redirect HTTP to HTTPS, then send HSTS on the HTTPS response.

25. What do X-Frame-Options and X-Content-Type-Options do? ​

The short answer

X-Frame-Options says whether other sites may show your page inside a frame. DENY forbids all framing, and SAMEORIGIN allows only your own site. It stops clickjacking, where an attacker hides your real page under a fake button (the clickjacking question). The modern replacement is CSP's frame-ancestors. X-Content-Type-Options: nosniff tells the browser to trust the Content-Type header and not guess. This stops an uploaded file labelled as an image from being run as a script or HTML.

Why MIME sniffing was dangerous. Old browsers looked at the first bytes of a file to guess its type. Suppose a user uploads avatar.png that really contains HTML and JavaScript. Without nosniff, a browser might decide it is HTML and run the script on your origin. That is stored XSS through an image upload. With nosniff, a file served as image/png is only ever treated as an image. A script must arrive with a JavaScript type, or it is refused.

WantOld headerModern header
Never framedX-Frame-Options: DENYframe-ancestors 'none'
Only framed by youX-Frame-Options: SAMEORIGINframe-ancestors 'self'
Framed by one partnerNot possibleframe-ancestors https://partner.example

Send both framing headers. frame-ancestors wins in modern browsers. X-Frame-Options covers very old ones. Helmet sends both by default.

26. What are Referrer-Policy and Permissions-Policy? ​

The short answer

Referrer-Policy controls how much of the current URL the browser sends in the Referer header when the user follows a link or the page loads a resource. A URL such as /reset-password?token=abc leaking to an analytics site is a real bug. The common safe value is strict-origin-when-cross-origin: the full URL inside your own site, only the origin to other sites, and nothing when going from HTTPS to HTTP. Permissions-Policy switches off powerful browser features, such as the camera, microphone and location, for your page and any frames inside it.

What each Referrer-Policy sends when a user on https://shop.example/orders/42?coupon=X clicks a link to another site:

PolicyOther site receives
no-referrerNothing
strict-origin-when-cross-originhttps://shop.example/
unsafe-urlThe full URL, coupon included

Browsers default to strict-origin-when-cross-origin today. Helmet sends the stricter no-referrer. Some partners and analytics tools need at least the origin, so pick deliberately.

Permissions-Policy in practice:

http
Permissions-Policy: camera=(), microphone=(), geolocation=(self), payment=(self "https://js.stripe.com")
  1. camera=(): empty list, so no page or frame may use the camera.
  2. geolocation=(self): only your own pages may ask for location, not embedded frames.
  3. payment=(…): your page and Stripe's frame may use the browser's payment request feature.

Why bother. If an advertising frame or an injected script tries to turn on the microphone, the browser refuses before even asking the user. It limits what any compromised third-party code on your page can do.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Web & API Security
Attacks
Browser rules
Abuse
Secrets
Architecture
Other topics
Nothing picked yet