TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Cookies and Their Attributes: Secure, HttpOnly, SameSite

Cookies and Their Attributes: Secure, HttpOnly, SameSite

HTTP has no memory. The cookie is the patch that gives it one: the server sends Set-Cookie, the browser stores the value and sends it back in a Cookie header on later requests. Almost every login session on the web is a cookie, which makes cookies the most valuable thing in the browser after the password itself. Whoever has the session cookie is the user until it expires. The survey lesson Sessions and Tokens introduced the idea; this lesson goes through the attributes that decide where a cookie is sent, who can read it and how long it lives, because each attribute closes one specific attack.

Definitions (RFC 6265 and its successor draft, 6265bis)

Attribute Effect Attack it limits
Secure sent only over HTTPS (and to localhost, which browsers treat as secure) theft by anyone reading cleartext HTTP on the network
HttpOnly invisible to JavaScript (document.cookie) theft by injected script (XSS); the script can still use the session by sending requests, but can't carry the cookie away
SameSite=Strict sent only on same-site requests CSRF, cross-site leaks
SameSite=Lax same-site, plus cross-site top-level navigations with a safe method (clicking a link) CSRF through forms, images, fetch
SameSite=None sent on every request; requires Secure nothing; needed for real cross-site use such as embedded widgets
Domain=lab.test sent to the domain and all its subdomains; without Domain the cookie is host-only (widens exposure: any subdomain receives it and can overwrite it)
Path=/app sent only for matching paths nothing security-relevant: paths are not a security boundary inside one origin
Max-Age / Expires persistent cookie; without them it is a session cookie, deleted when the browser session ends limits the window for a stolen cookie
__Host- prefix browser accepts it only with Secure, Path=/ and no Domain a sibling subdomain planting or overwriting the cookie
__Secure- prefix browser accepts it only with Secure cookie set over plain HTTP

Chromium-based browsers treat a cookie without SameSite as Lax; other browsers have differed, so always set the attribute explicitly. SameSite and the cookie prefixes come from 6265bis (draft-ietf-httpbis-rfc6265bis), which browsers already implement; the IESG approved it in 2025, but as of late 2026 it is still an Internet-Draft waiting in the RFC Editor queue, not a numbered RFC.

Watching a browser-like client store cookies

The toy app (on 127.0.0.1 in your sandbox) sets three cookies at /login and echoes back whatever Cookie header it receives. curl -c saves cookies in the Netscape jar format, which marks HttpOnly cookies with a #HttpOnly_ prefix; the awk prints the columns that matter and skips the expiry time, which changes with the clock.

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

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

def app(environ, start_response):
    if environ["PATH_INFO"] == "/login":
        start_response("200 OK", [("Content-Type", "text/plain"),
            ("Set-Cookie", "sid=lab-7Qx2; Path=/; HttpOnly; Secure; SameSite=Lax"),
            ("Set-Cookie", "theme=dark; Path=/; Max-Age=3600"),
            ("Set-Cookie", "__Host-csrf=c9f1; Path=/; Secure; SameSite=Strict")])
        return [b"logged in\n"]
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [("cookie header: " + environ.get("HTTP_COOKIE", "(none)") + "\n").encode()]

make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
python3 app.py &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
curl -s -D - -o /dev/null -c jar.txt http://127.0.0.1:8000/login | grep -i '^set-cookie'
echo "== the jar: host, secure-only, name, readable by script?"
awk -F'\t' '/^#HttpOnly_/ {sub("#HttpOnly_", "", $1); print $1, "secure=" $4, $6, "httponly"; next}
            /^[^#]/ && NF {print $1, "secure=" $4, $6, "script-readable"}' jar.txt | sort -k3
echo "== next request to the same host"
curl -s -b jar.txt http://127.0.0.1:8000/whoami
echo "== another host (localhost is a different host name)"
curl -s -b jar.txt http://localhost:8000/whoami
kill %1
Set-Cookie: sid=lab-7Qx2; Path=/; HttpOnly; Secure; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=3600
Set-Cookie: __Host-csrf=c9f1; Path=/; Secure; SameSite=Strict
== the jar: host, secure-only, name, readable by script?
127.0.0.1 secure=TRUE __Host-csrf script-readable
127.0.0.1 secure=TRUE sid httponly
127.0.0.1 secure=FALSE theme script-readable
== next request to the same host
cookie header: __Host-csrf=c9f1; theme=dark; sid=lab-7Qx2
== another host (localhost is a different host name)
cookie header: (none)

The cookies are host-only (no Domain), so localhost gets none of them even though it is the same machine: cookies follow names, not addresses. The Secure cookies were still sent over plain http://127.0.0.1, because loopback counts as a secure context; on any other host they would need HTTPS.

Which cookies does a cross-site request carry?

SameSite is decided by the browser from three facts: is the request same-site, is it a top-level navigation, and is the method safe? This model of the rules (simplified from the 6265bis draft: it ignores the two-minute "Lax-allowing-unsafe" grace period some browsers apply to fresh cookies without an explicit attribute) prints what a browser sends from shop.lab.test cookies in five situations.

python · try it yourself
COOKIES = {"sid": "Lax", "pref": "None", "csrf": "Strict"}

def sends(samesite, same_site, top_level_nav, method):
    if same_site or samesite == "None":
        return True
    if samesite == "Lax":
        return top_level_nav and method in ("GET", "HEAD")
    return False                                   # Strict

cases = [
    ("click inside shop.lab.test",                 True,  True,  "POST"),
    ("link on blog.example clicked -> shop",        False, True,  "GET"),
    ("form on evil.example auto-POSTs to shop",     False, True,  "POST"),
    ("<img src=shop.lab.test/...> on evil.example", False, False, "GET"),
    ("fetch() from evil.example to shop",           False, False, "POST"),
]
print(f"{'situation':46}", "  ".join(f"{n}({s})" for n, s in COOKIES.items()))
for name, same, nav, method in cases:
    row = ["yes" if sends(s, same, nav, method) else "-" for s in COOKIES.values()]
    print(f"{name:46}", "  ".join(f"{r:^{len(n) + len(s) + 2}}" for r, (n, s) in zip(row, COOKIES.items())))
situation                                      sid(Lax)  pref(None)  csrf(Strict)
click inside shop.lab.test                       yes        yes          yes     
link on blog.example clicked -> shop             yes        yes           -      
form on evil.example auto-POSTs to shop           -         yes           -      
<img src=shop.lab.test/...> on evil.example       -         yes           -      
fetch() from evil.example to shop                 -         yes           -      

A Lax session cookie survives the ordinary case of following a link from another site (so users stay logged in) and blocks the three classic CSRF vehicles. Strict would even log the user out on the incoming link, which is why the CSRF token cookie, never needed on arrival, can be Strict. A None cookie goes everywhere: it needs other CSRF defences.

How weak cookies are detected

  • Response review: every Set-Cookie for a session or token should have Secure, HttpOnly (unless script must read it), an explicit SameSite, and no broad Domain. Scanners (ZAP's passive rules, Burp's scanner) flag missing attributes automatically; DevTools → Application → Cookies shows them per cookie.
  • Behaviour tests: log in, copy the cookie, log out, replay the old cookie: if it still works, logout doesn't invalidate the session. Check whether the session id changes at login (session fixation).
  • Logs: one session id used from two distant IP addresses or user agents at once is a classic sign of a stolen cookie (Session Hijacking).

How cookies are hardened

text
Set-Cookie: __Host-sid=<random 128+ bits>; Path=/; Secure; HttpOnly; SameSite=Lax
  • A random, server-side session id (not the user id, not a timestamp), a __Host- name, Secure, HttpOnly, SameSite=Lax or Strict.
  • No Domain unless several subdomains really must share it; then every one of them is part of your trust boundary.
  • Short idle and absolute timeouts, invalidation on logout and password change, a new id at login.
  • HTTPS everywhere plus HSTS, so Secure cookies never meet plain HTTP.

Pitfalls

  • HttpOnly is not an XSS fix. Injected script can still send requests that carry the cookie; it just can't export it.
  • SameSite is about sites, not origins. files.lab.test is same-site with shop.lab.test: a request from user-uploaded content there carries Strict cookies.
  • Storing session tokens in localStorage makes them readable by any script in the origin; it trades CSRF for XSS exposure. ExcelTAD keeps its TAD tokens there, which is why its rule is that no third-party script ever runs on the main thread (PKCE lesson).

Practice

1. A bank sets Set-Cookie: session=42; Domain=bank.lab.test. List three problems.

The value 42 looks sequential (guessable); Domain sends it to every subdomain; no Secure, HttpOnly or SameSite. Fix: random id, __Host- prefix, Secure; HttpOnly; SameSite=Lax.

2. Why can a cookie named __Host-sid not be overwritten from dev.bank.lab.test?

A __Host- cookie must have no Domain, so it is host-only for bank.lab.test; a subdomain can only set cookies for itself or with a Domain attribute, which __Host- forbids.

Test yourself

Which attribute stops injected JavaScript from reading the session cookie?

  1. Secure
  2. HttpOnly
  3. SameSite=Lax
  4. Path=/

A form on another site auto-submits a POST to the shop. Which session cookie does the browser attach?

  1. SameSite=Lax
  2. SameSite=Strict
  3. SameSite=None
  4. All three

In the session, why did http://localhost:8000 receive no cookies?

  1. localhost blocks cookies
  2. The cookies were host-only for 127.0.0.1, and localhost is a different host name
  3. The cookies had expired
  4. curl never sends Secure cookies

What does the __Host- prefix require?

  1. HttpOnly and SameSite=Strict
  2. Secure, Path=/ and no Domain attribute
  3. A Domain attribute
  4. Max-Age under one hour