Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/crypto/envelope.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / crypto / envelope.rs` 652 lines ยท 23045 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! M5 authenticated streaming envelope over Store v1 (ADR 0017 Section 2.3). 17 //! 18 //! Wraps application payload objects in chunked AEAD envelopes using AES-256-GCM-SIV. 19 //! Chunk size is bounded to 64 KiB to guarantee bounded memory scratchpads during 20 //! verification, and every chunk authenticates store identity, object kind/version, 21 //! envelope header, chunk index, and length to prevent splicing, reordering, truncation, 22 //! or cross-store replay. 23 24 extern crate alloc; 25 26 use alloc::vec::Vec; 27 28 pub use aienos_crypto::aes_gcm_siv::{ 29 decrypt as raw_decrypt, encrypt as raw_encrypt, AuthenticationError, KEY_LEN, NONCE_LEN, 30 TAG_LEN, 31 }; 32 33 /// 8-byte magic for M5 envelopes: "AIENENV1". 34 pub const ENVELOPE_MAGIC: &[u8; 8] = b"AIENENV1"; 35 /// Format version for M5 envelopes. 36 pub const ENVELOPE_VERSION_1: u16 = 1; 37 /// Cipher suite identifier for AES-256-GCM-SIV per ADR 0017. 38 pub const CIPHER_SUITE_AES_256_GCM_SIV: u16 = 0x0001; 39 /// Default chunk size: 64 KiB (65,536 bytes). 40 pub const DEFAULT_CHUNK_SIZE: u32 = 65536; 41 /// Envelope header length: fixed 64 bytes. 42 pub const ENVELOPE_HEADER_LEN: usize = 64; 43 /// Additional Authenticated Data domain separator prefix for M5 chunks. 44 pub const CHUNK_AAD_PREFIX: &[u8; 19] = b"AIENOS-M5-CHUNK-V1\0"; 45 /// Total length of per-chunk AAD: 19 + 16 + 2 + 2 + 64 + 4 + 4 = 111 bytes. 46 pub const CHUNK_AAD_LEN: usize = 111; 47 /// Largest plaintext a single envelope may carry: 64 MiB (67,108,864 bytes). 48 /// 49 /// `total_plaintext_len` comes from the unauthenticated header, so decryption rejects 50 /// anything above this before sizing or allocating from it. Callers of 51 /// `encrypt_envelope` must keep plaintexts at or below this bound, or the resulting 52 /// envelope will be rejected on decryption. 53 pub const MAX_ENVELOPE_PLAINTEXT: u64 = 64 * 1024 * 1024; 54 55 /// Error conditions encountered when inspecting or decrypting an envelope. 56 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 57 pub enum EnvelopeError { 58 /// Input is smaller than the 64-byte envelope header. 59 HeaderTooShort, 60 /// Invalid magic bytes. 61 InvalidMagic, 62 /// Unsupported envelope version. 63 UnsupportedVersion(u16), 64 /// Unsupported cipher suite. 65 UnsupportedCipherSuite(u16), 66 /// Invalid flags. 67 InvalidFlags(u32), 68 /// Invalid chunk size (must be > 0 and <= 64 KiB). 69 InvalidChunkSize(u32), 70 /// Nonzero reserved bytes. 71 NonzeroReserved, 72 /// Ciphertext length does not match expected length from header. 73 LengthMismatch, 74 /// AEAD authentication verification failed for a chunk. 75 AuthenticationFailed, 76 /// Header claims more plaintext than `MAX_ENVELOPE_PLAINTEXT`. 77 PlaintextTooLarge(u64), 78 /// Expected envelope length overflows the platform integer range. 79 LengthOverflow, 80 /// Allocation failed after the envelope header was authenticated. 81 AllocationFailed, 82 } 83 84 /// Temporary plaintext is wiped even when allocation or authentication fails. 85 struct PlaintextScratch(Vec); 86 87 impl Drop for PlaintextScratch { 88 fn drop(&mut self) { 89 for byte in &mut self.0 { 90 // SAFETY: exclusive reference to a live initialized byte. 91 unsafe { core::ptr::write_volatile(byte, 0) }; 92 } 93 core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); 94 } 95 } 96 97 /// Fixed 64-byte authenticated envelope header. 98 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 99 pub struct EnvelopeHeader { 100 pub magic: [u8; 8], 101 pub envelope_version: u16, 102 pub cipher_suite: u16, 103 pub flags: u32, 104 pub chunk_size: u32, 105 pub total_plaintext_len: u64, 106 pub envelope_id: [u8; 16], 107 pub nonce_prefix: [u8; 8], 108 pub key_epoch: u64, 109 pub reserved: u32, 110 } 111 112 impl EnvelopeHeader { 113 /// Encode the header into a fixed 64-byte array. 114 pub fn encode(&self) -> [u8; ENVELOPE_HEADER_LEN] { 115 let mut out = [0u8; ENVELOPE_HEADER_LEN]; 116 out[0..8].copy_from_slice(&self.magic); 117 out[8..10].copy_from_slice(&self.envelope_version.to_le_bytes()); 118 out[10..12].copy_from_slice(&self.cipher_suite.to_le_bytes()); 119 out[12..16].copy_from_slice(&self.flags.to_le_bytes()); 120 out[16..20].copy_from_slice(&self.chunk_size.to_le_bytes()); 121 out[20..28].copy_from_slice(&self.total_plaintext_len.to_le_bytes()); 122 out[28..44].copy_from_slice(&self.envelope_id); 123 out[44..52].copy_from_slice(&self.nonce_prefix); 124 out[52..60].copy_from_slice(&self.key_epoch.to_le_bytes()); 125 out[60..64].copy_from_slice(&self.reserved.to_le_bytes()); 126 out 127 } 128 129 /// Decode and validate a 64-byte envelope header. 130 pub fn decode(bytes: &[u8]) -> Result { 131 if bytes.len() < ENVELOPE_HEADER_LEN { 132 return Err(EnvelopeError::HeaderTooShort); 133 } 134 135 let mut magic = [0u8; 8]; 136 magic.copy_from_slice(&bytes[0..8]); 137 if magic != *ENVELOPE_MAGIC { 138 return Err(EnvelopeError::InvalidMagic); 139 } 140 141 let envelope_version = u16::from_le_bytes([bytes[8], bytes[9]]); 142 if envelope_version != ENVELOPE_VERSION_1 { 143 return Err(EnvelopeError::UnsupportedVersion(envelope_version)); 144 } 145 146 let cipher_suite = u16::from_le_bytes([bytes[10], bytes[11]]); 147 if cipher_suite != CIPHER_SUITE_AES_256_GCM_SIV { 148 return Err(EnvelopeError::UnsupportedCipherSuite(cipher_suite)); 149 } 150 151 let flags = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]); 152 if flags != 0 { 153 return Err(EnvelopeError::InvalidFlags(flags)); 154 } 155 156 let chunk_size = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); 157 if chunk_size == 0 || chunk_size > DEFAULT_CHUNK_SIZE { 158 return Err(EnvelopeError::InvalidChunkSize(chunk_size)); 159 } 160 161 let mut total_pt_bytes = [0u8; 8]; 162 total_pt_bytes.copy_from_slice(&bytes[20..28]); 163 let total_plaintext_len = u64::from_le_bytes(total_pt_bytes); 164 165 let mut envelope_id = [0u8; 16]; 166 envelope_id.copy_from_slice(&bytes[28..44]); 167 168 let mut nonce_prefix = [0u8; 8]; 169 nonce_prefix.copy_from_slice(&bytes[44..52]); 170 171 let mut epoch_bytes = [0u8; 8]; 172 epoch_bytes.copy_from_slice(&bytes[52..60]); 173 let key_epoch = u64::from_le_bytes(epoch_bytes); 174 175 let reserved = u32::from_le_bytes([bytes[60], bytes[61], bytes[62], bytes[63]]); 176 if reserved != 0 { 177 return Err(EnvelopeError::NonzeroReserved); 178 } 179 180 Ok(Self { 181 magic, 182 envelope_version, 183 cipher_suite, 184 flags, 185 chunk_size, 186 total_plaintext_len, 187 envelope_id, 188 nonce_prefix, 189 key_epoch, 190 reserved, 191 }) 192 } 193 194 /// Calculate the number of chunks for this envelope. 195 pub fn chunk_count(&self) -> usize { 196 if self.total_plaintext_len == 0 { 197 1 198 } else { 199 let cs = self.chunk_size as u64; 200 self.total_plaintext_len.div_ceil(cs) as usize 201 } 202 } 203 204 /// Calculate the expected total ciphertext envelope size (header + ciphertext + tags). 205 /// 206 /// The header fields are unauthenticated at this point, so every step is checked 207 /// and an overflow returns `LengthOverflow` instead of wrapping or panicking. 208 pub fn expected_envelope_len(&self) -> Result { 209 if self.chunk_size == 0 { 210 return Err(EnvelopeError::InvalidChunkSize(0)); 211 } 212 let chunks = if self.total_plaintext_len == 0 { 213 1 214 } else { 215 self.total_plaintext_len.div_ceil(self.chunk_size as u64) 216 }; 217 let len = chunks 218 .checked_mul(TAG_LEN as u64) 219 .and_then(|tags| tags.checked_add(self.total_plaintext_len)) 220 .and_then(|body| body.checked_add(ENVELOPE_HEADER_LEN as u64)) 221 .ok_or(EnvelopeError::LengthOverflow)?; 222 usize::try_from(len).map_err(|_| EnvelopeError::LengthOverflow) 223 } 224 } 225 226 /// Derive the 12-byte nonce for a specific chunk index: nonce_prefix[8] || chunk_index:u32le. 227 pub fn derive_chunk_nonce(nonce_prefix: &[u8; 8], chunk_index: u32) -> [u8; NONCE_LEN] { 228 let mut nonce = [0u8; NONCE_LEN]; 229 nonce[0..8].copy_from_slice(nonce_prefix); 230 nonce[8..12].copy_from_slice(&chunk_index.to_le_bytes()); 231 nonce 232 } 233 234 /// Format the 111-byte AAD for a specific chunk. 235 pub fn compute_chunk_aad( 236 store_uuid: &[u8; 16], 237 object_kind: u16, 238 object_version: u16, 239 header_64b: &[u8; ENVELOPE_HEADER_LEN], 240 chunk_index: u32, 241 chunk_plaintext_len: u32, 242 ) -> [u8; CHUNK_AAD_LEN] { 243 let mut aad = [0u8; CHUNK_AAD_LEN]; 244 let mut offset = 0; 245 246 aad[offset..offset + 19].copy_from_slice(CHUNK_AAD_PREFIX); 247 offset += 19; 248 249 aad[offset..offset + 16].copy_from_slice(store_uuid); 250 offset += 16; 251 252 aad[offset..offset + 2].copy_from_slice(&object_kind.to_le_bytes()); 253 offset += 2; 254 255 aad[offset..offset + 2].copy_from_slice(&object_version.to_le_bytes()); 256 offset += 2; 257 258 aad[offset..offset + 64].copy_from_slice(header_64b); 259 offset += 64; 260 261 aad[offset..offset + 4].copy_from_slice(&chunk_index.to_le_bytes()); 262 offset += 4; 263 264 aad[offset..offset + 4].copy_from_slice(&chunk_plaintext_len.to_le_bytes()); 265 offset += 4; 266 267 debug_assert_eq!(offset, CHUNK_AAD_LEN); 268 aad 269 } 270 271 /// Encrypt arbitrary plaintext into an authenticated streaming envelope. 272 #[allow(clippy::too_many_arguments)] 273 pub fn encrypt_envelope( 274 key: &[u8; KEY_LEN], 275 store_uuid: &[u8; 16], 276 object_kind: u16, 277 object_version: u16, 278 envelope_id: &[u8; 16], 279 nonce_prefix: &[u8; 8], 280 key_epoch: u64, 281 plaintext: &[u8], 282 ) -> Vec { 283 let header = EnvelopeHeader { 284 magic: *ENVELOPE_MAGIC, 285 envelope_version: ENVELOPE_VERSION_1, 286 cipher_suite: CIPHER_SUITE_AES_256_GCM_SIV, 287 flags: 0, 288 chunk_size: DEFAULT_CHUNK_SIZE, 289 total_plaintext_len: plaintext.len() as u64, 290 envelope_id: *envelope_id, 291 nonce_prefix: *nonce_prefix, 292 key_epoch, 293 reserved: 0, 294 }; 295 296 let header_bytes = header.encode(); 297 debug_assert!(plaintext.len() as u64 <= MAX_ENVELOPE_PLAINTEXT); 298 let capacity = header 299 .expected_envelope_len() 300 .unwrap_or(ENVELOPE_HEADER_LEN); 301 let mut out = Vec::with_capacity(capacity); 302 out.extend_from_slice(&header_bytes); 303 304 let chunk_size = header.chunk_size as usize; 305 306 if plaintext.is_empty() { 307 // Zero-length plaintext has 1 empty chunk producing a 16-byte tag 308 let nonce = derive_chunk_nonce(nonce_prefix, 0); 309 let aad = compute_chunk_aad(store_uuid, object_kind, object_version, &header_bytes, 0, 0); 310 let mut chunk_out = [0u8; TAG_LEN]; 311 raw_encrypt(key, &nonce, &aad, &[], &mut chunk_out); 312 out.extend_from_slice(&chunk_out); 313 } else { 314 for (i, pt_chunk) in plaintext.chunks(chunk_size).enumerate() { 315 let chunk_idx = i as u32; 316 let nonce = derive_chunk_nonce(nonce_prefix, chunk_idx); 317 let aad = compute_chunk_aad( 318 store_uuid, 319 object_kind, 320 object_version, 321 &header_bytes, 322 chunk_idx, 323 pt_chunk.len() as u32, 324 ); 325 let mut chunk_out = alloc::vec![0u8; pt_chunk.len() + TAG_LEN]; 326 raw_encrypt(key, &nonce, &aad, pt_chunk, &mut chunk_out); 327 out.extend_from_slice(&chunk_out); 328 } 329 } 330 331 debug_assert_eq!(header.expected_envelope_len(), Ok(out.len())); 332 out 333 } 334 335 /// Decrypt an authenticated streaming envelope, returning the verified plaintext. 336 /// 337 /// Invariant: Plaintext chunks are verified in private scratch buffers before being 338 /// committed to the output buffer. Any tag mismatch halts immediately and wipes memory. 339 pub fn decrypt_envelope( 340 key: &[u8; KEY_LEN], 341 store_uuid: &[u8; 16], 342 object_kind: u16, 343 object_version: u16, 344 envelope_bytes: &[u8], 345 ) -> Result, EnvelopeError> { 346 if envelope_bytes.len() < ENVELOPE_HEADER_LEN { 347 return Err(EnvelopeError::HeaderTooShort); 348 } 349 350 let header = EnvelopeHeader::decode(&envelope_bytes[0..ENVELOPE_HEADER_LEN])?; 351 // Bound the unauthenticated length claim before any size is derived from it. 352 if header.total_plaintext_len > MAX_ENVELOPE_PLAINTEXT { 353 return Err(EnvelopeError::PlaintextTooLarge(header.total_plaintext_len)); 354 } 355 if envelope_bytes.len() != header.expected_envelope_len()? { 356 return Err(EnvelopeError::LengthMismatch); 357 } 358 359 let mut header_bytes = [0u8; ENVELOPE_HEADER_LEN]; 360 header_bytes.copy_from_slice(&envelope_bytes[0..ENVELOPE_HEADER_LEN]); 361 362 let chunk_size = header.chunk_size as usize; 363 let chunk_count = header.chunk_count(); 364 // Reserve only after the first chunk authenticates the complete header. 365 // One reservation prevents plaintext copies being left in freed growth buffers. 366 let mut plaintext = Vec::new(); 367 368 let mut cursor = ENVELOPE_HEADER_LEN; 369 370 if header.total_plaintext_len == 0 { 371 let chunk_bytes = &envelope_bytes[cursor..cursor + TAG_LEN]; 372 let nonce = derive_chunk_nonce(&header.nonce_prefix, 0); 373 let aad = compute_chunk_aad(store_uuid, object_kind, object_version, &header_bytes, 0, 0); 374 375 let mut scratchpad = [0u8; 0]; 376 raw_decrypt(key, &nonce, &aad, chunk_bytes, &mut scratchpad) 377 .map_err(|_| EnvelopeError::AuthenticationFailed)?; 378 return Ok(plaintext); 379 } 380 381 let mut remaining = header.total_plaintext_len as usize; 382 383 for i in 0..chunk_count { 384 let chunk_idx = i as u32; 385 let pt_chunk_len = core::cmp::min(remaining, chunk_size); 386 let ct_chunk_len = pt_chunk_len + TAG_LEN; 387 388 let ct_chunk = &envelope_bytes[cursor..cursor + ct_chunk_len]; 389 cursor += ct_chunk_len; 390 remaining -= pt_chunk_len; 391 392 let nonce = derive_chunk_nonce(&header.nonce_prefix, chunk_idx); 393 let aad = compute_chunk_aad( 394 store_uuid, 395 object_kind, 396 object_version, 397 &header_bytes, 398 chunk_idx, 399 pt_chunk_len as u32, 400 ); 401 402 // Verification scratchpad: verified before writing to caller buffer 403 let mut scratchpad = PlaintextScratch(alloc::vec![0u8; pt_chunk_len]); 404 if raw_decrypt(key, &nonce, &aad, ct_chunk, &mut scratchpad.0).is_err() { 405 // Scratchpad was wiped by raw_decrypt on failure; wipe and drop plaintext 406 for b in plaintext.iter_mut() { 407 unsafe { core::ptr::write_volatile(b, 0) }; 408 } 409 return Err(EnvelopeError::AuthenticationFailed); 410 } 411 412 if i == 0 { 413 plaintext 414 .try_reserve_exact(header.total_plaintext_len as usize) 415 .map_err(|_| EnvelopeError::AllocationFailed)?; 416 } 417 plaintext.extend_from_slice(&scratchpad.0); 418 } 419 420 Ok(plaintext) 421 } 422 423 #[cfg(test)] 424 mod tests { 425 use super::*; 426 427 #[test] 428 fn test_envelope_roundtrip_small() { 429 let key = [0x42u8; 32]; 430 let store_uuid = [0x11u8; 16]; 431 let envelope_id = [0x22u8; 16]; 432 let nonce_prefix = [0x33u8; 8]; 433 let pt = b"Sovereign AIENOS M5 Encrypted State"; 434 435 let env = encrypt_envelope( 436 &key, 437 &store_uuid, 438 16, 439 1, 440 &envelope_id, 441 &nonce_prefix, 442 100, 443 pt, 444 ); 445 446 let decrypted = decrypt_envelope(&key, &store_uuid, 16, 1, &env).unwrap(); 447 assert_eq!(decrypted, pt); 448 } 449 450 #[test] 451 fn test_envelope_roundtrip_empty() { 452 let key = [0x55u8; 32]; 453 let store_uuid = [0x77u8; 16]; 454 let envelope_id = [0x88u8; 16]; 455 let nonce_prefix = [0x99u8; 8]; 456 let pt = b""; 457 458 let env = encrypt_envelope(&key, &store_uuid, 17, 1, &envelope_id, &nonce_prefix, 1, pt); 459 460 assert_eq!(env.len(), ENVELOPE_HEADER_LEN + TAG_LEN); 461 let decrypted = decrypt_envelope(&key, &store_uuid, 17, 1, &env).unwrap(); 462 assert_eq!(decrypted, pt); 463 } 464 465 #[test] 466 fn test_envelope_roundtrip_multi_chunk() { 467 let key = [0xaau8; 32]; 468 let store_uuid = [0xbbu8; 16]; 469 let envelope_id = [0xccu8; 16]; 470 let nonce_prefix = [0xddu8; 8]; 471 472 // 70 KiB of test data (crosses 64 KiB boundary into 2 chunks) 473 let mut pt = alloc::vec![0u8; 70 * 1024]; 474 for (i, b) in pt.iter_mut().enumerate() { 475 *b = (i % 251) as u8; 476 } 477 478 let env = encrypt_envelope( 479 &key, 480 &store_uuid, 481 18, 482 1, 483 &envelope_id, 484 &nonce_prefix, 485 42, 486 &pt, 487 ); 488 489 let header = EnvelopeHeader::decode(&env).unwrap(); 490 assert_eq!(header.chunk_count(), 2); 491 assert_eq!(env.len(), ENVELOPE_HEADER_LEN + pt.len() + 2 * TAG_LEN); 492 493 let decrypted = decrypt_envelope(&key, &store_uuid, 18, 1, &env).unwrap(); 494 assert_eq!(decrypted, pt); 495 } 496 497 #[test] 498 fn test_envelope_cross_store_and_kind_binding() { 499 let key = [0x12u8; 32]; 500 let store_uuid = [0x34u8; 16]; 501 let other_store = [0x99u8; 16]; 502 let envelope_id = [0x56u8; 16]; 503 let nonce_prefix = [0x78u8; 8]; 504 let pt = b"Confidential branch checkpoint"; 505 506 let env = encrypt_envelope(&key, &store_uuid, 20, 1, &envelope_id, &nonce_prefix, 1, pt); 507 508 // Foreign store UUID must fail verification 509 assert_eq!( 510 decrypt_envelope(&key, &other_store, 20, 1, &env), 511 Err(EnvelopeError::AuthenticationFailed) 512 ); 513 514 // Mismatched object kind must fail verification 515 assert_eq!( 516 decrypt_envelope(&key, &store_uuid, 21, 1, &env), 517 Err(EnvelopeError::AuthenticationFailed) 518 ); 519 520 // Bit-flip in ciphertext must fail verification 521 let mut corrupted = env.clone(); 522 corrupted[ENVELOPE_HEADER_LEN + 5] ^= 0x01; 523 assert_eq!( 524 decrypt_envelope(&key, &store_uuid, 20, 1, &corrupted), 525 Err(EnvelopeError::AuthenticationFailed) 526 ); 527 } 528 529 #[test] 530 fn tampered_late_chunk_rejects_the_entire_plaintext() { 531 let key = [0x6au8; 32]; 532 let store_uuid = [0x19u8; 16]; 533 let envelope_id = [0x2bu8; 16]; 534 let nonce_prefix = [0x3cu8; 8]; 535 let plaintext = alloc::vec![0x5d; DEFAULT_CHUNK_SIZE as usize + 37]; 536 537 let mut envelope = encrypt_envelope( 538 &key, 539 &store_uuid, 540 18, 541 1, 542 &envelope_id, 543 &nonce_prefix, 544 42, 545 &plaintext, 546 ); 547 let header = EnvelopeHeader::decode(&envelope).unwrap(); 548 assert_eq!(header.chunk_count(), 2); 549 550 // Corrupt the second chunk's tag, after the first chunk has verified. 551 *envelope.last_mut().unwrap() ^= 0x01; 552 553 assert_eq!( 554 decrypt_envelope(&key, &store_uuid, 18, 1, &envelope), 555 Err(EnvelopeError::AuthenticationFailed), 556 "a valid prefix must not be returned as a successful partial decrypt" 557 ); 558 } 559 560 /// Build a valid small envelope, then overwrite the unauthenticated header's 561 /// chunk_size and total_plaintext_len fields with hostile values. 562 fn hostile_envelope(chunk_size: u32, total_plaintext_len: u64) -> Vec { 563 let mut env = encrypt_envelope( 564 &[0x01u8; 32], 565 &[0x02u8; 16], 566 16, 567 1, 568 &[0x03u8; 16], 569 &[0x04u8; 8], 570 1, 571 b"hostile header probe", 572 ); 573 env[16..20].copy_from_slice(&chunk_size.to_le_bytes()); 574 env[20..28].copy_from_slice(&total_plaintext_len.to_le_bytes()); 575 env 576 } 577 578 #[test] 579 fn test_hostile_header_huge_total_rejected_before_alloc() { 580 let env = hostile_envelope(DEFAULT_CHUNK_SIZE, u64::MAX); 581 assert_eq!( 582 decrypt_envelope(&[0x01u8; 32], &[0x02u8; 16], 16, 1, &env), 583 Err(EnvelopeError::PlaintextTooLarge(u64::MAX)) 584 ); 585 } 586 587 #[test] 588 fn test_hostile_header_chunk_size_one_huge_count_rejected() { 589 let env = hostile_envelope(1, u64::MAX); 590 assert_eq!( 591 decrypt_envelope(&[0x01u8; 32], &[0x02u8; 16], 16, 1, &env), 592 Err(EnvelopeError::PlaintextTooLarge(u64::MAX)) 593 ); 594 595 let over = MAX_ENVELOPE_PLAINTEXT + 1; 596 let env = hostile_envelope(1, over); 597 assert_eq!( 598 decrypt_envelope(&[0x01u8; 32], &[0x02u8; 16], 16, 1, &env), 599 Err(EnvelopeError::PlaintextTooLarge(over)) 600 ); 601 } 602 603 #[test] 604 fn test_hostile_header_at_bound_hits_length_check() { 605 // Exactly at the bound is allowed by the size check, but the claimed length 606 // cannot match the short input, so the checked length comparison rejects it. 607 let env = hostile_envelope(1, MAX_ENVELOPE_PLAINTEXT); 608 assert_eq!( 609 decrypt_envelope(&[0x01u8; 32], &[0x02u8; 16], 16, 1, &env), 610 Err(EnvelopeError::LengthMismatch) 611 ); 612 } 613 614 #[test] 615 fn test_expected_envelope_len_overflow_is_error() { 616 let env = hostile_envelope(DEFAULT_CHUNK_SIZE, 0); 617 let valid = EnvelopeHeader::decode(&env).unwrap(); 618 619 // chunk_size 1 with u64::MAX bytes: chunks * TAG_LEN overflows. 620 let header = EnvelopeHeader { 621 chunk_size: 1, 622 total_plaintext_len: u64::MAX, 623 ..valid 624 }; 625 assert_eq!( 626 header.expected_envelope_len(), 627 Err(EnvelopeError::LengthOverflow) 628 ); 629 630 // Largest chunks: the tag term fits but adding the plaintext length overflows. 631 let header = EnvelopeHeader { 632 chunk_size: DEFAULT_CHUNK_SIZE, 633 total_plaintext_len: u64::MAX - 8, 634 ..valid 635 }; 636 assert_eq!( 637 header.expected_envelope_len(), 638 Err(EnvelopeError::LengthOverflow) 639 ); 640 641 // A hand-built zero chunk size must not divide by zero. 642 let header = EnvelopeHeader { 643 chunk_size: 0, 644 total_plaintext_len: 1, 645 ..valid 646 }; 647 assert_eq!( 648 header.expected_envelope_len(), 649 Err(EnvelopeError::InvalidChunkSize(0)) 650 ); 651 } 652 }