From a40dbef52e0871feed8e499b6f986bdefbccf27c Mon Sep 17 00:00:00 2001 From: Thomas Vermeilh Date: Thu, 1 Aug 2024 15:59:41 +0200 Subject: [PATCH] fix panic on 256 bits RC4 keys Found this bug while fuzzing the crate. The spec says that in the ecryption dictonary, /Length is the length of the key, and should be between 40 to 128 bits. However, if we specify 256 the parser still accepts it but panics in Decoder::decrypt() while performing the b) step. The b) step is implemented by truncating the key length to a maximum of 128 bits (16 bytes) before concatenating the object number and generation of the string being decrypted. However, while computing the size of n, Decoder::decode() does not truncate the key size to 16, and this leads to an out of bound panic. Note that I can't find the reason for this trucation to 16 bytes in the b) step. The spec does require truncating the key to 16 bytes, but that's in the d) step which is where we truncate the resulting hash. Maybe a better fix would be to reject a /Length of 256 bits in the parser instead. --- pdf/src/crypt.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pdf/src/crypt.rs b/pdf/src/crypt.rs index c91bdce..562f420 100644 --- a/pdf/src/crypt.rs +++ b/pdf/src/crypt.rs @@ -562,7 +562,7 @@ impl Decoder { CryptMethod::V2 => { // b) let mut key = [0; 16 + 5]; - let n = self.key_size; + let n = self.key().len(); key[..n].copy_from_slice(self.key()); key[n..n + 3].copy_from_slice(&id.id.to_le_bytes()[..3]); key[n + 3..n + 5].copy_from_slice(&id.gen.to_le_bytes()[..2]);