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
This commit is contained in:
Cameron Gutman committed 2026-11-01 14:07:45 -06:00
1 parent 5d3c0ecca0
commit c7dff22963
7 files changed
+139 -17

No files matched your search

+2 -2
View File
@@ -72,7 +72,7 @@ int initializeAudioStream(void) {
receivedDataFromPeer = false; receivedDataFromPeer = false;
pingThreadStarted = false; pingThreadStarted = false;
firstReceiveTime = 0; firstReceiveTime = 0;
audioDecryptionCtx = PltCreateCryptoContext(); audioDecryptionCtx = PltCreateCryptoContext(0);
#ifdef LC_DEBUG #ifdef LC_DEBUG
opusHeaderByte = INVALID_OPUS_HEADER; opusHeaderByte = INVALID_OPUS_HEADER;
#endif #endif
@@ -189,7 +189,7 @@ static void decodeInputData(PQUEUED_AUDIO_PACKET packet) {
memcpy(iv, &ivSeq, sizeof(ivSeq)); 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), (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey),
iv, sizeof(iv), iv, sizeof(iv),
NULL, 0, NULL, 0,
+8 -5
View File
@@ -356,8 +356,8 @@ int initializeControlStream(void) {
firstFrameTimeMs = 0; firstFrameTimeMs = 0;
currentEnetSequenceNumber = 0; currentEnetSequenceNumber = 0;
usePeriodicPing = APP_VERSION_AT_LEAST(7, 1, 415); usePeriodicPing = APP_VERSION_AT_LEAST(7, 1, 415);
encryptionCtx = PltCreateCryptoContext(); encryptionCtx = PltCreateCryptoContext(0);
decryptionCtx = PltCreateCryptoContext(); decryptionCtx = PltCreateCryptoContext(CTRL_CHANNEL_COUNT);
hdrEnabled = false; hdrEnabled = false;
memset(&hdrMetadata, 0, sizeof(hdrMetadata)); memset(&hdrMetadata, 0, sizeof(hdrMetadata));
@@ -595,9 +595,10 @@ static bool encryptControlMessage(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket, PNVC
} }
// Caller must free() *packet on success!!! // 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 }; unsigned char iv[16] = { 0 };
int ivSize; int ivSize;
int cipherFlags;
*packet = NULL; *packet = NULL;
@@ -631,10 +632,12 @@ static bool decryptControlMessageToV1(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket,
// Use 12-byte IV which is ideal for AES-GCM // Use 12-byte IV which is ideal for AES-GCM
ivSize = 12; ivSize = 12;
cipherFlags = 0;
} }
else { else {
// This is a truncating cast, but it's what Nvidia does, so we have to mimic it. // This is a truncating cast, but it's what Nvidia does, so we have to mimic it.
iv[0] = (unsigned char)encPacket->seq; iv[0] = (unsigned char)encPacket->seq;
cipherFlags = CIPHER_FLAG_NO_REPLAY_CHECK;
// Nvidia's old style encryption uses a 16-byte IV // Nvidia's old style encryption uses a 16-byte IV
ivSize = 16; ivSize = 16;
@@ -648,7 +651,7 @@ static bool decryptControlMessageToV1(PNVCTL_ENCRYPTED_PACKET_HEADER encPacket,
LC_ASSERT(ivSize <= (int)sizeof(iv)); LC_ASSERT(ivSize <= (int)sizeof(iv));
LC_ASSERT(ivSize == 12 || ivSize == 16); 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), (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey),
iv, ivSize, iv, ivSize,
(unsigned char*)(encPacket + 1), AES_GCM_TAG_LENGTH, // The tag is located right after the header (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; ctlHdr = NULL;
packetLength = (int)event.packet->dataLength; 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); Limelog("Failed to decrypt control packet of size %d\n", event.packet->dataLength);
enet_packet_destroy(event.packet); enet_packet_destroy(event.packet);
continue; continue;
+1 -1
View File
@@ -98,7 +98,7 @@ int initializeInputStream(void) {
LbqInitializeLinkedBlockingQueue(&packetQueue, MAX_QUEUED_INPUT_PACKETS); LbqInitializeLinkedBlockingQueue(&packetQueue, MAX_QUEUED_INPUT_PACKETS);
LbqInitializeLinkedBlockingQueue(&packetHolderFreeList, MAX_QUEUED_INPUT_PACKETS); LbqInitializeLinkedBlockingQueue(&packetHolderFreeList, MAX_QUEUED_INPUT_PACKETS);
cryptoContext = PltCreateCryptoContext(); cryptoContext = PltCreateCryptoContext(0);
encryptedControlStream = APP_VERSION_AT_LEAST(7, 1, 431); encryptedControlStream = APP_VERSION_AT_LEAST(7, 1, 431);
// FIXME: Unsure if this is exactly right, but it's probably good enough. // FIXME: Unsure if this is exactly right, but it's probably good enough.
+106 -3
View File
@@ -264,6 +264,100 @@ bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
#endif #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 // 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. // 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. // 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. // Using the same crypto context for both encryption and decryption is not supported.
bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
unsigned char replayWindowIndex,
unsigned int sequenceNumber,
unsigned char* key, int keyLength, unsigned char* key, int keyLength,
unsigned char* iv, int ivLength, unsigned char* iv, int ivLength,
unsigned char* tag, int tagLength, unsigned char* tag, int tagLength,
unsigned char* inputData, int inputDataLength, unsigned char* inputData, int inputDataLength,
unsigned char* outputData, int* outputDataLength) { unsigned char* outputData, int* outputDataLength) {
if (isReplayedMessage(ctx, algorithm, flags, replayWindowIndex, sequenceNumber)) {
return false;
}
#ifdef USE_PSA_CRYPTO #ifdef USE_PSA_CRYPTO
if (algorithm == ALGORITHM_AES_GCM) { if (algorithm == ALGORITHM_AES_GCM) {
LC_ASSERT(tag != NULL); LC_ASSERT(tag != NULL);
@@ -330,6 +430,7 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
return false; return false;
} }
recordSuccessfulAuthenticatedDecryption(ctx, flags, replayWindowIndex, sequenceNumber);
*outputDataLength = (int)(outLen + verifyLen); *outputDataLength = (int)(outLen + verifyLen);
return true; return true;
} }
@@ -477,6 +578,8 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
return false; return false;
} }
LC_ASSERT(len == 0); LC_ASSERT(len == 0);
recordSuccessfulAuthenticatedDecryption(ctx, flags, replayWindowIndex, sequenceNumber);
} }
else if (flags & CIPHER_FLAG_FINISH) { else if (flags & CIPHER_FLAG_FINISH) {
int len; int len;
@@ -492,13 +595,13 @@ bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
#endif #endif
} }
PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(void) { PPLT_CRYPTO_CONTEXT PltCreateCryptoContext(unsigned char replayWindowCount) {
PPLT_CRYPTO_CONTEXT ctx = malloc(sizeof(*ctx)); PPLT_CRYPTO_CONTEXT ctx = calloc(1, sizeof(*ctx) + (replayWindowCount * sizeof(REPLAY_WINDOW)));
if (!ctx) { if (!ctx) {
return NULL; return NULL;
} }
ctx->initialized = false; ctx->replayWindowCount = replayWindowCount;
#ifdef USE_PSA_CRYPTO #ifdef USE_PSA_CRYPTO
ctx->key = PSA_KEY_ID_NULL; ctx->key = PSA_KEY_ID_NULL;
+16 -1
View File
@@ -1,6 +1,7 @@
#pragma once #pragma once
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h>
// Retain backwards compatibility with older USE_MBEDTLS // Retain backwards compatibility with older USE_MBEDTLS
#if defined(USE_MBEDTLS) && !defined(USE_PSA_CRYPTO) #if defined(USE_MBEDTLS) && !defined(USE_PSA_CRYPTO)
@@ -14,6 +15,15 @@
typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX; typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX;
#endif #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 { typedef struct _PLT_CRYPTO_CONTEXT {
#ifdef USE_PSA_CRYPTO #ifdef USE_PSA_CRYPTO
psa_key_id_t key; psa_key_id_t key;
@@ -24,11 +34,13 @@ typedef struct _PLT_CRYPTO_CONTEXT {
EVP_CIPHER_CTX* ctx; EVP_CIPHER_CTX* ctx;
bool initialized; bool initialized;
#endif #endif
unsigned char replayWindowCount;
REPLAY_WINDOW replayWindows[];
} PLT_CRYPTO_CONTEXT, *PPLT_CRYPTO_CONTEXT; } PLT_CRYPTO_CONTEXT, *PPLT_CRYPTO_CONTEXT;
#define ROUND_TO_PKCS7_PADDED_LEN(x) ((((x) + 15) / 16) * 16) #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); void PltDestroyCryptoContext(PPLT_CRYPTO_CONTEXT ctx);
#define ALGORITHM_AES_CBC 1 #define ALGORITHM_AES_CBC 1
@@ -37,6 +49,7 @@ void PltDestroyCryptoContext(PPLT_CRYPTO_CONTEXT ctx);
#define CIPHER_FLAG_RESET_IV 0x01 #define CIPHER_FLAG_RESET_IV 0x01
#define CIPHER_FLAG_FINISH 0x02 #define CIPHER_FLAG_FINISH 0x02
#define CIPHER_FLAG_PAD_TO_BLOCK_SIZE 0x04 #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, bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
unsigned char* key, int keyLength, unsigned char* key, int keyLength,
@@ -46,6 +59,8 @@ bool PltEncryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
unsigned char* outputData, int* outputDataLength); unsigned char* outputData, int* outputDataLength);
bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags, bool PltDecryptMessage(PPLT_CRYPTO_CONTEXT ctx, int algorithm, int flags,
unsigned char replayWindowIndex,
unsigned int sequenceNumber,
unsigned char* key, int keyLength, unsigned char* key, int keyLength,
unsigned char* iv, int ivLength, unsigned char* iv, int ivLength,
unsigned char* tag, int tagLength, unsigned char* tag, int tagLength,
+3 -3
View File
@@ -211,7 +211,7 @@ static bool unsealRtspMessage(char* rawMessage, int rawMessageLen, PRTSP_MESSAGE
return false; 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), (uint8_t*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey),
iv, sizeof(iv), iv, sizeof(iv),
encryptedMessage->tag, sizeof(encryptedMessage->tag), 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"; controlStreamId = APP_VERSION_AT_LEAST(7, 1, 431) ? "streamid=control/13/0" : "streamid=control/1/0";
AudioEncryptionEnabled = false; AudioEncryptionEnabled = false;
encryptedRtspEnabled = serverInfo->rtspSessionUrl && strstr(serverInfo->rtspSessionUrl, "rtspenc://"); encryptedRtspEnabled = serverInfo->rtspSessionUrl && strstr(serverInfo->rtspSessionUrl, "rtspenc://");
encryptionCtx = PltCreateCryptoContext(); encryptionCtx = PltCreateCryptoContext(0);
decryptionCtx = PltCreateCryptoContext(); decryptionCtx = PltCreateCryptoContext(1);
// HACK: In order to get GFE to respect our request for a lower audio bitrate, we must // 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 // fake our target address so it doesn't match any of the PC's local interfaces. It seems
+3 -2
View File
@@ -38,7 +38,7 @@ static bool receivedFullFrame;
void initializeVideoStream(void) { void initializeVideoStream(void) {
initializeVideoDepacketizer(StreamConfig.packetSize); initializeVideoDepacketizer(StreamConfig.packetSize);
RtpvInitializeQueue(&rtpQueue); RtpvInitializeQueue(&rtpQueue);
decryptionCtx = PltCreateCryptoContext(); decryptionCtx = PltCreateCryptoContext(0);
receivedDataFromPeer = false; receivedDataFromPeer = false;
firstDataTimeMs = 0; firstDataTimeMs = 0;
receivedFullFrame = false; receivedFullFrame = false;
@@ -210,7 +210,8 @@ static void VideoReceiveThreadProc(void* context) {
continue; 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), (unsigned char*)StreamConfig.remoteInputAesKey, sizeof(StreamConfig.remoteInputAesKey),
encHeader->iv, sizeof(encHeader->iv), encHeader->iv, sizeof(encHeader->iv),
encHeader->tag, sizeof(encHeader->tag), encHeader->tag, sizeof(encHeader->tag),