Skip to content
CSY203 Week 04 Intermediate

Week Content

Secure Software & Web Security

Track your progress through this week's content

Opening Framing: Maintaining State in a Stateless Protocol

HTTP is stateless—each request is independent. Yet applications need to remember who you are. Session management bridges this gap by assigning a unique identifier that links requests to authenticated users.

This creates a valuable target. Whoever possesses the session identifier becomes that user. Session tokens are the keys to the kingdom—steal them, predict them, or forge them, and you gain unauthorized access.

This week covers session management mechanisms, token analysis, session hijacking techniques, and Cross-Site Request Forgery— tricking users into making requests they didn't intend.

Key insight: Authentication happens once; session management happens with every request. Weaknesses multiply.

1) Session Management Fundamentals

How applications track authenticated users:

Session Management Flow:

1. User authenticates
   POST /login → credentials valid

2. Server creates session
   - Generate unique session ID
   - Store session data server-side
   - Associate with user identity

3. Server sends session identifier
   Set-Cookie: SESSIONID=abc123xyz

4. Browser stores and sends cookie
   Cookie: SESSIONID=abc123xyz

5. Server validates session
   - Look up session ID
   - Retrieve user context
   - Process request as that user

6. Session terminates
   - User logs out
   - Session expires
   - Server invalidation

Session Storage Methods:

Server-Side Sessions:
- Session ID in cookie
- Data stored on server
- Most secure approach
- Session ID is only reference

Client-Side Sessions (JWT):
- All data in token
- Signed but readable
- Server doesn't store state
- Can't be invalidated easily

Cookie Attributes:
Set-Cookie: session=abc123;
    Secure;      ← Only over HTTPS
    HttpOnly;    ← No JavaScript access
    SameSite=Strict;  ← CSRF protection
    Path=/;      ← Cookie scope
    Domain=.example.com;
    Max-Age=3600;  ← Expiration

Missing attributes = vulnerabilities!

Session Token Requirements:

Secure Session IDs must be:

1. Unpredictable
   - Cryptographically random
   - No patterns
   - No sequential values

2. Sufficient length
   - Minimum 128 bits of entropy
   - Typically 32+ characters

3. Unique
   - No collisions
   - Not reused

Bad session IDs:
- session=1, session=2 (sequential)
- session=admin (username-based)
- session=1703123456 (timestamp)
- session=abc123 (short, guessable)

Good session IDs:
- session=a7f3b2c9d4e5f6a7b8c9d0e1f2a3b4c5
- 256-bit random hex string

Key insight: Session security depends on token randomness and proper cookie configuration. Weakness in either is exploitable.

2) Session Token Analysis

Analyzing tokens for weaknesses:

Token Analysis Goals:

1. Identify token format
   - Hex, Base64, JWT
   - Custom encoding

2. Check for patterns
   - Sequential values
   - Timestamps
   - User data embedded

3. Assess randomness
   - Statistical analysis
   - Prediction attempts

4. Test manipulation
   - Decode and modify
   - Check signature validation

Burp Sequencer:

# Analyze session token randomness

1. Capture request that returns session token
   - Login response with Set-Cookie
   - Any response with new token

2. Send to Sequencer
   Right-click → Send to Sequencer

3. Configure token location
   - Select the session token value
   - Define start and end markers

4. Start live capture
   - Collects many tokens
   - Minimum 100, ideally 1000+

5. Analyze results
   - Character-level analysis
   - Bit-level analysis
   - Overall randomness score

Interpretation:
- Effective entropy > 100 bits = good
- Predictable patterns = vulnerable
- Low entropy = can be brute forced

Manual Token Analysis:

# Collect multiple tokens

Token 1: YWRtaW46MTcwMzEyMzQ1Ng==
Token 2: YWRtaW46MTcwMzEyMzQ1Nw==
Token 3: YWRtaW46MTcwMzEyMzQ1OA==

# Decode (Base64)
admin:1703123456
admin:1703123457
admin:1703123458

# Pattern identified: username:timestamp
# Completely predictable!

# Analysis steps:
1. Is it encoded? Try Base64, URL decode, hex
2. Are there patterns? Compare multiple tokens
3. Is user data embedded? Look for username, email
4. Is there a timestamp? Look for epoch times
5. Is there a signature? JWT has three parts

JWT Token Analysis:

# JWT structure
header.payload.signature

# Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VyIjoiYWRtaW4iLCJyb2xlIjoiYWRtaW4ifQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

# Decode header:
{"alg":"HS256","typ":"JWT"}

# Decode payload:
{"user":"admin","role":"admin"}

# Signature (verify integrity)

# JWT vulnerabilities to test:
1. Algorithm confusion (alg:none)
2. Weak secret (brute force)
3. Key confusion (RS256 → HS256)
4. Missing signature validation
5. Sensitive data in payload

# Tools:
# jwt.io - decode and edit
# jwt_tool - comprehensive testing

Key insight: Weak tokens can be predicted or forged. Analysis reveals the attack approach.

3) Session Hijacking

Stealing or capturing session tokens:

Session Hijacking Methods:

1. Network Interception (MITM)
   - Unencrypted HTTP
   - ARP spoofing
   - WiFi sniffing

2. Cross-Site Scripting (XSS)
   - Steal cookie via JavaScript
   - If HttpOnly not set

3. Session Fixation
   - Force victim to use known session
   - Attacker already knows the ID

4. Session Prediction
   - Weak token generation
   - Guess valid sessions

5. Physical Access
   - Browser left open
   - Session in URL history

Session Fixation Attack:

# Session Fixation Flow

1. Attacker obtains session ID
   - Visit target site
   - Get assigned: session=abc123

2. Attacker tricks victim into using that session
   - Send link: https://target.com/?session=abc123
   - Some apps accept session ID in URL

3. Victim authenticates
   - Logs in with session=abc123
   - Session now associated with victim's account

4. Attacker hijacks session
   - Uses same session=abc123
   - Now authenticated as victim

# Testing for session fixation:
1. Get session before login
2. Login
3. Check if session ID changed

# Vulnerable: Same session ID after login
# Secure: New session ID generated

Cookie Theft via XSS:

# If HttpOnly is NOT set:





# Attacker receives:
GET /steal?c=session=abc123xyz

# Attacker uses cookie:
Cookie: session=abc123xyz

# Now authenticated as victim!

# Prevention:
Set-Cookie: session=abc123; HttpOnly

# HttpOnly prevents JavaScript access
# XSS can't steal HttpOnly cookies

Session Token Prediction:

# If tokens are predictable:

Observed tokens:
user1: session=100001
user2: session=100002
user3: session=100003

# Predict next user:
session=100004, 100005, 100006...

# Or timestamp-based:
session=1703123456
session=1703123457

# Brute force with Burp Intruder:
1. Capture authenticated request
2. Send to Intruder
3. Payload: Numbers 100000-100999
4. Look for 200 responses with content

# Sequential sessions allow mass account takeover

Key insight: Session hijacking gives full account access without knowing the password. Protect tokens accordingly.

4) Cross-Site Request Forgery (CSRF)

Tricking users into making unintended requests:

CSRF Attack Concept:

Victim is logged into bank.com
Victim visits malicious site
Malicious site triggers:
  POST bank.com/transfer
  to=attacker&amount=10000

Browser sends victim's bank.com cookies
Bank sees valid session
Transfer executes!

Key requirements:
1. Victim authenticated to target
2. Target doesn't validate request origin
3. Attacker knows required parameters

CSRF Attack Examples:

# GET-based CSRF (easy)

# Change email:


# Hidden in image tag, loads automatically

# POST-based CSRF

# Auto-submits when page loads # JSON-based CSRF (harder)
# Creates: {"email":"attacker@evil.com","ignore":"="}

CSRF Protections:

# Anti-CSRF Tokens

Server includes token in form:


Server validates token on submission
Attacker can't guess the token

# Token bypass attempts:
1. Remove token entirely
2. Use empty token
3. Use token from different session
4. Use token from different user
5. Reuse old token

# SameSite Cookie Attribute

Set-Cookie: session=abc; SameSite=Strict

Strict: Cookie never sent cross-site
Lax: Sent on top-level GET only
None: Always sent (requires Secure)

# Testing SameSite:
1. Check cookie attributes
2. If None or missing, CSRF possible
3. If Lax, GET-based CSRF possible

# Referer/Origin Validation

Server checks:
Origin: https://target.com
Referer: https://target.com/page

# Bypass attempts:
- Remove header
- Spoof header (not in browser)
- Use data: or javascript: URLs

Testing for CSRF:

# CSRF testing methodology

1. Identify state-changing requests
   - Password change
   - Email change
   - Money transfer
   - Settings update

2. Check for protections
   - CSRF token present?
   - SameSite cookie?
   - Referer validation?

3. Test token validation
   - Remove token
   - Change token value
   - Use different session's token

4. Create PoC
   # Burp: Right-click → Engagement tools → Generate CSRF PoC
   
5. Test PoC
   - Open in different browser
   - While logged in as victim
   - Does action execute?

# Burp extension: CSRF Scanner

Key insight: CSRF exploits the trust a site has in the user's browser. Any action the user can take, CSRF can trigger.

5) Session Management Best Practices Testing

Comprehensive session security assessment:

Session Security Checklist:

Token Generation:
□ Cryptographically random?
□ Sufficient length (128+ bits)?
□ No predictable patterns?
□ No embedded user data?

Cookie Configuration:
□ HttpOnly flag set?
□ Secure flag set?
□ SameSite attribute?
□ Appropriate scope (Path, Domain)?
□ Reasonable expiration?

Session Lifecycle:
□ New session on login?
□ Session invalidated on logout?
□ Session timeout implemented?
□ Concurrent session handling?

CSRF Protection:
□ Anti-CSRF tokens used?
□ Tokens properly validated?
□ SameSite cookies?
□ Referer validation?

Testing Session Timeout:

# Session timeout tests

1. Idle timeout
   - Login, wait (30min, 1hr)
   - Try to access protected page
   - Should require re-authentication

2. Absolute timeout
   - Session should expire regardless of activity
   - Prevents infinite sessions

3. Timeout on sensitive actions
   - Password change should require recent auth
   - Not rely on old session

# Test methodology:
1. Login and note session token
2. Wait beyond expected timeout
3. Use old token
4. Should receive 401/403 or redirect to login

Testing Logout:

# Logout security tests

1. Is session invalidated server-side?
   - Logout
   - Try using old session token
   - Should be rejected

2. Is cookie cleared client-side?
   - Check Set-Cookie after logout
   - Should clear/expire session cookie

3. Are all sessions terminated?
   - Login on device A and B
   - Logout on A
   - Is B still valid?

4. "Logout everywhere" function?
   - Should invalidate all sessions
   - Test if it works

# Common issues:
- Session not invalidated (can reuse token)
- Only clears cookie (token still valid)
- Doesn't handle concurrent sessions

Testing Concurrent Sessions:

# Multiple session tests

1. Are concurrent sessions allowed?
   - Login from browser A
   - Login from browser B
   - Both should work? Or one invalidated?

2. Session limit enforcement
   - Login from many browsers
   - Is there a maximum?
   - What happens when exceeded?

3. Session visibility
   - Can user see active sessions?
   - Can user terminate other sessions?

# Security implications:
- No limit = attacker maintains access
- Old sessions survive password change?
- Password change should invalidate all sessions

Key insight: Session security is holistic. Weak links in generation, storage, or lifecycle all create vulnerabilities.

Real-World Context: Session Attacks in Practice

Session vulnerabilities in the wild:

OAuth Session Issues: Modern applications use OAuth extensively. Token theft, improper validation, and scope escalation are common. OAuth adds complexity that creates new attack surfaces.

Mobile Session Security: Mobile apps often store tokens insecurely—in shared preferences, plain files, or logs. Tokens may not expire, enabling persistent access if device is compromised.

API Token Management: API keys and tokens often lack proper lifecycle management. Keys that should be temporary become permanent. Rotation is rare. Leaked keys remain valid indefinitely.

MITRE ATT&CK Mapping:

  • T1539 - Steal Web Session Cookie: Session hijacking
  • T1550.001 - Use Alternate Auth Material: Token reuse
  • T1185 - Browser Session Hijacking: MITM attacks

Key insight: Session management vulnerabilities provide persistent access. Once you have a valid token, you're in until it expires or is revoked.

Guided Lab: Session Management Testing

Test session management on vulnerable applications.

Step 1: Cookie Analysis

# Login to DVWA or target application
# Examine cookies in browser DevTools or Burp

# Check for:
# - HttpOnly flag
# - Secure flag
# - SameSite attribute
# - Expiration

# Document findings

Step 2: Session Token Analysis

# Collect multiple session tokens
# Login, get token, logout, repeat 5x

# Analyze tokens:
# - Encoding (Base64?)
# - Patterns (sequential?)
# - Length
# - Character set

# Use Burp Sequencer for randomness analysis

Step 3: Session Fixation Test

# Test for session fixation:
1. Get session token before login
2. Login
3. Check if token changed

# If same token: vulnerable to fixation

Step 4: CSRF Testing

# Find state-changing request (password change, etc.)
# Check for CSRF protection

# Use Burp to generate CSRF PoC:
Right-click request → Engagement tools → Generate CSRF PoC

# Test PoC in different browser while logged in

Step 5: PortSwigger Labs

# Complete these labs:
# 1. CSRF vulnerability with no defenses
# 2. CSRF where token validation depends on request method
# 3. CSRF where token is not tied to user session
# 4. SameSite Lax bypass via method override

# https://portswigger.net/web-security/csrf

Reflection (mandatory)

  1. What cookie security attributes were missing?
  2. How predictable were the session tokens?
  3. Was the application vulnerable to session fixation?
  4. Which CSRF protections were present or absent?

Week 04 Quiz

Test your understanding of Session Management and CSRF.

Format: 10 multiple-choice questions. Passing score: 70%. Time: Untimed.

Take Quiz

Week 4 Outcome Check

By the end of this week, you should be able to:

Next week: SQL Injection Deep Dive—mastering the most dangerous injection attack.

🎯 Hands-On Labs (Free & Essential)

Apply what you learned through practical session management and CSRF testing exercises. Complete these labs before moving to reading resources.

🕷️ PortSwigger: CSRF Labs (ALL 8 LABS)

What you'll do: Master Cross-Site Request Forgery attacks through comprehensive hands-on practice:

Basic CSRF (Labs 1-3):
• CSRF with no defenses
• CSRF where token validation depends on request method
• CSRF where token validation depends on token being present

Token Bypass (Labs 4-6):
• CSRF where token is not tied to user session
• CSRF where token is tied to non-session cookie
• CSRF where token is duplicated in cookie

Advanced CSRF (Labs 7-8):
• SameSite Lax bypass via method override
• SameSite Strict bypass via client-side redirect

Why it matters: CSRF forces authenticated users to perform unwanted actions. PortSwigger's 8 CSRF labs teach you to identify missing protections, bypass common defenses, and understand SameSite cookie attributes—critical skills for modern web security testing.
Time estimate: 3-4 hours (comprehensive mastery)

Start PortSwigger CSRF Labs →

🎮 TryHackMe: JWT Security

What you'll do: Learn JSON Web Token vulnerabilities through interactive challenges. Practice JWT decoding, algorithm confusion attacks, signature bypass, and token manipulation techniques.

Why it matters: JWTs are increasingly common for session management in modern applications. Understanding JWT vulnerabilities (algorithm confusion, weak secrets, none algorithm) is essential for API and SPA security testing.
Time estimate: 1.5-2 hours

Start TryHackMe JWT Security →

🔐 JWT.io Debugger + Common Vulnerabilities

What you'll do: Practice JWT analysis using jwt.io debugger. Learn to decode tokens, identify algorithms, test signature verification, and exploit common JWT misconfigurations (none algorithm, weak HMAC secrets, algorithm confusion).

Why it matters: JWT.io is the go-to tool for JWT analysis in penetration testing. Understanding how to decode, modify, and re-sign JWTs is essential for session security testing in modern web applications and APIs.
Time estimate: 1 hour

Start JWT.io Practice →

🧃 OWASP Juice Shop: Session & CSRF Challenges

What you'll do: Find and exploit session management and CSRF vulnerabilities in a realistic e-commerce application. Practice session hijacking, JWT exploitation, weak session tokens, and CSRF attacks on state-changing functions.

Why it matters: Juice Shop provides realistic session management vulnerabilities you need to discover through testing. This develops the investigation skills needed to find session flaws in real applications during pentests and bug bounties.
Time estimate: 2-3 hours

Start Juice Shop Session Challenges →

💡 Lab Strategy: Start with PortSwigger CSRF labs for comprehensive attack techniques. Then practice JWT security with TryHackMe and jwt.io for modern session management. Finally, use Juice Shop for realistic session vulnerability discovery. This combination covers traditional cookies + modern JWTs: 600 total XP, 7-10 hours of session security mastery!

🛡️ Defensive Architecture & Secure Design Patterns

Sessions are the continuity of identity. Defensive design makes sessions short-lived, strongly bound, and hard to steal.

Secure Session Architecture

Session hardening baseline:
- Generate high-entropy session IDs (128+ bits)
- Regenerate session ID on login and privilege change
- Set Secure, HttpOnly, SameSite, and short Max-Age
- Enforce idle + absolute timeouts
- Invalidate sessions on logout and password change

CSRF Protection Patterns:

Preferred defenses:
- Synchronizer token pattern (per-session token)
- SameSite=Lax or Strict suggested for browsers
- Verify Origin/Referer for state-changing requests

Real-World Breach: Facebook 2018 "View As" Token Theft

Attackers exploited a chain in the "View As" feature to steal access tokens for millions of users. Lessons learned: rotate tokens after sensitive actions, minimize token scope, and invalidate sessions quickly when anomalies appear.

Defensive Labs

Lab: Harden Session Cookies

Configure Secure, HttpOnly, SameSite, and Max-Age on session cookies. Validate with DevTools or `curl -I`.

Lab: Implement CSRF Tokens

Add synchronizer tokens to state-changing forms and verify server-side validation with a manual CSRF PoC.

Lab: Session Rotation and Timeout Policy

Implement session rotation on login and privilege changes, plus idle and absolute timeouts. Document the policy and test with old tokens.

📚 Building on CSY101 Week-13: Threat model session workflows and abuse cases (token theft, fixation, CSRF). CSY101 Week-14: Map controls to NIST 800-53 (IA/AC) and CIS Controls. CSY104 Week-11: Use CVSS to prioritize session fixes.

Reading Resources (Free + Authoritative)

Complete the required resources to build your foundation.

Lab: Complete Session Security Assessment

Goal: Perform comprehensive session management assessment of target application.

Part 1: Token Analysis

  1. Collect 10+ session tokens
  2. Analyze format and encoding
  3. Run Burp Sequencer analysis
  4. Attempt token prediction
  5. Document entropy assessment

Part 2: Cookie Security

  1. Audit all cookie attributes
  2. Test missing HttpOnly (XSS steal)
  3. Test missing Secure (HTTP interception)
  4. Test SameSite configuration

Part 3: Session Lifecycle

  1. Test session fixation
  2. Test session invalidation on logout
  3. Test session timeout
  4. Test concurrent session handling
  5. Test session behavior after password change

Part 4: CSRF Assessment

  1. Identify all state-changing functions
  2. Test for CSRF protections
  3. Attempt token bypass techniques
  4. Create working CSRF PoCs

Part 5: JWT Testing (if applicable)

  1. Decode and analyze JWT
  2. Test algorithm confusion
  3. Test signature validation
  4. Test token manipulation

Deliverable (submit):

Checkpoint Questions

  1. What is the purpose of the HttpOnly cookie flag?
  2. How does session fixation differ from session hijacking?
  3. What makes a session token cryptographically secure?
  4. What is CSRF and what conditions make it possible?
  5. How does SameSite=Strict protect against CSRF?
  6. Why should sessions be regenerated after login?

Weekly Reflection

Reflection Prompt (200-300 words):

This week you learned session management attacks—techniques that exploit how applications maintain user identity across requests. You analyzed tokens, tested hijacking scenarios, and exploited CSRF vulnerabilities.

Reflect on these questions:

A strong reflection will consider both attack effectiveness and practical defensive challenges.

Verified Resources & Videos

Session management security is often overlooked but critical. A single session vulnerability can compromise any user account. The skills you've developed—token analysis, hijacking techniques, CSRF exploitation—apply to virtually every web application. Next week: SQL injection, where we go deep on the most impactful injection attack.

← Previous: Week 03 Next: Week 05 →