From ff5241fdb2081f1aa0861fc56740bc2e9ebf57c0 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 10 Oct 2026 02:53:06 +0200 Subject: [PATCH] Verify sealed KAR SHA and section CRC in one scan --- crates/model-format/src/kar.rs | 128 +++++++++++++++----- crates/model-format/tests/kar_ple/mod.rs | 145 +++++++++++++++++++++++ 2 files changed, 245 insertions(+), 28 deletions(-) diff --git a/crates/model-format/src/kar.rs b/crates/model-format/src/kar.rs index 69b7844a..fa54456b 100644 --- a/crates/model-format/src/kar.rs +++ b/crates/model-format/src/kar.rs @@ -271,6 +271,15 @@ impl KarInspection { } Ok(()) } + fn verify_integrity(&mut self, bytes: u64, pin: &[u8; 32]) -> Result<(), KarError> { + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(8 * 1024 * 1024) + .map_err(|_| KarError::Allocation)?; + buffer.resize(8 * 1024 * 1024, 0); + self.file.seek(SeekFrom::Start(0)).map_err(KarError::Io)?; + verify_integrity_stream(&mut self.file, &self.sections, bytes, pin, &mut buffer) + } pub fn decode_range( &mut self, name: &str, @@ -755,16 +764,102 @@ pub fn crc32(bytes: &[u8]) -> u32 { !crc32_step(!0u32, bytes) } +const CRC32_TABLE: [u32; 256] = { + let mut table = [0; 256]; + let mut byte = 0; + while byte < table.len() { + let mut crc = byte as u32; + let mut bit = 0; + while bit < 8 { + crc = (crc >> 1) ^ (0xedb88320u32 & (0u32.wrapping_sub(crc & 1))); + bit += 1; + } + table[byte] = crc; + byte += 1; + } + table +}; pub fn crc32_step(mut crc: u32, bytes: &[u8]) -> u32 { for &byte in bytes { - crc ^= byte as u32; - for _ in 0..8 { - crc = (crc >> 1) ^ (0xedb88320u32 & (0u32.wrapping_sub(crc & 1))); - } + crc = (crc >> 8) ^ CRC32_TABLE[((crc ^ u32::from(byte)) & 255) as usize]; } crc } +/// Inspect has already admitted contiguous sections. Recheck their bounds here +/// before consuming bytes, including in the small streaming regression seam. +fn integrity_sections(sections: &[Section], bytes: u64) -> Result<(), KarError> { + let mut end = sections.first().map_or(bytes, |s| s.offset); + for section in sections { + if section.offset != end || section.bytes == 0 { + return Err(KarError::Range("KAR integrity section bounds")); + } + end = end + .checked_add(section.bytes) + .filter(|end| *end <= bytes) + .ok_or(KarError::Range("KAR integrity section bounds"))?; + } + if sections.is_empty() || end != bytes { + return Err(KarError::Range("KAR integrity section bounds")); + } + Ok(()) +} + +fn verify_integrity_stream( + file: &mut impl Read, + sections: &[Section], + bytes: u64, + pin: &[u8; 32], + buffer: &mut [u8], +) -> Result<(), KarError> { + integrity_sections(sections, bytes)?; + if buffer.is_empty() { + return Err(KarError::Range("KAR integrity buffer is empty")); + } + let mut digest = Sha256::new(); + let mut total = 0u64; + let mut index = 0; + let mut crc = !0u32; + let mut crc_failed = false; + loop { + let n = file.read(buffer).map_err(KarError::Io)?; + if n == 0 { + break; + } + let end = total + .checked_add(n as u64) + .ok_or(KarError::Range("KAR hash length overflow"))?; + digest.update(&buffer[..n]); // Metadata and padding belong to the SHA too. + while let Some(section) = sections.get(index) { + if section.offset >= end { + break; + } + let section_end = section.offset + section.bytes; // Checked above. + let start = total.max(section.offset); + let stop = end.min(section_end); + crc = crc32_step( + crc, + &buffer[(start - total) as usize..(stop - total) as usize], + ); + if stop != section_end { + break; + } + crc_failed |= !crc != section.crc32; + crc = !0u32; + index += 1; + } + total = end; + } + // A CRC failure never shortcuts the full hash or changes SHA-first precedence. + if total != bytes || digest.finalize().as_slice() != pin { + return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); + } + if crc_failed || index != sections.len() { + return Err(KarError::Integrity("KAR payload CRC-32 mismatch")); + } + Ok(()) +} + fn round_up(value: u64, alignment: u64) -> Option { value.div_ceil(alignment).checked_mul(alignment) } @@ -878,30 +973,7 @@ impl VerifiedKarPleArtifact { "KAR archive/provenance identity mismatch", )); } - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(8 * 1024 * 1024) - .map_err(|_| KarError::Allocation)?; - buffer.resize(8 * 1024 * 1024, 0); - reader.file.seek(SeekFrom::Start(0)).map_err(KarError::Io)?; - let mut digest = Sha256::new(); - let mut total = 0u64; - loop { - let n = reader.file.read(&mut buffer).map_err(KarError::Io)?; - if n == 0 { - break; - } - total = total - .checked_add(n as u64) - .ok_or(KarError::Range("KAR hash length overflow"))?; - digest.update(&buffer[..n]); - } - if total != profile.spec.archive_bytes - || digest.finalize().as_slice() != profile.spec.archive_sha256 - { - return Err(KarError::Integrity("KAR full archive SHA-256 mismatch")); - } - reader.verify_payloads()?; + reader.verify_integrity(profile.spec.archive_bytes, &profile.spec.archive_sha256)?; let mut parts = Vec::new(); let mut books = Vec::new(); parts diff --git a/crates/model-format/tests/kar_ple/mod.rs b/crates/model-format/tests/kar_ple/mod.rs index 86560703..e4640f4f 100644 --- a/crates/model-format/tests/kar_ple/mod.rs +++ b/crates/model-format/tests/kar_ple/mod.rs @@ -477,3 +477,148 @@ fn serving_verifier_refuses_nonfinite_partition_book_before_later_mapping() { assert!(result.err().unwrap().to_string().contains("nonfinite book")); // There is still no successful tiny serving verification or fake capability. } + +#[test] +fn fused_integrity_scan_preserves_crc_bits_boundaries_and_sha_precedence() { + fn bit_step(mut crc: u32, bytes: &[u8]) -> u32 { + for &byte in bytes { + crc ^= u32::from(byte); + for _ in 0..8 { + crc = (crc >> 1) ^ if crc & 1 == 0 { 0 } else { 0xedb8_8320 }; + } + } + crc + } + struct Counted<'a> { + bytes: &'a [u8], + read: usize, + eof: usize, + } + impl Read for Counted<'_> { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + let n = out.len().min(self.bytes.len()); + out[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + self.read += n; + self.eof += usize::from(n == 0); + Ok(n) + } + } + let mut domain: Vec = (0..=255).collect(); + domain.extend((0..4097).map(|i| ((i * 29 + i / 7) & 255) as u8)); + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + assert_eq!(crc32(&[]), 0); + for initial in [0, !0, 0x1234_5678, 0x8000_0001] { + for chunk in [1, 7, 256, 1025] { + let folded = domain.chunks(chunk).fold(initial, crc32_step); + assert_eq!(folded, bit_step(initial, &domain)); + } + } + let bytes = tiny_archive(); + let fixture = Fixture::new(&bytes); + let mut inspection = fixture.inspect(); + let pin: [u8; 32] = Sha256::digest(&bytes).into(); + for chunk in [1, 17, 255, 257, 1025, 2048] { + let mut input = Counted { + bytes: &bytes, + read: 0, + eof: 0, + }; + verify_integrity_stream( + &mut input, + &inspection.sections, + bytes.len() as u64, + &pin, + &mut vec![0; chunk], + ) + .unwrap(); + assert_eq!(input.read, bytes.len()); // No separate payload reread. + assert_eq!(input.eof, 1); + } + inspection + .verify_integrity(bytes.len() as u64, &pin) + .unwrap(); + let row = inspection + .decode_range("fixture.part0", 2, 0, 160, scalar) + .unwrap(); + for (i, value) in row.iter().enumerate() { + assert_eq!(value.to_bits(), EXPECTED[i / 32][i % 4]); + } + // Metadata/padding and both payload sections remain covered by the SHA. + for at in [700, 800, 1100] { + let mut changed = bytes.clone(); + changed[at] ^= 1; + let error = verify_integrity_stream( + &mut &changed[..], + &inspection.sections, + bytes.len() as u64, + &pin, + &mut [0; 257], + ) + .unwrap_err(); + assert!(matches!( + error, + KarError::Integrity("KAR full archive SHA-256 mismatch") + )); + } + // An admitted header can contain a wrong stored CRC while its whole-file + // SHA is correct. Preserve CRC failure, including after the first section. + let mut bad_crc = bytes.clone(); + put32(&mut bad_crc, 448 + 108, 0); + directory_digest(&mut bad_crc); + let bad_fixture = Fixture::new(&bad_crc); + let bad_inspection = bad_fixture.inspect(); + let bad_pin: [u8; 32] = Sha256::digest(&bad_crc).into(); + let error = verify_integrity_stream( + &mut &bad_crc[..], + &bad_inspection.sections, + bad_crc.len() as u64, + &bad_pin, + &mut [0; 1025], + ) + .unwrap_err(); + assert!(matches!( + error, + KarError::Integrity("KAR payload CRC-32 mismatch") + )); + let error = verify_integrity_stream( + &mut &bad_crc[..], + &bad_inspection.sections, + bad_crc.len() as u64, + &pin, + &mut [0; 257], + ) + .unwrap_err(); + assert!(matches!( + error, + KarError::Integrity("KAR full archive SHA-256 mismatch") + )); + for length in [bytes.len() - 1, bytes.len() + 1] { + let mut altered = bytes.clone(); + altered.resize(length, 0); + let error = verify_integrity_stream( + &mut &altered[..], + &inspection.sections, + bytes.len() as u64, + &pin, + &mut [0; 257], + ) + .unwrap_err(); + assert!(matches!( + error, + KarError::Integrity("KAR full archive SHA-256 mismatch") + )); + } + // The public verifier still goes through the combined scan before mapping; + // no successful serving capability can be minted from this miniature file. + let error = VerifiedKarPleArtifact::verify( + bad_inspection.into_owner_controlled(), + KarPleProfile::new(profile(&bad_crc)).unwrap(), + ) + .err() + .unwrap(); + assert!(matches!( + error, + KarError::Integrity("KAR payload CRC-32 mismatch") + )); +}