From c7dff2296392fce19b2c325adf8e2ebef1c72dee Mon Sep 17 00:00:00 2001 From: Cameron Gutman Date: Sun, 1 Nov 2026 14:07:45 -0600 Subject: [PATCH] Add replay detection to RTSP and control streams Replays can do very little harm in these contexts, but let's detect and prevent them anyways. Fixes #165 Closes #170 --- src/AudioStream.c | 4 +- src/ControlStream.c | 13 ++++-- src/InputStream.c | 2 +- src/PlatformCrypto.c | 109 +++++++++++++++++++++++++++++++++++++++++-- src/PlatformCrypto.h | 17 ++++++- src/RtspConnection.c | 6 +-- src/VideoStream.c | 5 +- 7 files changed, 139 insertions(+), 17 deletions(-) diff --git a/src/AudioStream.c b/src/AudioStream.c index 2fcc1f0..bb76b22 100644 --- a/src/AudioStream.c +++ b/src/AudioStream.c @@ -72,7 +72,7 @@ int initializeAudioStream(void) { receivedDataFromPeer = false; pingThreadStarted = false; firstReceiveTime = 0; - audioDecryptionCtx = PltCreateCryptoContext(); + audioDecryptionCtx = PltCreateCryptoContext(0); #ifdef LC_DEBUG opusHeaderByte = INVALID_OPUS_HEADER; #endif @@ -189,7 +189,7 @@ static void decodeInputData(PQUEUED_AUDIO_PACKET packet) { memcpy(iv, &ivSeq, sizeof(ivSeq)); - if (!PltDecryptMessage(audioDecryptionCtx, ALGORITHM_AES_CBC, CIPHER_FLAG_RESET_IV | CIPHER_FLAG_FINISH, + if (!PltDecryptMessage(audioDecryptionCtx, ALGORITHM_AES_CBC, CIPHER_FLAG_RESET_IV | CIPHER_FLAG_FINISH, 0, ivSeq, (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey), iv, sizeof(iv), NULL, 0, diff --git a/src/ControlStream.c b/src/ControlStream.c index 859bd18..e7d131e 100644 --- a/src/ControlStream.c +++ b/src/ControlStream.c @@ -356,8 +356,8 @@ int initializeControlStream(void) { firstFrameTimeMs = 0; currentEnetSequenceNumber = 0; usePeriodicPing = APP_VERSION_AT_LEAST(7, 1, 415); - encryptionCtx = PltCreateCryptoContext(); - decryptionCtx = PltCreateCryptoContext(); + encryptionCtx = PltCreateCryptoContext(0); + decryptionCtx = PltCreateCryptoContext(CTRL_CHANNEL_COUNT); hdrEnabled = false; memset(&hdrMetadata, 0, sizeof(hdrMetadata)); @@ -595,9 +595,10 @@ static bool encryptControlMessage(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, PNVC } // Caller must free() *packet on success!!! -static bool decryptControlMessageToV1(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, int encPacketLength, PNVCTL_ENET_PACKET_HEADER_V1* packet, int* packetLength) { +static bool decryptControlMessageToV1(uint8_t channelId, PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, int encPacketLength, PNVCTL_ENET_PACKET_HEADER_V1* packet, int* packetLength) { unsigned char iv[16] = { 0 }; int ivSize; + int cipherFlags; *packet = NULL; @@ -631,10 +632,12 @@ static bool decryptControlMessageToV1(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, // Use 12-byte IV which is ideal for AES-GCM ivSize = 12; + cipherFlags = 0; } else { // This is a truncating cast, but it's what Nvidia does, so we have to mimic it. iv[0] = (unsigned char)encPacket->seq; + cipherFlags = CIPHER_FLAG_NO_REPLAY_CHECK; // Nvidia's old style encryption uses a 16-byte IV ivSize = 16; @@ -648,7 +651,7 @@ static bool decryptControlMessageToV1(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, LC_ASSERT(ivSize <= (int)sizeof(iv)); LC_ASSERT(ivSize == 12 || ivSize == 16); - if (!PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, 0, + if (!PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, cipherFlags, channelId, encPacket->seq, (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey), iv, ivSize, (unsigned char*)(encPacket + 1), AES_GCM_TAG_LENGTH, // The tag is located right after the header @@ -1251,7 +1254,7 @@ static void controlReceiveThreadFunc(void* context) { ctlHdr = NULL; packetLength = (int)event.packet->dataLength; - if (!decryptControlMessageToV1(encHdr, packetLength, &ctlHdr, &packetLength)) { + if (!decryptControlMessageToV1(event.channelID, encHdr, packetLength, &ctlHdr, &packetLength)) { Limelog("Failed to decrypt control packet of size %d\n", event.packet->dataLength); enet_packet_destroy(event.packet); continue; diff --git a/src/InputStream.c b/src/InputStream.c index e953c6e..c851f8c 100644 --- a/src/InputStream.c +++ b/src/InputStream.c @@ -98,7 +98,7 @@ int initializeInputStream(void) { LbqInitializeLinkedBlockingQueue(&packetQueue, MAX_QUEUED_INPUT_PACKETS); LbqInitializeLinkedBlockingQueue(&packetHolderFreeList, MAX_QUEUED_INPUT_PACKETS); - cryptoContext = PltCreateCryptoContext(); + cryptoContext = PltCreateCryptoContext(0); encryptedControlStream = APP_VERSION_AT_LEAST(7, 1, 431); // FIXME: Unsure if this is exactly right, but it's probably good enough. diff --git a/src/PlatformCrypto.c b/src/PlatformCrypto.c index 7cad833..35493e3 100644 --- a/src/PlatformCrypto.c +++ b/src/PlatformCrypto.c @@ -264,6 +264,100 @@ bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, #endif } +static bool isReplayedMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, unsigned char replayWindowIndex, unsigned int sequenceNumber) { + if (algorithm == ALGORITHM_AES_CBC || (flags & CIPHER_FLAG_NO_REPLAY_CHECK)) { + return false; + } + + if (replayWindowIndex >= ctx->replayWindowCount) { + LC_ASSERT(false); + return true; + } + + PREPLAY_WINDOW window = &ctx->replayWindows[replayWindowIndex]; + if (!window->decryptedAuthedMessage) { + return false; + } + + uint32_t diff = sequenceNumber - window->lastDecryptedAuthedSeqNum; + if (diff > 0 && diff < 0x80000000) { + // Newer sequence number + return false; + } + + if (diff == 0) { + // Duplicate of highest received sequence number + return true; + } + + // Packet is older than lastDecryptedAuthedSeqNum + uint32_t offset = window->lastDecryptedAuthedSeqNum - sequenceNumber; + if (offset >= REPLAY_WINDOW_SIZE) { + return true; + } + + int wordIndex = (int)(offset / 64); + int bitIndex = (int)(offset % 64); + return (window->replayWindow[wordIndex] & ((uint64_t)1 << bitIndex)) != 0; +} + +static void shiftReplayWindow(PREPLAY_WINDOW window, uint32_t shift) { + if (shift >= REPLAY_WINDOW_SIZE) { + memset(window->replayWindow, 0, sizeof(window->replayWindow)); + window->replayWindow[0] = 1; + return; + } + + int wordShift = (int)(shift / 64); + int bitShift = (int)(shift % 64); + + for (int i = REPLAY_WINDOW_WORDS - 1; i >= 0; i--) { + uint64_t val = 0; + if (i >= wordShift) { + val = window->replayWindow[i - wordShift] << bitShift; + if (bitShift > 0 && i > wordShift) { + val |= window->replayWindow[i - wordShift - 1] >> (64 - bitShift); + } + } + window->replayWindow[i] = val; + } + + window->replayWindow[0] |= 1; +} + +static void recordSuccessfulAuthenticatedDecryption(PPLT_CRYPTO_CONTEXT ctx, int flags, unsigned char replayWindowIndex, unsigned int sequenceNumber) { + if (flags & CIPHER_FLAG_NO_REPLAY_CHECK) { + return; + } + + if (replayWindowIndex >= ctx->replayWindowCount) { + LC_ASSERT(false); + return; + } + + PREPLAY_WINDOW window = &ctx->replayWindows[replayWindowIndex]; + if (!window->decryptedAuthedMessage) { + window->decryptedAuthedMessage = true; + window->lastDecryptedAuthedSeqNum = sequenceNumber; + memset(window->replayWindow, 0, sizeof(window->replayWindow)); + window->replayWindow[0] = 1; + return; + } + + uint32_t diff = sequenceNumber - window->lastDecryptedAuthedSeqNum; + if (diff > 0 && diff < 0x80000000) { + shiftReplayWindow(window, diff); + window->lastDecryptedAuthedSeqNum = sequenceNumber; + } + else if (diff >= 0x80000000) { + uint32_t offset = window->lastDecryptedAuthedSeqNum - sequenceNumber; + LC_ASSERT(offset < REPLAY_WINDOW_SIZE); + int wordIndex = (int)(offset / 64); + int bitIndex = (int)(offset % 64); + window->replayWindow[wordIndex] |= ((uint64_t)1 << bitIndex); + } +} + // When CBC is used, outputData buffer must be allocated such that the buffer length is // at least ROUND_TO_PKCS7_PADDED_LEN(inputDataLength) to allow room for PKCS7 padding. // @@ -273,11 +367,17 @@ bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, // Changing the key between encrypt/decrypt calls on a single context is not supported. // Using the same crypto context for both encryption and decryption is not supported. bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, + unsigned char replayWindowIndex, + unsigned int sequenceNumber, unsigned char* key, int keyLength, unsigned char* iv, int ivLength, unsigned char* tag, int tagLength, unsigned char* inputData, int inputDataLength, unsigned char* outputData, int* outputDataLength) { + if (isReplayedMessage(ctx, algorithm, flags, replayWindowIndex, sequenceNumber)) { + return false; + } + #ifdef USE_PSA_CRYPTO if (algorithm == ALGORITHM_AES_GCM) { LC_ASSERT(tag != NULL); @@ -330,6 +430,7 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, return false; } + recordSuccessfulAuthenticatedDecryption(ctx, flags, replayWindowIndex, sequenceNumber); *outputDataLength = (int)(outLen + verifyLen); return true; } @@ -477,6 +578,8 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, return false; } LC_ASSERT(len == 0); + + recordSuccessfulAuthenticatedDecryption(ctx, flags, replayWindowIndex, sequenceNumber); } else if (flags & CIPHER_FLAG_FINISH) { int len; @@ -492,13 +595,13 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, #endif } -PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(void) { - PPLT_CRYPTO_CONTEXT ctx = malloc(sizeof(*ctx)); +PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(unsigned char replayWindowCount) { + PPLT_CRYPTO_CONTEXT ctx = calloc(1, sizeof(*ctx) + (replayWindowCount * sizeof(REPLAY_WINDOW))); if (!ctx) { return NULL; } - ctx->initialized = false; + ctx->replayWindowCount = replayWindowCount; #ifdef USE_PSA_CRYPTO ctx->key = PSA_KEY_ID_NULL; diff --git a/src/PlatformCrypto.h b/src/PlatformCrypto.h index ddbb568..c111e29 100644 --- a/src/PlatformCrypto.h +++ b/src/PlatformCrypto.h @@ -1,6 +1,7 @@ #pragma once #include +#include // Retain backwards compatibility with older USE_MBEDTLS #if defined(USE_MBEDTLS) && !defined(USE_PSA_CRYPTO) @@ -14,6 +15,15 @@ typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX; #endif +#define REPLAY_WINDOW_SIZE 512 +#define REPLAY_WINDOW_WORDS (REPLAY_WINDOW_SIZE / 64) + +typedef struct _REPLAY_WINDOW { + bool decryptedAuthedMessage; + unsigned int lastDecryptedAuthedSeqNum; + uint64_t replayWindow[REPLAY_WINDOW_WORDS]; +} REPLAY_WINDOW, *PREPLAY_WINDOW; + typedef struct _PLT_CRYPTO_CONTEXT { #ifdef USE_PSA_CRYPTO psa_key_id_t key; @@ -24,11 +34,13 @@ typedef struct _PLT_CRYPTO_CONTEXT { EVP_CIPHER_CTX* ctx; bool initialized; #endif + unsigned char replayWindowCount; + REPLAY_WINDOW replayWindows[]; } PLT_CRYPTO_CONTEXT, *PPLT_CRYPTO_CONTEXT; #define ROUND_TO_PKCS7_PADDED_LEN(x) ((((x) + 15) / 16) * 16) -PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(void); +PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(unsigned char replayWindowCount); void PltDestroyCryptoContext(PPLT_CRYPTO_CONTEXT ctx); #define ALGORITHM_AES_CBC 1 @@ -37,6 +49,7 @@ void PltDestroyCryptoContext(PPLT_CRYPTO_CONTEXT ctx); #define CIPHER_FLAG_RESET_IV 0x01 #define CIPHER_FLAG_FINISH 0x02 #define CIPHER_FLAG_PAD_TO_BLOCK_SIZE 0x04 +#define CIPHER_FLAG_NO_REPLAY_CHECK 0x08 bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, unsigned char* key, int keyLength, @@ -46,6 +59,8 @@ bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, unsigned char* outputData, int* outputDataLength); bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, + unsigned char replayWindowIndex, + unsigned int sequenceNumber, unsigned char* key, int keyLength, unsigned char* iv, int ivLength, unsigned char* tag, int tagLength, diff --git a/src/RtspConnection.c b/src/RtspConnection.c index e958101..a754843 100644 --- a/src/RtspConnection.c +++ b/src/RtspConnection.c @@ -211,7 +211,7 @@ static bool unsealRtspMessage(char* rawMessage, int rawMessageLen, PRTSP_MESSAGE return false; } - success = PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, 0, + success = PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, 0, 0, seq, (uint8_t*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey), iv, sizeof(iv), encryptedMessage->tag, sizeof(encryptedMessage->tag), @@ -953,8 +953,8 @@ int performRtspHandshake(PSERVER_INFORMATION serverInfo) { controlStreamId = APP_VERSION_AT_LEAST(7, 1, 431) ? "streamid=control/13/0" : "streamid=control/1/0"; AudioEncryptionEnabled = false; encryptedRtspEnabled = serverInfo->rtspSessionUrl && strstr(serverInfo->rtspSessionUrl, "rtspenc://"); - encryptionCtx = PltCreateCryptoContext(); - decryptionCtx = PltCreateCryptoContext(); + encryptionCtx = PltCreateCryptoContext(0); + decryptionCtx = PltCreateCryptoContext(1); // HACK: In order to get GFE to respect our request for a lower audio bitrate, we must // fake our target address so it doesn't match any of the PC's local interfaces. It seems diff --git a/src/VideoStream.c b/src/VideoStream.c index 402b056..fa31e92 100644 --- a/src/VideoStream.c +++ b/src/VideoStream.c @@ -38,7 +38,7 @@ static bool receivedFullFrame; void initializeVideoStream(void) { initializeVideoDepacketizer(StreamConfig.packetSize); RtpvInitializeQueue(&rtpQueue); - decryptionCtx = PltCreateCryptoContext(); + decryptionCtx = PltCreateCryptoContext(0); receivedDataFromPeer = false; firstDataTimeMs = 0; receivedFullFrame = false; @@ -210,7 +210,8 @@ static void VideoReceiveThreadProc(void* context) { continue; } - if (!PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, 0, + // Replay detection is handled by the check above and in the RtpFecQueue + if (!PltDecryptMessage(decryptionCtx, ALGORITHM_AES_GCM, CIPHER_FLAG_NO_REPLAY_CHECK, 0, 0, (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey), encHeader->iv, sizeof(encHeader->iv), encHeader->tag, sizeof(encHeader->tag),