// Hidden C++ exception states: #wind=1 char __fastcall…
- User
// Hidden C++ exception states: #wind=1 char __fastcall RakNet::RakPeer::sendRbxOpenReply2( RakNet::RakPeer *this, RakNet::RakPeer::RemoteSystemStruct *rss, const RakNet::SystemAddress *systemAddress, const RakNet::SystemAddress *udmuxAddress, std::shared_ptrRakNet::RakNetSocket *rakNetSocket) { unsigned int v10; // edx bool v11; // al RBX::Security::RakPeerCrypto *v12; // r15 const unsigned __int8 *v13; // rdx unsigned __int8 *v14; // rdx RakNet::RakPeer_vtbl *v15; // rax unsigned __int8 *v16; // rbx unsigned __int8 *v17; // rdx const unsigned __int8 *v18; // rdx const char *v19; // rdi const char *v20; // rbx bool v21; // al const char *v22; // r8 unsigned __int64 v23; // rbx const unsigned __int8 *v24; // rdx unsigned __int8 v25; // cl const char *v26; // rdx unsigned int v27; // r8d unsigned __int8 *data; // rdx std::shared_ptrRakNet::RakNetSocket *v29; // rax std::_Ref_count_base *Rep; // rcx char v31; // bl unsigned __int8 version[4]; // [rsp+60h] [rbp-A0h] BYREF unsigned __int16 ciphertextLen[2]; // [rsp+64h] [rbp-9Ch] BYREF unsigned __int8 inByteArray; // [rsp+68h] [rbp-98h] BYREF unsigned __int8 selectedEncryption; // [rsp+69h] [rbp-97h] BYREF unsigned __int8 tokenSize[2]; // [rsp+6Ah] [rbp-96h] BYREF unsigned __int16 mtu16[2]; // [rsp+6Ch] [rbp-94h] BYREF unsigned __int8 inOutByteArray[4]; // [rsp+70h] [rbp-90h] BYREF unsigned __int8 v39[4]; // [rsp+74h] [rbp-8Ch] BYREF unsigned __int8 v40[8]; // [rsp+78h] [rbp-88h] BYREF unsigned __int8 v41[8]; // [rsp+80h] [rbp-80h] BYREF std::shared_ptrRakNet::RakNetSocket v42; // [rsp+88h] [rbp-78h] BYREF unsigned __int8 v43[8]; // [rsp+98h] [rbp-68h] BYREF unsigned __int8 v44[8]; // [rsp+A0h] [rbp-60h] BYREF RBX::ArrayView publicEphemeralKey; // [rsp+A8h] [rbp-58h] BYREF unsigned __int8 token[24]; // [rsp+B8h] [rbp-48h] BYREF RakNet::BitStream bsOut; // [rsp+D0h] [rbp-30h] BYREF RakNet::SystemAddress v48; // [rsp+200h] [rbp+100h] BYREF unsigned __int8 aadLen; // [rsp+258h] [rbp+158h] BYREF
if ( *(&rss->reliabilityLayer.rbxSessionCrypto._Ptr + 4) ) { v10 = 952; if ( FFlag::RuppTokEn4.value ) v10 = 1088; RakNet::BitStream::BitStream(&bsOut, v10); v11 = FFlag::RuppTokEn4.value && this->getServerReceiveRuppToken(this) && rss->tokenOptions._Has_value; version[0] = v11; aadLen = 0; ciphertextLen[0] = 0; v12 = *(&rss->reliabilityLayer.rbxSessionCrypto._Ptr + 4); RBX::Security::RakPeerCrypto::getPublicKey(v12, &publicEphemeralKey); if ( publicEphemeralKey.buffer && publicEphemeralKey.length ) { selectedEncryption = RBX::Security::SessionCrypto::getRakCryptoFormat(v12); inByteArray = 125; RakNet::BitStream::WriteBits(&bsOut, &inByteArray, 8u, 1); RakNet::BitStream::WriteAlignedBytes(&bsOut, OFFLINE_MESSAGE_DATA_ID, 0x10u); RakNet::BitStream::WriteBits(&bsOut, version, 8u, 1); RakNet::BitStream::WriteBits(&bsOut, &aadLen, 8u, 1); if ( RakNet::BitStream::IsNetworkOrder() ) { v13 = ciphertextLen; } else { RBX::Network::NetworkStream::ReverseBytes(ciphertextLen, inOutByteArray, 2u); v13 = inOutByteArray; } RakNet::BitStream::WriteBits(&bsOut, v13, 0x10u, 1); aadLen = bsOut.numberOfBitsUsed >> 3; RakNet::BitStream::WriteAlignedBytes(&bsOut, publicEphemeralKey.buffer, 0x20u); *v41 = rss->remoteCommonCapabilities; if ( RakNet::BitStream::IsNetworkOrder() ) { v14 = v41; } else { RBX::Network::NetworkStream::ReverseBytes(v41, v43, 8u); v14 = v43; } RakNet::BitStream::WriteBits(&bsOut, v14, 0x40u, 1); v15 = this->__vftable; v48 = RakNet::UNASSIGNED_SYSTEM_ADDRESS_35; v16 = (v15->GetGuidFromSystemAddress)(this, &v48); if ( RakNet::BitStream::IsNetworkOrder() ) { v17 = v16; } else { RBX::Network::NetworkStream::ReverseBytes(v16, v44, 8u); v17 = v44; } RakNet::BitStream::WriteBits(&bsOut, v17, 0x40u, 1); mtu16[0] = rss->MTUSize; if ( RakNet::BitStream::IsNetworkOrder() ) { v18 = mtu16; } else { RBX::Network::NetworkStream::ReverseBytes(mtu16, v39, 2u); v18 = v39; } RakNet::BitStream::WriteBits(&bsOut, v18, 0x10u, 1); RakNet::BitStream::WriteBits(&bsOut, &selectedEncryption, 8u, 1); RakNet::BitStream::WriteRakNet::SystemAddress(&bsOut, &rss->systemAddress); if ( FFlag::RuppTokEn4.value && version[0] ) { tokenSize[0] = 16; RakNet::BitStream::WriteBits(&bsOut, tokenSize, 8u, 1); *token = 0LL; this->generateUdmuxToken(this, token, systemAddress, rss->tokenOptions._Value); RakNet::BitStream::WriteAlignedBytes(&bsOut, token, 0x10u); } if ( DFLog::RuppTokenLog ) { v19 = "not replied."; if ( version[0] ) v19 = "replied."; v20 = "not received"; if ( rss->tokenOptions._Has_value ) v20 = "received"; v21 = this->getServerReceiveRuppToken(this); v22 = "not expected"; if ( v21 ) v22 = "expected"; FLog::FastLogFormatted( DFLog::RuppTokenLog, "[DFLog::RuppTokenLog] Token %s. RbxOpenRequest2 token %s. RbxOpenReply2 token %s", v22, v20, v19); } ciphertextLen[0] = (bsOut.numberOfBitsUsed >> 3) - aadLen; RakNet::BitStream::WriteAlignedBytes(&bsOut, kZeroPacket, 0x1Cu); v23 = bsOut.numberOfBitsUsed >> 3; RakNet::BitStream::SetWriteOffset(&bsOut, 0x90u, 0); RakNet::BitStream::WriteBits(&bsOut, &aadLen, 8u, 1); if ( RakNet::BitStream::IsNetworkOrder() ) { v24 = ciphertextLen; } else { RBX::Network::NetworkStream::ReverseBytes(ciphertextLen, v40, 2u); v24 = v40; } RakNet::BitStream::WriteBits(&bsOut, v24, 0x10u, 1); RakNet::BitStream::SetWriteOffset(&bsOut, 8 * v23, 0); if ( RBX::Security::RakPeerCrypto::earlyEncryptData(v12, &bsOut, aadLen, 0) ) { v27 = (bsOut.numberOfBitsUsed + 7) >> 3; data = bsOut.data; v42 = 0LL; v29 = rakNetSocket; Rep = rakNetSocket->_Rep; if ( Rep ) { _InterlockedIncrement(&Rep->_Uses); Rep = v29->_Rep; } v42._Ptr = v29->_Ptr; v42._Rep = Rep; if ( !RakNet::SocketLayer::SendToOrDelay( &v42, data, v27, systemAddress, udmuxAddress, 0, this, 0LL, 0LL, "C:\buildAgent\work\ci_nbs_stu-x64\Client\Network\raknet\Source\RakPeer.cpp", 6771) ) RakNet::RakPeer::ConnectionRequestsStats::Increment(&this->connectionRequestsStats, OpenRep2Sent); v31 = 1; goto LABEL_52; } v25 = DFLog::SessionCrypto; if ( DFLog::SessionCrypto ) { v26 = "[DFLog::SessionCrypto] RbxOpenReply2 encrypt failed"; LABEL_50: FLog::FastLog(v25, v26, 0LL); } } else { v25 = DFLog::SessionCrypto; if ( DFLog::SessionCrypto ) { v26 = "[DFLog::SessionCrypto] RbxOpenReply2 no public key"; goto LABEL_50; } } v31 = 0; LABEL_52: RakNet::BitStream::~BitStream(&bsOut); return v31; } if ( DFLog::SessionCrypto ) FLog::FastLog(DFLog::SessionCrypto, "[DFLog::SessionCrypto] RbxOpenReply2 no session crypto", 0LL); return 0; }
Reverse engineer this C++ psuedocode.
- Assistant
Sure, let's break down and reverse engineer the provided C++ function
RakNet::RakPeer::sendRbxOpenReply2into a more comprehensible pseudocode. This function appears to handle the creation and sending of an encrypted reply (possibly as part of a handshake or authentication process) within the RakNet networking library. Here's a step-by-step interpretation of the function's logic:
Function Overview
Function Name:
RakNet::RakPeer::sendRbxOpenReply2Purpose: Constructs and sends an encrypted reply (
RbxOpenReply2) to a remote system using session cryptography. It builds a bitstream with necessary data, encrypts it, and sends it through a network socket.Parameters:
this: Pointer to the currentRakPeerinstance.rss: Pointer toRemoteSystemStructcontaining information about the remote system.systemAddress: Pointer to the system's network address.udmuxAddress: Pointer to the UDMUX (User Datagram Multiplexing) network address.rakNetSocket: Shared pointer to theRakNetSocketused for sending data.
Return Value:
char: Success (1) or failure (0) of the send operation.
Pseudocode Representation
Function sendRbxOpenReply2(this, rss, systemAddress, udmuxAddress, rakNetSocket): // Check if session cryptography is available if (rss.reliabilityLayer.rbxSessionCrypto.ptr + 4 is not null): // Determine the size of the BitStream based on a feature flag if (FFlag.RuppTokEn4.value is true): bitstream_size = 1088 else: bitstream_size = 952 // Initialize the BitStream with the determined size bsOut = BitStream(bitstream_size) // Determine if the version flag should be set version_flag = FFlag.RuppTokEn4.value AND this.getServerReceiveRuppToken() AND rss.tokenOptions.has_value // Store the version flag in the BitStream version_byte = version_flag ? 1 : 0 bsOut.writeBits(version_byte, 8) // Initialize additional fields aadLen = 0 ciphertextLen = 0 // Retrieve session cryptography object sessionCrypto = rss.reliabilityLayer.rbxSessionCrypto.ptr + 4 // Get the public ephemeral key from the session cryptography publicEphemeralKey = sessionCrypto.getPublicKey() // Proceed if the public ephemeral key is valid if (publicEphemeralKey.isValid()): // Get the selected encryption format selectedEncryption = sessionCrypto.getRakCryptoFormat() // Write initial encryption parameters to BitStream inByteArray = 125 bsOut.writeBits(inByteArray, 8) bsOut.writeAlignedBytes(OFFLINE_MESSAGE_DATA_ID, 2) // 16 bits bsOut.writeBits(version_byte, 8) bsOut.writeBits(aadLen, 8) // Handle byte order for ciphertext length if (BitStream.isNetworkOrder()): write_ciphertextLen = ciphertextLen else: write_ciphertextLen = ReverseBytes(ciphertextLen, 2) bsOut.writeBits(write_ciphertextLen, 16) // Update aadLen based on current BitStream usage aadLen = bsOut.bitsUsed() / 8 // Write the public ephemeral key to the BitStream bsOut.writeAlignedBytes(publicEphemeralKey.buffer, 32) // 256 bits // Write remote capabilities, handling byte order remoteCapabilities = rss.remoteCommonCapabilities if (!BitStream.isNetworkOrder()): remoteCapabilities = ReverseBytes(remoteCapabilities, 8) bsOut.writeBits(remoteCapabilities, 64) // Retrieve and write GUID from an unassigned system address guid = this.GetGuidFromSystemAddress(UNASSIGNED_SYSTEM_ADDRESS) if (!BitStream.isNetworkOrder()): guid = ReverseBytes(guid, 8) bsOut.writeBits(guid, 64) // Write MTU size, handling byte order mtu16 = rss.MTUSize if (!BitStream.isNetworkOrder()): mtu16 = ReverseBytes(mtu16, 2) bsOut.writeBits(mtu16, 16) // Write the selected encryption byte bsOut.writeBits(selectedEncryption, 8) // Write the system address to the BitStream bsOut.write(rss.systemAddress) // If specific feature flags are set, handle token generation if (FFlag.RuppTokEn4.value AND version_flag): tokenSize = 16 bsOut.writeBits(tokenSize, 8) // Initialize token with zeros token = [0] * 24 // Generate the Udmux token this.generateUdmuxToken(token, systemAddress, rss.tokenOptions.value) // Write the token to the BitStream bsOut.writeAlignedBytes(token, 16) // 128 bits // Optional logging for token information if (DFLog.RuppTokenLog is enabled): log_status = version_flag ? "replied." : "not replied." token_received = rss.tokenOptions.has_value ? "received" : "not received" token_expected = this.getServerReceiveRuppToken() ? "expected" : "not expected" FLog.FastLogFormatted( DFLog.RuppTokenLog, "[DFLog::RuppTokenLog] Token %s. RbxOpenRequest2 token %s. RbxOpenReply2 token %s", token_expected, token_received, log_status ) // Calculate ciphertext length ciphertextLen = (bsOut.bitsUsed() / 8) - aadLen // Write zero padding to the BitStream bsOut.writeAlignedBytes(kZeroPacket, 28) // 224 bits // Store the current BitStream length in bytes totalBytes = bsOut.bitsUsed() / 8 // Update specific positions in the BitStream with aadLen and ciphertextLen bsOut.setWriteOffset(0x90) // Offset to byte 144 bsOut.writeBits(aadLen, 8) if (!BitStream.isNetworkOrder()): write_ciphertextLen = ReverseBytes(ciphertextLen, 2) bsOut.writeBits(write_ciphertextLen, 16) bsOut.setWriteOffset(totalBytes * 8) // Move to end of BitStream // Attempt to encrypt the BitStream data if (sessionCrypto.earlyEncryptData(bsOut, aadLen, false)): dataLength = ceil(bsOut.bitsUsed() / 8.0) data = bsOut.data // Prepare the shared pointer for the socket socketSharedPtr = rakNetSocket.copy() // Attempt to send the encrypted data success = SocketLayer.SendToOrDelay( socketSharedPtr, data, dataLength, systemAddress, udmuxAddress, additionalParams... ) // If sending fails, increment the statistic if (!success): this.connectionRequestsStats.Increment(OpenRep2Sent) result = 1 // Success else: // Log encryption failure if (DFLog.SessionCrypto is enabled): FLog.FastLog( DFLog.SessionCrypto, "[DFLog::SessionCrypto] RbxOpenReply2 encrypt failed" ) result = 0 // Failure else: // Log absence of public ephemeral key if (DFLog.SessionCrypto is enabled): FLog.FastLog( DFLog.SessionCrypto, "[DFLog::SessionCrypto] RbxOpenReply2 no public key" ) result = 0 // Failure // Clean up the BitStream bsOut.~BitStream() return result else: // Log absence of session cryptography if (DFLog.SessionCrypto is enabled): FLog.FastLog( DFLog.SessionCrypto, "[DFLog::SessionCrypto] RbxOpenReply2 no session crypto" ) return 0 // Failure
Detailed Step-by-Step Explanation
-
Session Cryptography Check:
- The function begins by checking if session cryptography (
rbxSessionCrypto) is available within theRemoteSystemStruct(rss). If not present, it logs an error and returns failure (0).
- The function begins by checking if session cryptography (
-
BitStream Size Determination:
- Depending on the feature flag
FFlag::RuppTokEn4, it sets thebitstream_sizeto either1088or952bytes. This size determines the initial capacity of theBitStreamused to assemble the reply packet.
- Depending on the feature flag
-
BitStream Initialization:
- A
BitStreamobject (bsOut) is initialized with the determined size. This stream will be used to serialize the data that needs to be sent.
- A
-
Version Flag Determination:
- A
version_flagis set based on three conditions:FFlag::RuppTokEn4is enabled.- The server is configured to receive a Rupp token (
getServerReceiveRuppTokenreturnstrue). tokenOptionswithinrsshas a value.
- This flag is then written as an 8-bit value into the
BitStream.
- A
-
Session Cryptography Object Retrieval:
- The session cryptography object (
sessionCrypto) is retrieved from therss. This object is essential for cryptographic operations like key retrieval and data encryption.
- The session cryptography object (
-
Public Ephemeral Key Handling:
- The public ephemeral key is obtained from
sessionCrypto. If the key is valid (i.e., both buffer and length are present), the function proceeds to serialize various cryptographic and session-related data into theBitStream.
- The public ephemeral key is obtained from
-
Serialization into BitStream:
-
Encryption Parameters:
- An
inByteArraywith a value of125is written as an 8-bit value. - A predefined identifier (
OFFLINE_MESSAGE_DATA_ID) is written as 16 bits. - The previously determined
version_flagis written as 8 bits. - An
aadLen(Additional Authenticated Data Length) is initialized and written as 8 bits.
- An
-
Ciphertext Length Handling:
- Depending on the network byte order, the
ciphertextLenis either written directly or after reversing its bytes.
- Depending on the network byte order, the
-
Public Ephemeral Key:
- The public ephemeral key buffer (32 bytes) is written into the
BitStream.
- The public ephemeral key buffer (32 bytes) is written into the
-
Remote Capabilities and GUID:
- Remote system capabilities and a GUID (Globally Unique Identifier) are serialized, with byte order adjustments if necessary.
-
MTU Size and Encryption Selection:
- The MTU (Maximum Transmission Unit) size is written as a 16-bit value after handling byte order.
- The selected encryption method is written as an 8-bit value.
-
System Address:
- The system's network address is serialized into the
BitStream.
- The system's network address is serialized into the
-
Token Generation (Conditional):
- If both
FFlag::RuppTokEn4andversion_flagare true, a token size is written, and a Udmux token is generated and serialized. This likely relates to session authentication or validation.
- If both
-
Logging (Optional):
- If logging for Rupp tokens is enabled (
DFLog::RuppTokenLog), detailed information about the token status is logged for debugging or auditing purposes.
- If logging for Rupp tokens is enabled (
-
-
Ciphertext Length Calculation and Padding:
- The actual length of the ciphertext is calculated based on the current
BitStreamusage. - A zero padding (
kZeroPacket) is written to theBitStreamto align the data correctly.
- The actual length of the ciphertext is calculated based on the current
-
Finalizing the BitStream:
- Specific offsets within the
BitStreamare updated withaadLenandciphertextLento finalize the packet structure.
- Specific offsets within the
-
Data Encryption:
- The function attempts to encrypt the serialized data using
sessionCrypto.earlyEncryptData. - If encryption succeeds:
- The encrypted data is sent using the provided
rakNetSocket. - If sending fails, a statistic (
OpenRep2Sent) is incremented for tracking purposes. - The function returns success (
1).
- The encrypted data is sent using the provided
- If encryption fails:
- An error is logged indicating the failure.
- The function returns failure (
0).
- The function attempts to encrypt the serialized data using
-
Handling Missing Public Ephemeral Key:
- If the public ephemeral key is missing, an error is logged, and the function returns failure (
0).
- If the public ephemeral key is missing, an error is logged, and the function returns failure (
-
Cleanup and Exit:
- The
BitStreamis destructed to free resources. - The function returns the result based on the success or failure of the operations.
- The
Key Components and Concepts
-
BitStream:
- A utility for serializing and deserializing binary data. It allows writing and reading bits and bytes at specific offsets, which is crucial for network packet construction.
-
Session Cryptography (
sessionCrypto):- Handles cryptographic operations such as key management and data encryption. Ensures secure communication between systems.
-
Feature Flags (
FFlag):- Boolean flags that enable or disable specific features or code paths at runtime, allowing for configurable behavior without code changes.
-
Logging (
DFLogandFLog):- Logging mechanisms used for debugging, auditing, and monitoring the behavior of the function, especially around token handling and cryptographic operations.
-
Token Handling:
- Tokens are likely used for authenticating sessions or validating requests. Proper generation and management of tokens are critical for security.
-
Error Handling:
- Comprehensive checks and logging ensure that issues are detected, logged, and handled gracefully, preventing undefined behavior or security vulnerabilities.
Conclusion
The
sendRbxOpenReply2function is a comprehensive method that constructs an encrypted reply packet using session cryptography, handles various serialization tasks, manages tokens based on feature flags, and ensures secure data transmission over a network socket. Proper error handling and logging are integral parts of the function, ensuring robustness and maintainability.This pseudocode and explanation should provide a clear understanding of the function's workflow and its role within the RakNet networking library.