From 1e25260337faa9427d34d8c95047ede823e60ae6 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 9 Nov 2026 05:17:54 -0500 Subject: [PATCH] fix(sign): read OCSP responseStatus as ENUMERATED; drop redundant RSA leading zeros (#6005) --- crates/sign/src/der.rs | 31 ++++++++++++++++++++++++++++++- crates/sign/src/revocation.rs | 2 +- crates/sign/src/rsa_pad.rs | 8 ++++++++ crates/sign/tests/it/crypto.rs | 11 ++++++++++- 4 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/sign/src/der.rs b/crates/sign/src/der.rs index f9f2f3e6d9..a4740b4707 100644 --- a/crates/sign/src/der.rs +++ b/crates/sign/src/der.rs @@ -16,6 +16,7 @@ use crate::SignError; pub mod tag { pub const BOOLEAN: u8 = 0x01; pub const INTEGER: u8 = 0x02; + pub const ENUMERATED: u8 = 0x0A; pub const BIT_STRING: u8 = 0x03; pub const OCTET_STRING: u8 = 0x04; /// An OCTET STRING split into segments (BER only, X.690 §8.21); see [`super::Tlv::octets`]. @@ -205,12 +206,26 @@ impl<'a> Tlv<'a> { /// A non-negative INTEGER that fits in a u64. pub fn u64(&self) -> Result { - if self.tag != tag::INTEGER || self.value.is_empty() || self.value.len() > 9 || self.value[0] & 0x80 != 0 { + // (nine bytes only with a 0x00 pad: a nonzero first byte is past 64 bits) + if self.tag != tag::INTEGER + || self.value.is_empty() + || self.value.len() > 9 + || self.value[0] & 0x80 != 0 + || (self.value.len() == 9 && self.value[0] != 0) + { return Err(bad("expected a small non-negative INTEGER")); } Ok(self.value.iter().fold(0u64, |acc, b| (acc << 8) | *b as u64)) } + /// A non-negative ENUMERATED that fits in a u64 (same encoding as an INTEGER). + pub fn enumerated(&self) -> Result { + if self.tag != tag::ENUMERATED { + return Err(bad("expected an ENUMERATED")); + } + Tlv { tag: tag::INTEGER, ..*self }.u64() + } + /// The magnitude of an INTEGER (leading zero dropped). pub fn uint_bytes(&self) -> &'a [u8] { match self.value { @@ -544,6 +559,20 @@ pub fn algorithm(oid_s: &str, params: Option<&[u8]>) -> Vec { mod tests { use super::*; + #[test] + fn a_nine_byte_integer_needs_a_zero_pad_to_fit_64_bits() { + let tlv = |value: &[u8]| { + let mut b = vec![tag::INTEGER, value.len() as u8]; + b.extend_from_slice(value); + b + }; + // 2^64 would fold to 0: refused, not read as 0 + assert!(Tlv::parse_all(&tlv(&[1, 0, 0, 0, 0, 0, 0, 0, 0])).unwrap().u64().is_err()); + // u64::MAX with its pad is fine + let max = [0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]; + assert_eq!(Tlv::parse_all(&tlv(&max)).unwrap().u64().unwrap(), u64::MAX); + } + #[test] fn try_oid_rejects_signs_and_empty_arcs() { for bad in ["+1.2.840", "1.+2", "1.2.-3", "1..2"] { diff --git a/crates/sign/src/revocation.rs b/crates/sign/src/revocation.rs index 057e0717de..93191b2528 100644 --- a/crates/sign/src/revocation.rs +++ b/crates/sign/src/revocation.rs @@ -181,7 +181,7 @@ impl OcspResponse { return Err(bad("OCSP response is empty or exceeds the 2 MiB limit")); } let resp = Tlv::parse_all(bytes)?.expect(tag::SEQUENCE, "OCSPResponse")?.children()?; - let status = resp.first().ok_or_else(|| bad("missing responseStatus"))?.u64()?; + let status = resp.first().ok_or_else(|| bad("missing responseStatus"))?.enumerated()?; if status != 0 { return Err(bad(format!("responder reported an error (status {status})"))); } diff --git a/crates/sign/src/rsa_pad.rs b/crates/sign/src/rsa_pad.rs index 8cc6e08f1e..531f703d52 100644 --- a/crates/sign/src/rsa_pad.rs +++ b/crates/sign/src/rsa_pad.rs @@ -14,6 +14,9 @@ use crate::keys::{DigestAlg, PssParams}; /// signature value was not written with exactly the modulus' length (RFC 8017 §8.2.2 wants /// that); some signers drop or add leading zero bytes. fn encoded_message(n: &[u8], e: &[u8], sig: &[u8], notes: &mut Vec<&'static str>) -> Result>, SignError> { + // Redundant leading zeros would size the big-integer arithmetic (and the backend's own size + // limit) by the encoding rather than the number, so they are dropped before anything is built. + let (n, e) = (trim_zeros(n), trim_zeros(e)); let k = n.len(); let key = RsaPublicKey::new(BoxedUint::from_be_slice_vartime(n), BoxedUint::from_be_slice_vartime(e)) .map_err(|e| SignError::Malformed(format!("RSA key: {e}")))?; @@ -40,6 +43,10 @@ fn encoded_message(n: &[u8], e: &[u8], sig: &[u8], notes: &mut Vec<&'static str> Ok(Some(out)) } +fn trim_zeros(b: &[u8]) -> &[u8] { + b.get(b.iter().position(|x| *x != 0).unwrap_or(b.len())..).unwrap_or_default() +} + /// `DigestInfo ::= SEQUENCE { AlgorithmIdentifier, OCTET STRING }`. fn digest_info(alg: DigestAlg, digest: &[u8], null_params: bool) -> Vec { let id = der::algorithm(alg.oid(), null_params.then(der::null).as_deref()); @@ -99,6 +106,7 @@ pub fn pss_verify( notes: &mut Vec<&'static str>, ) -> Result { let Some(raw) = encoded_message(n, e, sig, notes)? else { return Ok(false) }; + let n = trim_zeros(n); let mod_bits = n.first().map_or(0, |b| (n.len() * 8) as u32 - b.leading_zeros()); let Some(em_bits) = mod_bits.checked_sub(1) else { return Ok(false) }; let em_len = em_bits.div_ceil(8) as usize; diff --git a/crates/sign/tests/it/crypto.rs b/crates/sign/tests/it/crypto.rs index f184d7161a..0df66b25e9 100644 --- a/crates/sign/tests/it/crypto.rs +++ b/crates/sign/tests/it/crypto.rs @@ -369,7 +369,7 @@ fn signed_ocsp(key: &pdfcraft_sign::PrivateKey, responder_id: &[u8], certs: Opti None => der::seq(&[&tbs, &alg, &der::bit_string(&sig)]), }; let basic_type = der::oid("1.3.6.1.5.5.7.48.1.1"); - der::seq(&[&der::int(0), &der::explicit(0, &der::seq(&[&basic_type, &der::octets(&basic)]))]) + der::seq(&[&der::tlv(tag::ENUMERATED, &[0]), &der::explicit(0, &der::seq(&[&basic_type, &der::octets(&basic)]))]) } fn mid_june() -> Time { @@ -470,6 +470,9 @@ fn ocsp_responses_verify_and_match_the_certificate() { let wrong_key = OcspResponse::parse(&ocsp(&other, RevocationStatus::Good, this, next)).unwrap(); assert_eq!(wrong_key.check(issuer, issuer, at), RevocationStatus::Unknown); // An error response is rejected at parse time. + let error = der::seq(&[&der::tlv(tag::ENUMERATED, &[6])]); + assert!(OcspResponse::parse(&error).is_err()); + // responseStatus is an ENUMERATED (RFC 6960); an INTEGER is not one. let error = der::seq(&[&der::int(6)]); assert!(OcspResponse::parse(&error).is_err()); } @@ -524,6 +527,12 @@ fn rsa_signatures_are_read_with_every_digestinfo_variant() { for (name, sig) in [("standard", RSA_STD), ("no NULL", RSA_NO_NULL)] { assert!(key.verify(Scheme::RsaPkcs1, DigestAlg::Sha256, &digest, &unhex(sig)).unwrap(), "{name}"); } + // Redundant leading zeros on the modulus change neither the result nor the arithmetic size. + if let pdfcraft_sign::keys::PublicKey::Rsa { n, e } = key { + let pad = |v: &[u8]| [vec![0u8; 1 << 16], v.to_vec()].concat(); + let padded = pdfcraft_sign::keys::PublicKey::Rsa { n: pad(n), e: pad(e) }; + assert!(padded.verify(Scheme::RsaPkcs1, DigestAlg::Sha256, &digest, &unhex(RSA_STD)).unwrap(), "padded key"); + } // The bare digest, with no DigestInfo, binds no hash algorithm: not a signature we accept. assert!(!key.verify(Scheme::RsaPkcs1, DigestAlg::Sha256, &digest, &unhex(RSA_BARE)).unwrap(), "bare digest"); // PSS with the salt length it declares, or any when none is declared.