Video in progress

Why are WebSocket frames sent by the client masked, while the ones sent by the server are not?

Masking means every client frame is XORed with a random 4-byte key. It is not encryption. The point is that a malicious page can't use WebSocket to trick intermediary caching proxies into poisoning their cache.

📖 Answer

The problem arises in a browser context. JavaScript on a malicious page chooses which bytes to send over WebSocket. If the bytes traveled in the clear, it could craft a sequence that looks like a normal HTTP request, make an old proxy that doesn't understand the protocol well think "this is a new HTTP request", and get a fake response planted in its cache.

Because the mask is new and random for each frame, JavaScript can't control exactly which bytes reach the network.

On the server side there's no such risk: server code is not a foreign script in the browser. So:

  • client → server frames must be masked, otherwise the server closes the connection;
  • server → client frames must not be masked.

In practice you almost never run into this detail, since Tomcat, Jetty and Netty handle it. But if you write a low-level WebSocket client yourself, or you can't read the payload in Wireshark, this is why.