From 2af29e050bad553feec8e885f0c6d318d57c4e13 Mon Sep 17 00:00:00 2001 From: DrPerkyLegit <116128211+DrPerkyLegit@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:40:00 -0400 Subject: [PATCH] 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 --- Minecraft.Client/ClientConnection.cpp | 90 ------ Minecraft.Client/Extrax64Stubs.cpp | 13 +- Minecraft.Client/PlayerList.cpp | 181 ----------- .../Windows64/Network/WinsockNetLayer.cpp | 296 +----------------- .../Windows64/Network/WinsockNetLayer.h | 35 +-- Minecraft.Client/cmake/sources/Common.cmake | 2 - .../Security/CipherHandshakeEnforcer.cpp | 60 ---- .../Security/CipherHandshakeEnforcer.h | 64 ---- .../Security/ConnectionCipher.cpp | 115 ------- Minecraft.Server/Security/ConnectionCipher.h | 97 ------ .../Security/IdentityTokenManager.cpp | 288 ----------------- .../Security/IdentityTokenManager.h | 63 ---- Minecraft.Server/Security/SecurityConfig.h | 3 - Minecraft.Server/Security/StreamCipher.cpp | 206 ------------ Minecraft.Server/Security/StreamCipher.h | 98 ------ Minecraft.Server/ServerProperties.cpp | 3 - Minecraft.Server/ServerProperties.h | 6 - Minecraft.Server/Windows64/ServerMain.cpp | 20 +- Minecraft.Server/cmake/sources/Common.cmake | 8 - Minecraft.World/CustomPayloadPacket.cpp | 8 - Minecraft.World/CustomPayloadPacket.h | 10 - 21 files changed, 22 insertions(+), 1644 deletions(-) delete mode 100644 Minecraft.Server/Security/CipherHandshakeEnforcer.cpp delete mode 100644 Minecraft.Server/Security/CipherHandshakeEnforcer.h delete mode 100644 Minecraft.Server/Security/ConnectionCipher.cpp delete mode 100644 Minecraft.Server/Security/ConnectionCipher.h delete mode 100644 Minecraft.Server/Security/IdentityTokenManager.cpp delete mode 100644 Minecraft.Server/Security/IdentityTokenManager.h delete mode 100644 Minecraft.Server/Security/StreamCipher.cpp delete mode 100644 Minecraft.Server/Security/StreamCipher.h diff --git a/Minecraft.Client/ClientConnection.cpp b/Minecraft.Client/ClientConnection.cpp index 86c842b6..f376fcfc 100644 --- a/Minecraft.Client/ClientConnection.cpp +++ b/Minecraft.Client/ClientConnection.cpp @@ -3911,96 +3911,6 @@ void ClientConnection::handleCustomPayload(shared_ptr custo return std::string(exePath) + filename; }; - // Identity token: server issued us a new token - store it locally - if (CustomPayloadPacket::IDENTITY_TOKEN_ISSUE.compare(customPayloadPacket->identifier) == 0) - { - if (customPayloadPacket->data.data != nullptr && customPayloadPacket->length == 32) - { - std::string tokenPath = buildIdentityTokenPath(); - if (!tokenPath.empty()) - { - FILE *f = nullptr; - fopen_s(&f, tokenPath.c_str(), "wb"); - if (f != nullptr) - { - size_t written = fwrite(customPayloadPacket->data.data, 1, 32, f); - fclose(f); - if (written == 32) - { - app.DebugPrintf("Client: Stored identity token to %s\n", tokenPath.c_str()); - } - else - { - app.DebugPrintf("Client: Failed to write full identity token (wrote %zu/32)\n", written); - } - } - else - { - app.DebugPrintf("Client: Failed to open %s for writing\n", tokenPath.c_str()); - } - } - } - return; - } - - // Identity token: server is challenging us to present our stored token - if (CustomPayloadPacket::IDENTITY_TOKEN_CHALLENGE.compare(customPayloadPacket->identifier) == 0) - { - std::string tokenPath = buildIdentityTokenPath(); - FILE *f = nullptr; - if (!tokenPath.empty()) - fopen_s(&f, tokenPath.c_str(), "rb"); - if (f != nullptr) - { - uint8_t token[32] = {}; - size_t bytesRead = fread(token, 1, 32, f); - fclose(f); - if (bytesRead == 32) - { - byteArray tokenData(32); - memcpy(tokenData.data, token, 32); - connection->send(std::make_shared( - CustomPayloadPacket::IDENTITY_TOKEN_RESPONSE, tokenData)); - app.DebugPrintf("Client: Sent identity token response\n"); - } - else - { - app.DebugPrintf("Client: identity-token.dat is invalid (%zu bytes)\n", bytesRead); - connection->send(std::make_shared( - CustomPayloadPacket::IDENTITY_TOKEN_RESPONSE, byteArray())); - } - SecureZeroMemory(token, sizeof(token)); - } - else - { - app.DebugPrintf("Client: No identity-token.dat found, sending empty response\n"); - connection->send(std::make_shared( - CustomPayloadPacket::IDENTITY_TOKEN_RESPONSE, byteArray())); - } - return; - } - - // Stream cipher handshake: server sent us a key - if (CustomPayloadPacket::CIPHER_KEY_CHANNEL.compare(customPayloadPacket->identifier) == 0) - { - if (customPayloadPacket->length == ServerRuntime::Security::StreamCipher::KEY_SIZE && - customPayloadPacket->data.data != nullptr) - { - app.DebugPrintf("Client: Received MC|CKey from server (%d bytes)\n", customPayloadPacket->length); - // Store key and send ack+activate atomically to prevent ResetClientCipher race - WinsockNetLayer::StoreClientCipherKey(customPayloadPacket->data.data); - if (!WinsockNetLayer::SendAckAndActivateClientSendCipher()) - { - app.DebugPrintf("Client: Failed to send cipher ack, connection will be closed\n"); - } - } - else - { - app.DebugPrintf("Client: Received malformed MC|CKey (length=%d)\n", customPayloadPacket->length); - } - return; - } - // Fork server identification: enables render-distance-independent player list if (CustomPayloadPacket::FORK_HELLO_CHANNEL.compare(customPayloadPacket->identifier) == 0) { diff --git a/Minecraft.Client/Extrax64Stubs.cpp b/Minecraft.Client/Extrax64Stubs.cpp index 2fd6cfcc..e414d5f4 100644 --- a/Minecraft.Client/Extrax64Stubs.cpp +++ b/Minecraft.Client/Extrax64Stubs.cpp @@ -204,20 +204,11 @@ void IQNetPlayer::SendData(IQNetPlayer * player, const void* pvData, DWORD dwDat // Encrypt if client send cipher is active if (dwDataSize > 0) { - std::vector buf(static_cast(pvData), - static_cast(pvData) + dwDataSize); - if (WinsockNetLayer::TryEncryptClientOutgoing(buf.data(), static_cast(dwDataSize))) - { - WinsockNetLayer::SendOnSocket(sock, buf.data(), static_cast(dwDataSize)); - } - else - { - WinsockNetLayer::SendOnSocket(sock, pvData, dwDataSize); - } + WinsockNetLayer::SendOnSocket(m_smallId, sock, pvData, dwDataSize); } else { - WinsockNetLayer::SendOnSocket(sock, pvData, dwDataSize); + WinsockNetLayer::SendOnSocket(m_smallId, sock, pvData, dwDataSize); } } } diff --git a/Minecraft.Client/PlayerList.cpp b/Minecraft.Client/PlayerList.cpp index 3ce51d10..19ea7b64 100644 --- a/Minecraft.Client/PlayerList.cpp +++ b/Minecraft.Client/PlayerList.cpp @@ -46,9 +46,6 @@ #include "../Minecraft.Server/ServerLogManager.h" #include "../Minecraft.Server/ServerProperties.h" #include "../Minecraft.Server/Security/SecurityConfig.h" -#include "../Minecraft.Server/Security/ConnectionCipher.h" -#include "../Minecraft.Server/Security/CipherHandshakeEnforcer.h" -#include "../Minecraft.Server/Security/IdentityTokenManager.h" extern bool g_Win64DedicatedServer; static unsigned int s_playerListTickCount = 0; static const int kIdentityResponseGraceTicks = 200; // 10 seconds at 20 TPS @@ -387,48 +384,6 @@ bool PlayerList::placeNewPlayer(Connection *connection, shared_ptr } } -#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) - // Initiate stream cipher handshake if enabled. - // Send MC|CKey with the generated key. Old clients will ignore the unknown channel. - if (g_Win64DedicatedServer && ServerRuntime::Security::GetSettings().enableStreamCipher) - { - BYTE smallId = 0; - Socket *cipherSock = connection->getSocket(); - INetworkPlayer *cipherNp = cipherSock ? cipherSock->getPlayer() : nullptr; - if (cipherNp != nullptr && !cipherNp->IsLocal()) - { - smallId = cipherNp->GetSmallId(); - uint8_t key[ServerRuntime::Security::StreamCipher::KEY_SIZE]; - if (ServerRuntime::Security::GetCipherRegistry().PrepareKey(smallId, key)) - { - byteArray keyData(ServerRuntime::Security::StreamCipher::KEY_SIZE); - memcpy(keyData.data, key, ServerRuntime::Security::StreamCipher::KEY_SIZE); - playerConnection->send(std::make_shared( - CustomPayloadPacket::CIPHER_KEY_CHANNEL, keyData)); - SecureZeroMemory(key, sizeof(key)); - app.DebugPrintf("Server: Sent MC|CKey to player %ls (smallId=%d)\n", - player->getName().c_str(), smallId); - - // Register with enforcer for timeout tracking - if (ServerRuntime::Security::GetSettings().requireSecureClient) - { - ServerRuntime::Security::GetHandshakeEnforcer().OnCipherKeySent(smallId, s_playerListTickCount); - } - } - - // Close the security gate AFTER sending the essential login sequence - // and MC|CKey. The login setup packets (LoginPacket, spawn position, - // abilities, chunks, teleport) must arrive in plaintext before the - // cipher handshake completes. Only subsequent tick data is buffered - // until the handshake finishes and openSecurityGate() flushes. - if (ServerRuntime::Security::GetSettings().requireSecureClient) - { - playerConnection->m_securityGateOpen = false; - } - } - } -#endif - return true; } @@ -668,16 +623,6 @@ void PlayerList::move(shared_ptr player) void PlayerList::remove(shared_ptr player) { -#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) - if (g_Win64DedicatedServer && player->connection != nullptr) - { - INetworkPlayer *np = player->connection->getNetworkPlayer(); - if (np != nullptr) - { - ServerRuntime::Security::GetHandshakeEnforcer().OnDisconnected(np->GetSmallId()); - } - } -#endif save(player); //4J Stu - We don't want to save the map data for guests, so when we are sure that the player is gone delete the map if(player->isGuest()) playerIo->deleteMapFilesForPlayer(player); @@ -1162,132 +1107,6 @@ void PlayerList::repositionAcrossDimension(shared_ptr entity, int lastDi void PlayerList::tick() { -#if defined(_WINDOWS64) && defined(MINECRAFT_SERVER_BUILD) - ++s_playerListTickCount; - - // Cipher handshake enforcement: kick clients that haven't completed the handshake - if (g_Win64DedicatedServer && - ServerRuntime::Security::GetSettings().enableStreamCipher && - ServerRuntime::Security::GetSettings().requireSecureClient) - { - std::vector expired; - std::vector completed; - ServerRuntime::Security::GetHandshakeEnforcer().CheckTimeouts(s_playerListTickCount, expired, completed); - - for (unsigned char smallId : expired) - { - app.DebugPrintf("SECURITY: Kicking unsecured client (smallId=%d) - cipher handshake timed out\n", smallId); - ServerRuntime::ServerLogManager::OnUnsecuredClientKicked(smallId); - EnterCriticalSection(&m_closePlayersCS); - m_smallIdsToClose.push_back(smallId); - LeaveCriticalSection(&m_closePlayersCS); - } - - // Report cipher completion and open security gate for all completed handshakes - vector > tickSnapshot = getPlayersSnapshot(); - for (unsigned char smallId : completed) - { - // Open the security gate -- flush buffered game packets now that cipher is active - for (auto &p : tickSnapshot) - { - if (p == nullptr || p->connection == nullptr) continue; - INetworkPlayer *np = p->connection->getNetworkPlayer(); - if (np != nullptr && np->GetSmallId() == smallId) - { - if (!p->connection->isSecurityGateOpen()) - { - p->connection->openSecurityGate(); - } - break; - } - } - - if (ServerRuntime::Security::GetSettings().requireChallengeToken) - { - ServerRuntime::ServerLogManager::OnCipherHandshakeCompleted(smallId); - } - else - { - ServerRuntime::ServerLogManager::OnCipherCompletedNoTokenRequired(smallId); - } - } - - // For newly-completed cipher handshakes, initiate identity token exchange - if (ServerRuntime::Security::GetSettings().requireChallengeToken) - { - for (unsigned char smallId : completed) - { - // Find the player by smallId - for (auto &p : tickSnapshot) - { - if (p == nullptr || p->connection == nullptr) continue; - INetworkPlayer *np = p->connection->getNetworkPlayer(); - if (np == nullptr || np->GetSmallId() != smallId) continue; - - PlayerUID xuid = p->connection->m_offlineXUID; - if (xuid == INVALID_XUID) xuid = p->connection->m_onlineXUID; - - if (p->connection->getIdentityChallengeTick() >= 0) - { - // Already challenged, skip - } - else if (ServerRuntime::Security::GetIdentityTokenManager().HasToken(xuid)) - { - // Returning player - challenge them - p->connection->send(std::make_shared( - CustomPayloadPacket::IDENTITY_TOKEN_CHALLENGE, byteArray())); - p->connection->setIdentityChallengeTick(s_playerListTickCount); - app.DebugPrintf("Server: Sent identity challenge to %ls (smallId=%d)\n", - p->getName().c_str(), smallId); - } - else - { - // New player - issue a token over the encrypted channel - uint8_t token[ServerRuntime::Security::IdentityTokenManager::TOKEN_SIZE]; - if (ServerRuntime::Security::GetIdentityTokenManager().IssueToken(xuid, token)) - { - byteArray tokenData(ServerRuntime::Security::IdentityTokenManager::TOKEN_SIZE); - memcpy(tokenData.data, token, ServerRuntime::Security::IdentityTokenManager::TOKEN_SIZE); - p->connection->send(std::make_shared( - CustomPayloadPacket::IDENTITY_TOKEN_ISSUE, tokenData)); - SecureZeroMemory(token, sizeof(token)); - p->connection->setIdentityVerified(true); - app.DebugPrintf("Server: Issued identity token to %ls (smallId=%d)\n", - p->getName().c_str(), smallId); - ServerRuntime::ServerLogManager::OnIdentityTokenIssued(smallId); - } - } - break; - } - } - - // Enforce identity token response timeout - for (auto &p : tickSnapshot) - { - if (p == nullptr || p->connection == nullptr) continue; - int challengeTick = p->connection->getIdentityChallengeTick(); - if (challengeTick >= 0 && !p->connection->isIdentityVerified() && - (s_playerListTickCount - challengeTick) > kIdentityResponseGraceTicks) - { - app.DebugPrintf("SECURITY: Kicking %ls - identity token response timed out\n", - p->getName().c_str()); - INetworkPlayer *npLog = p->connection->getNetworkPlayer(); - if (npLog != nullptr) - ServerRuntime::ServerLogManager::OnIdentityTokenTimeout(npLog->GetSmallId(), p->getName()); - p->connection->setIdentityChallengeTick(-1); // prevent re-queuing - INetworkPlayer *np = p->connection->getNetworkPlayer(); - if (np != nullptr) - { - EnterCriticalSection(&m_closePlayersCS); - m_smallIdsToClose.push_back(np->GetSmallId()); - LeaveCriticalSection(&m_closePlayersCS); - } - } - } - } - } -#endif - // 4J - brought changes to how often this is sent forward from 1.2.3 if (++sendAllPlayerInfoIn > SEND_PLAYER_INFO_INTERVAL) { diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp index 904103b7..6172bd0b 100644 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.cpp @@ -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 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((kCipherAckPatternSize >> 24) & 0xFF); - header[1] = static_cast((kCipherAckPatternSize >> 16) & 0xFF); - header[2] = static_cast((kCipherAckPatternSize >> 8) & 0xFF); - header[3] = static_cast(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 ®istry = 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((kCipherOnPatternSize >> 24) & 0xFF); - header[1] = static_cast((kCipherOnPatternSize >> 16) & 0xFF); - header[2] = static_cast((kCipherOnPatternSize >> 8) & 0xFF); - header[3] = static_cast(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((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(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 buf(static_cast(data), - static_cast(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 buf(static_cast(data), - static_cast(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; } diff --git a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h index dc830c84..34cc7389 100644 --- a/Minecraft.Client/Windows64/Network/WinsockNetLayer.h +++ b/Minecraft.Client/Windows64/Network/WinsockNetLayer.h @@ -9,7 +9,6 @@ #include #include "../../Common/Network/NetworkPlayerInterface.h" #include "../../..\Minecraft.World\DisconnectPacket.h" -#include "../../..\Minecraft.Server\Security\StreamCipher.h" #pragma comment(lib, "Ws2_32.lib") @@ -90,7 +89,7 @@ public: static DisconnectPacket::eDisconnectReason GetJoinRejectReason(); static bool SendToSmallId(BYTE targetSmallId, const void* data, int dataSize); - static bool SendOnSocket(SOCKET sock, const void* data, int dataSize); + static bool SendOnSocket(BYTE targetSmallId, SOCKET sock, const void* data, int dataSize); // Non-host split-screen: additional TCP connections to host, one per pad static bool JoinSplitScreen(int padIndex, BYTE* outSmallId); @@ -148,7 +147,7 @@ private: static BYTE s_hostSmallId; static unsigned int s_nextSmallId; - static CRITICAL_SECTION s_sendLock; + static CRITICAL_SECTION s_sendLock[MINECRAFT_NET_MAX_PLAYERS]; static CRITICAL_SECTION s_connectionsLock; static std::vector s_connections; @@ -191,38 +190,8 @@ private: static BYTE s_splitScreenSmallId[XUSER_MAX_COUNT]; static HANDLE s_splitScreenRecvThread[XUSER_MAX_COUNT]; - // Client-side stream cipher (non-host only, one connection to server) - static ServerRuntime::Security::StreamCipher s_clientSendCipher; - static ServerRuntime::Security::StreamCipher s_clientRecvCipher; - static CRITICAL_SECTION s_clientCipherLock; - static uint8_t s_clientPendingKey[ServerRuntime::Security::StreamCipher::KEY_SIZE]; - static bool s_clientKeyStored; // protected by s_clientCipherLock - public: static void ClearSocketForSmallId(BYTE smallId); - - /** Store the cipher key received from the server. Does not activate yet. */ - static void StoreClientCipherKey(const uint8_t key[ServerRuntime::Security::StreamCipher::KEY_SIZE]); - - /** Send MC|CAck directly to socket then activate client send cipher. Atomic under s_sendLock. */ - static bool SendAckAndActivateClientSendCipher(); - - /** Activate client recv cipher. Called from ClientRecvThreadProc on MC|COn detection. */ - static void ActivateClientRecvCipher(); - - /** Reset client ciphers on disconnect. */ - static void ResetClientCipher(); - - /** - * Encrypt data in-place for client->server send if the client send cipher is active. - * Returns true if data was encrypted. Thread-safe. - */ - static bool TryEncryptClientOutgoing(uint8_t *data, int length); - -#if defined(MINECRAFT_SERVER_BUILD) - /** Atomically send MC|COn plaintext then commit server cipher. Called from RecvThreadProc. */ - static bool SendCOnAndCommitServerCipher(BYTE smallId); -#endif }; extern bool g_Win64MultiplayerHost; diff --git a/Minecraft.Client/cmake/sources/Common.cmake b/Minecraft.Client/cmake/sources/Common.cmake index 36a0287f..f088fb73 100644 --- a/Minecraft.Client/cmake/sources/Common.cmake +++ b/Minecraft.Client/cmake/sources/Common.cmake @@ -423,8 +423,6 @@ source_group("Windows64/Iggy/gdraw" FILES ${_MINECRAFT_CLIENT_COMMON_WINDOWS64_I set(_MINECRAFT_CLIENT_COMMON_WINDOWS64_NETWORK "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/WinsockNetLayer.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/Windows64/Network/WinsockNetLayer.h" - "${CMAKE_CURRENT_SOURCE_DIR}/../Minecraft.Server/Security/StreamCipher.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/../Minecraft.Server/Security/StreamCipher.h" ) source_group("Windows64/Network" FILES ${_MINECRAFT_CLIENT_COMMON_WINDOWS64_NETWORK}) diff --git a/Minecraft.Server/Security/CipherHandshakeEnforcer.cpp b/Minecraft.Server/Security/CipherHandshakeEnforcer.cpp deleted file mode 100644 index 2052f94c..00000000 --- a/Minecraft.Server/Security/CipherHandshakeEnforcer.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "stdafx.h" -#include "CipherHandshakeEnforcer.h" -#include "ConnectionCipher.h" - -namespace ServerRuntime -{ - namespace Security - { - CipherHandshakeEnforcer::CipherHandshakeEnforcer() - { - memset(m_sentTick, 0, sizeof(m_sentTick)); - memset(m_tracked, 0, sizeof(m_tracked)); - } - - CipherHandshakeEnforcer::~CipherHandshakeEnforcer() - { - } - - void CipherHandshakeEnforcer::OnCipherKeySent(unsigned char smallId, unsigned int currentTick) - { - m_sentTick[smallId] = currentTick; - m_tracked[smallId] = true; - } - - void CipherHandshakeEnforcer::CheckTimeouts(unsigned int currentTick, - std::vector &outExpired, - std::vector &outCompleted) - { - auto ®istry = GetCipherRegistry(); - - for (int i = 0; i < MAX_CONNECTIONS; ++i) - { - if (!m_tracked[i]) - continue; - - if (registry.IsCipherActive(static_cast(i))) - { - outCompleted.push_back(static_cast(i)); - m_tracked[i] = false; - } - else if ((currentTick - m_sentTick[i]) > static_cast(kGraceTicks)) - { - outExpired.push_back(static_cast(i)); - m_tracked[i] = false; - } - } - } - - void CipherHandshakeEnforcer::OnDisconnected(unsigned char smallId) - { - m_tracked[smallId] = false; - } - - CipherHandshakeEnforcer &GetHandshakeEnforcer() - { - static CipherHandshakeEnforcer s_instance; - return s_instance; - } - } -} diff --git a/Minecraft.Server/Security/CipherHandshakeEnforcer.h b/Minecraft.Server/Security/CipherHandshakeEnforcer.h deleted file mode 100644 index 77baed3c..00000000 --- a/Minecraft.Server/Security/CipherHandshakeEnforcer.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#ifdef _WINDOWS64 -#include -#endif - -#include - -namespace ServerRuntime -{ - namespace Security - { - /** - * Tracks pending cipher handshakes and kicks clients that don't complete - * within the grace period. - * - * When require-secure-client is enabled, old/unpatched clients that ignore - * MC|CKey are disconnected before they receive any PlayerInfoPacket data - * containing other players' XUIDs. - * - * Called from the main tick thread only (PlayerList::tick). - */ - class CipherHandshakeEnforcer - { - public: - // 5 seconds at 20 TPS. The security gate buffers all game data until - // cipher completes, so no data leaks regardless of grace period length. - // 5 seconds accommodates high-latency connections. - static const int kGraceTicks = 100; - - CipherHandshakeEnforcer(); - ~CipherHandshakeEnforcer(); - - CipherHandshakeEnforcer(const CipherHandshakeEnforcer &) = delete; - CipherHandshakeEnforcer &operator=(const CipherHandshakeEnforcer &) = delete; - - /** - * Register that MC|CKey was sent to this smallId at the given tick. - */ - void OnCipherKeySent(unsigned char smallId, unsigned int currentTick); - - /** - * Check for timed-out handshakes. Returns smallIds that exceeded the - * grace period without the cipher becoming active. Also returns - * smallIds that just completed (cipher became active) in outCompleted. - */ - void CheckTimeouts(unsigned int currentTick, - std::vector &outExpired, - std::vector &outCompleted); - - /** - * Clean up tracking for a disconnected connection. - */ - void OnDisconnected(unsigned char smallId); - - private: - static const int MAX_CONNECTIONS = 256; - unsigned int m_sentTick[MAX_CONNECTIONS]; // 0 = not tracked - bool m_tracked[MAX_CONNECTIONS]; - }; - - CipherHandshakeEnforcer &GetHandshakeEnforcer(); - } -} diff --git a/Minecraft.Server/Security/ConnectionCipher.cpp b/Minecraft.Server/Security/ConnectionCipher.cpp deleted file mode 100644 index 58e2a79c..00000000 --- a/Minecraft.Server/Security/ConnectionCipher.cpp +++ /dev/null @@ -1,115 +0,0 @@ -#include "stdafx.h" -#include "ConnectionCipher.h" - -#include - -namespace ServerRuntime -{ - namespace Security - { - ConnectionCipherRegistry::ConnectionCipherRegistry() - { - InitializeCriticalSection(&m_lock); - memset(m_pending, 0, sizeof(m_pending)); - memset(m_pendingKeys, 0, sizeof(m_pendingKeys)); - } - - ConnectionCipherRegistry::~ConnectionCipherRegistry() - { - SecureZeroMemory(m_pendingKeys, sizeof(m_pendingKeys)); - DeleteCriticalSection(&m_lock); - } - - bool ConnectionCipherRegistry::PrepareKey(unsigned char smallId, uint8_t outKey[StreamCipher::KEY_SIZE]) - { - uint8_t key[StreamCipher::KEY_SIZE]; - if (!StreamCipher::GenerateKey(key)) - { - return false; - } - - EnterCriticalSection(&m_lock); - memcpy(m_pendingKeys[smallId], key, StreamCipher::KEY_SIZE); - m_pending[smallId] = true; - LeaveCriticalSection(&m_lock); - - memcpy(outKey, key, StreamCipher::KEY_SIZE); - SecureZeroMemory(key, sizeof(key)); - return true; - } - - bool ConnectionCipherRegistry::CommitCipher(unsigned char smallId) - { - EnterCriticalSection(&m_lock); - if (!m_pending[smallId]) - { - LeaveCriticalSection(&m_lock); - return false; - } - - m_ciphers[smallId].Initialize(m_pendingKeys[smallId]); - SecureZeroMemory(m_pendingKeys[smallId], StreamCipher::KEY_SIZE); - m_pending[smallId] = false; - LeaveCriticalSection(&m_lock); - return true; - } - - void ConnectionCipherRegistry::CancelPending(unsigned char smallId) - { - EnterCriticalSection(&m_lock); - SecureZeroMemory(m_pendingKeys[smallId], StreamCipher::KEY_SIZE); - m_pending[smallId] = false; - LeaveCriticalSection(&m_lock); - } - - bool ConnectionCipherRegistry::HasPendingKey(unsigned char smallId) const - { - EnterCriticalSection(&m_lock); - bool pending = m_pending[smallId]; - LeaveCriticalSection(&m_lock); - return pending; - } - - void ConnectionCipherRegistry::DeactivateCipher(unsigned char smallId) - { - EnterCriticalSection(&m_lock); - m_ciphers[smallId].Reset(); - SecureZeroMemory(m_pendingKeys[smallId], StreamCipher::KEY_SIZE); - m_pending[smallId] = false; - LeaveCriticalSection(&m_lock); - } - - bool ConnectionCipherRegistry::TryEncryptOutgoing(unsigned char smallId, uint8_t *data, int length) - { - EnterCriticalSection(&m_lock); - bool active = m_ciphers[smallId].IsActive(); - if (active) - { - m_ciphers[smallId].Encrypt(data, length); - } - LeaveCriticalSection(&m_lock); - return active; - } - - bool ConnectionCipherRegistry::IsCipherActive(unsigned char smallId) const - { - EnterCriticalSection(&m_lock); - bool active = m_ciphers[smallId].IsActive(); - LeaveCriticalSection(&m_lock); - return active; - } - - void ConnectionCipherRegistry::DecryptIncoming(unsigned char smallId, uint8_t *data, int length) - { - EnterCriticalSection(&m_lock); - m_ciphers[smallId].Decrypt(data, length); - LeaveCriticalSection(&m_lock); - } - - ConnectionCipherRegistry &GetCipherRegistry() - { - static ConnectionCipherRegistry s_instance; - return s_instance; - } - } -} diff --git a/Minecraft.Server/Security/ConnectionCipher.h b/Minecraft.Server/Security/ConnectionCipher.h deleted file mode 100644 index bd3c294c..00000000 --- a/Minecraft.Server/Security/ConnectionCipher.h +++ /dev/null @@ -1,97 +0,0 @@ -#pragma once - -#include "StreamCipher.h" - -#ifdef _WINDOWS64 -#include -#endif - -namespace ServerRuntime -{ - namespace Security - { - /** - * Per-connection cipher registry for the dedicated server. - * - * Handshake protocol (4-message, via CustomPayloadPacket): - * 1. Server calls PrepareKey(smallId) -> sends MC|CKey with key to client - * 2. Client stores key, sends MC|CAck, activates send cipher - * 3. Server recv thread detects MC|CAck -> calls SendCOnAndCommit which - * atomically sends MC|COn plaintext then calls CommitCipher(smallId) - * 4. Client recv thread detects MC|COn -> activates recv cipher - * - * Backwards compatible: old clients ignore MC|CKey, server never gets ack, - * cipher stays inactive. Old servers never send MC|CKey, client stays plaintext. - */ - class ConnectionCipherRegistry - { - public: - ConnectionCipherRegistry(); - ~ConnectionCipherRegistry(); - - ConnectionCipherRegistry(const ConnectionCipherRegistry &) = delete; - ConnectionCipherRegistry &operator=(const ConnectionCipherRegistry &) = delete; - ConnectionCipherRegistry(ConnectionCipherRegistry &&) = delete; - ConnectionCipherRegistry &operator=(ConnectionCipherRegistry &&) = delete; - - /** - * Generate a random key and store it in pending state for the given smallId. - * Does NOT activate the cipher. Call CommitCipher() after the client acks. - * Returns the generated key in outKey. - */ - bool PrepareKey(unsigned char smallId, uint8_t outKey[StreamCipher::KEY_SIZE]); - - /** - * Activate a previously prepared cipher. Called from the recv thread - * when the client's MC|CAck is detected by raw byte matching. - * Returns false if no key was pending for this smallId. - */ - bool CommitCipher(unsigned char smallId); - - /** - * Cancel a pending key (e.g., client disconnected before ack). - */ - void CancelPending(unsigned char smallId); - - /** - * Check if a key is pending for the given smallId (no side effects). - */ - bool HasPendingKey(unsigned char smallId) const; - - /** - * Deactivate the cipher and cancel any pending key for a disconnected connection. - */ - void DeactivateCipher(unsigned char smallId); - - /** - * Atomically check if cipher is active and encrypt outgoing data. - * Returns true if data was encrypted, false if cipher is inactive (data untouched). - */ - bool TryEncryptOutgoing(unsigned char smallId, uint8_t *data, int length); - - /** - * Check if the cipher is active (handshake completed) for a given smallId. - * Thread-safe, read-only query. - */ - bool IsCipherActive(unsigned char smallId) const; - - /** - * Decrypt incoming data from a specific connection. - * No-op if the cipher is not active for this connection. - */ - void DecryptIncoming(unsigned char smallId, uint8_t *data, int length); - - private: - static const int MAX_CONNECTIONS = 256; - StreamCipher m_ciphers[MAX_CONNECTIONS]; - bool m_pending[MAX_CONNECTIONS]; - uint8_t m_pendingKeys[MAX_CONNECTIONS][StreamCipher::KEY_SIZE]; - mutable CRITICAL_SECTION m_lock; - }; - - /** - * Global cipher registry singleton. - */ - ConnectionCipherRegistry &GetCipherRegistry(); - } -} diff --git a/Minecraft.Server/Security/IdentityTokenManager.cpp b/Minecraft.Server/Security/IdentityTokenManager.cpp deleted file mode 100644 index b47063bf..00000000 --- a/Minecraft.Server/Security/IdentityTokenManager.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "stdafx.h" -#include "IdentityTokenManager.h" - -#ifdef _WINDOWS64 -#include -#endif - -#include "../Common/FileUtils.h" -#include "../Common/StringUtils.h" -#include "../ServerLogger.h" -#include "../vendor/nlohmann/json.hpp" - -#include - -namespace ServerRuntime -{ - namespace Security - { - using OrderedJson = nlohmann::ordered_json; - - IdentityTokenManager::IdentityTokenManager() - : m_initialized(false) - { - InitializeCriticalSection(&m_lock); - } - - IdentityTokenManager::~IdentityTokenManager() - { - DeleteCriticalSection(&m_lock); - } - - static std::string BytesToBase64(const uint8_t *data, int length) - { - static const char kTable[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - std::string out; - out.reserve(((length + 2) / 3) * 4); - for (int i = 0; i < length; i += 3) - { - uint32_t n = static_cast(data[i]) << 16; - if (i + 1 < length) n |= static_cast(data[i + 1]) << 8; - if (i + 2 < length) n |= static_cast(data[i + 2]); - out.push_back(kTable[(n >> 18) & 0x3F]); - out.push_back(kTable[(n >> 12) & 0x3F]); - out.push_back((i + 1 < length) ? kTable[(n >> 6) & 0x3F] : '='); - out.push_back((i + 2 < length) ? kTable[n & 0x3F] : '='); - } - return out; - } - - static bool Base64ToBytes(const std::string &encoded, std::vector &out) - { - static const int kDecodeTable[128] = { - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63, - 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14, - 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, - -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, - 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1 - }; - out.clear(); - out.reserve(encoded.size() * 3 / 4); - uint32_t buf = 0; - int bits = 0; - for (char c : encoded) - { - if (c == '=') break; - if (c < 0 || c >= 128 || kDecodeTable[(int)c] < 0) return false; - buf = (buf << 6) | kDecodeTable[(int)c]; - bits += 6; - if (bits >= 8) - { - bits -= 8; - out.push_back(static_cast((buf >> bits) & 0xFF)); - } - } - return true; - } - - static std::string FormatXuid(PlayerUID xuid) - { - char buffer[32] = {}; - sprintf_s(buffer, sizeof(buffer), "0x%016llx", (unsigned long long)xuid); - return buffer; - } - - bool IdentityTokenManager::Initialize(const std::string &filePath) - { - EnterCriticalSection(&m_lock); - m_filePath = filePath; - m_tokens.clear(); - bool ok = Load(); - m_initialized = true; - LeaveCriticalSection(&m_lock); - - if (ok) - { - LogInfof("security", "loaded %u identity tokens from %s", - (unsigned)m_tokens.size(), filePath.c_str()); - } - else - { - LogInfof("security", "no existing identity tokens found, starting fresh"); - } - return true; - } - - void IdentityTokenManager::Shutdown() - { - EnterCriticalSection(&m_lock); - m_tokens.clear(); - m_initialized = false; - LeaveCriticalSection(&m_lock); - } - - bool IdentityTokenManager::HasToken(PlayerUID xuid) const - { - EnterCriticalSection(&m_lock); - bool found = m_tokens.find(xuid) != m_tokens.end(); - LeaveCriticalSection(&m_lock); - return found; - } - - bool IdentityTokenManager::GetToken(PlayerUID xuid, uint8_t outToken[TOKEN_SIZE]) const - { - EnterCriticalSection(&m_lock); - auto it = m_tokens.find(xuid); - if (it == m_tokens.end() || it->second.size() != TOKEN_SIZE) - { - LeaveCriticalSection(&m_lock); - return false; - } - memcpy(outToken, it->second.data(), TOKEN_SIZE); - LeaveCriticalSection(&m_lock); - return true; - } - - bool IdentityTokenManager::IssueToken(PlayerUID xuid, uint8_t outToken[TOKEN_SIZE]) - { - // Generate a random 32-byte identity token - uint8_t token[TOKEN_SIZE]; -#ifdef _WINDOWS64 - NTSTATUS status = BCryptGenRandom(nullptr, token, TOKEN_SIZE, - BCRYPT_USE_SYSTEM_PREFERRED_RNG); - if (!BCRYPT_SUCCESS(status)) - { - SecureZeroMemory(token, sizeof(token)); - return false; - } -#else - for (int i = 0; i < TOKEN_SIZE; ++i) - token[i] = static_cast(rand() & 0xFF); -#endif - - EnterCriticalSection(&m_lock); - m_tokens[xuid] = std::vector(token, token + TOKEN_SIZE); - bool saved = Save(); - LeaveCriticalSection(&m_lock); - - if (saved) - { - memcpy(outToken, token, TOKEN_SIZE); - SecureZeroMemory(token, sizeof(token)); - return true; - } - - SecureZeroMemory(token, sizeof(token)); - return false; - } - - bool IdentityTokenManager::VerifyToken(PlayerUID xuid, const uint8_t token[TOKEN_SIZE]) const - { - EnterCriticalSection(&m_lock); - auto it = m_tokens.find(xuid); - if (it == m_tokens.end() || it->second.size() != TOKEN_SIZE) - { - LeaveCriticalSection(&m_lock); - return false; - } - - // Constant-time comparison to prevent timing attacks - uint8_t diff = 0; - for (int i = 0; i < TOKEN_SIZE; ++i) - { - diff |= it->second[i] ^ token[i]; - } - LeaveCriticalSection(&m_lock); - return diff == 0; - } - - bool IdentityTokenManager::RevokeToken(PlayerUID xuid) - { - EnterCriticalSection(&m_lock); - auto it = m_tokens.find(xuid); - if (it == m_tokens.end()) - { - LeaveCriticalSection(&m_lock); - return false; - } - SecureZeroMemory(it->second.data(), it->second.size()); - m_tokens.erase(it); - bool saved = Save(); - LeaveCriticalSection(&m_lock); - return saved; - } - - bool IdentityTokenManager::Load() - { - std::string text; - if (!FileUtils::ReadTextFile(m_filePath, &text)) - { - return false; - } - - if (text.empty()) - { - return true; - } - - OrderedJson root; - try - { - root = OrderedJson::parse(StringUtils::StripUtf8Bom(text)); - } - catch (const nlohmann::json::exception &) - { - LogErrorf("security", "failed to parse %s", m_filePath.c_str()); - return false; - } - - if (!root.is_object() || !root.contains("tokens") || !root["tokens"].is_object()) - { - return true; - } - - for (auto it = root["tokens"].begin(); it != root["tokens"].end(); ++it) - { - const std::string &xuidStr = it.key(); - if (!it.value().is_string()) continue; - - unsigned long long parsed = 0; - if (!StringUtils::TryParseUnsignedLongLong(xuidStr, &parsed) || parsed == 0ULL) - continue; - - std::vector tokenBytes; - if (!Base64ToBytes(it.value().get(), tokenBytes)) - continue; - if (tokenBytes.size() != TOKEN_SIZE) - continue; - - m_tokens[static_cast(parsed)] = tokenBytes; - } - - return true; - } - - bool IdentityTokenManager::Save() const - { - OrderedJson root = OrderedJson::object(); - OrderedJson tokens = OrderedJson::object(); - - for (const auto &pair : m_tokens) - { - std::string xuidStr = FormatXuid(pair.first); - std::string tokenB64 = BytesToBase64(pair.second.data(), TOKEN_SIZE); - tokens[xuidStr] = tokenB64; - } - - root["tokens"] = tokens; - - std::string json = root.dump(2) + "\n"; - if (!FileUtils::WriteTextFileAtomic(m_filePath, json)) - { - LogErrorf("security", "failed to write %s", m_filePath.c_str()); - return false; - } - return true; - } - - IdentityTokenManager &GetIdentityTokenManager() - { - static IdentityTokenManager s_instance; - return s_instance; - } - } -} diff --git a/Minecraft.Server/Security/IdentityTokenManager.h b/Minecraft.Server/Security/IdentityTokenManager.h deleted file mode 100644 index 1fd6850d..00000000 --- a/Minecraft.Server/Security/IdentityTokenManager.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#ifdef _WINDOWS64 -#include -#endif - -typedef unsigned __int64 PlayerUID; - -namespace ServerRuntime -{ - namespace Security - { - /** - * Persistent XUID-to-token binding for identity verification. - * - * On first login, the server issues a random 32-byte token to the client - * over the encrypted cipher channel. The client stores it locally. - * On subsequent logins, the server challenges the client to present - * its stored token. Mismatch = kicked. - * - * This prevents XUID replay attacks: an attacker who steals a XUID - * still needs the token, which was only sent over the encrypted channel. - * - * Tokens are stored in `identity-tokens.json` and persist across restarts. - */ - class IdentityTokenManager - { - public: - static const int TOKEN_SIZE = 32; - - IdentityTokenManager(); - ~IdentityTokenManager(); - - IdentityTokenManager(const IdentityTokenManager &) = delete; - IdentityTokenManager &operator=(const IdentityTokenManager &) = delete; - - bool Initialize(const std::string &filePath); - void Shutdown(); - - bool HasToken(PlayerUID xuid) const; - bool GetToken(PlayerUID xuid, uint8_t outToken[TOKEN_SIZE]) const; - bool IssueToken(PlayerUID xuid, uint8_t outToken[TOKEN_SIZE]); - bool VerifyToken(PlayerUID xuid, const uint8_t token[TOKEN_SIZE]) const; - bool RevokeToken(PlayerUID xuid); - - private: - bool Load(); - bool Save() const; - - std::string m_filePath; - std::unordered_map> m_tokens; - mutable CRITICAL_SECTION m_lock; - bool m_initialized; - }; - - IdentityTokenManager &GetIdentityTokenManager(); - } -} diff --git a/Minecraft.Server/Security/SecurityConfig.h b/Minecraft.Server/Security/SecurityConfig.h index 476dc6b2..5d927816 100644 --- a/Minecraft.Server/Security/SecurityConfig.h +++ b/Minecraft.Server/Security/SecurityConfig.h @@ -10,9 +10,6 @@ namespace ServerRuntime int rateLimitConnectionsPerWindow = 5; int rateLimitWindowSeconds = 30; int maxPendingConnections = 10; - bool requireChallengeToken = false; - bool enableStreamCipher = true; - bool requireSecureClient = true; bool proxyProtocol = false; }; diff --git a/Minecraft.Server/Security/StreamCipher.cpp b/Minecraft.Server/Security/StreamCipher.cpp deleted file mode 100644 index 1275b566..00000000 --- a/Minecraft.Server/Security/StreamCipher.cpp +++ /dev/null @@ -1,206 +0,0 @@ -#include "stdafx.h" -#include "StreamCipher.h" - -#ifdef _WINDOWS64 -#include -#pragma comment(lib, "bcrypt.lib") -#endif - -#include - -namespace ServerRuntime -{ - namespace Security - { - StreamCipher::StreamCipher() - : m_sendKeystreamPos(AES_BLOCK) - , m_recvKeystreamPos(AES_BLOCK) - , m_active(false) - { -#ifdef _WINDOWS64 - m_hAlg = nullptr; - m_hKey = nullptr; -#endif - memset(m_sendCounter, 0, sizeof(m_sendCounter)); - memset(m_recvCounter, 0, sizeof(m_recvCounter)); - memset(m_sendKeystream, 0, sizeof(m_sendKeystream)); - memset(m_recvKeystream, 0, sizeof(m_recvKeystream)); - } - - StreamCipher::~StreamCipher() - { - Reset(); - } - - void StreamCipher::Initialize(const uint8_t key[KEY_SIZE], Role role) - { - if (m_active) - { - Reset(); - } - -#ifdef _WINDOWS64 - NTSTATUS status; - - status = BCryptOpenAlgorithmProvider(&m_hAlg, BCRYPT_AES_ALGORITHM, nullptr, 0); - if (!BCRYPT_SUCCESS(status)) - { - m_hAlg = nullptr; - return; - } - - // Set ECB mode -- we manage CTR ourselves for streaming support - status = BCryptSetProperty(m_hAlg, BCRYPT_CHAINING_MODE, - (PUCHAR)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0); - if (!BCRYPT_SUCCESS(status)) - { - BCryptCloseAlgorithmProvider(m_hAlg, 0); - m_hAlg = nullptr; - return; - } - - // Create symmetric key from first 16 bytes - status = BCryptGenerateSymmetricKey(m_hAlg, &m_hKey, nullptr, 0, - (PUCHAR)key, AES_BLOCK, 0); - if (!BCRYPT_SUCCESS(status)) - { - BCryptCloseAlgorithmProvider(m_hAlg, 0); - m_hAlg = nullptr; - m_hKey = nullptr; - return; - } - - // Derive separate counters for send and recv to prevent CTR nonce reuse. - // Flipping the top bit of byte 0 guarantees the two counter spaces never - // overlap (one in 0x00-0x7F range, the other in 0x80-0xFF for byte 0). - // Server send = IV, Server recv = IV^0x80 - // Client send = IV^0x80, Client recv = IV - // This ensures: server-send matches client-recv, client-send matches server-recv. - uint8_t ivBase[AES_BLOCK]; - uint8_t ivFlipped[AES_BLOCK]; - memcpy(ivBase, key + AES_BLOCK, AES_BLOCK); - memcpy(ivFlipped, key + AES_BLOCK, AES_BLOCK); - ivFlipped[0] ^= 0x80; - - if (role == Server) - { - memcpy(m_sendCounter, ivBase, AES_BLOCK); - memcpy(m_recvCounter, ivFlipped, AES_BLOCK); - } - else - { - memcpy(m_sendCounter, ivFlipped, AES_BLOCK); - memcpy(m_recvCounter, ivBase, AES_BLOCK); - } - - SecureZeroMemory(ivBase, sizeof(ivBase)); - SecureZeroMemory(ivFlipped, sizeof(ivFlipped)); - - m_sendKeystreamPos = AES_BLOCK; // force generation on first use - m_recvKeystreamPos = AES_BLOCK; - m_active = true; -#endif - } - - void StreamCipher::Reset() - { -#ifdef _WINDOWS64 - if (m_hKey != nullptr) - { - BCryptDestroyKey(m_hKey); - m_hKey = nullptr; - } - if (m_hAlg != nullptr) - { - BCryptCloseAlgorithmProvider(m_hAlg, 0); - m_hAlg = nullptr; - } -#endif - SecureZeroMemory(m_sendCounter, sizeof(m_sendCounter)); - SecureZeroMemory(m_recvCounter, sizeof(m_recvCounter)); - SecureZeroMemory(m_sendKeystream, sizeof(m_sendKeystream)); - SecureZeroMemory(m_recvKeystream, sizeof(m_recvKeystream)); - m_sendKeystreamPos = AES_BLOCK; - m_recvKeystreamPos = AES_BLOCK; - m_active = false; - } - - void StreamCipher::IncrementCounter(uint8_t counter[AES_BLOCK]) - { - // Big-endian 128-bit increment (standard NIST CTR convention) - for (int i = AES_BLOCK - 1; i >= 0; --i) - { - if (++counter[i] != 0) - break; - } - } - - void StreamCipher::GenerateKeystream(uint8_t counter[AES_BLOCK], uint8_t keystream[AES_BLOCK]) - { -#ifdef _WINDOWS64 - ULONG cbResult = 0; - NTSTATUS status = BCryptEncrypt(m_hKey, counter, AES_BLOCK, nullptr, - nullptr, 0, keystream, AES_BLOCK, &cbResult, 0); // flags=0: exact block, no padding - if (!BCRYPT_SUCCESS(status)) - { - SecureZeroMemory(keystream, AES_BLOCK); - m_active = false; - return; - } - IncrementCounter(counter); -#endif - } - - void StreamCipher::Encrypt(uint8_t *data, int length) - { - if (!m_active || data == nullptr || length <= 0) - { - return; - } - - for (int i = 0; i < length; ++i) - { - if (m_sendKeystreamPos >= AES_BLOCK) - { - GenerateKeystream(m_sendCounter, m_sendKeystream); - m_sendKeystreamPos = 0; - } - data[i] ^= m_sendKeystream[m_sendKeystreamPos++]; - } - } - - void StreamCipher::Decrypt(uint8_t *data, int length) - { - if (!m_active || data == nullptr || length <= 0) - { - return; - } - - for (int i = 0; i < length; ++i) - { - if (m_recvKeystreamPos >= AES_BLOCK) - { - GenerateKeystream(m_recvCounter, m_recvKeystream); - m_recvKeystreamPos = 0; - } - data[i] ^= m_recvKeystream[m_recvKeystreamPos++]; - } - } - - bool StreamCipher::GenerateKey(uint8_t outKey[KEY_SIZE]) - { -#ifdef _WINDOWS64 - NTSTATUS status = BCryptGenRandom(nullptr, outKey, KEY_SIZE, - BCRYPT_USE_SYSTEM_PREFERRED_RNG); - return BCRYPT_SUCCESS(status); -#else - // Fallback: not cryptographically random - for (int i = 0; i < KEY_SIZE; ++i) - { - outKey[i] = static_cast(rand() & 0xFF); - } - return true; -#endif - } - } -} diff --git a/Minecraft.Server/Security/StreamCipher.h b/Minecraft.Server/Security/StreamCipher.h deleted file mode 100644 index 5db2327f..00000000 --- a/Minecraft.Server/Security/StreamCipher.h +++ /dev/null @@ -1,98 +0,0 @@ -#pragma once - -#include - -#ifdef _WINDOWS64 -#include -#include -#endif - -namespace ServerRuntime -{ - namespace Security - { - /** - * AES-128-CTR stream cipher for game traffic encryption. - * - * Uses the Windows BCrypt API to generate AES-encrypted keystream - * blocks that are XOR'd with plaintext. Each direction (send/recv) - * maintains its own counter for independent keystream generation. - * - * Key material: 32 bytes (16-byte AES key + 16-byte IV/nonce). - * The IV is used as the initial counter block for both directions. - * - * Usage: - * 1. Server generates a random 32-byte key via GenerateKey() - * 2. Key is sent to the client in the MC|CKey CustomPayloadPacket - * 3. Both sides call Initialize() with the same 32 bytes - * 4. All subsequent TCP traffic is encrypted via Encrypt/Decrypt - */ - class StreamCipher - { - public: - static const int KEY_SIZE = 32; // 16 AES key + 16 IV - - enum Role { Server, Client }; - - StreamCipher(); - ~StreamCipher(); - - StreamCipher(const StreamCipher &) = delete; - StreamCipher &operator=(const StreamCipher &) = delete; - StreamCipher(StreamCipher &&) = delete; - StreamCipher &operator=(StreamCipher &&) = delete; - - /** - * Initialize with key material. First 16 bytes = AES key, last 16 bytes = IV. - * Role determines counter assignment to prevent nonce reuse between directions: - * Server: send=IV, recv=IV^0x80 (top bit flipped) - * Client: send=IV^0x80, recv=IV - * This ensures server-send matches client-recv and vice versa. - */ - void Initialize(const uint8_t key[KEY_SIZE], Role role = Server); - - /** - * AES-CTR encrypt data in place for sending. - */ - void Encrypt(uint8_t *data, int length); - - /** - * AES-CTR decrypt data in place after receiving. - */ - void Decrypt(uint8_t *data, int length); - - /** - * Returns true if the cipher has been initialized. - */ - bool IsActive() const { return m_active; } - - /** - * Reset to inactive state and securely wipe all key material. - */ - void Reset(); - - /** - * Generate 32 cryptographically random bytes (16 AES key + 16 IV). - */ - static bool GenerateKey(uint8_t outKey[KEY_SIZE]); - - private: - static const int AES_BLOCK = 16; - - static void IncrementCounter(uint8_t counter[AES_BLOCK]); - void GenerateKeystream(uint8_t counter[AES_BLOCK], uint8_t keystream[AES_BLOCK]); - -#ifdef _WINDOWS64 - BCRYPT_ALG_HANDLE m_hAlg; - BCRYPT_KEY_HANDLE m_hKey; -#endif - uint8_t m_sendCounter[AES_BLOCK]; - uint8_t m_recvCounter[AES_BLOCK]; - uint8_t m_sendKeystream[AES_BLOCK]; - uint8_t m_recvKeystream[AES_BLOCK]; - int m_sendKeystreamPos; - int m_recvKeystreamPos; - bool m_active; - }; - } -} diff --git a/Minecraft.Server/ServerProperties.cpp b/Minecraft.Server/ServerProperties.cpp index 1b6c5c0a..43ec5ee0 100644 --- a/Minecraft.Server/ServerProperties.cpp +++ b/Minecraft.Server/ServerProperties.cpp @@ -903,9 +903,6 @@ ServerPropertiesConfig LoadServerPropertiesConfig() config.rateLimitConnectionsPerWindow = ReadNormalizedIntProperty(&merged, "rate-limit-connections-per-window", 5, 1, 100, &shouldWrite); config.rateLimitWindowSeconds = ReadNormalizedIntProperty(&merged, "rate-limit-window-seconds", 30, 5, 300, &shouldWrite); config.maxPendingConnections = ReadNormalizedIntProperty(&merged, "max-pending-connections", 10, 1, 50, &shouldWrite); - config.requireChallengeToken = ReadNormalizedBoolProperty(&merged, "require-challenge-token", false, &shouldWrite); - config.enableStreamCipher = ReadNormalizedBoolProperty(&merged, "enable-stream-cipher", true, &shouldWrite); - config.requireSecureClient = ReadNormalizedBoolProperty(&merged, "require-secure-client", true, &shouldWrite); config.proxyProtocol = ReadNormalizedBoolProperty(&merged, "proxy-protocol", false, &shouldWrite); if (shouldWrite) diff --git a/Minecraft.Server/ServerProperties.h b/Minecraft.Server/ServerProperties.h index fd251fc3..b9568300 100644 --- a/Minecraft.Server/ServerProperties.h +++ b/Minecraft.Server/ServerProperties.h @@ -104,12 +104,6 @@ namespace ServerRuntime int rateLimitWindowSeconds; /** `max-pending-connections` — max simultaneous pending (pre-login) connections */ int maxPendingConnections; - /** `require-challenge-token` — reserved for future protocol extension (not yet enforced) */ - bool requireChallengeToken; - /** `enable-stream-cipher` — enable XOR stream cipher for traffic obfuscation */ - bool enableStreamCipher; - /** `require-secure-client` — kick clients that do not complete the cipher handshake */ - bool requireSecureClient; /** `proxy-protocol` — parse PROXY protocol v1 headers from TCP tunnel (e.g. playit.gg) */ bool proxyProtocol; diff --git a/Minecraft.Server/Windows64/ServerMain.cpp b/Minecraft.Server/Windows64/ServerMain.cpp index b423a90c..8fa6e83a 100644 --- a/Minecraft.Server/Windows64/ServerMain.cpp +++ b/Minecraft.Server/Windows64/ServerMain.cpp @@ -15,7 +15,6 @@ #include "../Console/ServerCli.h" #include "../Security/SecurityConfig.h" #include "../Security/RateLimiter.h" -#include "../Security/IdentityTokenManager.h" #include "../FourKitBridge.h" #include "Tesselator.h" #include "Windows64/4JLibs/inc/4J_Render.h" @@ -448,32 +447,17 @@ int main(int argc, char **argv) secSettings.rateLimitConnectionsPerWindow = serverProperties.rateLimitConnectionsPerWindow; secSettings.rateLimitWindowSeconds = serverProperties.rateLimitWindowSeconds; secSettings.maxPendingConnections = serverProperties.maxPendingConnections; - secSettings.requireChallengeToken = serverProperties.requireChallengeToken; - secSettings.enableStreamCipher = serverProperties.enableStreamCipher; - secSettings.requireSecureClient = serverProperties.requireSecureClient; secSettings.proxyProtocol = serverProperties.proxyProtocol; ServerRuntime::Security::InitializeSettings(secSettings); - LogInfof("startup", "Security: hide-player-list=%s, rate-limit=%d/%ds, max-pending=%d, challenge-token=%s, stream-cipher=%s, require-secure-client=%s", + LogInfof("startup", "Security: hide-player-list=%s, rate-limit=%d/%ds, max-pending=%d", secSettings.hidePlayerListPreLogin ? "true" : "false", secSettings.rateLimitConnectionsPerWindow, secSettings.rateLimitWindowSeconds, - secSettings.maxPendingConnections, - secSettings.requireChallengeToken ? "required" : "optional", - secSettings.enableStreamCipher ? "enabled" : "disabled", - secSettings.requireSecureClient ? "true" : "false"); + secSettings.maxPendingConnections); if (secSettings.proxyProtocol) { LogInfof("startup", "PROXY protocol: enabled (all connections must send PROXY v1 header)"); } - if (secSettings.requireSecureClient && !secSettings.enableStreamCipher) - { - LogInfof("startup", "WARNING: require-secure-client is enabled but enable-stream-cipher is disabled -- secure client enforcement will have no effect"); - } - - if (secSettings.requireChallengeToken) - { - ServerRuntime::Security::GetIdentityTokenManager().Initialize("identity-tokens.json"); - } } LogInfof("startup", "LAN advertise: %s", serverProperties.lanAdvertise ? "enabled" : "disabled"); diff --git a/Minecraft.Server/cmake/sources/Common.cmake b/Minecraft.Server/cmake/sources/Common.cmake index 63d2a76c..dfd816c5 100644 --- a/Minecraft.Server/cmake/sources/Common.cmake +++ b/Minecraft.Server/cmake/sources/Common.cmake @@ -631,14 +631,6 @@ set(_MINECRAFT_SERVER_COMMON_SERVER_SECURITY "${_MS_SRC}/Security/SecurityConfig.h" "${_MS_SRC}/Security/RateLimiter.cpp" "${_MS_SRC}/Security/RateLimiter.h" - "${_MS_SRC}/Security/StreamCipher.cpp" - "${_MS_SRC}/Security/StreamCipher.h" - "${_MS_SRC}/Security/ConnectionCipher.cpp" - "${_MS_SRC}/Security/ConnectionCipher.h" - "${_MS_SRC}/Security/CipherHandshakeEnforcer.cpp" - "${_MS_SRC}/Security/CipherHandshakeEnforcer.h" - "${_MS_SRC}/Security/IdentityTokenManager.cpp" - "${_MS_SRC}/Security/IdentityTokenManager.h" ) source_group("Server/Security" FILES ${_MINECRAFT_SERVER_COMMON_SERVER_SECURITY}) diff --git a/Minecraft.World/CustomPayloadPacket.cpp b/Minecraft.World/CustomPayloadPacket.cpp index 6b706d6f..dec288eb 100644 --- a/Minecraft.World/CustomPayloadPacket.cpp +++ b/Minecraft.World/CustomPayloadPacket.cpp @@ -21,14 +21,6 @@ const wstring CustomPayloadPacket::SET_ADVENTURE_COMMAND_PACKET = CreateVanillaP const wstring CustomPayloadPacket::SET_BEACON_PACKET = CreateVanillaPayloadKey(L"Beacon"); const wstring CustomPayloadPacket::SET_ITEM_NAME_PACKET = CreateVanillaPayloadKey(L"ItemName"); -const wstring CustomPayloadPacket::CIPHER_KEY_CHANNEL = CreateVanillaPayloadKey(L"CKey"); -const wstring CustomPayloadPacket::CIPHER_ACK_CHANNEL = CreateVanillaPayloadKey(L"CAck"); -const wstring CustomPayloadPacket::CIPHER_ON_CHANNEL = CreateVanillaPayloadKey(L"COn"); - -const wstring CustomPayloadPacket::IDENTITY_TOKEN_ISSUE = CreateVanillaPayloadKey(L"CTIssue"); -const wstring CustomPayloadPacket::IDENTITY_TOKEN_CHALLENGE = CreateVanillaPayloadKey(L"CTChallenge"); -const wstring CustomPayloadPacket::IDENTITY_TOKEN_RESPONSE = CreateVanillaPayloadKey(L"CTResponse"); - const wstring CustomPayloadPacket::FORK_HELLO_CHANNEL = CreateVanillaPayloadKey(L"ForkHello"); const wstring CustomPayloadPacket::FORK_PLAYER_LEAVE_CHANNEL = CreateVanillaPayloadKey(L"ForkPLeave"); diff --git a/Minecraft.World/CustomPayloadPacket.h b/Minecraft.World/CustomPayloadPacket.h index 4fd30f05..399d3f2d 100644 --- a/Minecraft.World/CustomPayloadPacket.h +++ b/Minecraft.World/CustomPayloadPacket.h @@ -24,16 +24,6 @@ public: static const wstring UPDATE_RECIPE_REGISTRY; static const wstring UPDATE_CREATIVE_REGISTRY; - // Security: stream cipher handshake channels - static const wstring CIPHER_KEY_CHANNEL; // server->client: carries 32-byte key (16 AES key + 16 IV) - static const wstring CIPHER_ACK_CHANNEL; // client->server: ack (empty payload) - static const wstring CIPHER_ON_CHANNEL; // server->client: activation signal (empty payload) - - // Security: identity token channels - static const wstring IDENTITY_TOKEN_ISSUE; // server->client: issue new 32-byte token - static const wstring IDENTITY_TOKEN_CHALLENGE; // server->client: request stored token - static const wstring IDENTITY_TOKEN_RESPONSE; // client->server: present stored token - // Fork extensions: server capability and player lifecycle static const wstring FORK_HELLO_CHANNEL; // server->client: identifies fork server (empty payload) static const wstring FORK_PLAYER_LEAVE_CHANNEL; // server->client: player disconnected (payload: UTF gamertag)