Practice Problems
A web application sets its session cookie as follows: ``` Set-Cookie: session=abc123; Domain=.example.com; Path=/; Max-Age=2592000 ``` Identify all security issues with this cookie configuration and explain the risks.
Solution
Security issues:
1. **Missing `Secure` flag**: The cookie can be sent over unencrypted HTTP, allowing network eavesdropping. An attacker on the same network can intercept the session cookie.
2. **Missing `HttpOnly` flag**: JavaScript can read the cookie via `document.cookie`. If an XSS vulnerability exists, the attacker can steal the session cookie.
3. **Missing `SameSite` attribute**: The browser sends the cookie with all cross-site requests, enabling CSRF attacks.
4. **Overly broad `Domain`**: `Domain=.example.com` sends the cookie to all subdomains (api.example.com, admin.example.com, etc.). If any subdomain is compromised, the session cookie is exposed.
5. **Excessive `Max-Age`**: 30 days (2592000 seconds) is too long for a session cookie. If the cookie is stolen, the attacker has a month to use it.
Secure configuration:
```
Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=1800
``` Implement a session management system with both idle timeout (30 minutes) and absolute timeout (8 hours). The system should: 1. Track the last activity time for each session 2. Expire the session after 30 minutes of inactivity 3. Expire the session after 8 hours regardless of activity 4. Regenerate the session ID on login
Solution
```python
import time
import secrets
from flask import Flask, session, request, redirect
app = Flask(__name__)
IDLE_TIMEOUT = 1800 # 30 minutes
ABSOLUTE_TIMEOUT = 28800 # 8 hours
@app.before_request
def check_session():
if 'user_id' not in session:
return
now = time.time()
# Check absolute timeout
if now - session.get('created_at', now) > ABSOLUTE_TIMEOUT:
session.clear()
return redirect('/login')
# Check idle timeout
if now - session.get('last_activity', now) > IDLE_TIMEOUT:
session.clear()
return redirect('/login')
# Update last activity
session['last_activity'] = now
@app.route('/login', methods=['POST'])
def login():
username = request.form['username']
password = request.form['password']
if verify_credentials(username, password):
# Regenerate session ID to prevent fixation
session.clear()
session['user_id'] = get_user_id(username)
session['created_at'] = time.time()
session['last_activity'] = time.time()
return redirect('/dashboard')
return 'Invalid credentials', 401
@app.route('/logout')
def logout():
session.clear()
return redirect('/login')
```
This implementation tracks both idle time (last activity) and absolute time (session creation), expiring the session when either limit is exceeded. The session ID is regenerated on login to prevent fixation. Quiz
1. What does the `HttpOnly` cookie attribute prevent?
2. Which SameSite cookie value provides the best balance between CSRF protection and usability for a typical web application?
3. What is the purpose of the `Secure` cookie attribute?
4. Why is `Domain=.example.com` considered a security risk for session cookies?
5. What is session rotation and why is it important?
Flashcards
Question
What does the `Secure` cookie attribute do?
Click to reveal answer
Answer
Ensures the cookie is only sent over HTTPS connections. Prevents network eavesdropping where an attacker intercepts unencrypted HTTP traffic.
Question
What does the `HttpOnly` cookie attribute prevent?
Click to reveal answer
Answer
Prevents client-side JavaScript from accessing the cookie via document.cookie. Critical defense against XSS-based session theft. Does not prevent the browser from sending the cookie with requests.
Question
What is the difference between SameSite=Strict and SameSite=Lax?
Click to reveal answer
Answer
Strict never sends the cookie with cross-site requests (including top-level GET). Lax sends with top-level GET requests (email links work) but not with cross-site POST/PUT/DELETE. Lax provides better usability while maintaining CSRF protection.
Question
Why is `Domain=.example.com` a security risk?
Click to reveal answer
Answer
It sends the cookie to all subdomains. If any subdomain is compromised (XSS, subdomain takeover), the session cookie is exposed. Omit the Domain attribute to limit the cookie to the exact host.
Question
What is session rotation?
Click to reveal answer
Answer
Issuing a new session ID immediately after login. Prevents session fixation attacks where an attacker sets a known session ID before the victim logs in.
Revision Notes
Key Takeaways
- 1. The Secure flag ensures cookies are only sent over HTTPS, preventing network eavesdropping
- 2. HttpOnly prevents JavaScript from reading the cookie, blocking XSS-based session theft
- 3. SameSite=Lax sends cookies with top-level GET requests but blocks cross-site POST, balancing security and usability
- 4. Session rotation (new session ID on login) prevents session fixation attacks
- 5. Use idle timeout (30 min) and absolute timeout (8 hours) to limit session lifetime
Interview Tips
- • Explain each cookie attribute and the specific attack it prevents with a concrete scenario
- • Discuss the trade-offs between SameSite=Strict and SameSite=Lax in terms of usability
- • Describe a complete session management strategy including rotation, timeout, and server-side storage
- • Connect cookie security to the OWASP Top 10 — HttpOnly defends against XSS (A03), SameSite defends against CSRF
Cheat Sheet
Session Cookie Attributes Cheat Sheet
Phase: Password Storage and Session Security | Level: intermediate
Essential Cookie Configuration:
Set-Cookie: session_id=abc123; Secure; HttpOnly; SameSite=Lax; Path=/; Max-Age=1800
Attribute Reference:
Secure— only send over HTTPSHttpOnly— prevent JavaScript access (XSS protection)SameSite=Lax— send with top-level GET, block cross-site POST (CSRF protection)Path=/— valid for entire applicationMax-Age=1800— expire after 30 minutes
Session Management:
- Regenerate session ID on login (prevents fixation)
- Implement idle timeout (30 min) and absolute timeout (8 hours)
- Store sessions server-side (Redis, database)
- Clear session on logout
Key points:
- The Secure flag keeps cookies off unencrypted HTTP connections entirely
- HttpOnly blocks JavaScript access, so injected scripts cannot steal session tokens
- SameSite=Lax or Strict limits cross-site cookie sending to prevent CSRF-style abuse
- Session rotation on login prevents fixation attacks
Tags: sessions, web-security
Continue Learning
Before You Start
- No prerequisites listed.