Introduction
WebSocket is an application-layer protocol that enables two-way communication between WebSocket clients and servers. Understanding how WebSockets work will help us identify vulnerabilities in web applications that utilize them.
What are WebSockets?
The Problem with HTTP/1.1
Before HTTP/2, servers could only send data in response to a client's request. Servers had no means of pushing data to clients unconditionally.
HTTP/1.1 Chat Room Example
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HTTP/1.1 Chat (Polling Required) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β Alice sends message: β
β POST /chat/bob {"message": "Hello Bob"} β Server β 200 OK β
β β
β Bob must POLL for messages: β
β GET /messages β Server β {"messages": []} β
β GET /messages β Server β {"messages": []} β
β GET /messages β Server β {"messages": ["Hello Bob"]} β Finally! β
β β
β Problem: Lots of unnecessary traffic, inefficient β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββWebSocket Solution
WebSocket enables full-duplex (bi-directional) message transmission:
No polling required
Messages sent/received instantly
Connection remains open for extended period
Either party can send data at any time
WebSocket Protocol Schemes
ws://
WebSocket over unencrypted HTTP (insecure)
wss://
WebSocket over encrypted HTTPS (secure)
HTTP server β typically
ws://(insecure)HTTPS server β should use
wss://(encrypted)
WebSocket Connection Establishment
Step 1: Client Initiates Handshake
JavaScript example:
HTTP request sent:
Important Request Headers
Connection
Upgrade
Indicates intent to upgrade connection
Upgrade
websocket
Specifies WebSocket protocol
Sec-WebSocket-Version
13
WebSocket protocol version (13 is latest)
Sec-WebSocket-Key
<unique_value>
Confirms client wants WebSocket (no security)
Origin
http://websockets.htb
Used for security purposes
Step 2: Server Responds
Response Headers
Status
101 Switching Protocols
WebSocket connection established
Connection
Upgrade
Confirms upgrade
Upgrade
websocket
Confirms WebSocket
Sec-WebSocket-Accept
<derived_value>
Derived from client's Sec-WebSocket-Key; confirms server accepts
Step 3: Connection Established
After server response, WebSocket connection is open. Messages can be exchanged freely in both directions!
Summary
Last updated