From 5ee59415f90d25e37419bda8026cc0120db3b0ed Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Sat, 5 Dec 2026 10:50:50 +0100 Subject: [PATCH] Fix: throttle TLS/WS handshake failure logs Exposed ports see a constant stream of scanners and HTTP probes. Every TLS handshake attempt logged an ioctlsocket(FIONBIO=0) failure, but WSAEINVAL is the documented result once WSAEventSelect owns the listening socket and the code already falls back to select; that line alone accounted for 6678 of the 8970 "handshake" lines in a four-day log. It is now logged only for other error codes. A failed handshake used to print three or four lines (recv EOF, AcceptSecurityContext, final status, failed-for-IP) with no per-peer dedup, and WS upgrade failures printed once per HTTP probe. ServerTlsSession now records a human-readable reason (Schannel status name for ASC failures) instead of logging per connection; IOCPServer prints one line per peer per hour with the reason and a suppressed count, for both TLS and WS. Peer close_notify is a normal shutdown and is no longer logged; MCP TLS failures now carry the same reason. Failure details are copied before the context's I/O reference is released, so the log path cannot touch a context that another thread may recycle. No handshake, crypto or connection behaviour changes. Verified with a Debug x64 build and a live probe run: six failed connections to the device port produced exactly one TLS and one WS line, with no ioctlsocket lines. Co-Authored-By: deepseek-flash --- server/2015Remote/IOCPServer.cpp | 110 +++++++++++++++++++++++-- server/2015Remote/McpTlsProxy.cpp | 3 +- server/2015Remote/ServerTlsSession.cpp | 76 +++++++++++++++-- server/2015Remote/ServerTlsSession.h | 6 ++ 4 files changed, 176 insertions(+), 19 deletions(-) diff --git a/server/2015Remote/IOCPServer.cpp b/server/2015Remote/IOCPServer.cpp index 5bd72bc..5eacde3 100644 --- a/server/2015Remote/IOCPServer.cpp +++ b/server/2015Remote/IOCPServer.cpp @@ -8,6 +8,9 @@ #include #include +#include +#include +#include // 服务端 RTT 反代理(试用版执法)。声明在主对话框 cpp 中,无单独头文件。 BOOL IsTrail(const std::string& passcode); @@ -896,6 +899,54 @@ BOOL ParseReceivedData(CONTEXT_OBJECT * ContextObject, PBYTE data, DWORD dataLen return ret; } +// 握手失败日志限流。 +// +// 设备端口/WS 端口暴露在公网时,扫描器会持续制造两类噪声:只发半截 ClientHello 就 +// 断开的连接(Schannel 报 EOF / SEC_E_INTERNAL_ERROR),以及用 HTTP GET 探测端口的 +// 请求(WS 升级因缺 Upgrade 头失败)。按「(类别, 对端) 每小时一条、首条必记」输出, +// 并把窗口内被抑制的条数在下次放行时一并带出:既保留「谁在失败、失败多少」的有效 +// 信息,又不会让几千行相同日志淹没真正的问题。 +static bool ShouldLogHandshakeFailure(const char* kind, const std::string& peer, + unsigned* suppressed) +{ + const int kWindowSec = 3600; + struct Entry { time_t lastLog; unsigned pending; }; + static std::mutex s_mtx; + static std::map s_cache; + + *suppressed = 0; + const std::string key = std::string(kind) + "|" + peer; + const time_t now = time(nullptr); + + std::lock_guard lk(s_mtx); + + // 对端 IP 随机轮换时表会无限增长:超过阈值先清过期项,仍有异常量则整体重置。 + if (s_cache.size() > 2048) { + for (auto it = s_cache.begin(); it != s_cache.end(); ) { + if (now - it->second.lastLog >= kWindowSec) + it = s_cache.erase(it); + else + ++it; + } + if (s_cache.size() > 4096) + s_cache.clear(); + } + + auto it = s_cache.find(key); + if (it == s_cache.end()) { + s_cache[key] = Entry{ now, 0 }; + return true; + } + if (now - it->second.lastLog >= kWindowSec) { + *suppressed = it->second.pending; + it->second.lastLog = now; + it->second.pending = 0; + return true; + } + it->second.pending++; + return false; +} + // 握手线程参数:把嗅探阶段已收到的 ClientHello 字节与连接上下文一起移交。 struct TlsHandshakeParam { IOCPServer* server; @@ -920,11 +971,15 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam) } // 握手期间做同步 recv/send。注意:监听套接字经 WSAEventSelect 置为非阻塞后,accept 出的 - // 子套接字继承非阻塞态,FIONBIO=0 不一定能切回阻塞;ServerTlsSession::Handshake 内部已用 - // select 兜底 WSAEWOULDBLOCK,故这里仍设 FIONBIO=0 只是「尽量阻塞」的优化。 + // 子套接字继承非阻塞态,FIONBIO=0 切不回阻塞模式(文档明确如此,返回 WSAEINVAL); + // ServerTlsSession::Handshake 内部已用 select 兜底 WSAEWOULDBLOCK,故这里只是 + // 「尽量阻塞」的优化,WSAEINVAL 属预期结果,不记日志。其它错误码才值得关注。 u_long nb = 0; - if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR) - Mprintf("[TLS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", WSAGetLastError()); + if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR) { + int err = WSAGetLastError(); + if (err != WSAEINVAL) + Mprintf("[TLS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", err); + } int tmo = 15000; // 15s 握手超时 setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tmo, sizeof(tmo)); setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tmo, sizeof(tmo)); @@ -969,6 +1024,17 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam) } } + // 失败信息必须在释放引用之前取好:fetch_sub 之后对象可能被其它线程回收/复用(#215), + // 此时再解引用 ctx->tls 会读到已释放的会话。 + bool logHandshakeFailure = false; + std::string failPeer, failReason; + if (!ok && (ctx->tls == NULL || !ctx->tls->Ready())) { + logHandshakeFailure = true; + failPeer = ctx->GetPeerName(); + failReason = (ctx->tls != NULL && !ctx->tls->LastError().empty()) + ? ctx->tls->LastError() : "handshake failed"; + } + ctx->IoRefCount.fetch_sub(1); if (ok) { @@ -976,7 +1042,19 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam) This->PostRecv(ctx); // 交还 IOCP 接收 } } else { - Mprintf("[TLS] handshake failed for %s (fail-closed)\n", ctx->GetPeerName().c_str()); + // 握手本身失败时输出一行汇总(含具体原因,按对端限流);握手成功但首包解密/ + // 解析失败的情况已在各自分支记录过,这里不再重复。 + if (logHandshakeFailure) { + unsigned suppressed = 0; + if (ShouldLogHandshakeFailure("TLS", failPeer, &suppressed)) { + if (suppressed) + Mprintf("[TLS] handshake failed for %s: %s (fail-closed, +%u suppressed)\n", + failPeer.c_str(), failReason.c_str(), suppressed); + else + Mprintf("[TLS] handshake failed for %s: %s (fail-closed)\n", + failPeer.c_str(), failReason.c_str()); + } + } This->RemoveStaleContext(ctx); } return 0; @@ -1039,9 +1117,13 @@ DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam) } // 与 TLS 握手线程相同的 socket 准备工作:尽量切回阻塞,并加超时,避免慢速对端拖住线程。 + // WSAEINVAL 是预期结果(见 TLS 分支注释),不记日志。 u_long nb = 0; - if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR) - Mprintf("[WS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", WSAGetLastError()); + if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR) { + int err = WSAGetLastError(); + if (err != WSAEINVAL) + Mprintf("[WS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", err); + } int tmo = 15000; // 15s 升级超时 setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tmo, sizeof(tmo)); setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tmo, sizeof(tmo)); @@ -1054,8 +1136,18 @@ DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam) ctx->ws->Handshake(ctx->sClientSocket, tlsReady ? ctx->tls : NULL, initial, pending, ctx->GetPeerName(), &err); if (!ok) { - Mprintf("[WS] upgrade failed for %s: %s (fail-closed)\n", - ctx->GetPeerName().c_str(), err.c_str()); + // 公网端口上的 HTTP/半截握手探测会大量触发这条路径:按对端限流成一行/小时, + // 原因(缺 Upgrade/Connection/Sec-WebSocket-Key、超时等)照常输出,不再逐条刷屏。 + unsigned suppressed = 0; + const char* why = err.empty() ? "unknown" : err.c_str(); + if (ShouldLogHandshakeFailure("WS", ctx->GetPeerName(), &suppressed)) { + if (suppressed) + Mprintf("[WS] upgrade failed for %s: %s (fail-closed, +%u suppressed)\n", + ctx->GetPeerName().c_str(), why, suppressed); + else + Mprintf("[WS] upgrade failed for %s: %s (fail-closed)\n", + ctx->GetPeerName().c_str(), why); + } } bool wsTookOver = false; diff --git a/server/2015Remote/McpTlsProxy.cpp b/server/2015Remote/McpTlsProxy.cpp index 0d83300..0860703 100644 --- a/server/2015Remote/McpTlsProxy.cpp +++ b/server/2015Remote/McpTlsProxy.cpp @@ -323,7 +323,8 @@ void McpTlsProxy::ServeConn(std::shared_ptr sp) ServerTlsSession sess; if (!sess.HandshakeWithCred(client, NULL, 0, m_identity.cred)) { - Mprintf("[McpTls] TLS handshake failed; closing connection\n"); + Mprintf("[McpTls] TLS handshake failed: %s; closing connection\n", + sess.LastError().empty() ? "unknown" : sess.LastError().c_str()); CloseConn(c); return; } diff --git a/server/2015Remote/ServerTlsSession.cpp b/server/2015Remote/ServerTlsSession.cpp index 11e4018..141dfe6 100644 --- a/server/2015Remote/ServerTlsSession.cpp +++ b/server/2015Remote/ServerTlsSession.cpp @@ -650,6 +650,35 @@ static bool WaitSocketReady(SOCKET sock, bool forRead, int timeoutMs) return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0; } +// Schannel 失败码 → 名字。日志里直接看 SEC_E_ALGORITHM_MISMATCH 比 0x80090331 有用。 +static const char* SchannelStatusName(SECURITY_STATUS sc) +{ + switch (sc) + { + case SEC_E_INTERNAL_ERROR: return "SEC_E_INTERNAL_ERROR"; + case SEC_E_ALGORITHM_MISMATCH: return "SEC_E_ALGORITHM_MISMATCH"; + case SEC_E_UNTRUSTED_ROOT: return "SEC_E_UNTRUSTED_ROOT"; + case SEC_E_CERT_UNKNOWN: return "SEC_E_CERT_UNKNOWN"; + case SEC_E_CERT_EXPIRED: return "SEC_E_CERT_EXPIRED"; + case SEC_E_ILLEGAL_MESSAGE: return "SEC_E_ILLEGAL_MESSAGE"; + case SEC_E_UNSUPPORTED_FUNCTION: return "SEC_E_UNSUPPORTED_FUNCTION"; + case SEC_E_WRONG_PRINCIPAL: return "SEC_E_WRONG_PRINCIPAL"; + case SEC_E_NO_CREDENTIALS: return "SEC_E_NO_CREDENTIALS"; + case SEC_E_UNKNOWN_CREDENTIALS: return "SEC_E_UNKNOWN_CREDENTIALS"; + case SEC_E_INVALID_TOKEN: return "SEC_E_INVALID_TOKEN"; + case SEC_E_INVALID_HANDLE: return "SEC_E_INVALID_HANDLE"; + case SEC_E_ENCRYPT_FAILURE: return "SEC_E_ENCRYPT_FAILURE"; + case SEC_E_DECRYPT_FAILURE: return "SEC_E_DECRYPT_FAILURE"; + case SEC_E_MESSAGE_ALTERED: return "SEC_E_MESSAGE_ALTERED"; + case SEC_E_OUT_OF_SEQUENCE: return "SEC_E_OUT_OF_SEQUENCE"; + case SEC_E_BUFFER_TOO_SMALL: return "SEC_E_BUFFER_TOO_SMALL"; + case SEC_E_TIME_SKEW: return "SEC_E_TIME_SKEW"; + case SEC_E_QOP_NOT_SUPPORTED: return "SEC_E_QOP_NOT_SUPPORTED"; + case SEC_E_NO_AUTHENTICATING_AUTHORITY: return "SEC_E_NO_AUTHENTICATING_AUTHORITY"; + default: return "SEC_E_OTHER"; + } +} + bool ServerTlsSession::SendAll(SOCKET sock, const void* data, int len) { const BYTE* p = (const BYTE*)data; @@ -679,6 +708,8 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i CredHandle cred) { std::lock_guard lk(m_mtx); + m_lastStatus = SEC_E_OK; + m_lastError.clear(); if (m_ctxValid) CloseHandles(); // 防御:会话应只握手一次 @@ -708,8 +739,9 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i { if (!WaitSocketReady(sock, true, 15000)) { - r = SOCKET_ERROR; - break; // 等可读超时 + m_lastStatus = SEC_E_INTERNAL_ERROR; + m_lastError = "timeout waiting for handshake bytes"; + return false; // 等可读超时 } continue; } @@ -717,7 +749,12 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i } if (r <= 0) { - Mprintf("[TLS] handshake recv failed/EOF (r=%d err=%d)\n", r, WSAGetLastError()); + // 失败原因交给调用方汇总成一行日志;这里不再逐连接打印。 + char msg[96]; + sprintf_s(msg, sizeof(msg), "peer closed mid-handshake (recv r=%d err=%d)", + r, (int)WSAGetLastError()); + m_lastStatus = SEC_E_INTERNAL_ERROR; + m_lastError = msg; return false; } buf.insert(buf.end(), (BYTE*)raw, (BYTE*)raw + r); @@ -739,13 +776,19 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i } if (hs[0] != 0x16) { - Mprintf("[TLS] handshake: first byte 0x%02x is not a handshake record; fail-closed\n", hs[0]); + char msg[96]; + sprintf_s(msg, sizeof(msg), "first byte 0x%02x is not a TLS handshake record", hs[0]); + m_lastStatus = SEC_E_ILLEGAL_MESSAGE; + m_lastError = msg; return false; } const size_t recLen = 5 + (((size_t)hs[3] << 8) | (size_t)hs[4]); if (recLen > 18432) // TLS 记录上限 16384 + 允许的额外开销 { - Mprintf("[TLS] handshake: absurd record length %u; fail-closed\n", (unsigned)recLen); + char msg[96]; + sprintf_s(msg, sizeof(msg), "absurd TLS record length %u", (unsigned)recLen); + m_lastStatus = SEC_E_ILLEGAL_MESSAGE; + m_lastError = msg; return false; } if (hs.size() >= recLen) @@ -777,6 +820,8 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i if (!ok) { sc = SEC_E_INTERNAL_ERROR; + m_lastStatus = sc; + m_lastError = "send failed during handshake"; break; } } @@ -799,8 +844,11 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i break; if (FAILED(sc) && sc != SEC_E_INCOMPLETE_MESSAGE && sc != SEC_I_INCOMPLETE_CREDENTIALS) { - Mprintf("[TLS] AcceptSecurityContext failed 0x%08x (in=%u consumed? extra=%u)\n", - (unsigned)sc, inBufs[0].cbBuffer, inBufs[1].BufferType == SECBUFFER_EXTRA ? inBufs[1].cbBuffer : 0); + char msg[128]; + sprintf_s(msg, sizeof(msg), "AcceptSecurityContext 0x%08x (%s)", + (unsigned)sc, SchannelStatusName(sc)); + m_lastStatus = sc; + m_lastError = msg; break; // 真正的失败 } @@ -813,7 +861,15 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i if (sc != SEC_E_OK) { - Mprintf("[TLS] handshake failed: final status 0x%08x (fail-closed)\n", (unsigned)sc); + // RecvMore/AcceptSecurityContext 已记录更具体的原因;仅在没有时补一条通用描述。 + if (m_lastStatus == SEC_E_OK) + { + char msg[128]; + sprintf_s(msg, sizeof(msg), "handshake failed 0x%08x (%s)", + (unsigned)sc, SchannelStatusName(sc)); + m_lastStatus = sc; + m_lastError = msg; + } if (ctxValid) DeleteSecurityContext(&ctx); return false; @@ -828,6 +884,8 @@ bool ServerTlsSession::HandshakeWithCred(SOCKET sock, const BYTE* initial, int i SecPkgContext_StreamSizes sizes = {}; if (QueryContextAttributes(&ctx, SECPKG_ATTR_STREAM_SIZES, &sizes) != SEC_E_OK) { + m_lastStatus = SEC_E_INTERNAL_ERROR; + m_lastError = "QueryContextAttributes(STREAM_SIZES) failed"; DeleteSecurityContext(&ctx); return false; } @@ -866,7 +924,7 @@ int ServerTlsSession::Decrypt(const BYTE* cipher, int len, std::vector& pl if (sc == SEC_E_INCOMPLETE_MESSAGE) break; // 记录不完整,等下一轮 WSARecv if (sc == SEC_I_CONTEXT_EXPIRED) { - Mprintf("[TLS] DecryptMessage: peer close_notify (SEC_I_CONTEXT_EXPIRED)\n"); + // 对端 close_notify:正常的 TLS 关闭,不是错误,不记日志。 return -1; // 对端 close_notify / 会话结束 } if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) { diff --git a/server/2015Remote/ServerTlsSession.h b/server/2015Remote/ServerTlsSession.h index 286fa5f..86107cd 100644 --- a/server/2015Remote/ServerTlsSession.h +++ b/server/2015Remote/ServerTlsSession.h @@ -115,6 +115,10 @@ public: bool Ready() const { return m_ready; } + // 握手失败原因(人类可读;未失败时为空)。由调用方在 Handshake* 返回 false 后输出 + // 一行汇总日志——会话内部不再逐条打印,避免公网扫描器/半截握手刷屏。 + const std::string& LastError() const { return m_lastError; } + private: void CloseHandles(); bool SendAll(SOCKET sock, const void* data, int len); @@ -125,4 +129,6 @@ private: bool m_ready = false; SecPkgContext_StreamSizes m_sizes = {}; std::vector m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节 + SECURITY_STATUS m_lastStatus = SEC_E_OK; + std::string m_lastError; // 握手失败原因,供调用方汇总输出 };