implement per socket send locks, remove useless cipher encryption

cipher encryption is useless, we legit have the source code, someone can just add cheats to the game or hook into where the client decodes / encodes the packets, its just useless performance overhead rn
This commit is contained in:
DrPerkyLegit committed 2026-10-30 14:40:00 -04:00
1 parent c24978fed8
commit 2af29e050b
21 files changed
+22 -1644

No files matched your search

@@ -15,7 +15,6 @@
#include "../../../Minecraft.Server/ServerLogger.h"
#include "../../../Minecraft.Server/Security/SecurityConfig.h"
#include "../../../Minecraft.Server/Security/RateLimiter.h"
#include "../../../Minecraft.Server/Security/ConnectionCipher.h"
#endif
#include "../../../Minecraft.World/DisconnectPacket.h"
@@ -32,28 +31,6 @@ static bool RecvExact(SOCKET sock, BYTE* buf, int len);
static bool TryGetNumericRemoteIp(const sockaddr_in &remoteAddress, std::string *outIp);
#endif
// Raw serialized byte patterns for cipher handshake packets (CustomPayloadPacket ID 250).
// Used by recv threads to detect handshake messages at the byte level before packet parsing,
// enabling atomic cipher activation at the exact byte boundary.
// MC|CAck: 7-char channel, empty payload. Client sends this; server recv thread matches it.
static const BYTE kCipherAckPattern[] = {
0xFA, // packet ID 250
0x00, 0x07, // channel length = 7
0x00, 0x4D, 0x00, 0x43, 0x00, 0x7C, 0x00, 0x43, 0x00, 0x41, 0x00, 0x63, 0x00, 0x6B, // "MC|CAck" UTF-16BE
0x00, 0x00 // data length = 0
};
static const int kCipherAckPatternSize = sizeof(kCipherAckPattern); // 19
// MC|COn: 6-char channel, empty payload. Client recv thread matches this from server.
static const BYTE kCipherOnPattern[] = {
0xFA, // packet ID 250
0x00, 0x06, // channel length = 6
0x00, 0x4D, 0x00, 0x43, 0x00, 0x7C, 0x00, 0x43, 0x00, 0x4F, 0x00, 0x6E, // "MC|COn" UTF-16BE
0x00, 0x00 // data length = 0
};
static const int kCipherOnPatternSize = sizeof(kCipherOnPattern); // 17
SOCKET WinsockNetLayer::s_listenSocket = INVALID_SOCKET;
SOCKET WinsockNetLayer::s_hostConnectionSocket = INVALID_SOCKET;
HANDLE WinsockNetLayer::s_acceptThread = nullptr;
@@ -68,7 +45,7 @@ BYTE WinsockNetLayer::s_localSmallId = 0;
BYTE WinsockNetLayer::s_hostSmallId = 0;
unsigned int WinsockNetLayer::s_nextSmallId = XUSER_MAX_COUNT;
CRITICAL_SECTION WinsockNetLayer::s_sendLock;
CRITICAL_SECTION WinsockNetLayer::s_sendLock[MINECRAFT_NET_MAX_PLAYERS];
CRITICAL_SECTION WinsockNetLayer::s_connectionsLock;
std::vector<Win64RemoteConnection> WinsockNetLayer::s_connections;
@@ -107,12 +84,6 @@ int WinsockNetLayer::s_joinPort = 0;
BYTE WinsockNetLayer::s_joinAssignedSmallId = 0;
DisconnectPacket::eDisconnectReason WinsockNetLayer::s_joinRejectReason = DisconnectPacket::eDisconnect_Quitting;
ServerRuntime::Security::StreamCipher WinsockNetLayer::s_clientSendCipher;
ServerRuntime::Security::StreamCipher WinsockNetLayer::s_clientRecvCipher;
CRITICAL_SECTION WinsockNetLayer::s_clientCipherLock;
uint8_t WinsockNetLayer::s_clientPendingKey[ServerRuntime::Security::StreamCipher::KEY_SIZE] = {};
bool WinsockNetLayer::s_clientKeyStored = false;
bool g_Win64MultiplayerHost = false;
bool g_Win64MultiplayerJoin = false;
bool g_Win64MultiplayerQuitOnDisconnect = false;
@@ -135,14 +106,16 @@ bool WinsockNetLayer::Initialize()
return false;
}
InitializeCriticalSection(&s_sendLock);
for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) {
InitializeCriticalSection(&s_sendLock[i]);
}
InitializeCriticalSection(&s_connectionsLock);
InitializeCriticalSection(&s_advertiseLock);
InitializeCriticalSection(&s_discoveryLock);
InitializeCriticalSection(&s_disconnectLock);
InitializeCriticalSection(&s_freeSmallIdLock);
InitializeCriticalSection(&s_smallIdToSocketLock);
InitializeCriticalSection(&s_clientCipherLock);
for (int i = 0; i < 256; i++)
s_smallIdToSocket[i] = INVALID_SOCKET;
@@ -256,9 +229,9 @@ void WinsockNetLayer::Shutdown()
s_freeSmallIds.clear();
LeaveCriticalSection(&s_freeSmallIdLock);
ResetClientCipher();
DeleteCriticalSection(&s_clientCipherLock);
DeleteCriticalSection(&s_sendLock);
for (int i = 0; i < MINECRAFT_NET_MAX_PLAYERS; i++) {
InitializeCriticalSection(&s_sendLock[i]);
}
DeleteCriticalSection(&s_connectionsLock);
DeleteCriticalSection(&s_advertiseLock);
DeleteCriticalSection(&s_discoveryLock);
@@ -270,163 +243,6 @@ void WinsockNetLayer::Shutdown()
}
}
void WinsockNetLayer::StoreClientCipherKey(const uint8_t key[ServerRuntime::Security::StreamCipher::KEY_SIZE])
{
EnterCriticalSection(&s_clientCipherLock);
memcpy(s_clientPendingKey, key, ServerRuntime::Security::StreamCipher::KEY_SIZE);
s_clientKeyStored = true;
LeaveCriticalSection(&s_clientCipherLock);
}
bool WinsockNetLayer::SendAckAndActivateClientSendCipher()
{
if (s_hostConnectionSocket == INVALID_SOCKET)
return false;
// Atomic: send the MC|CAck plaintext then activate the send cipher, all under s_sendLock.
// No other send can interleave between the ack and cipher activation.
EnterCriticalSection(&s_sendLock);
// Write framed packet: 4-byte length header + ack pattern
BYTE header[4];
header[0] = static_cast<BYTE>((kCipherAckPatternSize >> 24) & 0xFF);
header[1] = static_cast<BYTE>((kCipherAckPatternSize >> 16) & 0xFF);
header[2] = static_cast<BYTE>((kCipherAckPatternSize >> 8) & 0xFF);
header[3] = static_cast<BYTE>(kCipherAckPatternSize & 0xFF);
bool ok = true;
int totalSent = 0;
while (ok && totalSent < 4)
{
int sent = send(s_hostConnectionSocket, (const char *)header + totalSent, 4 - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0) { ok = false; break; }
totalSent += sent;
}
totalSent = 0;
while (ok && totalSent < kCipherAckPatternSize)
{
int sent = send(s_hostConnectionSocket, (const char *)kCipherAckPattern + totalSent, kCipherAckPatternSize - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0) { ok = false; break; }
totalSent += sent;
}
if (ok)
{
// Activate send cipher immediately after the ack is on the wire
EnterCriticalSection(&s_clientCipherLock);
s_clientSendCipher.Initialize(s_clientPendingKey, ServerRuntime::Security::StreamCipher::Client);
LeaveCriticalSection(&s_clientCipherLock);
app.DebugPrintf("Client: Send cipher activated (MC|CAck sent)\n");
}
else
{
// Partial send corrupts the stream - force disconnect to prevent desync
app.DebugPrintf("Client: MC|CAck send failed, closing connection\n");
closesocket(s_hostConnectionSocket);
s_hostConnectionSocket = INVALID_SOCKET;
}
LeaveCriticalSection(&s_sendLock);
return ok;
}
void WinsockNetLayer::ActivateClientRecvCipher()
{
EnterCriticalSection(&s_clientCipherLock);
s_clientRecvCipher.Initialize(s_clientPendingKey, ServerRuntime::Security::StreamCipher::Client);
SecureZeroMemory(s_clientPendingKey, sizeof(s_clientPendingKey));
s_clientKeyStored = false;
LeaveCriticalSection(&s_clientCipherLock);
}
void WinsockNetLayer::ResetClientCipher()
{
EnterCriticalSection(&s_clientCipherLock);
s_clientSendCipher.Reset();
s_clientRecvCipher.Reset();
SecureZeroMemory(s_clientPendingKey, sizeof(s_clientPendingKey));
s_clientKeyStored = false;
LeaveCriticalSection(&s_clientCipherLock);
}
bool WinsockNetLayer::TryEncryptClientOutgoing(uint8_t *data, int length)
{
if (data == nullptr || length <= 0)
return false;
EnterCriticalSection(&s_clientCipherLock);
bool active = s_clientSendCipher.IsActive();
if (active)
{
s_clientSendCipher.Encrypt(data, length);
}
LeaveCriticalSection(&s_clientCipherLock);
return active;
}
#if defined(MINECRAFT_SERVER_BUILD)
bool WinsockNetLayer::SendCOnAndCommitServerCipher(BYTE smallId)
{
// Verify a pending key exists before sending MC|COn (prevents rogue ack from triggering spurious activation)
auto &registry = ServerRuntime::Security::GetCipherRegistry();
SOCKET sock = GetSocketForSmallId(smallId);
if (sock == INVALID_SOCKET)
return false;
// Verify a pending key exists before sending (rejects rogue acks)
if (!registry.HasPendingKey(smallId))
{
app.DebugPrintf("Server: Ignoring MC|CAck for smallId=%d (no pending key)\n", smallId);
return false;
}
// Atomic: send MC|COn plaintext then commit the cipher, all under s_sendLock.
// No other send to this smallId can happen between MC|COn and CommitCipher.
EnterCriticalSection(&s_sendLock);
BYTE header[4];
header[0] = static_cast<BYTE>((kCipherOnPatternSize >> 24) & 0xFF);
header[1] = static_cast<BYTE>((kCipherOnPatternSize >> 16) & 0xFF);
header[2] = static_cast<BYTE>((kCipherOnPatternSize >> 8) & 0xFF);
header[3] = static_cast<BYTE>(kCipherOnPatternSize & 0xFF);
bool ok = true;
int totalSent = 0;
while (ok && totalSent < 4)
{
int sent = send(sock, (const char *)header + totalSent, 4 - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0) { ok = false; break; }
totalSent += sent;
}
totalSent = 0;
while (ok && totalSent < kCipherOnPatternSize)
{
int sent = send(sock, (const char *)kCipherOnPattern + totalSent, kCipherOnPatternSize - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0) { ok = false; break; }
totalSent += sent;
}
if (ok)
{
// Commit AFTER the send - MC|COn is the last plaintext packet
registry.CommitCipher(smallId);
app.DebugPrintf("Server: Cipher committed for smallId=%d (MC|COn sent)\n", smallId);
}
else
{
// Partial send corrupts the stream - force close
app.DebugPrintf("Server: MC|COn send failed for smallId=%d, closing socket\n", smallId);
registry.CancelPending(smallId);
closesocket(sock);
ClearSocketForSmallId(smallId);
}
LeaveCriticalSection(&s_sendLock);
return ok;
}
#endif
bool WinsockNetLayer::HostGame(int port, const char* bindIp)
{
if (!s_initialized && !Initialize()) return false;
@@ -968,18 +784,11 @@ int WinsockNetLayer::GetJoinAttempt() { return s_joinAttempt; }
int WinsockNetLayer::GetJoinMaxAttempts() { return JOIN_MAX_ATTEMPTS; }
DisconnectPacket::eDisconnectReason WinsockNetLayer::GetJoinRejectReason() { return s_joinRejectReason; }
bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize)
bool WinsockNetLayer::SendOnSocket(BYTE targetSmallId, SOCKET sock, const void* data, int dataSize)
{
if (sock == INVALID_SOCKET || dataSize <= 0 || dataSize > WIN64_NET_MAX_PACKET_SIZE) return false;
// TODO: s_sendLock is a single global lock for ALL sockets. If one client's
// send() blocks (TCP window full, slow WiFi), every other write thread stalls
// waiting for this lock — no data flows to any player until the slow send
// completes. This scales badly with player count (8+ players = noticeable).
// Fix: replace with per-socket locks indexed by smallId (s_perSocketSendLock[256]).
// The lock only needs to prevent interleaving of header+payload on the SAME socket;
// sends to different sockets are independent and should never block each other.
EnterCriticalSection(&s_sendLock);
EnterCriticalSection(&s_sendLock[targetSmallId]);
BYTE header[4];
header[0] = static_cast<BYTE>((dataSize >> 24) & 0xFF);
@@ -994,7 +803,7 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize)
int sent = send(sock, (const char*)header + totalSent, toSend - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
LeaveCriticalSection(&s_sendLock[targetSmallId]);
return false;
}
totalSent += sent;
@@ -1006,13 +815,13 @@ bool WinsockNetLayer::SendOnSocket(SOCKET sock, const void* data, int dataSize)
int sent = send(sock, static_cast<const char *>(data) + totalSent, dataSize - totalSent, 0);
if (sent == SOCKET_ERROR || sent == 0)
{
LeaveCriticalSection(&s_sendLock);
LeaveCriticalSection(&s_sendLock[targetSmallId]);
return false;
}
totalSent += sent;
}
LeaveCriticalSection(&s_sendLock);
LeaveCriticalSection(&s_sendLock[targetSmallId]);
return true;
}
@@ -1025,37 +834,9 @@ bool WinsockNetLayer::SendToSmallId(BYTE targetSmallId, const void* data, int da
SOCKET sock = GetSocketForSmallId(targetSmallId);
if (sock == INVALID_SOCKET) return false;
#if defined(MINECRAFT_SERVER_BUILD)
// Encrypt outgoing data if a cipher is active for this connection.
// TryEncryptOutgoing atomically checks and encrypts under a single lock
// to avoid TOCTOU races with DeactivateCipher on disconnect.
if (g_Win64DedicatedServer && dataSize > 0)
{
std::vector<BYTE> buf(static_cast<const BYTE*>(data),
static_cast<const BYTE*>(data) + dataSize);
if (ServerRuntime::Security::GetCipherRegistry().TryEncryptOutgoing(
targetSmallId, buf.data(), dataSize))
{
return SendOnSocket(sock, buf.data(), dataSize);
}
}
#endif
return SendOnSocket(sock, data, dataSize);
}
else
{
// Client sending to server - encrypt if send cipher is active
EnterCriticalSection(&s_clientCipherLock);
if (s_clientSendCipher.IsActive() && dataSize > 0)
{
std::vector<BYTE> buf(static_cast<const BYTE*>(data),
static_cast<const BYTE*>(data) + dataSize);
s_clientSendCipher.Encrypt(buf.data(), dataSize);
LeaveCriticalSection(&s_clientCipherLock);
return SendOnSocket(s_hostConnectionSocket, buf.data(), dataSize);
}
LeaveCriticalSection(&s_clientCipherLock);
return SendOnSocket(s_hostConnectionSocket, data, dataSize);
return SendOnSocket(targetSmallId, sock, data, dataSize);
} else {
return SendOnSocket(targetSmallId, s_hostConnectionSocket, data, dataSize);
}
}
@@ -1528,25 +1309,6 @@ DWORD WINAPI WinsockNetLayer::RecvThreadProc(LPVOID param)
break;
}
#if defined(MINECRAFT_SERVER_BUILD)
// Check for MC|CAck cipher handshake (raw byte match, before decryption).
// The ack is always plaintext - it's the last plaintext packet from the client.
if (g_Win64DedicatedServer &&
packetSize == kCipherAckPatternSize &&
memcmp(&recvBuf[0], kCipherAckPattern, kCipherAckPatternSize) == 0)
{
// Atomically send MC|COn plaintext then commit the cipher
SendCOnAndCommitServerCipher(clientSmallId);
continue; // consumed - do not pass to game packet handler
}
// Decrypt incoming data if a cipher is active for this connection
if (g_Win64DedicatedServer)
{
ServerRuntime::Security::GetCipherRegistry().DecryptIncoming(clientSmallId, &recvBuf[0], packetSize);
}
#endif
HandleDataReceived(clientSmallId, s_hostSmallId, &recvBuf[0], packetSize);
}
@@ -1589,13 +1351,6 @@ bool WinsockNetLayer::PopDisconnectedSmallId(BYTE* outSmallId)
void WinsockNetLayer::PushFreeSmallId(BYTE smallId)
{
#if defined(MINECRAFT_SERVER_BUILD)
// Clean up any active cipher for this connection
if (g_Win64DedicatedServer)
{
ServerRuntime::Security::GetCipherRegistry().DeactivateCipher(smallId);
}
#endif
// SmallIds 0..(XUSER_MAX_COUNT-1) are permanently reserved for the host's
// local pads and must never be recycled to remote clients.
@@ -1833,29 +1588,10 @@ DWORD WINAPI WinsockNetLayer::ClientRecvThreadProc(LPVOID param)
break;
}
// Check for MC|COn cipher activation signal (raw byte match, before decryption).
// This is always sent in plaintext as the last plaintext packet from the server.
if (packetSize == kCipherOnPatternSize &&
memcmp(&recvBuf[0], kCipherOnPattern, kCipherOnPatternSize) == 0)
{
ActivateClientRecvCipher();
app.DebugPrintf("Client: Recv cipher activated (MC|COn received)\n");
continue; // consumed - do not pass to game packet handler
}
// Decrypt incoming data if recv cipher is active
EnterCriticalSection(&s_clientCipherLock);
if (s_clientRecvCipher.IsActive())
{
s_clientRecvCipher.Decrypt(&recvBuf[0], packetSize);
}
LeaveCriticalSection(&s_clientCipherLock);
HandleDataReceived(s_hostSmallId, s_localSmallId, &recvBuf[0], packetSize);
}
s_connected = false;
ResetClientCipher();
return 0;
}