30 Mins

4. HTTP Cookies, Sessions & State Management

HTTP Statelessness & Session Management

HTTP is fundamentally a stateless protocol, meaning each request/response cycle exists in a vacuum. A server has no inherent memory of previous requests from the same client. To create a cohesive session (e.g., staying logged in), we use cookies as a side-channel mechanism to transmit identity tokens.

When a user authenticates, the server responds with a Set-Cookie header. The client stores this and includes the Cookie header in all subsequent requests. This creates the illusion of state in an otherwise ephemeral protocol.

Security Operator Note: Use 'curl -v' to inspect raw HTTP headers in transit.
Python 3
import socket

# Mocking an HTTP response with a session cookie
response = b'HTTP/1.1 200 OK\r\nSet-Cookie: session_id=abc123xyz; Path=/;\r\n\r\nWelcome to the dashboard!'
print(f'Captured Header: {response.split(b'\r\n')[1].decode()}')

Set-Cookie Header Attributes

Cookie security is defined by specific flags that control browser behavior. HttpOnly prevents JavaScript from accessing the cookie (mitigating XSS theft). Secure ensures the cookie is only sent over HTTPS. SameSite (Strict/Lax/None) restricts cross-site request context to prevent CSRF.

The Domain and Path attributes define the scope. Domain limits the scope to a host and its subdomains; Path restricts it to specific URL subdirectories.

Security Operator Note: Always set HttpOnly and Secure for sensitive session cookies to prevent leakage.
Text
# Inspecting cookies using tshark
tshark -r traffic.pcap -Y 'http.cookie' -T fields -e http.cookie

Session Tokens vs JWT Tokens

Session tokens are server-side references where the state is stored in a database (e.g., Redis). JWT (JSON Web Tokens) are client-side claims cryptographically signed. JWTs reduce database overhead but cannot be easily revoked before they expire.

FeatureSession TokensJWT Tokens
StorageServer-sideClient-side
RevocationImmediateDifficult
Security Operator Note: If using JWTs, always implement a robust refresh token strategy.
Python 3
import hashlib

# Simulating a basic session token generation
session_id = hashlib.sha256(b'user_123_random_salt').hexdigest()
print(f'Generated Session Token: {session_id}')

Mitigating Session Hijacking

Session hijacking occurs when an attacker steals a cookie. Defense-in-depth includes binding sessions to IP addresses (risky for mobile users) or User-Agent strings, and rotating session IDs upon privilege escalation.

Using Tcpdump is critical for detecting anomalous patterns or cleartext cookie transmission in local network testing.

Security Operator Note: Implement Content-Security-Policy (CSP) to limit where cookies can be sent.
Text
tcpdump -i eth0 -A 'tcp port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420)'

Knowledge Check

Ready to test your understanding of 4. HTTP Cookies, Sessions & State Management?

Back