Why cookies and sessions are central to hacking
HTTP is stateless: the server does not remember you from one request to the next. Yet you log in once and stay logged in. The glue that makes this work is the session, and the most common carrier of a session is the cookie. Whoever holds a valid session identifier is, as far as the server is concerned, the user.
That makes sessions the crown jewels of a web application. A huge share of web attacks are ultimately about getting, forging, fixing, riding or bypassing a session:
- XSS steals or abuses the session.
- CSRF rides the session without stealing it.
- Session fixation forces a known session onto a victim.
- Weak tokens let an attacker guess or forge a session.
- Broken logout and expiry keep stolen sessions alive.
Understanding cookies precisely, especially the attributes Secure, HttpOnly, SameSite, Domain, Path and expiration, lets you reason about each of these attacks and about which defenses actually apply.
What is a cookie?
A cookie is a small piece of data (name, value and attributes) that the server asks the browser to store and send back on later requests to the same site. It works in two steps.
The server sets it with a response header:
HTTP/1.1 200 OK
Set-Cookie: session=9f8e7d6c5b4a; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
The browser then attaches it automatically to matching requests:
GET /account HTTP/1.1
Host: app.example.com
Cookie: session=9f8e7d6c5b4a; theme=dark
Key points:
- The browser sends only
name=valuepairs back. The server never sees the attributes on incoming requests; it cannot tell whether a cookie wasHttpOnlyor where it was set. - Sending is automatic. The page's JavaScript does not need to be involved, which is precisely what makes CSRF possible.
- Each cookie is limited to roughly 4 KB, and browsers limit the number per domain (commonly around 180 in Chrome, 150 in Firefox, per domain).
- Multiple cookies are separated with
;in theCookieheader. MultipleSet-Cookieheaders set multiple cookies.
Cookie attributes in depth
Expires and Max-Age: lifetime
- A cookie without
ExpiresorMax-Ageis a session cookie: it lives until the browser session ends (although modern browsers that "restore tabs" can keep them much longer). Expires=Wed, 21 Oct 2026 07:28:00 GMTsets an absolute date.Max-Age=3600sets seconds from now and wins if both are present.- To delete a cookie, the server sends it again with a past date or
Max-Age=0. - Long-lived "remember me" cookies are valuable to attackers; a stolen one gives access for weeks. Browsers cap cookie lifetime (Chrome limits it to 400 days).
Domain: which hosts receive it
- If
Domainis omitted, the cookie is host-only: sent only to the exact host that set it (app.example.com), not to its subdomains. - If
Domain=example.comis set, the cookie is sent toexample.comand every subdomain (app.example.com,blog.example.com,anything.example.com).
This is a frequent source of bugs. A cookie scoped to the parent domain is readable and overwritable by every subdomain. If any subdomain is vulnerable to XSS or can be taken over, the attacker can read the session cookie or set a cookie tossing payload (a cookie the main app will trust or that fixes the session). Prefer host-only cookies.
A site can never set a cookie for an unrelated domain or for a public suffix such as .com or .co.uk (the Public Suffix List governs this).
Path: which URL paths receive it
Path=/admin sends the cookie only for requests whose path begins with /admin. It is a convenience, not a security boundary: any page on the same origin can still read it with JavaScript (via an iframe to /admin for instance). Do not use Path to protect secrets.
Secure: HTTPS only
Secure makes the browser send the cookie only over HTTPS. Without it, the cookie leaks in clear text on any plain-HTTP request, including the first visit before a redirect to HTTPS, to anyone on the network. Browsers also refuse to let insecure origins overwrite Secure cookies. Always set it, and combine with HSTS.
HttpOnly: no JavaScript access
HttpOnly hides the cookie from document.cookie and from other script APIs. Effects:
- An XSS payload cannot simply read and exfiltrate the session cookie.
- It does not stop XSS. An attacker with script execution can still make authenticated requests from the victim's browser (the cookie is attached automatically), change the password, or read pages.
- It does not prevent CSRF.
Think of HttpOnly as reducing the damage of XSS from "full session theft" to "actions while the victim's tab is open."
SameSite: cross-site sending
SameSite controls whether the cookie is sent on cross-site requests, the main browser defense against CSRF.
| Value | Behavior |
|---|---|
Strict |
Never sent on cross-site requests, even when the user clicks a link from another site. |
Lax |
Sent on cross-site top-level navigations with safe methods (clicking a link, GET), not on cross-site subrequests (images, iframes, fetch) or cross-site POST forms. |
None |
Sent on all cross-site requests. Requires Secure. |
Modern browsers treat cookies without a SameSite attribute as Lax by default (Chrome and Edge; Firefox and Safari vary and have different details). Lax-by-default has a special exception: Chrome historically allowed cross-site top-level POST for roughly two minutes after a cookie was set ("Lax + POST"). Also remember that "site" is not "origin": requests between a.example.com and b.example.com are same-site, so SameSite does nothing for CSRF from a sibling subdomain. (The next lessons on origins and the same-origin policy explain the difference precisely.)
Prefixes
Two name prefixes give the browser extra enforcement:
__Secure-requires theSecureattribute and an HTTPS origin.__Host-requiresSecure,Path=/, noDomainattribute and HTTPS. This guarantees a host-only cookie that subdomains cannot overwrite, which defeats cookie tossing.
A well-hardened session cookie looks like:
Set-Cookie: __Host-sid=7f3c9a...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
Other client-side storage
Cookies are not the only browser storage. Know the differences:
| Storage | Sent automatically? | Readable by JS? | Typical size | Lifetime |
|---|---|---|---|---|
| Cookie | Yes, every matching request | Unless HttpOnly |
~4 KB | Per attributes |
localStorage |
No | Yes, any script on the origin | ~5 MB | Until cleared |
sessionStorage |
No | Yes | ~5 MB | Per tab |
| IndexedDB | No | Yes | Large | Until cleared |
Storing a session token in localStorage removes CSRF risk (it is not auto-sent) but makes it fully readable by XSS. Cookies with HttpOnly have the opposite trade-off. Neither is magically safe; the right answer depends on the whole design.
Sessions: the server-side idea
A session is the server's record that a series of requests belong to the same authenticated user. There are two main designs.
Server-side sessions (opaque identifiers)
- User submits credentials.
- The server verifies them, creates a random session id, and stores state in memory, a database or a store such as Redis:
{ id: "9f8e...", userId: 7, role: "user", expires: ... }. - The id is sent to the browser as a cookie.
- On each request, the server looks the id up.
Advantages: the server controls everything. It can revoke a session instantly (delete the record), see all active sessions, and change roles without reissuing anything. The cookie itself carries no data, so there is nothing to forge except guessing a random id.
Disadvantages: needs shared storage when you have multiple servers.
Token-based sessions (stateless tokens)
The server issues a self-contained, signed token, commonly a JWT (JSON Web Token): header.payload.signature, each part Base64URL-encoded. The server stores no state; it just verifies the signature on each request.
Advantages: scales easily across services, works for APIs and mobile apps.
Disadvantages: revocation is hard (a token stays valid until it expires unless you keep a deny-list, which reintroduces state), and any flaw in verification is catastrophic. Classic JWT bugs include accepting alg: none, confusing RS256 with HS256, weak HMAC secrets, not validating exp, and trusting claims in the payload without verifying the signature. The payload is only encoded, not encrypted: anyone can read it.
Tokens can be carried in a cookie, or in an Authorization: Bearer ... header set by JavaScript. The carrier determines the attack surface (CSRF applies to cookies; XSS theft applies to JS-accessible storage).
The session lifecycle
A secure design handles every stage:
- Creation. A session is created on login (and sometimes before, for anonymous users). The id must come from a cryptographically secure random generator with at least 64 bits of entropy (OWASP recommends at least 128-bit ids, in practice 16+ random bytes).
- Rotation at privilege change. On login, logout, password change or role change, issue a new id and invalidate the old one. Failing to do this causes session fixation.
- Use. Every request is authenticated by the id. Optionally bind to additional context (but beware that IP binding breaks mobile users).
- Expiry. Enforce both an idle timeout (for example 15 to 30 minutes) and an absolute timeout (for example 8 to 12 hours), on the server. A cookie's
Max-Ageis only a client-side hint. - Termination. Logout must destroy the server-side session, not just delete the cookie in the browser. Password reset or change should kill other sessions.
Where it goes wrong
| Weakness | What the attacker does |
|---|---|
| Predictable ids (sequential, timestamps, short) | Guess or brute-force another user's session |
| Session fixation (id not rotated after login) | Plants a known id in the victim's browser (via a link, or a vulnerable sibling subdomain), waits for the victim to log in, then uses it |
Session id in URL (?sid=...) |
Leaks through Referer, browser history, logs, shared links |
Missing Secure |
Sniffs the cookie over HTTP |
Missing HttpOnly |
Steals it with XSS via document.cookie |
Missing or weak SameSite and no CSRF token |
CSRF: the victim's browser attaches the cookie to the attacker's request |
Overly broad Domain |
Takeover or XSS on any subdomain compromises the session |
| Logout only clears the client cookie | A stolen session stays valid |
| No server-side expiry | Old tokens live for months |
| JWT flaws | Forge or tamper tokens, escalate to admin |
Client-controlled state in cookies (role=user, isAdmin=false) |
Edit the cookie value to admin |
| Unsigned or reversible cookie contents | Decode (often Base64), modify, resend |
| Same session allowed forever from anywhere | No detection of theft |
| Weak "remember me" tokens | Long-lived access after one theft |
A closer look: tampering with client-held state
A classic finding is a cookie that contains the authorization data itself:
Cookie: session=abc123; role=user; userid=1042
If the server believes role and userid from the cookie, changing them to role=admin and userid=1 is privilege escalation. The rule is simple: cookies identify; the server decides. Anything the client can change must be treated as untrusted input, the same as a form field.
A closer look: fixation
GET /login?sid=ATTACKER_KNOWN_VALUE HTTP/1.1
If the application accepts an id supplied by the client and keeps using it after authentication, the attacker who knew the id before login now has the authenticated session. The fix: always generate a fresh id on authentication.
How cookies relate to other attacks
- CSRF works because the browser attaches cookies automatically. Defenses: SameSite, anti-CSRF tokens, checking
Origin/Referer, custom headers. - XSS can read non-HttpOnly cookies, and with HttpOnly can still act as the user.
- CORS with credentials (
Access-Control-Allow-Credentials: true) lets another origin read authenticated responses if the policy is wrongly permissive. - Cache problems can leak
Set-Cookieor personalized pages between users when responses are cached withoutVary: CookieorCache-Control: private/no-store. - Subdomain takeover plus a wide
Domainattribute yields session access.
Hands-on exercises
Use your own browser on sites you are allowed to look at (your own accounts on public sites are fine for read-only inspection).
- Inventory cookies. Open DevTools, Application tab (Chrome/Edge) or Storage tab (Firefox), Cookies. For a site you log in to, list each cookie and write whether it has
Secure,HttpOnly,SameSite, aDomainand an expiry. - Watch
Set-Cookie. In the Network tab, log in to a practice app, select the login response, and findSet-Cookiein the response headers. Compare to what the Application tab shows. - Test HttpOnly. In the Console, run
document.cookie. Which cookies are missing from the output and why? - Check rotation. Note your session cookie value before logging in, then after. Did it change? Do the same before and after logout and after a password change on a test account.
- Judge randomness. Log in five times (or collect five anonymous sessions) and compare the ids. Are they long and unpredictable, or do they share a pattern?
- Decode a token. If a cookie looks like Base64 or like
xxx.yyy.zzz, decode the first two parts withatob()in the Console or with your proxy's Decoder. Is the content readable? Is there a signature? (Do not forge tokens on systems you do not own.) - Edit and replay. On a practice app, double-click a cookie value in DevTools and edit it. Reload and observe what the server does with an invalid or modified value.
- Understand SameSite. Read
SameSiteon a cookie, then open a page from a different site that links to it, and in the Network tab check whether the cookie was sent (Chrome shows blocked cookies with an icon and reason).
Checklist
- I can explain what each of Secure, HttpOnly, SameSite, Domain, Path and Expires/Max-Age does.
- I know the difference between host-only and domain cookies and why it matters.
- I can explain what
__Host-guarantees. - I understand server-side sessions versus signed tokens and the trade-offs.
- I can list at least five ways session handling fails.
- I know what HttpOnly does not protect against.
- I know "site" is not "origin" and why that affects SameSite.
Key takeaways
- A session id is a bearer credential: whoever holds it is the user.
- Cookies are sent automatically, which enables CSRF; JS-readable storage enables theft through XSS.
- Set
Secure,HttpOnlyandSameSite, prefer host-only__Host-cookies, and keep lifetimes short. - Rotate ids on authentication and privilege change; enforce expiry and logout on the server.
- Never keep authorization decisions in client-controlled data.
Further reading
- MDN: "Using HTTP cookies" and the
Set-Cookiereference - RFC 6265 and the updated RFC 6265bis draft (cookie syntax, SameSite)
- OWASP Session Management Cheat Sheet and OWASP Testing Guide: Session Management
- PortSwigger Web Security Academy: CSRF, SameSite cookies, JWT attacks