TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Security Headers: HSTS, nosniff and frame-ancestors

Security Headers: HSTS, nosniff and frame-ancestors

Some of the browser's protections are off by default for compatibility, and a site turns them on with response headers. They cost one line of configuration each, they close whole attack classes (SSL stripping, clickjacking, MIME confusion, referrer leaks), and missing ones are among the most common findings in any web assessment, filed under OWASP 2025 A02 Security Misconfiguration. This lesson explains what each header defends against, builds a small checker, and runs it against a toy app before and after hardening.

The headers that matter

Header Recommended value Defends against
Strict-Transport-Security (HSTS, RFC 6797) max-age=31536000; includeSubDomains (add preload once you are sure) SSL stripping: after one visit over HTTPS, the browser refuses plain HTTP to the host for max-age seconds, and certificate errors can't be clicked through
Content-Security-Policy a strict policy (CSP lesson), including frame-ancestors 'none' or 'self' XSS; frame-ancestors also stops clickjacking (your page loaded invisibly in an attacker's frame, the victim's clicks landing on your buttons)
X-Frame-Options DENY or SAMEORIGIN clickjacking, for old browsers; superseded by frame-ancestors
X-Content-Type-Options nosniff MIME sniffing: a user upload served as text/plain that the browser "guesses" is HTML or script
Referrer-Policy strict-origin-when-cross-origin (browser default today) or no-referrer tokens and private paths leaking to other sites in Referer
Permissions-Policy camera=(), microphone=(), geolocation=() embedded or injected content using powerful features
Cross-Origin-Opener-Policy same-origin cross-window attacks through window.opener, XS-Leaks; needed for cross-origin isolation
Cache-Control no-store on pages with personal data shared caches or the back button showing someone else's data

Headers that are gone or harmful: X-XSS-Protection (the old XSS auditor was removed from browsers and could itself be abused; send 0 or nothing), Public-Key-Pins (HPKP, removed: it locked sites out of their own domains).

A checker and two versions of an app

The session writes a small header checker in Python, starts a toy app on 127.0.0.1 without security headers, checks it, restarts it with a hardening middleware, and checks again. Because this app is plain HTTP on loopback, HSTS is only sent here for the demonstration: browsers ignore HSTS received over HTTP, by design (an attacker on the network could otherwise inject it).

bash · try it yourself
cat > app.py <<'PY'
import sys
from wsgiref.simple_server import make_server, WSGIRequestHandler

class Quiet(WSGIRequestHandler):
    def log_message(self, *args):
        pass

def app(environ, start_response):
    start_response("200 OK", [("Content-Type", "text/html; charset=utf-8")])
    return [b"<h1>account page</h1>\n"]

SECURITY_HEADERS = [
    ("Strict-Transport-Security", "max-age=31536000; includeSubDomains"),
    ("Content-Security-Policy", "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"),
    ("X-Content-Type-Options", "nosniff"),
    ("Referrer-Policy", "strict-origin-when-cross-origin"),
    ("Permissions-Policy", "camera=(), microphone=(), geolocation=()"),
    ("Cross-Origin-Opener-Policy", "same-origin"),
    ("Cache-Control", "no-store"),
]

def harden(inner):
    def wrapped(environ, start_response):
        def sr(status, headers, exc_info=None):
            return start_response(status, headers + SECURITY_HEADERS, exc_info)
        return inner(environ, sr)
    return wrapped

wsgi = harden(app) if sys.argv[1] == "hardened" else app
make_server("127.0.0.1", 8000, wsgi, handler_class=Quiet).serve_forever()
PY
cat > check_headers.py <<'PY'
import sys, urllib.request

RULES = {   # header -> (test on the lower-cased value, advice)
    "strict-transport-security": (lambda v: "max-age=" in v and int(v.split("max-age=")[1].split(";")[0]) >= 15552000,
                                  "max-age of at least 180 days"),
    "content-security-policy": (lambda v: "unsafe-inline" not in v and ("frame-ancestors" in v),
                                "no 'unsafe-inline', and frame-ancestors set"),
    "x-content-type-options": (lambda v: v == "nosniff", "nosniff"),
    "referrer-policy": (lambda v: v in {"no-referrer", "strict-origin", "strict-origin-when-cross-origin", "same-origin"},
                        "a strict policy"),
    "permissions-policy": (lambda v: "camera=()" in v, "disable unused features"),
}
resp = urllib.request.urlopen(sys.argv[1])
headers = {k.lower(): v.strip() for k, v in resp.headers.items()}
score = 0
for name, (ok, advice) in RULES.items():
    value = headers.get(name)
    if value is None:
        print(f"  MISSING  {name}: want {advice}")
    elif ok(value.lower()):
        score += 1
        print(f"  ok       {name}")
    else:
        print(f"  WEAK     {name}: {value!r}; want {advice}")
if "server" in headers:
    print(f"  info     server banner: {headers['server']}")
print(f"  score {score}/{len(RULES)}")
PY
for mode in plain hardened; do
  python3 app.py $mode &
  for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
  echo "== $mode"
  python3 check_headers.py http://127.0.0.1:8000/
  kill %1; wait 2>/dev/null
done
== plain
  MISSING  strict-transport-security: want max-age of at least 180 days
  MISSING  content-security-policy: want no 'unsafe-inline', and frame-ancestors set
  MISSING  x-content-type-options: want nosniff
  MISSING  referrer-policy: want a strict policy
  MISSING  permissions-policy: want disable unused features
  info     server banner: WSGIServer/0.2 CPython/3.12.3
  score 0/5
== hardened
  ok       strict-transport-security
  ok       content-security-policy
  ok       x-content-type-options
  ok       referrer-policy
  ok       permissions-policy
  info     server banner: WSGIServer/0.2 CPython/3.12.3
  score 5/5

The plain app fails every check, which is the normal state of a framework's "hello world". The hardened version adds the headers in one middleware, so every response gets them, including error pages and redirects, which are often forgotten when headers are added per route. The Server banner remains: wsgiref always sends one; production servers such as nginx can reduce it (server_tokens off).

Clickjacking in one picture

evil.example (what the user sees) Win a prize! shop.lab.test, invisible iframe Delete account same spot with frame-ancestors: blocked

The victim is logged in to the shop, so the framed page is fully functional; opacity 0 hides it. frame-ancestors 'none' (or X-Frame-Options: DENY) makes the browser refuse to render the shop inside any frame, and the click lands on nothing.

How missing headers are detected

  • Automated checks: the script above, ZAP's passive scanner, Burp, Mozilla's HTTP Observatory, curl -sI https://… | grep -i … on your own sites. Check several kinds of responses: HTML pages, API responses, errors, redirects, static files.
  • HSTS details: max-age too short, missing includeSubDomains while subdomains serve cookies, HTTP-to-HTTPS redirect missing on the first request.
  • Uploads served from the main origin without nosniff and a fixed Content-Type (and ideally Content-Disposition: attachment).

How they are deployed

  • Add them once, centrally: a middleware, the reverse proxy (add_header … always; in nginx, where always includes error responses), or the CDN.
  • Turn HSTS on in steps (max-age=300, then a week, then a year) so a mistake is reversible, and only submit to the HSTS preload list when every subdomain is HTTPS.
  • Test that nothing legitimate needs framing before setting frame-ancestors 'none'; use 'self' or a list of partner origins if it does.

Pitfalls

  • HSTS on HTTP responses is ignored; it must come over HTTPS.
  • Headers set by the app but stripped by a proxy or CDN (or duplicated with different values): check what the client actually receives.
  • Header checkers as a score to maximise. The headers reduce risk; they don't fix XSS or broken access control.

Practice

1. Why does HSTS not protect a user's very first visit, and what does?

Before the first HTTPS response the browser has no HSTS entry, so a first request over HTTP can be intercepted. The HSTS preload list, built into browsers, covers listed domains even on the first visit.

2. A site allows uploads served at /uploads/ with Content-Type: text/plain. Which header and which design choice reduce the risk?

X-Content-Type-Options: nosniff (no guessing HTML or script), plus serving uploads from a separate origin (e.g. uploads.lab-usercontent.test) with Content-Disposition: attachment.

Test yourself

Which header stops clickjacking in modern browsers?

  1. X-Content-Type-Options
  2. CSP frame-ancestors
  3. Referrer-Policy
  4. Strict-Transport-Security

What does HSTS prevent?

  1. XSS
  2. SSL stripping: downgrading the user to plain HTTP
  3. SQL injection
  4. CSRF

Why did the session add headers in a middleware rather than per route?

  1. It is faster
  2. So every response, including errors and redirects, gets them
  3. Browsers require it
  4. It hides the Server header

What should a site send for X-XSS-Protection today?

  1. 1; mode=block
  2. 0 or nothing: the XSS auditor is gone from browsers
  3. nosniff
  4. DENY