WebSocket Security
Chat, live dashboards, trading screens and multiplayer games keep a connection open so the server can push data without waiting for a request. WebSockets (RFC 6455) provide that: an ordinary HTTP request asks to "upgrade", and from then on both sides exchange messages over the same TCP (or TLS) connection. Two properties make them a security topic of their own. The handshake is a normal browser request, with cookies, that is not protected by the same-origin policy or CORS: any site can open a WebSocket to your server in the victim's browser. And after the handshake, the messages bypass most of the machinery the rest of the application relies on: no per-request middleware, no CSRF tokens, often no logging. This lesson computes the handshake from the RFC's example, then models the classic flaw, cross-site WebSocket hijacking, with its fix.
Definitions
- Upgrade handshake: the client sends
GET /chatwithConnection: Upgrade,Upgrade: websocket,Sec-WebSocket-Version: 13, a randomSec-WebSocket-Keyand (from browsers)Origin; the server answers101 Switching ProtocolswithSec-WebSocket-Accept = Base64(SHA-1(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")). The accept value proves the server speaks WebSocket; it is not authentication. ws://andwss://: cleartext and TLS. Onlywss://belongs on the Internet.- Cross-site WebSocket hijacking (CSWSH): a page on another origin opens a WebSocket to the target; the browser sends the target's cookies with the handshake; if the server authenticates by cookie and doesn't check
Origin, the attacker's page gets an authenticated, two-way channel (unlike CSRF, it can read the answers). - Frames: messages travel in frames; client-to-server frames are masked with a random key, which protects proxies from cache-poisoning tricks, not the data.
The handshake, checked against RFC 6455
RFC 6455 §1.3 gives a sample key and its accept value:
import base64, hashlib
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" # fixed by RFC 6455
def accept_for(key: str) -> str:
return base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
key = "dGhlIHNhbXBsZSBub25jZQ==" # "the sample nonce", from the RFC
print("Sec-WebSocket-Accept:", accept_for(key))
print("matches RFC 6455 section 1.3:", accept_for(key) == "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=")Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
matches RFC 6455 section 1.3: True
Nothing in this computation involves a secret: it only stops non-WebSocket clients from being confused into a WebSocket conversation. Who the client is and where it came from are left entirely to the application.
Cross-site WebSocket hijacking, modelled
The model is the server's handshake decision and its message handler. The browser side is described by the headers each handshake carries: the victim's own page, and a page on evil.example that the logged-in victim has opened. The vulnerable server authenticates by cookie only; the fixed one checks Origin against an allow-list and requires a short-lived, single-use ticket that the real page fetched over an authenticated, same-origin API call (which the attacker's page can't read).
import hashlib, base64
SESSIONS = {"sess-alice": "alice"}
TICKETS = {"tkt-91f2": "alice"} # issued by GET /api/ws-ticket (same-origin, CSRF-safe)
ALLOWED_ORIGINS = {"https://chat.lab.test"}
INBOX = {"alice": ["hi from bob", "your 2FA backup codes are ready"]}
def handshake(headers, fixed):
user = SESSIONS.get(headers.get("Cookie", "").removeprefix("sid="))
if fixed:
if headers.get("Origin") not in ALLOWED_ORIGINS:
return None, "403 origin not allowed"
user = TICKETS.pop(headers.get("ticket", ""), None) # single use
if user is None:
return None, "401 missing or used ticket"
if user is None:
return None, "401 not logged in"
return user, "101 Switching Protocols"
def on_message(user, msg):
if msg == "read inbox":
return INBOX[user]
if msg.startswith("send "):
return f"sent as {user}: {msg[5:]}"
return "unknown command"
victim_page = {"Origin": "https://chat.lab.test", "Cookie": "sid=sess-alice", "ticket": "tkt-91f2"}
attacker_page = {"Origin": "https://evil.example", "Cookie": "sid=sess-alice"} # browser adds the cookie
for fixed in (False, True):
TICKETS["tkt-91f2"] = "alice"
print("=== fixed" if fixed else "=== vulnerable")
for name, h in [("attacker page", attacker_page), ("victim page", victim_page), ("victim page, ticket replayed", victim_page)]:
user, status = handshake(dict(h), fixed)
line = f" {name:30} {status}"
if user:
line += f" -> read inbox: {on_message(user, 'read inbox')}"
print(line)=== vulnerable
attacker page 101 Switching Protocols -> read inbox: ['hi from bob', 'your 2FA backup codes are ready']
victim page 101 Switching Protocols -> read inbox: ['hi from bob', 'your 2FA backup codes are ready']
victim page, ticket replayed 101 Switching Protocols -> read inbox: ['hi from bob', 'your 2FA backup codes are ready']
=== fixed
attacker page 403 origin not allowed
victim page 101 Switching Protocols -> read inbox: ['hi from bob', 'your 2FA backup codes are ready']
victim page, ticket replayed 401 missing or used ticket
In the vulnerable version the attacker's page got a live channel as alice and read her messages; it could also send as her. The fixed version refused the foreign origin, and the ticket's single use means even a leaked ticket can't open a second connection. SameSite=Lax cookies also help, since a cross-site WebSocket handshake is not a top-level navigation, but the Origin check is the direct fix and doesn't depend on cookie settings or browser versions.
How WebSocket issues are detected
- Testing (in scope): intercept the handshake in Burp or ZAP (both proxy WebSockets and show messages); replay it with
Origin: https://evil.exampleand with the cookie but no other token; check whetherws://is accepted; send messages with other users' ids (BOLA through messages), oversized messages, malformed JSON, and injection payloads into fields that end up in HTML (stored XSS through chat) or SQL. - Code review: handshake handlers without an
Origincheck, authorization done only at connect time (a user whose role changes keeps the old rights for hours), message handlers that trust ids in the message, no size or rate limits. - Monitoring: handshakes with foreign
Originvalues, connections per user, message rates, closed-on-error counts. Log message-level security events; WebSocket traffic is invisible to ordinary access logs after the101.
How they are secured
wss://only; checkOriginagainst an exact allow-list in the handshake.- Authenticate the handshake with something the attacker's page can't send: a short-lived ticket or token in the first message or query string (single use, a few seconds valid), not cookies alone.
- Authorize every message like an API request: object-level and function-level checks, input validation with a schema.
- Limits on message size, rate and connections per user; idle timeouts; re-check authorization periodically or close connections on logout and role change.
- Encode message content where it is rendered (XSS).
Pitfalls
- Assuming CORS applies: browsers send the handshake cross-origin without any preflight; only the server's
Origincheck stops it. - Tokens in the URL (
wss://…?token=…) end up in proxy and server logs: make them single-use and short-lived if you must. - Socket.IO and similar libraries fall back to HTTP long-polling, which has its own CORS settings; check both transports.
Practice
1. What does a valid Sec-WebSocket-Accept prove to the client?
Only that the server understood the WebSocket handshake for this key (it isn't a cached or confused HTTP response). It proves nothing about identity; TLS authenticates the server, and the application authenticates the user.
2. Why is CSWSH worse than classic CSRF?
CSRF can only send requests and can't read responses. A hijacked WebSocket is two-way: the attacker's page receives every message the server pushes to the victim and can send commands as them.
Test yourself
Does the same-origin policy stop evil.example from opening a WebSocket to chat.lab.test?
- Yes, always
- No: the handshake is sent cross-origin with cookies; the server must check Origin
- Only with HTTP/2
- Only on Safari
What does Sec-WebSocket-Accept contain?
- A session token
- Base64(SHA-1(key + a fixed GUID))
- The user's password hash
- The server certificate
In the fixed model, why did the replayed ticket fail?
- Wrong origin
- Tickets are single-use and were already consumed
- The cookie expired
- SHA-1 is broken
Where must authorization happen on a WebSocket API?
- Only at the handshake
- At the handshake and on every message
- Only in the browser
- Nowhere: WebSockets are encrypted