//! QA second review (PR #1): the cases of `qa/01_arcanum_attacks.md` that the builder listed as //! partial or not done and that can be done honestly here, plus regression tests for the review's //! own findings (QA-R2-nn, see `qa/review-arcanum-pr1.md` outside this repository and the PR //! comments). mod common; use arcanum::exchange::{self, Initiation, Session, WireGuardPsk}; use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PublicKey, SecretKey, SharedSecret}; use common::rng; use std::collections::HashSet; use zeroize::ZeroizeOnDrop; // --------------------------------------------------------------------------------------------- // A-28 and A-31, at compile time. A hand-rolled `assert_not_impl` (the `static_assertions` trick: // if `$t` implements `$tr`, the call below is ambiguous and the crate does not compile), so no new // dev-dependency is needed. Checked by adding `#[derive(Clone, Copy, PartialEq)]` to a secret type: // this file then fails to compile. // --------------------------------------------------------------------------------------------- macro_rules! assert_not_impl { ($t:ty : $($tr:path),+ $(,)?) => { $( const _: fn() = || { #[allow(dead_code)] trait AmbiguousIfImpl { fn some_item() {} } impl AmbiguousIfImpl<()> for T {} #[allow(dead_code)] struct Invalid; impl AmbiguousIfImpl for T {} let _ = <$t as AmbiguousIfImpl<_>>::some_item; }; )+ }; } fn assert_zeroize_on_drop() {} // A secret that is `Copy` can never be wiped; `Clone` multiplies what must be wiped; `PartialEq` // on secret bytes is a variable-time comparison (A-31); `Display` is one `{}` away from a log line. assert_not_impl!(SecretKey: Copy, Clone, PartialEq, core::fmt::Display); assert_not_impl!(SharedSecret: Copy, Clone, PartialEq, core::fmt::Display); assert_not_impl!(Session: Copy, Clone, PartialEq, core::fmt::Display); assert_not_impl!(WireGuardPsk: Copy, Clone, PartialEq, core::fmt::Display); assert_not_impl!(Initiation<'static>: Copy, Clone, PartialEq, core::fmt::Display); /// QA A-28: the secret types promise `ZeroizeOnDrop`. (`Initiation` wipes its fields but does not /// carry the marker; noted in the review as a nit, not asserted here.) #[test] fn a28_secret_types_are_zeroize_on_drop() { assert_zeroize_on_drop::(); assert_zeroize_on_drop::(); assert_zeroize_on_drop::(); assert_zeroize_on_drop::(); assert_zeroize_on_drop::>(); // R2-05, added by the builder with the fix } /// QA A-28: `Debug` of every secret type is redacted (the PSK and Session case is already in /// `psk_epochs.rs`; this adds the key, the X-Wing secret and the half-finished exchange). #[test] fn a28_debug_of_secret_types_is_redacted() { let seed = [0xab; 32]; let sk = SecretKey::from_seed(seed); let peer = SecretKey::from_seed([0xcd; 32]); let (ct, ss) = peer.public_key().encapsulate(&mut rng(1)).unwrap(); let init = exchange::initiate(&sk, peer.public_key(), b"ctx", &mut rng(2)).unwrap(); let ss_hex = hex::encode(ss.as_bytes()); let shown = format!("{sk:?} {ss:?} {init:?} {ct:?}"); for needle in ["abab", "171, 171", &ss_hex[..8], &format!("{}, {}", ss.as_bytes()[0], ss.as_bytes()[1])] { assert!(!shown.to_lowercase().contains(needle), "{needle} in {shown}"); } assert_eq!(shown.matches("redacted").count(), 3, "{shown}"); } /// QA A-31, the rung-1 guardrail: no variable-time comparison of secret bytes in `src/`. #[test] fn a31_no_variable_time_comparison_of_secrets_in_src() { for file in ["xwing.rs", "exchange.rs", "schedule.rs", "seal.rs"] { let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join(file); let text = std::fs::read_to_string(&path).unwrap(); for (n, line) in text.lines().enumerate() { let code = line.split("//").next().unwrap_or(""); for bad in ["== [0", "as_bytes() ==", "as_bytes() !=", "ss_x.as_bytes() ==", "== *"] { assert!(!code.contains(bad), "src/{file}:{}: `{bad}` in `{line}`", n + 1); } } } } // --------------------------------------------------------------------------------------------- // Partial cases completed. // --------------------------------------------------------------------------------------------- /// QA A-03 (the missing half): every one of the 1120 single-byte flips gives a different secret /// from the honest one **and from every other flip**. #[test] fn a03_every_ciphertext_flip_gives_a_distinct_secret() { let r = SecretKey::from_seed([0x31; 32]); let (ct, ss) = r.public_key().encapsulate(&mut rng(3)).unwrap(); let mut seen = HashSet::new(); seen.insert(*ss.as_bytes()); let mut refused = 0; for i in 0..CIPHERTEXT_LEN { let mut b = *ct.as_bytes(); b[i] ^= 0x01; match r.decapsulate(&Ciphertext::from_bytes(&b).unwrap()) { Ok(out) => { assert!(seen.insert(*out.as_bytes()), "byte {i}: collides with the honest secret or another flip") } Err(_) => refused += 1, // a flip that lands on a low-order ct_X } } assert!(refused <= 1, "{refused} flips refused"); } /// QA A-06 (the missing half): a "hybrid" key spliced from A's ML-KEM half and B's X25519 half /// matches neither A nor B. #[test] fn a06_a_spliced_public_key_matches_neither_owner() { let a = SecretKey::from_seed([0x61; 32]); let b = SecretKey::from_seed([0x62; 32]); let mut spliced = *a.public_key().as_bytes(); spliced[1184..].copy_from_slice(&b.public_key().as_bytes()[1184..]); let pk = PublicKey::from_bytes(&spliced).unwrap(); let (ct, ss) = pk.encapsulate(&mut rng(4)).unwrap(); assert_ne!(a.decapsulate(&ct).unwrap().as_bytes(), ss.as_bytes()); assert_ne!(b.decapsulate(&ct).unwrap().as_bytes(), ss.as_bytes()); // And through the exchange: a responder given the spliced key as "A's" cannot agree with A. let init = exchange::initiate(&a, b.public_key(), b"ctx", &mut rng(5)).unwrap(); let (ct_ri, rs) = exchange::respond(&b, &pk, init.ciphertext(), b"ctx", &mut rng(6)).unwrap(); let is = init.finish(&ct_ri).unwrap(); assert_ne!(is.wireguard_psk(0).as_bytes(), rs.wireguard_psk(0).as_bytes()); } /// QA A-18 (the missing half): implicit rejection is `Ok`, deterministic for one ciphertext, /// different for two tamperings, and recipient-specific. #[test] fn a18_implicit_rejection_is_ok_deterministic_and_recipient_specific() { let r = SecretKey::from_seed([0x71; 32]); let other = SecretKey::from_seed([0x72; 32]); let (ct, ss) = r.public_key().encapsulate(&mut rng(7)).unwrap(); let flip = |i: usize| { let mut b = *ct.as_bytes(); b[i] ^= 0x08; Ciphertext::from_bytes(&b).unwrap() }; let (c1, c2) = (flip(10), flip(11)); let k1a = r.decapsulate(&c1).expect("implicit rejection must not be an Err"); let k1b = r.decapsulate(&c1).unwrap(); assert_eq!(k1a.as_bytes(), k1b.as_bytes(), "J(z || c) must be deterministic"); assert_ne!(k1a.as_bytes(), r.decapsulate(&c2).unwrap().as_bytes()); assert_ne!(k1a.as_bytes(), ss.as_bytes()); assert_ne!(k1a.as_bytes(), other.decapsulate(&c1).unwrap().as_bytes(), "z differs per recipient"); } /// QA A-30: every error a hostile input can produce displays only lengths and variants. Feeds /// recognisable bytes (0xab) to every parser and checks that no Debug or Display shows them. #[test] fn a30_errors_from_hostile_input_carry_no_input_bytes() { let sk = SecretKey::from_seed([0x01; 32]); let mut errors = Vec::new(); for len in [0usize, 31, 33, 1119, 1121, 1215, 1217, 1136, 1137, 2000] { let junk = vec![0xab; len]; errors.extend(PublicKey::from_bytes(&junk).err()); errors.extend(Ciphertext::from_bytes(&junk).err()); errors.extend(SecretKey::from_bytes(&junk).err()); // Byte 0 is the public version byte, which `UnsupportedVersion(v)` echoes by design // (A-37); give it the valid value so the rest of the box reaches the parser. let mut boxed = junk.clone(); if let Some(v) = boxed.first_mut() { *v = arcanum::seal::VERSION; } errors.extend(arcanum::seal::open(&sk, &boxed, b"").err()); } errors.extend(PublicKey::from_bytes(&[0xab; 1216]).err()); assert!(errors.len() > 30); for e in errors { let shown = format!("{e} {e:?}").to_lowercase(); assert!(!shown.contains("abab") && !shown.contains("171"), "{shown}"); } } // --------------------------------------------------------------------------------------------- // Regression tests for this review's findings. // --------------------------------------------------------------------------------------------- /// QA-R2-02 (minor): `PublicKey::from_bytes` accepts a non-canonical X25519 half. X25519 ignores /// bit 255 (RFC 7748 ยง5), so `pk_X` and `pk_X | 0x80..` are the same key to the DH but different /// bytes to the X-Wing combiner and to Arcanum's transcript. An initiator handed the variant /// "succeeds" and silently derives a PSK the real owner can never match, and one secret key has /// two public encodings that compare unequal. Arcanum already refuses low-order points as stricter /// than the draft; refusing a non-canonical encoding is the same kind of check and changes no /// vector (honest keys are canonical). Fails while the variant parses. #[test] fn qa_r2_02_non_canonical_x25519_public_key_is_refused() { let i = SecretKey::from_seed([0x81; 32]); let r = SecretKey::from_seed([0x82; 32]); let mut variant = *r.public_key().as_bytes(); assert_eq!(variant[1215] & 0x80, 0, "an honest pk_X is canonical"); variant[1215] |= 0x80; if let Ok(pk) = PublicKey::from_bytes(&variant) { // Show the consequence before failing: the exchange "works" and the PSKs disagree. let init = exchange::initiate(&i, &pk, b"ctx", &mut rng(8)).unwrap(); let (ct_ri, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), b"ctx", &mut rng(9)).unwrap(); let is = init.finish(&ct_ri).unwrap(); assert_ne!(is.wireguard_psk(0).as_bytes(), rs.wireguard_psk(0).as_bytes()); assert_ne!(&pk, r.public_key(), "two encodings of one key compare unequal"); panic!("PublicKey::from_bytes accepted a non-canonical X25519 half (bit 255 set)"); } }