From bb158c0ab8dafbd89f63e2e97b62ae0f4be35266 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 15 Nov 2026 09:35:45 -0500 Subject: [PATCH 1/2] sign: delegate BER and DER encoding to existing craft-pkcs7 --- Cargo.lock | 43 ++- crates/sign/Cargo.toml | 2 + crates/sign/src/der.rs | 612 ++++++--------------------------------- crates/sign/src/ec512.rs | 2 +- 4 files changed, 124 insertions(+), 535 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a259e0fe5e..98fa828ef9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1327,6 +1327,38 @@ dependencies = [ "zeroize", ] +[[package]] +name = "craft-pkcs7" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f#2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" +dependencies = [ + "aes", + "aws-lc-rs", + "base64 0.23.1", + "bp256", + "bp384", + "cbc", + "chrono", + "crypto-bigint", + "des", + "ecdsa", + "ed25519-dalek", + "getrandom 0.4.3", + "hmac", + "p256", + "p384", + "p521", + "pbkdf2", + "rc2", + "ripemd", + "rsa", + "sha1 0.11.0", + "sha2 0.11.1", + "sha3", + "thiserror 2.0.21", + "zeroize", +] + [[package]] name = "craft-prc" version = "0.1.0" @@ -1548,9 +1580,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" [[package]] name = "crypto-bigint" -version = "0.7.6" +version = "0.7.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" dependencies = [ "cpubits", "ctutils", @@ -1596,9 +1628,9 @@ dependencies = [ [[package]] name = "ctutils" -version = "0.4.5" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ "cmov", "subtle", @@ -4934,6 +4966,7 @@ dependencies = [ "bp384", "cbc", "chrono", + "craft-pkcs7", "crypto-bigint", "des", "ecdsa", @@ -7136,7 +7169,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix 1.1.6", "windows-sys 0.61.2", diff --git a/crates/sign/Cargo.toml b/crates/sign/Cargo.toml index a72d91ad2a..4c587c4586 100644 --- a/crates/sign/Cargo.toml +++ b/crates/sign/Cargo.toml @@ -11,6 +11,8 @@ repository.workspace = true workspace = true [dependencies] +# Existing shared ASN.1 codec; PDF signature policy remains local. +craft-pkcs7 = { git = "https://github.com/storytold/craft-libs", rev = "2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" } pdfcraft-cos = { workspace = true } pdfcraft-annot = { workspace = true } pdfcraft-content = { workspace = true } diff --git a/crates/sign/src/der.rs b/crates/sign/src/der.rs index a4740b4707..f51937acec 100644 --- a/crates/sign/src/der.rs +++ b/crates/sign/src/der.rs @@ -1,564 +1,118 @@ -//! A small BER/DER reader and writer (ITU-T X.690): just what X.509, CMS and PKCS#12 need. +//! BER/DER codecs delegated to the existing shared `craft-pkcs7` implementation. //! -//! [`Tlv`] borrows from the input and keeps its full encoding (`raw`), so signed structures can -//! be verified over the exact bytes that were signed. -//! -//! Reading is strict DER by default, which is what everything signed must use. [`Tlv::parse_ber`] -//! also accepts the two BER constructions a reader meets in practice — the indefinite length form -//! and strings split into segments — which PKCS #12 needs: Windows writes `.p12` files that way. -//! Writing is always DER. - -use std::borrow::Cow; +//! This facade preserves PdfCraft's error type and borrowed signed encodings. Certificate +//! trust, signing policy and document interpretation remain in their existing app modules. use crate::SignError; +use craft_pkcs7::der as shared; +pub use shared::{Form, Time, algorithm, bit_string, boolean, explicit, ia5, int, null, octets, oid, printable, seq, set_of, tag, tlv, uint, utf8}; +use std::borrow::Cow; -/// Universal tags (single-byte identifiers). -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`]. - pub const OCTET_STRING_SEGMENTS: u8 = 0x24; - pub const NULL: u8 = 0x05; - pub const OID: u8 = 0x06; - pub const UTF8_STRING: u8 = 0x0C; - pub const PRINTABLE_STRING: u8 = 0x13; - pub const T61_STRING: u8 = 0x14; - pub const IA5_STRING: u8 = 0x16; - pub const UTC_TIME: u8 = 0x17; - pub const GENERALIZED_TIME: u8 = 0x18; - pub const BMP_STRING: u8 = 0x1E; - pub const SEQUENCE: u8 = 0x30; - pub const SET: u8 = 0x31; - /// `[n]` context-specific, constructed (EXPLICIT, or IMPLICIT over a constructed type). - pub const fn ctx(n: u8) -> u8 { - 0xA0 | n - } - /// `[n]` context-specific, primitive (IMPLICIT over a primitive type). - pub const fn ctx_prim(n: u8) -> u8 { - 0x80 | n +fn app_error(error: craft_pkcs7::Error) -> SignError { + match error { + craft_pkcs7::Error::Malformed(message) => SignError::Malformed(message), + craft_pkcs7::Error::Unsupported(message) => SignError::Unsupported(message), + craft_pkcs7::Error::WrongPassword => SignError::WrongPassword, + craft_pkcs7::Error::Crypto(message) => SignError::Crypto(message), } } -fn bad(what: &str) -> SignError { - SignError::Malformed(what.to_string()) -} - -/// Which encoding rules a reader accepts. +/// A borrowed shared element with the app's existing fallible method signatures. +/// Dereferencing exposes the same public tag, contents and exact original encoding. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Form { - /// DER: every length definite, every string primitive. Anything whose bytes are signed is read - /// this way, so that what is verified is exactly what was written. - Der, - /// BER as well: the indefinite length form (X.690 §8.1.3.6) and strings split into segments - /// (§8.21). - Ber, +pub struct Tlv<'a>(shared::Tlv<'a>); + +impl<'a> std::ops::Deref for Tlv<'a> { + type Target = shared::Tlv<'a>; + fn deref(&self) -> &Self::Target { + &self.0 + } } -/// One BER/DER element. -#[derive(Clone, Copy, Debug, Eq)] -pub struct Tlv<'a> { - pub tag: u8, - /// The contents octets (without the end-of-contents octets of an indefinite length). - pub value: &'a [u8], - /// The whole encoding (identifier, length, contents and any end-of-contents octets). - pub raw: &'a [u8], - /// The rules this element was read with. Its children are read the same way. - form: Form, -} - -/// Two elements are equal when they encode the same thing; the rules they were read with are not -/// part of that. -impl PartialEq for Tlv<'_> { - fn eq(&self, other: &Self) -> bool { - self.tag == other.tag && self.value == other.value && self.raw == other.raw +impl std::ops::DerefMut for Tlv<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 } } impl<'a> Tlv<'a> { - /// Parse one DER element at the start of `input`; returns it and the rest. - pub fn parse(input: &'a [u8]) -> Result<(Tlv<'a>, &'a [u8]), SignError> { - Tlv::read(input, Form::Der, 0) - } - - /// Parse one BER element at the start of `input`; returns it and the rest. - pub fn parse_ber(input: &'a [u8]) -> Result<(Tlv<'a>, &'a [u8]), SignError> { - Tlv::read(input, Form::Ber, 0) - } - - fn read(input: &'a [u8], form: Form, depth: usize) -> Result<(Tlv<'a>, &'a [u8]), SignError> { - let (&tag, rest) = input.split_first().ok_or_else(|| bad("truncated DER"))?; - if tag & 0x1F == 0x1F { - return Err(bad("multi-byte DER tags are not supported")); - } - let (&first, rest) = rest.split_first().ok_or_else(|| bad("truncated DER length"))?; - // `trailer` is the two end-of-contents octets, which belong to the element but not to its - // contents. - let (len, rest, trailer) = if first < 0x80 { - (first as usize, rest, 0) - } else if first == 0x80 { - if form == Form::Der { - return Err(bad("indefinite lengths are not allowed in DER")); - } - if tag & 0x20 == 0 { - return Err(bad("an indefinite length needs a constructed element")); - } - (contents_len(rest, form, depth)?, rest, 2) - } else { - let n = (first & 0x7F) as usize; - if n > 4 || rest.len() < n { - return Err(bad("unsupported DER length")); - } - let len = rest[..n].iter().fold(0usize, |acc, b| (acc << 8) | *b as usize); - (len, &rest[n..], 0) - }; - let end = len.checked_add(trailer).ok_or_else(|| bad("DER length overflows"))?; - if rest.len() < end { - return Err(bad("DER element runs past the end")); - } - // `end <= rest.len()`, so neither sum below can overflow. - let header = input.len() - rest.len(); - Ok((Tlv { tag, value: &rest[..len], raw: &input[..header + end], form }, &rest[end..])) - } - - /// Parse `input` as exactly one DER element. - pub fn parse_all(input: &'a [u8]) -> Result, SignError> { - Tlv::only(input, Form::Der) - } - - /// Parse `input` as exactly one BER element. - pub fn parse_all_ber(input: &'a [u8]) -> Result, SignError> { - Tlv::only(input, Form::Ber) - } - - fn only(input: &'a [u8], form: Form) -> Result, SignError> { - let (t, rest) = Tlv::read(input, form, 0)?; - if !rest.is_empty() { - return Err(bad("trailing bytes after DER element")); - } - Ok(t) - } - - /// Whether this element is written with the indefinite length form (BER, never DER). Tags are - /// single-octet here, so the length octet is the second. pub fn is_indefinite(&self) -> bool { - self.raw.get(1) == Some(&0x80) + self.0.is_indefinite() } - - /// The children of a constructed element, read with the same rules as their parent. - pub fn children(&self) -> Result>, SignError> { - let mut out = Vec::new(); - let mut rest = self.value; - while !rest.is_empty() { - let (t, r) = Tlv::read(rest, self.form, 0)?; - out.push(t); - rest = r; - } - Ok(out) - } - - /// Check the tag, for a clear error. - pub fn expect(self, tag: u8, what: &str) -> Result, SignError> { - if self.tag == tag { Ok(self) } else { Err(bad(&format!("{what}: expected tag {tag:#04x}, found {:#04x}", self.tag))) } - } - - /// The element inside an EXPLICIT tag. - pub fn inner(&self) -> Result, SignError> { - Tlv::only(self.value, self.form) - } - - /// An OCTET STRING's contents, joining the segments of BER's constructed form (X.690 §8.21). - /// Borrowed in the ordinary case, so the common path copies nothing. - pub fn octets(&self, what: &str) -> Result, SignError> { - self.join(what, 0) - } - - fn join(&self, what: &str, depth: usize) -> Result, SignError> { - /// Deep enough for anything real: a writer that segments at all segments once. - const MAX_DEPTH: usize = 16; - match self.tag { - tag::OCTET_STRING => Ok(Cow::Borrowed(self.value)), - tag::OCTET_STRING_SEGMENTS if self.form == Form::Ber => { - if depth >= MAX_DEPTH { - return Err(bad(&format!("{what}: OCTET STRING segments nested too deeply"))); - } - // The join is never larger than the segments it is made of, so this is bounded by - // the input. - let mut out: Vec = Vec::with_capacity(self.value.len()); - for s in self.children()? { - out.extend_from_slice(&s.join(what, depth + 1)?); - } - Ok(Cow::Owned(out)) - } - found => Err(bad(&format!("{what}: expected an OCTET STRING, found tag {found:#04x}"))), - } - } - - /// An OID in dotted form. - pub fn oid(&self) -> Result { - if self.tag != tag::OID { - return Err(bad("expected an OID")); - } - oid_to_string(self.value) - } - - /// A non-negative INTEGER that fits in a u64. - pub fn u64(&self) -> Result { - // (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 { - [0, rest @ ..] if !rest.is_empty() => rest, - v => v, - } + self.0.uint_bytes() } - - /// A BIT STRING's bytes (no unused bits allowed). - pub fn bits(&self) -> Result<&'a [u8], SignError> { - match self.value { - [0, rest @ ..] if self.tag == tag::BIT_STRING => Ok(rest), - _ => Err(bad("expected a whole-byte BIT STRING")), - } - } - - /// A string type as text (UTF-8, Printable, IA5, T61 as Latin-1, BMP). pub fn text(&self) -> Option { - match self.tag { - tag::UTF8_STRING | tag::PRINTABLE_STRING | tag::IA5_STRING => Some(String::from_utf8_lossy(self.value).into_owned()), - tag::T61_STRING => Some(self.value.iter().map(|b| *b as char).collect()), - tag::BMP_STRING => { - let units: Vec = self.value.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - Some(String::from_utf16_lossy(&units)) - } - _ => None, - } + self.0.text() } - /// UTCTime / GeneralizedTime as (year, month, day, hour, minute, second) in UTC. + pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), SignError> { + shared::Tlv::parse(input).map(|(element, rest)| (Self(element), rest)).map_err(app_error) + } + pub fn parse_ber(input: &'a [u8]) -> Result<(Self, &'a [u8]), SignError> { + shared::Tlv::parse_ber(input).map(|(element, rest)| (Self(element), rest)).map_err(app_error) + } + pub fn parse_all(input: &'a [u8]) -> Result { + shared::Tlv::parse_all(input).map(Self).map_err(app_error) + } + pub fn parse_all_ber(input: &'a [u8]) -> Result { + shared::Tlv::parse_all_ber(input).map(Self).map_err(app_error) + } + pub fn children(&self) -> Result, SignError> { + self.0.children().map(|children| children.into_iter().map(Self).collect()).map_err(app_error) + } + pub fn expect(self, tag: u8, what: &str) -> Result { + self.0.expect(tag, what).map(Self).map_err(app_error) + } + pub fn inner(&self) -> Result { + self.0.inner().map(Self).map_err(app_error) + } + pub fn octets(&self, what: &str) -> Result, SignError> { + self.0.octets(what).map_err(app_error) + } + pub fn oid(&self) -> Result { + self.0.oid().map_err(app_error) + } + pub fn u64(&self) -> Result { + self.0.u64().map_err(app_error) + } + pub fn enumerated(&self) -> Result { + self.0.enumerated().map_err(app_error) + } + pub fn bits(&self) -> Result<&'a [u8], SignError> { + self.0.bits().map_err(app_error) + } pub fn time(&self) -> Result { - let s = std::str::from_utf8(self.value).map_err(|_| bad("time"))?; - let s = s.strip_suffix('Z').ok_or_else(|| bad("times must be in UTC (Z)"))?; - let num = |r: std::ops::Range| s.get(r).and_then(|x| x.parse::().ok()).ok_or_else(|| bad("time")); - let (year, rest) = match self.tag { - tag::UTC_TIME => { - let y = num(0..2)?; - (if y >= 50 { 1900 + y } else { 2000 + y }, 2) - } - tag::GENERALIZED_TIME => (num(0..4)?, 4), - _ => return Err(bad("expected a time")), - }; - let t = Time { - year, - month: num(rest..rest + 2)?, - day: num(rest + 2..rest + 4)?, - hour: num(rest + 4..rest + 6)?, - minute: num(rest + 6..rest + 8)?, - second: if s.len() >= rest + 10 { num(rest + 8..rest + 10)? } else { 0 }, - }; - Ok(t) + self.0.time().map_err(app_error) } } -/// How many contents octets an indefinite-length element has: everything up to the matching -/// end-of-contents octets, which have to be there (X.690 §8.1.5). The contents are elements, so -/// finding the end means reading them, and one of those may be indefinite too — hence the depth -/// limit. Every step consumes at least two octets, so the walk always ends. -fn contents_len(input: &[u8], form: Form, depth: usize) -> Result { - /// Far deeper than any real file nests, and shallow enough never to exhaust the stack. - const MAX_DEPTH: usize = 48; - if depth >= MAX_DEPTH { - return Err(bad("BER elements nested too deeply")); - } - let mut rest = input; - loop { - match rest { - [] => return Err(bad("an indefinite length with no end-of-contents")), - [0, 0, ..] => return Ok(input.len() - rest.len()), - _ => rest = Tlv::read(rest, form, depth + 1)?.1, - } - } -} - -/// `NaiveDate::num_days_from_ce` of 1970-01-01, so the count can be rebased onto the Unix epoch. -const UNIX_EPOCH_DAYS_FROM_CE: i64 = 719_163; - -/// A UTC time. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub struct Time { - pub year: u32, - pub month: u32, - pub day: u32, - pub hour: u32, - pub minute: u32, - pub second: u32, -} - -impl Time { - /// From a PDF date (`D:YYYYMMDDHHmmSS±HH'mm'`), converted to UTC. - pub fn from_pdf(s: &str) -> Option