A WebSocket is an HTTP upgrade followed by a long-lived bidirectional channel. The handshake still carries cookies and an Origin header, and the server must authorize both. If the server trusts the cookie but not the origin, or maps a client-supplied subprotocol to a role, any page can speak to the socket.
Browsers send cookies with cross-origin WebSocket handshakes according to cookie policy, and they always send an Origin header. A server that authenticates only by cookie allows cross-site WebSocket hijacking: attacker JavaScript opens a socket to the victim host, rides the victim's session and reads or sends messages. A server that accepts Origin: null trusts sandboxed iframes. A server that treats a requested subprotocol as a role lets the client choose its own privilege.
Developers think of the socket as an internal channel after login and forget that the handshake is a cross-origin HTTP request. The browser is happy to open it from any page that knows the URL.
What is actually at stake?
Before touching a payload, map the assets, the actors and the boundary that is supposed to protect them. A finding only becomes a vulnerability when you can connect the failed boundary to a real asset.
Assets
- Private messages, support notes and administrator inboxes
- State-changing socket actions such as refunds or role changes
- Session cookies and socket tickets
- Tenant or user identifiers carried in messages
- Presence and typing data that reveals other users
Actors
- Attacker who can lure a victim to a page on another origin
- Malicious client that can send a raw handshake without a browser
- Sandboxed iframe that produces Origin: null
- Authenticated low-privilege user who can choose a subprotocol or role field
Trust boundaries
- Browser page origin to WebSocket handshake
- Cookie jar to handshake request
- Handshake authentication to per-message authorization
- Subprotocol negotiation to server-side role mapping
- Socket channel to shared back-end state
Abuse cases
- Open a cross-origin WebSocket with the victim's cookie and no Origin check
- Use a sandboxed iframe so the handshake carries Origin: null
- Request an admin subprotocol and receive administrator messages
- Send a first message with role=admin that the server trusts
- Leak a socket ticket through a URL and replay it from another origin
Follow the decision, not the payload
Every family has a moment where trusted data becomes an authorization, parsing or state decision. Learn to point at that moment in the request path.
- 01
Upgrade
The browser sends GET /ws with Upgrade: websocket, a key, cookies and an Origin header.
- 02
Authorize
The server authenticates the cookie or ticket and decides whether the origin may open a socket.
- 03
Negotiate
The server selects a subprotocol and returns 101 with Sec-WebSocket-Accept and the chosen protocol.
- 04
Message
Client and server exchange frames; the server must authorize every action, not just the connection.
- 05
Impact
A hijacked or self-elevated socket reads private messages or performs actions with the victim's or an admin role.
Cross-Site WebSocket Hijacking (CSWSH)
Christian Schneider, Cross-Site WebSocket Hijacking, 2017Christian Schneider documented how WebSocket endpoints that authenticated only by cookie could be opened from any origin. Because the browser attaches cookies to the handshake, an attacker page could read and write the victim's socket channel.
The researcher hosted a page on a different origin that opened a WebSocket to the victim application, sent a normal application message and read the response. The server performed no Origin check, so the victim's session authorized the channel.
Attackers could read private messages, exfiltrate data and perform state-changing actions through the socket. The impact depended on what the application allowed over the channel.
The server treated the WebSocket handshake as a trusted post-login channel and never validated Origin or bound messages to the authenticated user.
Validate Origin against an exact allowlist, reject null origins, authenticate with a dedicated short-lived ticket, and authorize each message against server-side state. Do not derive roles from client-supplied subprotocols.
Read it as a chain: discovery → failed decision → impact → fix. Then ask which link would have broken earliest.
A repeatable testing sequence
- Find WebSocket endpoints and record the handshake: path, cookies, Origin policy and requested subprotocols.
- Open the socket from a different origin and observe whether the server accepts it and returns authenticated data.
- Test Origin: null through a sandboxed iframe, and test missing or duplicated Origin headers through a raw client.
- Try subprotocol, query parameter or first-message fields that the server maps to a role or tenant.
- Prove impact by reading a victim-only message or performing a state-changing socket action, not by opening an unauthenticated socket.
Where smart people get fooled
- A 101 Switching Protocols response is not proof of impact; the socket must return data or accept actions belonging to another user.
- SameSite=Lax may still allow same-site subdomains to send the cookie; test the actual site boundary instead of assuming.
- Checking Origin with a prefix or substring is fragile; compare against an exact allowlist.
- A socket that requires a token in the URL may still leak the token through logs, referrers or the page source.
What would the logs show?
A control is stronger when someone can see it fail. These signals are starting points for a detection rule, not a complete SIEM use case.
- WebSocket handshakes with an Origin that is not in the application allowlist
- Origin: null or a missing Origin header on a production socket
- A single session opening sockets from multiple unrelated origins
- Subprotocol values such as admin, internal or privileged
- Messages carrying user_id, tenant or role fields supplied by the client
index=proxy sourcetype=websocket | eval bad_origin=if(!match(origin, "^https://app\.example$"),1,0) | eval bad_proto=if(match(subprotocol, "(?i)admin|internal|privileged"),1,0) | where bad_origin=1 OR bad_proto=1 | stats count values(origin) values(subprotocol) by user, src_ipFix the decision, then prove it stays fixed
- Validate the Origin header against an exact allowlist during the handshake and reject missing or null origins.
- Authenticate the handshake with a session token, bind the socket to that user and re-check authorization for every message.
- Never map a client-supplied subprotocol, query parameter or message field directly to a role.
- Use SameSite cookies, CSRF tokens where appropriate, short-lived socket tickets and server-side channel authorization.
wss.on('connection', (socket, request) => {
const user = sessionFromCookie(request.headers.cookie);
const role = request.headers['sec-websocket-protocol'] ?? 'user';
socket.on('message', (data) => handle(data, user, role));
});wss.on('connection', async (socket, request) => {
const origin = request.headers.origin;
if (!ALLOWED_ORIGINS.has(origin)) return socket.close(1008, 'origin');
const user = await sessionFromCookie(request.headers.cookie);
if (!user) return socket.close(1008, 'auth');
socket.on('message', async (data) => {
const message = parse(data);
if (!(await can(user, message.action, message.resource))) return socket.close(1008, 'forbidden');
return handle(message, user);
});
});Validate Origin exactly, authenticate the handshake, and authorize every message against server-side state. Treat subprotocols as protocol names, never as roles or permissions.
Regression tests a reviewer would ask for
Foreign origin is rejected
GivenA WebSocket handshake with Origin: https://attacker.example
WhenThe server processes the upgrade
ThenThe handshake is rejected before any message is accepted
Null origin is rejected
GivenA sandboxed iframe opens the socket with Origin: null
WhenThe server checks the origin allowlist
ThenThe connection is closed with a policy error
Subprotocol is not a role
GivenA client requests the admin subprotocol
WhenThe server negotiates protocols
ThenThe requested protocol does not change the user's server-side role
Per-message authorization
GivenAn authenticated socket sends an action for another tenant
WhenThe server handles the message
ThenThe action is denied even though the handshake was valid
What this finding is not
Strong testers kill their own findings before someone else does. These are the shortcuts that turn a real bug into a weak report — or a false alarm into a wasted escalation.
- The server returns 101 but closes the socket before any authenticated message is exchanged.
- The handshake requires a token that the attacker page cannot obtain; a stolen cookie alone is not enough.
- The socket only broadcasts public data and accepts no user-specific action.
- Origin is absent in a raw non-browser client but the server still requires a per-message authorization token.
Terms you should be able to use precisely
- WebSocket handshake
- An HTTP Upgrade request that establishes a long-lived bidirectional connection.
- Cross-Site WebSocket Hijacking
- Using a victim's cookies from an attacker origin to open and read an authenticated WebSocket.
- Origin: null
- The serialized origin of a sandboxed or opaque document; it must not be treated as trusted.
- Subprotocol
- A name negotiated in Sec-WebSocket-Protocol to select a message format, not a permission level.
- Socket ticket
- A short-lived, single-use credential used to authenticate a WebSocket handshake without relying on ambient cookies.
- Per-message authorization
- Checking the authenticated user's permission for each socket action rather than only at connection time.
Answer these without reciting a payload
Why is a cookie alone insufficient to authorize a WebSocket?
The browser attaches cookies to cross-origin handshakes, so any page can cause the victim's browser to open the socket. The server must also validate Origin and authorize each message.
What is wrong with accepting Origin: null?
Sandboxed iframes and other opaque contexts send null. An attacker can create one, so null is not a trustworthy origin and must be rejected.
Why can a subprotocol become a privilege escalation?
The client chooses the requested subprotocol. If the server maps it to a role or tenant, the client can select a more privileged channel without any server-side authorization.
Can you separate the mechanism from the payload?
Four questions, graded on the server. Answers and explanations are released only after you submit, and signed-in learners keep a best score.
WebSocket Hijacking تحدث عندما يكتفي الخادم بالكوكي في مصافحة WebSocket دون التحقق من Origin. المتصفح يرسل الكوكي مع المصافحة، فصفحة المهاجم تفتح قناة إلى تطبيق الضحية وتقرأ رسائله. هناك نمطان إضافيان: قبول Origin: null من iframe معزول، وتحويل subprotocol يختاره العميل إلى دور إداري. الحل: قائمة Origin تامة، رفض null والغياب، تذكرة قصيرة العمر للمصافحة، وربط القناة بالجلسة، والتحقق من الصلاحية لكل رسالة وليس عند الاتصال فقط. لا تجعل أي حقل يرسله العميل مصدرًا للدور أو المستأجر.
If the handshake checks Origin correctly but every message carries a client-supplied user_id, is the socket actually authorized?