Session Hijacking Tests
Session Hijacking Tests
The following files were used as context for generating this wiki page:
- .github/workflows/ghcr-publish.yml
- CHANGELOG.md
- README.md
- requirements.txt
- wshawk/advanced_cli.py
- wshawk/scanner_v2.py
Purpose and Scope
This document describes WSHawk's Session Hijacking Testing Module, which validates WebSocket session security through 6 specialized security tests. These tests identify authentication and authorization vulnerabilities that could allow attackers to hijack active sessions, impersonate users, or escalate privileges.
This module is part of WSHawk's Offensive Testing capabilities. For defensive validation tests (DNS exfiltration, bot detection, CSWSH, and WSS protocol security), see Defensive Validation. For XSS verification using real browsers, see Playwright XSS Verification.
Sources: README.md:34-44, wshawk/scanner_v2.py:23, wshawk/scanner_v2.py:708-732
Overview
The SessionHijackingTester class executes 6 distinct security tests that validate session management controls in WebSocket applications:
| Test Type | Purpose | Detection Method | |-----------|---------|-----------------| | Token Reuse | Validates that session tokens cannot be replayed after logout | Attempts reconnection with invalidated tokens | | Impersonation | Tests if one user's token can be used to access another user's session | Cross-user token substitution | | Privilege Escalation | Verifies that lower-privilege tokens cannot perform admin actions | Role-boundary testing | | Session Fixation | Checks if attacker-supplied tokens are accepted | Pre-authentication token injection | | Token Predictability | Analyzes token entropy and randomness | Statistical analysis of token generation patterns | | Timeout Validation | Ensures sessions expire after defined inactivity periods | Time-based session lifecycle testing |
Each test produces results with confidence levels (HIGH, MEDIUM, LOW), evidence artifacts, CVSS v3.1 scores, and remediation recommendations.
Sources: README.md:44, CHANGELOG.md:89-90
Architecture and Integration
Component Diagram
graph TB
WSHawkV2["WSHawkV2<br/>(scanner_v2.py)"]
SessionTester["SessionHijackingTester<br/>(session_hijacking_tester.py)"]
WSConnection["WebSocket Connection<br/>websockets library"]
AuthConfig["auth_config<br/>Authentication Flow"]
TestRunner["run_all_tests()"]
TokenReuse["test_token_reuse()"]
Impersonation["test_impersonation()"]
PrivEsc["test_privilege_escalation()"]
Fixation["test_session_fixation()"]
Predictability["test_token_predictability()"]
Timeout["test_timeout_validation()"]
Results["TestResult Objects"]
VulnList["vulnerabilities list"]
CVSSScoring["CVSS v3.1 Scoring"]
WSHawkV2 -->|"instantiates with url"| SessionTester
WSHawkV2 -->|"provides auth_config"| AuthConfig
SessionTester -->|"creates"| WSConnection
AuthConfig -->|"configures"| SessionTester
SessionTester -->|"orchestrates"| TestRunner
TestRunner -->|"executes"| TokenReuse
TestRunner -->|"executes"| Impersonation
TestRunner -->|"executes"| PrivEsc
TestRunner -->|"executes"| Fixation
TestRunner -->|"executes"| Predictability
TestRunner -->|"executes"| Timeout
TokenReuse -->|"returns"| Results
Impersonation -->|"returns"| Results
PrivEsc -->|"returns"| Results
Fixation -->|"returns"| Results
Predictability -->|"returns"| Results
Timeout -->|"returns"| Results
Results -->|"includes"| CVSSScoring
Results -->|"appended to"| VulnList
WSHawkV2 -->|"stores results"| VulnList
Sources: wshawk/scanner_v2.py:708-732, wshawk/scanner_v2.py:23
Execution Flow
The session hijacking tests are executed automatically at the end of each full scan, after all vulnerability injection tests complete:
sequenceDiagram
participant Scanner as WSHawkV2.run_heuristic_scan()
participant Tests as Injection Tests
participant WSConn as WebSocket Connection
participant SessionTest as SessionHijackingTester
participant Results as vulnerabilities list
Scanner->>Tests: Execute SQL, XSS, Command, etc.
Tests-->>Scanner: Returns findings
Scanner->>WSConn: Close main connection
Scanner->>SessionTest: SessionHijackingTester(url)
Scanner->>SessionTest: run_all_tests()
loop For each of 6 tests
SessionTest->>SessionTest: Execute test
SessionTest->>SessionTest: Collect evidence
SessionTest->>SessionTest: Calculate CVSS score
SessionTest-->>Scanner: TestResult object
end
Scanner->>Results: Append session vulnerabilities
Scanner->>Scanner: Generate report with session findings
Sources: wshawk/scanner_v2.py:708-732
Test Implementation Details
Test 1: Token Reuse Detection
Purpose: Validates that session tokens are properly invalidated after logout or session termination.
Method:
- Authenticate and obtain a valid session token
- Establish a WebSocket connection with the token
- Perform a logout action or close the connection
- Attempt to reconnect using the same token
- Verify that the server rejects the stale token
Vulnerability Indicators:
- Successful reconnection with invalidated token
- Access to protected resources after logout
- Token remains valid indefinitely
CVSS Vector Example: AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N (Critical: 9.1)
Test 2: Impersonation Testing
Purpose: Verifies that session tokens are bound to specific user identities and cannot be used to access other users' sessions.
Method:
- Authenticate as User A and obtain token_A
- Authenticate as User B and obtain token_B
- Connect as User A with token_A
- Attempt to substitute token_B while maintaining the connection
- Request User B's private data using User A's connection
- Verify that the server enforces user identity binding
Vulnerability Indicators:
- Successful access to User B's data from User A's session
- Token substitution accepted without re-authentication
- Cross-user data leakage
CVSS Vector Example: AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N (High: 8.1)
Test 3: Privilege Escalation
Purpose: Ensures that tokens with lower privilege levels cannot perform administrative or elevated actions.
Method:
- Authenticate as a standard user with limited privileges
- Establish a WebSocket connection
- Attempt to execute administrative commands (e.g., delete all users, modify system settings)
- Check if the server enforces role-based access control (RBAC)
Vulnerability Indicators:
- Low-privilege token can execute admin commands
- No role validation on privileged operations
- Horizontal or vertical privilege escalation
CVSS Vector Example: AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H (Critical: 9.9)
Test 4: Session Fixation
Purpose: Tests if the application accepts attacker-supplied session tokens, allowing session fixation attacks.
Method:
- Generate a token with a predictable or attacker-controlled value
- Attempt to authenticate using the pre-set token
- Check if the server accepts the fixed token instead of generating a new one
- Verify that the server regenerates tokens on authentication
Vulnerability Indicators:
- Server accepts attacker-supplied tokens
- Token not regenerated after authentication
- Predictable token acceptance
CVSS Vector Example: AV:N/AC:H/PR:N/UI:R/S:U/C:H/I:H/A:N (High: 7.1)
Test 5: Token Predictability Analysis
Purpose: Analyzes token generation to detect weak randomness or predictable patterns that could allow token guessing.
Method:
- Collect multiple session tokens (10-50 samples)
- Perform statistical analysis:
- Entropy calculation using Shannon's formula
- Sequential pattern detection
- Timestamp correlation analysis
- Character distribution analysis
- Compare against cryptographic randomness standards (minimum 128 bits entropy)
Vulnerability Indicators:
- Token entropy below 100 bits
- Sequential or incremental tokens
- Timestamp-based tokens without sufficient randomness
- Predictable character patterns
CVSS Vector Example: AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N (High: 7.4)
Analysis Techniques:
Entropy (H) = -Σ(p(x) × log₂(p(x)))
where p(x) is the probability of character x appearing in the token
Test 6: Timeout Validation
Purpose: Verifies that sessions expire after defined inactivity periods, preventing indefinite session persistence.
Method:
- Authenticate and establish a session
- Note the configured timeout value (or test with common values: 15, 30, 60 minutes)
- Remain idle for the timeout duration
- Attempt to perform an action after the timeout
- Verify that the session is terminated and requires re-authentication
Vulnerability Indicators:
- Sessions never expire
- Timeout not enforced on the server side
- Client-side timeout bypassed
- Timeout value excessively long (> 8 hours)
CVSS Vector Example: AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N (Medium: 6.5)
Sources: README.md:44, wshawk/scanner_v2.py:713-732
Configuration and Authentication
Authentication Configuration
The SessionHijackingTester accepts an auth_config parameter to support custom authentication flows. This replaced the hardcoded user1/pass1 credentials in version 2.0.3.
Configuration Structure:
auth_config = {
'method': 'websocket', # or 'http'
'credentials': [
{'username': 'user1', 'password': 'pass1', 'role': 'user'},
{'username': 'admin', 'password': 'admin123', 'role': 'admin'}
],
'auth_message_format': {
'type': 'authenticate',
'username': '{username}',
'password': '{password}'
},
'token_extraction': {
'field': 'session_token', # JSON path to token
'location': 'response' # or 'header', 'cookie'
},
'timeout_seconds': 1800 # Expected session timeout
}
Integration Points
graph LR
Config["auth_config Dictionary"]
Scanner["WSHawkV2"]
Tester["SessionHijackingTester"]
WSConnection["WebSocket<br/>Connection"]
HTTPAuth["HTTP Auth<br/>Endpoint"]
Config -->|"passed to"| Scanner
Scanner -->|"SessionHijackingTester(url, auth_config)"| Tester
Tester -->|"if method='websocket'"| WSConnection
Tester -->|"if method='http'"| HTTPAuth
WSConnection -->|"sends auth_message_format"| WSConnection
HTTPAuth -->|"POST credentials"| HTTPAuth
WSConnection -->|"extracts token"| Tester
HTTPAuth -->|"extracts token"| Tester
Sources: CHANGELOG.md:89-90, wshawk/scanner_v2.py:712-714
Result Structure
TestResult Object
Each session test returns a TestResult object with the following attributes:
| Attribute | Type | Description |
|-----------|------|-------------|
| is_vulnerable | bool | Whether the test detected a vulnerability |
| vuln_type | Enum | Type identifier (e.g., TOKEN_REUSE, IMPERSONATION) |
| confidence | str | Confidence level: CRITICAL, HIGH, MEDIUM, LOW |
| description | str | Human-readable description of the finding |
| evidence | dict | Evidence artifacts (tokens, responses, timing data) |
| recommendation | str | Remediation guidance |
| cvss_score | float | CVSS v3.1 base score (0.0-10.0) |
Integration with Main Scan Results
Session vulnerabilities are appended to the main vulnerabilities list with a type prefix:
self.vulnerabilities.append({
'type': f'Session Security: {result.vuln_type.value}',
'severity': result.confidence,
'confidence': result.confidence,
'description': result.description,
'payload': 'N/A',
'response_snippet': str(result.evidence)[:200],
'recommendation': result.recommendation,
'cvss_score': result.cvss_score
})
Sources: wshawk/scanner_v2.py:717-728
CVSS Scoring Methodology
Session hijacking vulnerabilities are scored using CVSS v3.1 with the following base metrics:
Scoring Guidelines
| Vulnerability Type | Attack Vector (AV) | Attack Complexity (AC) | Privileges Required (PR) | User Interaction (UI) | Typical Score Range | |--------------------|-------------------|------------------------|--------------------------|----------------------|---------------------| | Token Reuse | Network (N) | Low (L) | None (N) | None (N) | 8.5-9.1 (Critical) | | Impersonation | Network (N) | Low (L) | Low (L) | None (N) | 7.5-8.1 (High) | | Privilege Escalation | Network (N) | Low (L) | Low (L) | None (N) | 9.0-9.9 (Critical) | | Session Fixation | Network (N) | High (H) | None (N) | Required (R) | 6.5-7.1 (High) | | Token Predictability | Network (N) | High (H) | None (N) | None (N) | 6.5-7.4 (High) | | Timeout Issues | Network (N) | Low (L) | None (N) | None (N) | 5.0-6.5 (Medium) |
Confidentiality, Integrity, Availability (CIA):
- C:H (High) - Session hijacking exposes user data
- I:H (High) - Attackers can modify data as the victim
- A:N/L (None/Low) - Typically no direct availability impact
Scope (S):
- Unchanged (U) - Typically contained to the vulnerable application
- Changed (C) - If privilege escalation affects other systems
Sources: wshawk/scanner_v2.py:727, README.md:46
Usage Examples
Basic Execution (Automatic)
Session hijacking tests run automatically during a full scan:
# Standard scan with session tests
wshawk ws://target.com
# Advanced scan with all features
wshawk-advanced ws://target.com --full
The scanner automatically invokes the session tester at wshawk/scanner_v2.py:712-714:
session_tester = SessionHijackingTester(self.url)
session_results = await session_tester.run_all_tests()
Programmatic Usage with Custom Authentication
import asyncio
from wshawk.scanner_v2 import WSHawkV2
# Define custom authentication
auth_config = {
'method': 'websocket',
'credentials': [
{'username': 'testuser', 'password': 'testpass', 'role': 'user'},
{'username': 'testadmin', 'password': 'adminpass', 'role': 'admin'}
],
'auth_message_format': {
'action': 'login',
'username': '{username}',
'password': '{password}'
},
'token_extraction': {
'field': 'token',
'location': 'response'
},
'timeout_seconds': 900
}
# Create scanner with auth config
scanner = WSHawkV2(
url="ws://target.com/socket",
auth_sequence=auth_config # Passed to SessionHijackingTester
)
# Run scan (session tests included automatically)
asyncio.run(scanner.run_heuristic_scan())
Report Output
Session vulnerabilities appear in the HTML report under a dedicated section:
Session Security Findings:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
[CRITICAL] Session Security: TOKEN_REUSE
CVSS Score: 9.1
Description: Session token remains valid after logout. Token 'abc123...'
successfully reconnected after explicit logout action.
Evidence: {'token': 'abc123...', 'logout_response': '{"status":"ok"}',
'reuse_response': '{"status":"authenticated"}'}
Recommendation: Invalidate session tokens server-side on logout.
Implement token blacklisting or store logout timestamps.
Sources: wshawk/scanner_v2.py:709-732, README.md:177-186
Best Practices and Limitations
Testing Considerations
- Authentication Timing: Session tests may take 5-10 minutes depending on timeout values being tested
- Multiple Accounts Required: Impersonation and privilege escalation tests require at least 2 accounts with different roles
- State Management: Tests are stateful and may affect other concurrent sessions on the target
- Rate Limiting: Session tests respect the scanner's rate limiter but may still trigger account lockouts
Remediation Priorities
Based on CVSS scores, address vulnerabilities in this order:
- Critical (9.0-10.0): Privilege Escalation, Token Reuse
- High (7.0-8.9): Impersonation, Session Fixation, Token Predictability
- Medium (4.0-6.9): Timeout Configuration Issues
Known Limitations
- Cannot test multi-factor authentication (MFA) flows automatically
- Does not test client-side token storage security
- Requires explicit logout functionality to test token invalidation
- Token predictability analysis requires sufficient samples (minimum 10 tokens)
Sources: wshawk/scanner_v2.py:708-732, CHANGELOG.md:89-90
See Also
- Vulnerability Detection Overview - Complete list of all vulnerability types detected by WSHawk
- Defensive Validation - Blue team validation tests including CSWSH
- CVSS Scoring System - Detailed CVSS v3.1 methodology
- Advanced CLI Options - Command-line flags for session testing configuration