Fix: Close the gaps the WebSocket transport review found

Three of the findings only bite in deployment. First, the client's TLS and
WebSocket handshakes run synchronously on the reconnect thread with no socket
timeout, so a peer that accepts TCP and then goes quiet (black-holed proxy
upstream, middlebox that only receives) blocks recv() forever and stalls the
reconnect loop until the process is restarted. Set a 15 s SO_RCVTIMEO and
SO_SNDTIMEO for the handshake window - the same value both server handshake
threads use - and clear them once the connection is up so the worker thread's
select plus blocking recv keeps working as before.

Second, per-IP rate limiting counted the getpeername address before the real
device was known. Behind a same-host reverse proxy that address is loopback,
which IPWhitelist always trusts, so WS traffic was neither counted nor banned;
behind a remote proxy every device shares one bucket, and tripping the
threshold disconnected all of them. Count and ban by the forwarded device IP
once the upgrade resolves it, mirroring the Go server's limitDirectPeer and
handleConnection split. Direct connections keep their accept-time count and
are not counted twice.

Third, the protocol switch disarmed its five-minute auto-revert as soon as the
new entry connected, which only proves TCP/TLS/WS handshaking finished. If
login is never accepted there (wrong backend, reverse proxy pointing at some
other WS service), the revert could never fire and the client would keep
retrying a dead entry. Disarm on the first CMD_MASTERSETTING instead, which
the server only sends after adding the host to its online list, and re-check
it on every heartbeat so a late one still counts.

The smaller items came along: free the handshake parameter when CreateThread
fails in both handshake starters, move the WS_Handshaking fail-closed guard
ahead of the TLS branch so it also covers WSS (where tlsState is already
TLS_Ready), generate the frame mask from a per-channel PRNG inside the send
lock instead of an unseeded global rand(), make the transport flags and the WS
session's ready flag atomic, drop rather than send unframed application bytes
when a WS session has closed, and abort a protocol switch whose PEM fails to
load instead of moving to an entry that cannot connect.

The Go server now bounds the upgrade sniff even when ReadTimeout is zero, and
the design doc records the two-stage limiter, the login-based disarm and the
review items that stay as known limits.

The protocol switch's input prompt is cut down to "reverse-proxy entry
(host:port)" - the label static is only 81 dialog units wide, and the old
sentence ran to roughly three times that.

The three language files follow: en_US and zh_TW gain the shortened prompt and drop
the long key it replaced, the German file gains the protocol-switch block it never
had, and its WebSocket tip key is corrected - it had picked up a Go-server clause
the source string never carried, so the tip was never translated at all.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-30 18:11:34 +01:00
1 parent 99db28e2e2
commit 50a489e316
12 files changed
+264 -40

No files matched your search

+62 -5
View File
@@ -43,6 +43,9 @@ XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 W
> 兼容性:`PROTO_HTTPS` 从 5 移到 7。它在 `NewNetClient` 里本来就被直接拒绝、生成界面也从未
> 提供,因此不存在已发布客户端带 5 号协议的情况。
>
> 但这是**协议号复用**:从此任何历史落盘 / 历史配置里的 `proto=5` 一律按 `PROTO_WS` 解释。
> 老客户端与老服务端之间若曾有 `5` 的任何含义,都会在这次升级后变成 WS。
## 3. 客户端实现
@@ -65,6 +68,18 @@ XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 W
`m_useTls` 之前判 `m_useWs`;`ConnectServer` 在 socket 选项之后、`m_bConnected = TRUE` 之前
完成 `TLS 握手 → WS 握手`,`Disconnect` 清 `m_useWs` 并 `m_ws.Reset()`。
- 握手超时:`connect()` 之后、TLS/WS 握手之前给 socket 设 **15 s** `SO_RCVTIMEO`/`SO_SNDTIMEO`,
握手结束(成功路径)立刻清零。`WsChannel::Handshake` 是同步逐字节读 101 响应的;没有这道
保护时,对端接受 TCP 却不回数据(反代上游黑洞)会让 `StartClient` 的重连循环永久停摆。
服务端两个握手线程用的是同一个 15 s。
- `m_useWs` / `m_useTls` / `WsChannel::m_ready` 均为 `std::atomic<bool>`:写的一方是连接线程,
读的一方是接收/发送线程(`Disconnect` 也可能从接收线程侧清)。
- 帧掩码由 `WsChannel` 私有的 xorshift64 在 `m_sendMtx` **内**生成:不能用全局 `rand()`
——`HttpMask` 的构造函数里有 `srand(time(nullptr))`,会在同进程内重置全局序列,而收、发两个
线程都会写帧。
- 不校验 `Sec-WebSocket-Accept`(设计上由 TLS + 隧道内登录承担)。明文 `PROTO_WS` 下这意味着
中间人可以伪造 101 接管字节流——这正是「裸 WS 只适合内网」的另一半理由。
### 3.1 信任模型:不换锚,靠 SNI 分流
客户端证书校验仍是**钉死信任锚**(Windows:`CertCreateCertificateChainEngine` + `hExclusiveRoot`
@@ -193,6 +208,17 @@ WS 叠在同一层状态机之上,**与 TLS 是分层而不是并列**(`wss`
- 反代真实 IP:**仅当直接对端是回环地址**时才采信 `X-Forwarded-For` 的**最后一段**
(`X-Real-IP` 兜底),且必须是 IP 字面量;结果写回 `PeerName`,在线列表、封禁与
白名单看到的就是设备本身。非回环对端的转发头一律忽略(防伪造)。
- 两段式限流(与 Go 端 `limitDirectPeer` / `handleConnection` 同构):accept 阶段按
`getpeername` 计数——那一次对经反代的连接**没有意义**(反代同机时对端是回环地址,
`IPWhitelist` 对回环恒为 true,黑名单/封禁/计数全部不生效)。升级完成后在
`WsHandshakeThreadProc` 里按**真实设备 IP** 重做一次黑名单 / 封禁检查与计数,超阈值
直接 fail-closed。直连连接(无转发头)只在 accept 阶段计一次,不重复计。
反代**异机**部署时转发头不被采信(见 §8),此时需把反代地址加进白名单,否则所有设备
共用反代 IP 那一个计数桶。
- fail-closed 的两处:握手期间(`wsState == WS_Handshaking`)收到 IORead 直接断开(判断
放在 `OnClientReceiving` 最开头,WSS 下 `tlsState` 已是 `TLS_Ready`,放在 TLS 分支之后
就不生效);`wsState == WS_Ready` 但会话已关时,应用字节**丢弃而不是裸发**,否则对端
解帧错位。
- 既有客户端零影响:非 `GET ` 首包在攒够 6 字节后原样进入 `ParseReceivedData`。
## 5. nginx 最小改动
@@ -366,11 +392,16 @@ server {
## 8. 限制与非目标
- **MFC 服务端与 Go 服务端都已实现设备端口的 WS 嗅探**,生成界面里的协议选项两边通用;
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行),
也没有每 IP 限流的「直连/反代两段」细分(沿用既有的按连接数计)。
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行)。
每 IP 限流两边都是**两段式**(直连对端 / 反代后的真实设备),见 §4.1 与 §4.2。
- MFC 侧的转发头信任范围是**回环对端**(与 Go 的默认 `TrustedProxies` 一致);反代与服务端
不同机部署时,要么让反代用 Proxy Protocol v2(既有的 `ParseProxyProtocolV2` 会先改
`PeerName`),要么把反代地址加进白名单逻辑——目前的 WS 层不会采信非回环对端的转发头。
`PeerName`),要么把反代地址加进白名单——WS 层不采信非回环对端的转发头。此时限流按
「反代 IP」那一个桶算,**务必把反代地址加进白名单**,否则阈值一响就是全体设备一起被封。
- 试用模式的 WAN 入站检测(`m_bTrialMode && !IsPrivateIPv4Str(clientIP)`)在 accept 时判定,
经反代接入时 `clientIP` 是反代地址(回环或内网),该合规检查会被绕过;转发真实 IP 要到
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
容易发生)。
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
- macOS / Android 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443。
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
@@ -395,8 +426,34 @@ server {
- 客户端落盘(`settings` 下):`proto_override` / `entry_host` / `entry_port` /
`entry_try_at` 为当前覆盖;`base_*` 是首次切换时记下的安装入口(「还原」用它);`prev_*`
是每次切换前的入口(自动回退用它)。重连循环在建连前 `ApplyProtoSwitch` 覆盖入口——位置
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去;登录成功后
`ConfirmProtoSwitch` 把 `entry_try_at` 清零撤销计时。
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去。
- 撤销自动回退的判据是**登录被接受**,不是「连接建立」。客户端在收到
`CMD_MASTERSETTING` 时把当前连接标记为已登录(服务端只有在把本机加入在线列表之后才下发
它),重连循环每轮心跳都检查一次,命中才 `ConfirmProtoSwitch` 把 `entry_try_at` 清零。
只看 `IsConnected()` 是不够的:那只是 TCP/TLS/WS 握手完成,新入口能建连但登录始终不被
接受(选错后端 / 反代指到别的 WS 服务 / 服务端登录阶段丢弃)时,提前撤销会让自动回退
永久失效,客户端卡在错误入口反复重连。
- 随包下发的信任锚先落盘再 `TlsReload`;**加载失败即放弃本次切换**——回滚 `tls_cert`、
不写 `proto_override`/`entry_*`、不断连,并把失败原因用 `ClientMsg` 回报操作端。否则客户端
会进入 `TlsLoadError()` 的 fail-closed 状态,切过去只是「新入口连不上,等 5 分钟回退」。
- 自动回退:新入口 5 分钟内一直登不上,回到 `prev_*` 并把它改写成新的覆盖(不是清空,否则
下一轮会落进「还原」分支又跳回直连入口)。分享实例(`m_bShared`)忽略该命令——它的入口
由分享方控制。
- `ProtoSwitchPacket::certLen` 不做字节序转换:当前服务端与 Windows 客户端同为小端,无影响;
将来若出现大端平台的客户端,需要补一次 `ntohl`/`htonl`。
## 10. 审查遗留(已知边界,未改动)
以下条目来自 PR 审查,评估后保留现状,记录在此以免重复讨论:
- **`GetPeerName(SOCKET)` 只走 `sockaddr_in`(IPv4)**:`ServerWsSession.cpp::IsLoopbackPeer`
里的 `::1` / `::ffff:127.0.0.1` 分支目前是死代码。将来若监听 IPv6,转发头信任也需要跟着
改,否则会静默失效。
- **`tlsPreClassify` 名不副实**:它现在同时承担 ClientHello 嗅探与 WS 前缀("GET ")buffering。
改名会牵动状态机注释与多处引用,暂保留原名字,语义见 §4.2。
- **`DispatchPlain` 对明文首包引入「攒够 6 字节再解析」**:这是既有路径的行为变更。当前首包
是登录包(远大于 6 字节),实际无影响;极端情况下(<6 字节的合法首包)会多等一轮收包。
- **客户端不校验 `Sec-WebSocket-Accept`**:见 §3;明文 WS 下中间人可伪造 101,已在 §8 明确
裸 WS 只适合内网。
- **Go `wrapWebSocket` 的 `Peek`**:已改为即使 `ReadTimeout == 0` 也用 `wsHandshakeTimeout`
(10 s,取与 `ReadTimeout` 的较小值)封顶,慢速对端不再能长期占住 goroutine 与限流槽。