Skip to content

Keep unused AES-CTR keystream when a mirror frame is shorter than it - #615

Closed
PhilflowIO wants to merge 1 commit into
FDH2:masterfrom
PhilflowIO:mirror-short-frame-keystream
Closed

PhilflowIO wants to merge 1 commit into
FDH2:masterfrom
PhilflowIO:mirror-short-frame-keystream

Conversation

@PhilflowIO

Copy link
Copy Markdown

mirror_buffer_decrypt() XORs the start of each frame with the keystream
left over from the previous frame's trailing partial block (og[],
nextDecryptCount bytes). It always consumed all nextDecryptCount bytes,
even when the frame itself was shorter. For such a frame encryptlen
comes out 0, restlen negative, nextDecryptCount is reset to 0 and the
unused keystream is discarded:

  • AES-CTR is out of step with the sender for the rest of the session;
    every later frame fails to decrypt ("*** ERROR decryption of video
    packet failed") and the picture freezes on the last good frame;
  • the loop reads input[i] and writes output[i] for i >= inputLen: up
    to 15 bytes past both malloc(payload_size) buffers in
    raop_rtp_mirror.c (ASan: heap-buffer-overflow).

Apple senders seem never to send a frame shorter than 16 bytes, but
doubletake (a Linux AirPlay sender) strips SEI and sends 13-15 byte
"nothing changed" non-IDR frames when the desktop is idle.

Use only min(nextDecryptCount, inputLen) leftover bytes. If the frame is
fully covered by leftover keystream, keep the remainder for the next
frame and return without touching the AES context; og[] needs no
shifting because the remaining bytes stay at og[16 - nextDecryptCount].
Frames at least as long as the leftover behave exactly as before.

Fixes #614.

Tested: real mirror_buffer.c + crypto.c under ASan/UBSan with mixed frame sizes and a mid-session re-key: before 3981/4000 frames wrong plus heap read/write past both buffers; after 0/4000, clean. Live on 1.73.7 with doubletake on an idle desktop: 722 decrypt errors in 20 s before, 0 in 60 s after.

🤖 Generated with Claude Code

mirror_buffer_decrypt() XORs the start of each frame with the keystream
left over from the previous frame's trailing partial block (og[],
nextDecryptCount bytes).  It always consumed all nextDecryptCount bytes,
even when the frame itself was shorter.  For such a frame encryptlen
comes out 0, restlen negative, nextDecryptCount is reset to 0 and the
unused keystream is discarded:

 - AES-CTR is out of step with the sender for the rest of the session;
   every later frame fails to decrypt ("*** ERROR decryption of video
   packet failed") and the picture freezes on the last good frame;
 - the loop reads input[i] and writes output[i] for i >= inputLen: up
   to 15 bytes past both malloc(payload_size) buffers in
   raop_rtp_mirror.c (ASan: heap-buffer-overflow).

Apple senders seem never to send a frame shorter than 16 bytes, but
doubletake (a Linux AirPlay sender) strips SEI and sends 13-15 byte
"nothing changed" non-IDR frames when the desktop is idle.

Use only min(nextDecryptCount, inputLen) leftover bytes.  If the frame is
fully covered by leftover keystream, keep the remainder for the next
frame and return without touching the AES context; og[] needs no
shifting because the remaining bytes stay at og[16 - nextDecryptCount].
Frames at least as long as the leftover behave exactly as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@PhilflowIO

Copy link
Copy Markdown
Author

Thanks for checking with omarroth — good call to confirm the sender side.

One point that holds regardless of the answer: the current code mishandles any mirror frame shorter than the leftover keystream (nextDecryptCount). It reads and writes up to 15 bytes past both malloc(payload_size) buffers and permanently desyncs AES-CTR for the rest of the session. Any sender on the network can trigger that, so I'd see this as a robustness/memory-safety fix rather than a doubletake feature. The leftover-keystream logic that is already there treats the mirror stream as one continuous CTR stream; the patch just keeps that consistent when a frame ends inside the leftover.

For frames at least as long as the leftover — which includes everything Apple devices send — the path is unchanged: m == n, the early return is never taken, and the loop is the same as before.

UxPlay has no unit-test setup, so instead of adding one, here is the standalone harness I used. It encrypts random frames with the sender-side key derivation, feeds them through the real mirror_buffer.c/crypto.c, and re-keys mid-session. Mode 0 = mixed frame sizes including 13–15 byte frames, mode 1 = only frames ≥16 bytes (Apple-like).

harness.c (31 lines)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "mirror_buffer.h"
#include "crypto.h"
static aes_ctx_t *sender(const unsigned char *ak, uint64_t id){
  unsigned char k[64]={0}, iv[64]={0};
  snprintf((char*)k,64,"AirPlayStreamKey%" PRIu64,id); snprintf((char*)iv,64,"AirPlayStreamIV%" PRIu64,id);
  sha_ctx_t *c=sha_init(); sha_update(c,k,strlen((char*)k)); sha_update(c,ak,16); sha_final(c,k,NULL);
  sha_reset(c); sha_update(c,iv,strlen((char*)iv)); sha_update(c,ak,16); sha_final(c,iv,NULL); sha_destroy(c);
  return aes_ctr_init(k,iv);}
int main(int argc,char**argv){
  int mode=argc>1?atoi(argv[1]):0; /* 0 mixed, 1 only >=16 (apple-like) */
  unsigned char ak[16]; for(int i=0;i<16;i++)ak[i]=i*3+1;
  uint64_t id=1234567890123ULL;
  mirror_buffer_t *mb=mirror_buffer_init(NULL,ak); mirror_buffer_init_aes(mb,&id);
  aes_ctx_t *s=sender(ak,id);
  srand(7); int bad=0,nf=0;
  for(int f=0;f<4000;f++){
    int L;
    if(f==2000){ /* re-key mid-session with leftover pending */
      id++; mirror_buffer_init_aes(mb,&id); aes_ctr_destroy(s); s=sender(ak,id);}
    if(mode==1) L=16+rand()%6000; else {int r=rand()%10; L= r<6?13+rand()%3: r<8? rand()%41 : 16+rand()%6000;}
    unsigned char *pt=malloc(L?L:1),*ct=malloc(L?L:1),*out=malloc(L?L:1);
    for(int i=0;i<L;i++)pt[i]=rand();
    if(L) aes_ctr_encrypt(s,pt,ct,L);
    mirror_buffer_decrypt(mb,ct,out,L);
    if(L&&memcmp(pt,out,L))bad++; nf++;
    free(pt);free(ct);free(out);}
  printf("mode %d: %d/%d wrong\n",mode,bad,nf); mirror_buffer_destroy(mb); aes_ctr_destroy(s); return 0;}
gcc -fsanitize=address,undefined -g -Ilib -o harness harness.c \
    lib/mirror_buffer.c lib/crypto.c lib/utils.c -lcrypto
./harness 0; ./harness 1

Results on df67c21 (1.73.7):

mode 0 (mixed) mode 1 (≥16 B only)
master ASan heap-buffer-overflow 0/4000 wrong
this PR 0/4000 wrong, ASan/UBSan clean 0/4000 wrong

@omarroth

Copy link
Copy Markdown

Mentioned in omarroth/doubletake#75 that this LGTM and better matches the first-party implementation, but looking for ways to mitigate this issue on the sender side as well.

@fduncanh fduncanh closed this in f0ee39d Nov 3, 2026
@fduncanh

fduncanh commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Has been added (by hand, not as PR)
b1be2bd

fduncanh added a commit that referenced this pull request Nov 3, 2026
Use only as much leftover keystream as this frame is long.  A frame
shorter than the leftover (e.g. a ~13-byte "nothing changed" frame
from a sender that strips SEI) must keep the unused keystream suffix
for the next frame: consuming all of it desynchronizes AES-CTR for
the rest of the session and writes past the end of output.
fixes #615
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mirror video freezes and heap overflow when a frame is shorter than the leftover AES-CTR keystream

3 participants