highCWE-306A01:2021

WebSocket Without Authentication

WebSocket endpoints that accept connections without verifying authentication allow unauthenticated users to receive real-time data streams meant for authenticated users.

How It Works

HTTP requests are authenticated per-request via cookies or Authorization headers. WebSocket upgrades happen once — if you don't verify the user's identity during the upgrade handshake, any client that can reach the endpoint gets a persistent connection. Once connected without auth, they receive every broadcast message sent to that channel.

Vulnerable Code
// BAD: WebSocket server with no authentication check on connection
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
  // no auth check — any client gets a real-time stream
  ws.send(JSON.stringify(await getPrivateFeed()));
});
Secure Code
// GOOD: verify auth token during WebSocket upgrade
const wss = new WebSocketServer({ noServer: true });

httpServer.on('upgrade', async (req, socket, head) => {
  const token = new URL(req.url, 'ws://base').searchParams.get('token');
  const user = await verifyToken(token);
  if (!user) { socket.destroy(); return; } // reject unauthenticated upgrades
  wss.handleUpgrade(req, socket, head, (ws) => {
    wss.emit('connection', ws, req, user);
  });
});

Real-World Example

Several real-time chat and trading platforms have had WebSocket vulnerabilities where connecting without authentication granted access to other users' private channels. Trading platforms are especially targeted because real-time order flow data has direct financial value.

How to Prevent It

  • Authenticate the WebSocket connection during the HTTP upgrade handshake — before the connection is established
  • Pass an auth token as a query parameter or sub-protocol header during the ws:// upgrade
  • Validate the token server-side and reject the upgrade if invalid (socket.destroy())
  • Associate every WebSocket connection with a user ID and filter broadcast messages so users only receive their own data

Affected Technologies

Node.jsjavascript

Data Hogo detects this vulnerability automatically.

Scan Your Repo Free

Related Vulnerabilities