test(qa): second review, A-03/A-06/A-08/A-09/A-18/A-28/A-30/A-31 and R2-02 (non-canonical pk_X)

Completes the partial QA cases and adds the not-done ones that need no new
dependency: compile-time checks that no secret type is Copy, Clone, PartialEq
or Display (A-28, A-31, hand-rolled assert_not_impl), ZeroizeOnDrop markers,
redacted Debug, no input bytes in errors (A-30), distinct secrets for all 1120
ciphertext flips (A-03), a spliced key (A-06), deterministic implicit rejection
(A-18), and the KDF-encoding and purpose-separation unit tests (A-08, A-09).

qa_r2_02_non_canonical_x25519_public_key_is_refused FAILS on purpose: a pk_X
with bit 255 set parses, and the exchange then silently derives mismatched PSKs.
This commit is contained in:
2026-11-25 08:16:44 +01:00
parent 853f59ca60
commit 3dfc75075f
3 changed files with 312 additions and 0 deletions
+2
View File
@@ -27,6 +27,8 @@ pub mod xwing;
#[cfg(test)]
mod binding_tests;
#[cfg(test)]
mod qa_review_tests;
pub use error::{Error, Input};
pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk};
+98
View File
@@ -0,0 +1,98 @@
//! QA second review (PR #1): A-08 and A-09, which need the crate-private key schedule.
use alloc::vec::Vec;
use std::collections::HashSet;
use crate::schedule::{
LABEL_SEAL_KEY, LABEL_SEAL_NONCE, LABEL_WIREGUARD_PSK, Prk, Transcript, expand, seal_prk, session_prk,
};
use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, SecretKey, SharedSecret};
use zeroize::Zeroizing;
extern crate std;
fn ss(b: u8) -> SharedSecret {
SharedSecret(Zeroizing::new([b; 32]))
}
/// The `info` strings every `expand` call in the crate uses, built exactly as the call sites do.
fn psk_info(epoch: u64) -> Vec<u8> {
[LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()].concat()
}
/// QA A-08. `expand` concatenates its parts raw, so it is injective only because every call site
/// passes a fixed label followed by fixed-width fields. This test pins both halves of that
/// argument: (1) the helper itself is NOT length-prefixed (so a future variable-width part is a
/// collision, and this test documents it for whoever adds one), and (2) the encodings actually in
/// use are injective: fixed lengths per purpose, and no two purposes share a length-and-prefix.
#[test]
fn a08_kdf_info_encodings_in_use_are_injective() {
let prk: Prk = Zeroizing::new([9u8; 32]);
// (1) The helper is raw concatenation. If this ever fails, the helper became length-prefixed:
// update this test and the golden vectors together.
assert_eq!(*expand::<32>(&prk, &[b"ab", b"c"]), *expand::<32>(&prk, &[b"a", b"bc"]));
// (2) Every info string in use: one fixed length per purpose, and none a prefix of another.
let mut infos: Vec<Vec<u8>> = [0u64, 1, 255, 256, 1 << 32, u64::MAX].iter().map(|&e| psk_info(e)).collect();
infos.push(LABEL_SEAL_KEY.to_vec());
infos.push(LABEL_SEAL_NONCE.to_vec());
for info in &infos[..6] {
assert_eq!(info.len(), LABEL_WIREGUARD_PSK.len() + 8, "a PSK info has one fixed width");
}
for (i, a) in infos.iter().enumerate() {
for (j, b) in infos.iter().enumerate() {
if i != j {
assert_ne!(a, b);
assert!(!b.starts_with(a), "info {i} is a prefix of info {j}");
}
}
}
// The exchange transcript: the only variable field (the context) is last and length-prefixed,
// so moving a byte across the context boundary changes the hash.
let pk_i = SecretKey::from_bytes(&[1u8; 32]).unwrap().public_key().clone();
let pk_r = SecretKey::from_bytes(&[2u8; 32]).unwrap().public_key().clone();
let ct = Ciphertext::from_bytes(&[3u8; CIPHERTEXT_LEN]).unwrap();
let t = |ctx: &[u8]| {
*session_prk(
&ss(1),
&ss(2),
&Transcript { initiator: &pk_i, responder: &pk_r, ct_ir: &ct, ct_ri: &ct, context: ctx },
)
};
assert_ne!(t(b""), t(&[0u8; 8]), "an empty context is not 8 zero bytes");
assert_ne!(t(b"x"), t(b"x\0"));
}
/// QA A-09: from one X-Wing secret, no two purposes ever yield the same key. The seal key and
/// nonce, and the PSKs of 1024 epochs, are all distinct; and even under a single PRK the labels
/// keep the purposes apart.
#[test]
fn a09_one_secret_never_yields_the_same_key_for_two_purposes() {
let r = SecretKey::from_bytes(&[5u8; 32]).unwrap();
let ct = Ciphertext::from_bytes(&[6u8; CIPHERTEXT_LEN]).unwrap();
let secret = ss(7);
// The same secret, used as a seal and as both directions of an exchange.
let seal = seal_prk(&secret, r.public_key(), &ct, b"");
let session = session_prk(
&secret,
&secret,
&Transcript { initiator: r.public_key(), responder: r.public_key(), ct_ir: &ct, ct_ri: &ct, context: b"" },
);
assert_ne!(*seal, *session, "seal and exchange PRKs must differ for one secret");
let mut keys: HashSet<[u8; 32]> = HashSet::new();
for prk in [&seal, &session] {
let key = *expand::<32>(prk, &[LABEL_SEAL_KEY]);
assert!(keys.insert(key));
let mut nonce = [0u8; 32];
nonce[..12].copy_from_slice(&*expand::<12>(prk, &[LABEL_SEAL_NONCE]));
// HKDF output is prefix-consistent: a shared label would make the nonce the key's prefix.
assert_ne!(nonce[..12], key[..12], "the nonce is a prefix of the key: labels shared");
assert!(keys.insert(nonce));
for e in 0..1024u64 {
assert!(keys.insert(*expand::<32>(prk, &[LABEL_WIREGUARD_PSK, &e.to_be_bytes()])), "epoch {e}");
}
}
assert_eq!(keys.len(), 2 * (2 + 1024));
}
+212
View File
@@ -0,0 +1,212 @@
//! 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<A> {
fn some_item() {}
}
impl<T: ?Sized> AmbiguousIfImpl<()> for T {}
#[allow(dead_code)]
struct Invalid;
impl<T: ?Sized + $tr> AmbiguousIfImpl<Invalid> for T {}
let _ = <$t as AmbiguousIfImpl<_>>::some_item;
};
)+
};
}
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
// 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::<SecretKey>();
assert_zeroize_on_drop::<SharedSecret>();
assert_zeroize_on_drop::<Session>();
assert_zeroize_on_drop::<WireGuardPsk>();
}
/// 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)");
}
}