Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

// Hidden C++ exception states: #wind=1 char __fastcall…

  1. 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.

  2. Assistant

    Sure, let's break down and reverse engineer the provided C++ function RakNet::RakPeer::sendRbxOpenReply2 into 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::sendRbxOpenReply2
    

    Purpose: 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 current RakPeer instance.
    • rss: Pointer to RemoteSystemStruct containing 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 the RakNetSocket used 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

    1. Session Cryptography Check:

      • The function begins by checking if session cryptography (rbxSessionCrypto) is available within the RemoteSystemStruct (rss). If not present, it logs an error and returns failure (0).
    2. BitStream Size Determination:

      • Depending on the feature flag FFlag::RuppTokEn4, it sets the bitstream_size to either 1088 or 952 bytes. This size determines the initial capacity of the BitStream used to assemble the reply packet.
    3. BitStream Initialization:

      • A BitStream object (bsOut) is initialized with the determined size. This stream will be used to serialize the data that needs to be sent.
    4. Version Flag Determination:

      • A version_flag is set based on three conditions:
        • FFlag::RuppTokEn4 is enabled.
        • The server is configured to receive a Rupp token (getServerReceiveRuppToken returns true).
        • tokenOptions within rss has a value.
      • This flag is then written as an 8-bit value into the BitStream.
    5. Session Cryptography Object Retrieval:

      • The session cryptography object (sessionCrypto) is retrieved from the rss. This object is essential for cryptographic operations like key retrieval and data encryption.
    6. 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 the BitStream.
    7. Serialization into BitStream:

      • Encryption Parameters:

        • An inByteArray with a value of 125 is written as an 8-bit value.
        • A predefined identifier (OFFLINE_MESSAGE_DATA_ID) is written as 16 bits.
        • The previously determined version_flag is written as 8 bits.
        • An aadLen (Additional Authenticated Data Length) is initialized and written as 8 bits.
      • Ciphertext Length Handling:

        • Depending on the network byte order, the ciphertextLen is either written directly or after reversing its bytes.
      • Public Ephemeral Key:

        • The public ephemeral key buffer (32 bytes) is written into the BitStream.
      • 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.
      • Token Generation (Conditional):

        • If both FFlag::RuppTokEn4 and version_flag are true, a token size is written, and a Udmux token is generated and serialized. This likely relates to session authentication or validation.
      • Logging (Optional):

        • If logging for Rupp tokens is enabled (DFLog::RuppTokenLog), detailed information about the token status is logged for debugging or auditing purposes.
    8. Ciphertext Length Calculation and Padding:

      • The actual length of the ciphertext is calculated based on the current BitStream usage.
      • A zero padding (kZeroPacket) is written to the BitStream to align the data correctly.
    9. Finalizing the BitStream:

      • Specific offsets within the BitStream are updated with aadLen and ciphertextLen to finalize the packet structure.
    10. 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).
      • If encryption fails:
        • An error is logged indicating the failure.
        • The function returns failure (0).
    11. Handling Missing Public Ephemeral Key:

      • If the public ephemeral key is missing, an error is logged, and the function returns failure (0).
    12. Cleanup and Exit:

      • The BitStream is destructed to free resources.
      • The function returns the result based on the success or failure of the operations.

    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 (DFLog and FLog):

      • 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 sendRbxOpenReply2 function 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.