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:
1 parent
99db28e2e2
commit
50a489e316
12 files changed
+264
-40
No files matched your search
@@ -4933,7 +4933,9 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
|
||||
std::string certPem;
|
||||
if (!restore) {
|
||||
CInputDialog dlg(this);
|
||||
dlg.Init(_TR("协议切换"), _TR("请输入反向代理入口(域名:端口,例如 ws.example.com:443):"));
|
||||
// 提示语只能用关键信息:IDC_STATIC_INPUT_PROMPT 宽 81 个对话框单位(约 121 px),
|
||||
// 放不下完整句子,超出的部分会被直接裁掉。
|
||||
dlg.Init(_TR("协议切换"), _TR("反代入口(域名:端口):"));
|
||||
dlg.SetHistoryKey("proto_entry");
|
||||
CString lastEntry = THIS_CFG.GetStr("ws", "Entry", "").c_str();
|
||||
if (!lastEntry.IsEmpty()) dlg.m_str = lastEntry;
|
||||
|
||||
@@ -1009,6 +1009,7 @@ BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
delete ContextObject->tls;
|
||||
ContextObject->tls = NULL;
|
||||
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
|
||||
return FALSE;
|
||||
}
|
||||
CloseHandle(h);
|
||||
@@ -1066,23 +1067,46 @@ DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam)
|
||||
Mprintf("[WS] %s upgraded via reverse proxy, real client %s\n",
|
||||
ctx->GetPeerName().c_str(), fwd.c_str());
|
||||
ctx->SetPeerName(fwd);
|
||||
}
|
||||
ctx->wsState.store(WS_Ready, std::memory_order_release);
|
||||
|
||||
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
|
||||
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
|
||||
if (!pending.empty()) {
|
||||
ZSTD_DCtx* dctx = ZSTD_createDCtx();
|
||||
z_stream z = {};
|
||||
inflateInit2(&z, 15);
|
||||
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
|
||||
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
|
||||
inflateEnd(&z);
|
||||
ZSTD_freeDCtx(dctx);
|
||||
if (r < 0) {
|
||||
ok = false;
|
||||
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
|
||||
// 两段式限流(与 Go 端 limitDirectPeer / handleConnection 同构)。accept 阶段按
|
||||
// getpeername 计的那一次对经反代的连接没有意义:反代同机时对端是回环地址,
|
||||
// IPWhitelist 对回环恒为 true,黑名单 / 封禁 / 计数全部不生效。真实设备 IP 到
|
||||
// 这里才知道,所以在这里按真实 IP 重做一次。直连连接(fwd 为空)在 accept 阶段
|
||||
// 已经计过数,不重复计数。
|
||||
bool blocked = This->IsIPBlacklisted(fwd);
|
||||
if (!blocked) {
|
||||
blocked = This->IsIPBanned(fwd);
|
||||
if (!blocked) {
|
||||
This->RecordConnection(fwd); // 超阈值时内部会 BanIP
|
||||
blocked = This->IsIPBanned(fwd); // 本次连接把计数顶过阈值
|
||||
}
|
||||
}
|
||||
if (blocked) {
|
||||
Mprintf("[WS] real client %s rejected by IP ban/rate limit (fail-closed)\n", fwd.c_str());
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
ctx->wsState.store(WS_Ready, std::memory_order_release);
|
||||
|
||||
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
|
||||
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
|
||||
if (!pending.empty()) {
|
||||
ZSTD_DCtx* dctx = ZSTD_createDCtx();
|
||||
z_stream z = {};
|
||||
inflateInit2(&z, 15);
|
||||
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
|
||||
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
|
||||
inflateEnd(&z);
|
||||
ZSTD_freeDCtx(dctx);
|
||||
if (r < 0) {
|
||||
ok = false;
|
||||
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx->wsState.store(WS_None, std::memory_order_release);
|
||||
}
|
||||
} else {
|
||||
ctx->wsState.store(WS_None, std::memory_order_release);
|
||||
@@ -1124,6 +1148,7 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
ContextObject->FreeWs();
|
||||
ContextObject->wsState.store(WS_None, std::memory_order_release);
|
||||
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
|
||||
return FALSE;
|
||||
}
|
||||
CloseHandle(h);
|
||||
@@ -1132,6 +1157,18 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
|
||||
|
||||
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
|
||||
{
|
||||
// 握手线程独占 socket(TLS 或 WS 升级期间):正常不应出现 IORead,出现即属异常,fail-closed。
|
||||
// 必须放在函数最开头——WSS 升级时 tlsState 已经是 TLS_Ready,若把判断放在 TLS 分支之后,
|
||||
// 这段字节会先走解密分支再进 DispatchPlain,被当成业务协议解析,同时与握手线程并发读
|
||||
// 同一个 socket。放在最前面才能同时覆盖明文与 TLS 两条路径。
|
||||
if (ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
|
||||
Mprintf("[WS] unexpected IORead during handshake for %s (closing)\n",
|
||||
ContextObject->GetPeerName().c_str());
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
|
||||
int st = ContextObject->tlsState.load(std::memory_order_acquire);
|
||||
|
||||
// ---- 未分类:按 ClientHello 头嗅探明文 / TLS(见设计文档 §5.2)----
|
||||
@@ -1210,8 +1247,9 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// TLS_Handshaking / WS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
|
||||
if (st == TLS_Handshaking || ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
|
||||
// TLS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
|
||||
// (WS_Handshaking 在函数开头已判定,不在这里。)
|
||||
if (st == TLS_Handshaking) {
|
||||
Mprintf("[TLS] unexpected IORead during handshake for %s (closing)\n",
|
||||
ContextObject->GetPeerName().c_str());
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
@@ -1399,8 +1437,14 @@ BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
|
||||
// 客户端解密后得到的是「旧 TLS 记录」→ Unknown header 17 03 03。故只加密本次新追加的尾部。
|
||||
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
|
||||
// WS(含 WSS):同样只处理本次新追加的尾部——前缀可能还有在途未发完的帧/密文。
|
||||
bool wsReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready) &&
|
||||
ContextObject->ws != NULL && ContextObject->ws->IsOpen();
|
||||
const bool wsStateReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready);
|
||||
if (wsStateReady && (ContextObject->ws == NULL || !ContextObject->ws->IsOpen())) {
|
||||
// 升级过 WS 但会话已关(Feed 报错 / 收到 close)而状态还没降级:绝不能把应用字节
|
||||
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,由接收路径的 RemoveStaleContext 收尾。
|
||||
Mprintf("[WS] session closed for %s, dropping send\n", ContextObject->GetPeerName().c_str());
|
||||
return FALSE;
|
||||
}
|
||||
bool wsReady = wsStateReady;
|
||||
ULONG oldLen = (tlsReady || wsReady) ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
|
||||
|
||||
if (WriteContextData(ContextObject, szBuffer, ulOriginalLength, ContextObject->Zcctx)) {
|
||||
|
||||
@@ -279,7 +279,7 @@ Web
|
||||
通用=Allgemein
|
||||
高级 (非必填项)=Erweitert (Optional)
|
||||
提示: 多个上线地址用分号分隔,99个字符以内。仅供学习和自用,严禁用于非法目的使用。=Tipp: Mehrere Adressen durch Semikolons getrennt, max. 99 Zeichen.
|
||||
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名;服务端须为Go版本。=Tipp: WebSocket benoetigt einen Reverse-Proxy (z. B. nginx auf 443), der auf den Steuerungsport weiterleitet; als Adresse die Domain eintragen; der Server muss die Go-Version sein.
|
||||
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。=Tipp: WebSocket benoetigt einen Reverse-Proxy (z. B. nginx auf 443), der auf den Steuerungsport weiterleitet; als Adresse die Domain eintragen.
|
||||
|
||||
; ============================================
|
||||
; Service Manager
|
||||
@@ -2115,6 +2115,18 @@ TLS
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
|
||||
读取服务端 TLS 证书失败,无法下发=Server-TLS-Zertifikat konnte nicht gelesen werden; Verteilung nicht moeglich
|
||||
; ===== Protokollwechsel (Protocol Switch) =====
|
||||
协议切换=Protokollwechsel
|
||||
直连 TCP=Direktes TCP
|
||||
WS(经反向代理,明文)=WS (ueber Reverse-Proxy, Klartext)
|
||||
WSS(经反向代理,TLS)=WSS (ueber Reverse-Proxy, TLS)
|
||||
反代入口(域名:端口):=Proxy (Domain:Port):
|
||||
反向代理入口格式不正确,应为 域名:端口=Ungueltiger Reverse-Proxy-Eingang; erwartet wird Domain:Port
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=Server-TLS-Zertifikat ist nicht aktiviert; Wechsel zu WSS nicht moeglich
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=Server-TLS-Zertifikat konnte nicht gelesen werden; Wechsel zu WSS nicht moeglich
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Einige ausgewaehlte Hosts laufen mit einem Client ohne Protokollwechsel-Unterstuetzung (neuerer Client erforderlich)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Ausgewaehlte Hosts zurueck auf direktes TCP schalten?\n(Clients verbinden sich sofort neu; ist der direkte Port nicht erreichbar, fallen sie nach 5 Minuten auf den aktuellen Eingang zurueck)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Transportprotokoll der ausgewaehlten Hosts umschalten?\n(Clients verbinden sich sofort neu, laufende Sitzungen werden unterbrochen; ist der neue Eingang 5 Minuten lang nicht erreichbar, wird automatisch zurueckgefallen)
|
||||
白名单=Whitelist
|
||||
确定将选中日志中的 IP 加入白名单吗?=IP aus den ausgewaehlten Log-Eintraegen zur Whitelist hinzufuegen?
|
||||
已将 %d 个 IP 加入白名单=%d IP(s) zur Whitelist hinzugefuegt
|
||||
|
||||
@@ -2162,7 +2162,7 @@ Y
|
||||
直连 TCP=Direct TCP
|
||||
WS(经反向代理,明文)=WS (via reverse proxy, plaintext)
|
||||
WSS(经反向代理,TLS)=WSS (via reverse proxy, TLS)
|
||||
请输入反向代理入口(域名:端口,例如 ws.example.com:443):=Enter the reverse proxy entry (host:port, e.g. ws.example.com:443):
|
||||
反代入口(域名:端口):=Proxy (host:port):
|
||||
反向代理入口格式不正确,应为 域名:端口=Invalid reverse proxy entry; expected host:port
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=Server TLS certificate is not enabled; cannot switch to WSS
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=Failed to read the server TLS certificate; cannot switch to WSS
|
||||
|
||||
@@ -2153,7 +2153,7 @@ Y
|
||||
直连 TCP=直連 TCP
|
||||
WS(经反向代理,明文)=WS(經反向代理,明文)
|
||||
WSS(经反向代理,TLS)=WSS(經反向代理,TLS)
|
||||
请输入反向代理入口(域名:端口,例如 ws.example.com:443):=請輸入反向代理入口(網域:連接埠,例如 ws.example.com:443):
|
||||
反代入口(域名:端口):=反代入口(網域:埠):
|
||||
反向代理入口格式不正确,应为 域名:端口=反向代理入口格式不正確,應為 網域:連接埠
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=伺服器未啟用 TLS 憑證,無法切換到 WSS
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=讀取伺服器 TLS 憑證失敗,無法切換到 WSS
|
||||
|
||||
Reference in new issue
Block a user