Back
+30 XP
Concept

WebSocket Frame Encoder (RFC 6455)

WebSocket frames encapsulate payload data with bitfields for FIN, opcode, mask flag, and variable-length payload lengths (7-bit, 16-bit, or 64-bit). Client-to-server frames must be XOR-masked with a 4-byte key to prevent malicious intermediary cache poisoning.

python
# XOR masking algorithm:
masked = bytes(b ^ mask_key[i % 4] for i, b in enumerate(payload))

# WebSocket Frame Encoder (RFC 6455) The WebSocket protocol (RFC 6455) allows full-duplex communication over a single TCP socket. Unlike HTTP/1.1 which sends verbose headers per message, WebSocket frames start with a compact 2-byte base header. 🌐⚡ - **Byte 0**: FIN bit (`0x80`) indicating the final fragment, followed by a 4-bit Opcode (`0x1` text, `0x2` binary, `0x8` close, `0x9` ping). - **Byte 1**: MASK bit (`0x80`) and 7-bit length: - $< 126$: exact length. - $126$: followed by 2-byte length (`>H`). - $127$: followed by 8-byte length (`>Q`). - **Mask Key**: If masked (mandatory from browser clients), 4 random bytes follow the length, and payload bytes are XOR-masked: `payload[i] ^ mask_key[i % 4]`. ```python import struct # Example unmasked text frame header for 'Hi' header = bytes([0x81, 0x02]) + b"Hi" ``` ## Pop Quiz Why does RFC 6455 mandate that all client-to-server WebSocket frames must be XOR-masked with a random 4-byte key? - [ ] To prevent malicious browser scripts from poisoning intermediary transparent proxy caches with predictable byte patterns. - [ ] To encrypt WebSocket traffic without requiring TLS/HTTPS certificates. - [ ] Because Ethernet network interface cards cannot parse unmasked websocket headers. - [ ] To compress UTF-8 text strings by 50% across mobile cellular networks. ## Real-World Challenge Implement `encode_ws_frame(payload: bytes, opcode: int = 0x01, mask_key: bytes = None) -> bytes`. - If `mask_key` is provided (must be 4 bytes), set the mask bit in byte 1, append the mask key to the header, and XOR-mask the payload. - If `mask_key` is `None`, leave the mask bit 0 and append raw payload. - Correctly encode payloads with length $< 126$ and $126 \le \text{length} \le 65535$. <details> <summary>Solution</summary> ```python import struct def encode_ws_frame(payload: bytes, opcode: int = 0x01, mask_key: bytes = None) -> bytes: # FIN bit set (0x80) + 4-bit opcode byte0 = 0x80 | (opcode & 0x0F) length = len(payload) is_masked = mask_key is not None mask_bit = 0x80 if is_masked else 0x00 if length < 126: header = bytes([byte0, mask_bit | length]) elif length <= 0xFFFF: header = bytes([byte0, mask_bit | 126]) + struct.pack(">H", length) else: header = bytes([byte0, mask_bit | 127]) + struct.pack(">Q", length) if is_masked: if len(mask_key) != 4: raise ValueError("mask_key must be exactly 4 bytes") masked_payload = bytes(b ^ mask_key[i % 4] for i, b in enumerate(payload)) return header + mask_key + masked_payload else: return header + payload # Verification # 1. Unmasked short frame frame1 = encode_ws_frame(b"ping", opcode=0x09) assert frame1 == bytes([0x89, 0x04]) + b"ping" # 2. Masked short frame mask = b"\x01\x02\x03\x04" frame2 = encode_ws_frame(b"ping", opcode=0x09, mask_key=mask) assert frame2[0] == 0x89 assert frame2[1] == 0x84 # 0x80 | 4 assert frame2[2:6] == mask expected_masked = bytes(b ^ mask[i % 4] for i, b in enumerate(b"ping")) assert frame2[6:] == expected_masked # 3. Medium extended length frame (200 bytes) payload_200 = b"A" * 200 frame3 = encode_ws_frame(payload_200, opcode=0x02) assert frame3[0] == 0x82 assert frame3[1] == 126 declared_len, = struct.unpack(">H", frame3[2:4]) assert declared_len == 200 assert len(frame3) == 4 + 200 ``` </details>