Issue
A WebSocket creates a persistent, two-way connection between a client and a server. It begins with an HTTP handshake; if the server accepts the upgrade, the connection stays open and both sides can exchange messages. WebSockets are useful for features such as chat, notifications, and live dashboards, but the application must secure both the initial connection and every message sent over it. RFC 6455, OWASP WebSocket Security Cheat Sheet
The protocol does not provide application authentication or authorization. The server must decide who may connect and what each connected user may do. It must also validate message contents, enforce resource limits, and handle session expiration and logout.
A browser sends an Origin header during the WebSocket handshake. The server should compare it against an explicit list of trusted origins. If a server accepts a user’s authenticated cookie from an untrusted website, that site may be able to open a connection in the user’s browser. This risk is called Cross-Site WebSocket Hijacking (CSWSH). The attacker’s page may then send messages through the user’s connection, subject to the application’s permissions and the browser’s cookie rules. RFC 6455, OWASP WebSocket Security Cheat Sheet
The Origin header is a browser security signal, not an authentication credential: non-browser clients can supply or forge it. Origin checks should therefore complement authentication and authorization, not replace them. WebSocket origin checks are also separate from ordinary CORS response-header checks.
Other common causes of WebSocket weaknesses include:
- Using unencrypted ws:// for traffic that needs confidentiality or integrity. Use wss:// to protect the connection with TLS.
- Accepting connections before verifying the user, or failing to check permission for each sensitive action.
- Trusting message fields such as user IDs, account IDs, or role names supplied by the client.
- Failing to limit message size, connection count, message rate, or the time a connection can remain unauthenticated.
- Rendering received messages as HTML without context-appropriate encoding.
- Logging complete messages, session identifiers, or tokens.
- Enabling compression without considering whether secret data and attacker-controlled data can be compressed together. Review the application’s threat model and implementation before deciding whether compression is appropriate.
Examples
Example handshake
A browser request may resemble:
GET /realtime HTTP/1.1Host: app.example.comUpgrade: websocketConnection: UpgradeSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==Sec-WebSocket-Version: 13Origin: https://portal.example.comCookie: session=REDACTED
An accepted handshake commonly includes:
HTTP/1.1 101 Switching ProtocolsUpgrade: websocketConnection: UpgradeSec-WebSocket-Accept: <server-calculated value>
The 101 response confirms that this handshake was upgraded. It does not prove that the server has authenticated the user correctly or will authorize later messages.
Example message authorization check
A client might send:
{"type":"read_profile","userId":"user-123"}
The server must derive the caller’s identity from its authenticated session and check whether that caller may access user-123. It must not treat the client-supplied userId as proof of identity or permission.
Illustrative browser-origin check
This browser snippet can be served from a controlled test origin to see whether a test browser can open a connection. Run it only against an authorized test endpoint and account:
<script>
const socket = new WebSocket("wss://app.example.com/realtime");
socket.addEventListener("open", () => {
console.log("Connection established");
socket.close();
});
socket.addEventListener("message", (event) => {
console.log("Received a message:", event.data);
});
socket.addEventListener("error", () => {
console.log("Connection failed");
});
</script>
An open connection alone is not proof of CSWSH impact. To confirm a vulnerability, establish that the browser sent credentials, the server accepted an untrusted origin, and the connection can read protected data or perform an unauthorized action.
Impact
The impact depends on what the server allows a connected user to do and what data it returns.
If CSWSH is confirmed, an attacker-controlled website may be able to use a victim’s browser session to read WebSocket responses or perform actions available to that session. This requires, at a minimum, that the browser sends credentials accepted by the endpoint, the server accepts the untrusted origin, and the attacker can interact with the connection. Cookie SameSite settings and other browser behavior can affect whether credentials are sent. A successful handshake by itself does not prove that private data is exposed or that sensitive actions can be performed.
Weak message authorization may let a user access another user’s data or perform actions beyond their permissions. That conclusion requires evidence that the server accepts an unauthorized request and returns protected data or carries out a restricted action.
Missing limits or inefficient message handling may contribute to resource exhaustion. The severity depends on the limits, server capacity, and cost of processing each message. A large or rapid test payload is not proof of a remotely exploitable denial-of-service condition.
Testing
1. Check connection authorization and origin validation
Open the connection from the intended and a separate origin with test sessions. Check whether the server accepts an unauthorized connection or acts on its messages.
Example: A successful handshake alone does not establish access to private messages. Verify the identity and message permissions.
GET /chat HTTP/1.1
Host: app.example.test
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://outside.example.test
Cookie: session=TEST_SESSION
2. Check message and object permissions
Send normal test messages as two accounts and change one record identifier. Inspect whether a message exposes or modifies the other account’s test data.
Example: Use two test rooms with different owners. The server must check the requested room for each message.
{"action":"read","roomId":"TEST_ROOM_B"}
3. Check session expiry, validation, and transport
Observe what happens after logout or session expiry. Review message size limits, input handling, and whether the connection uses WSS when needed.
Example: A connection left open after logout is a lead. Check whether it can still read or change protected data.
False positives include protocol errors caused by malformed test messages, normal application messages that appear sensitive but are not accessible to another user, and a rejected browser connection caused by cookie policy or an unrelated network issue.
Mitigation
Primary fixes
- Use TLS. Serve the application over HTTPS and use wss:// for WebSocket connections. This protects traffic in transit from network eavesdropping and tampering.
- Validate origins at the handshake. Compare the complete origin—scheme, hostname, and port—to an explicit allowlist. Reject missing, null, or untrusted origins unless the application has a documented reason to allow them. Avoid substring checks and broad wildcards. For non-browser clients, use authentication because they can forge Origin.
- Authenticate connections and authorize every action. Bind the connection to a server-verified identity. Check permissions for each message that reads or changes protected data; do not rely on client-supplied identity or role fields.
- Protect cookie-authenticated endpoints from CSWSH. Apply strict origin validation. Set appropriate cookie attributes, including Secure, HttpOnly, and a suitable SameSite value, as additional protection. Cookie settings do not replace origin validation or authorization.
- Handle session changes. Stop accepting protected actions when a session expires or is revoked. Close or reauthorize affected connections on logout, password change, or account disablement.
- Validate messages and constrain resources. Enforce an expected message schema, maximum payload size, rate limits, connection limits, and timeouts. Reject malformed or oversized messages safely.
- Treat received content as data. Encode output for its eventual context, and avoid inserting untrusted message content into the DOM as HTML.
- Review compression and logging. Disable compression if it is unnecessary or if the application’s threat model makes compression side channels a concern. Log connection, authentication, authorization, and validation events without recording credentials, tokens, or full sensitive message bodies.
Retest
After changes, repeat the tests with a trusted origin, an untrusted origin, missing and expired credentials, and accounts with different permissions. Confirm the server rejects unauthorized handshakes and messages, refuses access to another test user’s data, enforces size and rate limits, and closes connections when sessions are revoked. Review server-side logs to verify the decisions without exposing secrets.
Sources
- RFC 6455: The WebSocket Protocol
- OWASP WebSocket Security Cheat Sheet
- OWASP Web Security Testing Guide: Testing WebSockets
- MDN: Origin header
- MDN: Writing WebSocket client applications