From 89b5329f0640bddac9cc9eb3b74418747cd5f75b Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 07:38:55 +0100 Subject: [PATCH] feat: X-Wing (draft -11), mutual exchange, WireGuard PSK per epoch, sealed box X-Wing is composed from ml-kem, x25519-dalek, sha3 and shake and matches the draft's vectors. The PSK comes from a mutual exchange (each peer encapsulates to the other, QA A-15) bound to the full transcript in Arcanum's own HKDF layer (QA D-QA-1). Low-order X25519 values are refused. Deterministic entry points sit behind the off-by-default hazmat feature, enabled only for the tests. --- Cargo.lock | 1 + Cargo.toml | 7 + src/binding_tests.rs | 101 +++++++++++-- src/error.rs | 83 +++++++++++ src/exchange.rs | 204 ++++++++++++++++++++++++++ src/lib.rs | 42 ++++++ src/schedule.rs | 113 +++++++++++++++ src/seal.rs | 121 ++++++++++++++++ src/xwing.rs | 304 +++++++++++++++++++++++++++++++++++++++ tests/binding.rs | 87 ++++++++--- tests/exchange.rs | 252 ++++++++++++++++++++++---------- tests/feature_hygiene.rs | 34 +++++ tests/malformed.rs | 54 ++++++- tests/no_unsafe.rs | 3 +- tests/psk_epochs.rs | 28 +++- 15 files changed, 1316 insertions(+), 118 deletions(-) create mode 100644 src/error.rs create mode 100644 src/exchange.rs create mode 100644 src/schedule.rs create mode 100644 src/seal.rs create mode 100644 src/xwing.rs create mode 100644 tests/feature_hygiene.rs diff --git a/Cargo.lock b/Cargo.lock index 01bfaca..b4f0829 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -16,6 +16,7 @@ dependencies = [ name = "arcanum" version = "0.1.0" dependencies = [ + "arcanum", "chacha20", "chacha20poly1305", "hex", diff --git a/Cargo.toml b/Cargo.toml index f929275..65cb2aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,14 @@ chacha20poly1305 = { version = "0.11", default-features = false, features = ["al rand_core = { version = "0.10", default-features = false } zeroize = { version = "1.8", default-features = false, features = ["alloc", "zeroize_derive"] } +[features] +# Deterministic entry points (`_derand`, `from_seed`) for the known-answer tests. Off by default; +# never enable it in a release build (tests/feature_hygiene.rs checks the normal dependency graph). +hazmat = [] + [dev-dependencies] +# The tests enable `hazmat` on the crate itself; dev-dependencies never reach a normal build. +arcanum = { path = ".", features = ["hazmat"] } # Reference implementation for the differential test only; never linked into the library. x-wing = { version = "=0.1.1" } chacha20 = { version = "0.10", default-features = false, features = ["rng"] } diff --git a/src/binding_tests.rs b/src/binding_tests.rs index d6e20b0..40aecb2 100644 --- a/src/binding_tests.rs +++ b/src/binding_tests.rs @@ -1,8 +1,11 @@ //! Mandatory test 3, at the combiner: replacing either component secret by zeros must change the -//! output, so both halves are bound. These are unit tests because the combiner is crate-private -//! (exposing it would invite misuse). +//! output, so both halves are bound. Also QA A-02 (the combiner is exactly the draft's SHA3-256) +//! and A-07 (labels are prefix-free). These are unit tests because the combiner and the schedule +//! are crate-private (exposing them would invite misuse). -use crate::schedule::session_prk; +use sha3::{Digest, Sha3_256}; + +use crate::schedule::{ALL_LABELS, session_prk_raw}; use crate::xwing::{SHARED_SECRET_LEN, combiner}; const SS_M: [u8; 32] = [0xa1; 32]; @@ -55,14 +58,94 @@ fn every_bit_of_each_component_reaches_the_output() { } } -/// The binding survives the key schedule: a zeroed component gives a different session key too. +/// The binding survives the key schedule: a zeroed component of either direction's X-Wing +/// secret gives a different session key. #[test] fn zeroed_components_give_a_different_session() { - let pk = [0x5a; crate::xwing::PUBLIC_KEY_LEN]; - let ct = [0x6b; crate::xwing::CIPHERTEXT_LEN]; - let honest = session_prk(&combiner(&SS_M, &SS_X, &CT_X, &PK_X), &pk, &ct, b"ctx"); - let no_m = session_prk(&combiner(&ZERO, &SS_X, &CT_X, &PK_X), &pk, &ct, b"ctx"); - let no_x = session_prk(&combiner(&SS_M, &ZERO, &CT_X, &PK_X), &pk, &ct, b"ctx"); + let th = [0x5a; 32]; + let ss_ri = combiner(&[0x01; 32], &[0x02; 32], &CT_X, &PK_X); + let honest = session_prk_raw(&combiner(&SS_M, &SS_X, &CT_X, &PK_X), &ss_ri, &th); + let no_m = session_prk_raw(&combiner(&ZERO, &SS_X, &CT_X, &PK_X), &ss_ri, &th); + let no_x = session_prk_raw(&combiner(&SS_M, &ZERO, &CT_X, &PK_X), &ss_ri, &th); + let no_ri = session_prk_raw(&combiner(&SS_M, &SS_X, &CT_X, &PK_X), &ZERO, &th); assert_ne!(*honest, *no_m); assert_ne!(*honest, *no_x); + assert_ne!(*honest, *no_ri); +} + +/// QA A-02: recomputed independently, the combiner is SHA3-256(ss_M || ss_X || ct_X || pk_X || +/// 5c2e2f2f5e5c), label last, no length prefixes. +#[test] +fn the_combiner_is_the_drafts_sha3_256() { + let mut h = Sha3_256::new(); + for part in [&SS_M[..], &SS_X, &CT_X, &PK_X, &[0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c]] { + h.update(part); + } + let want: [u8; 32] = h.finalize().into(); + assert_eq!(combiner(&SS_M, &SS_X, &CT_X, &PK_X), want); +} + +/// QA A-07: every label is unique, ASCII, versioned, and none is a prefix of another. +#[test] +fn labels_are_versioned_and_prefix_free() { + for (i, a) in ALL_LABELS.iter().enumerate() { + assert!(a.is_ascii() && a.starts_with(b"domi/arcanum/v1/")); + for (j, b) in ALL_LABELS.iter().enumerate() { + if i != j { + assert!(!b.starts_with(a), "{} is a prefix of {}", a.escape_ascii(), b.escape_ascii()); + } + } + } +} + +/// QA A-05: with both X-Wing secrets held fixed, every part of the transcript (both public keys, +/// both ciphertexts, the context and its length) still changes the session. This isolates the +/// key-schedule binding from what X-Wing itself hashes. +#[test] +fn the_schedule_binds_the_full_transcript() { + use crate::schedule::{Transcript, session_prk}; + use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SecretKey, SharedSecret}; + use zeroize::Zeroizing; + + let ss_ir = SharedSecret(Zeroizing::new([7u8; 32])); + let ss_ri = SharedSecret(Zeroizing::new([8u8; 32])); + 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_ir = Ciphertext::from_bytes(&[3u8; CIPHERTEXT_LEN]).unwrap(); + let ct_ri = Ciphertext::from_bytes(&[4u8; CIPHERTEXT_LEN]).unwrap(); + let prk = |i: &PublicKey, r: &PublicKey, a: &Ciphertext, b: &Ciphertext, ctx: &[u8]| { + *session_prk(&ss_ir, &ss_ri, &Transcript { initiator: i, responder: r, ct_ir: a, ct_ri: b, context: ctx }) + }; + let honest = prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctx"); + + let flip_pk = |pk: &PublicKey, n: usize| { + let mut b = *pk.as_bytes(); + b[n] ^= 0x01; + PublicKey::from_bytes(&b).ok() + }; + let flip_ct = |ct: &Ciphertext, n: usize| { + let mut b = *ct.as_bytes(); + b[n] ^= 0x01; + Ciphertext::from_bytes(&b).unwrap() + }; + let mut checked = 0; + for n in (0..PUBLIC_KEY_LEN).step_by(37).chain([0, 1183, 1184, PUBLIC_KEY_LEN - 1]) { + if let Some(p) = flip_pk(&pk_i, n) { + assert_ne!(prk(&p, &pk_r, &ct_ir, &ct_ri, b"ctx"), honest, "pk_I[{n}]"); + checked += 1; + } + if let Some(p) = flip_pk(&pk_r, n) { + assert_ne!(prk(&pk_i, &p, &ct_ir, &ct_ri, b"ctx"), honest, "pk_R[{n}]"); + checked += 1; + } + } + assert!(checked > 20, "the sampled public-key flips must mostly parse"); + for n in (0..CIPHERTEXT_LEN).step_by(37).chain([0, 1087, 1088, CIPHERTEXT_LEN - 1]) { + assert_ne!(prk(&pk_i, &pk_r, &flip_ct(&ct_ir, n), &ct_ri, b"ctx"), honest, "ct_IR[{n}]"); + assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &flip_ct(&ct_ri, n), b"ctx"), honest, "ct_RI[{n}]"); + } + assert_ne!(prk(&pk_r, &pk_i, &ct_ir, &ct_ri, b"ctx"), honest, "roles swapped"); + assert_ne!(prk(&pk_i, &pk_r, &ct_ri, &ct_ir, b"ctx"), honest, "ciphertexts swapped"); + assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctX"), honest, "context"); + assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctx\0"), honest, "context length"); } diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..f0f258c --- /dev/null +++ b/src/error.rs @@ -0,0 +1,83 @@ +//! Typed errors. No variant carries secret material, so an error can always be logged. + +use core::fmt; + +/// Which input was malformed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Input { + /// A hybrid public key (`pk_M || pk_X`). + PublicKey, + /// A hybrid secret key (the 32-byte seed). + SecretKey, + /// A hybrid ciphertext (`ct_M || ct_X`). + Ciphertext, + /// A sealed box. + SealedBox, +} + +impl fmt::Display for Input { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Input::PublicKey => "public key", + Input::SecretKey => "secret key", + Input::Ciphertext => "ciphertext", + Input::SealedBox => "sealed box", + }) + } +} + +/// Everything that can go wrong in Arcanum. Every parser returns one of these; none panics. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Error { + /// The input has a fixed length and this is not it. + InvalidLength { + /// What was being parsed. + input: Input, + /// The required length in bytes. + expected: usize, + /// The length that was given. + actual: usize, + }, + /// The input is shorter than the smallest valid value. + TooShort { + /// What was being parsed. + input: Input, + /// The minimum length in bytes. + minimum: usize, + /// The length that was given. + actual: usize, + }, + /// The ML-KEM-768 part of a public key fails the FIPS 203 §7.2 encapsulation key check. + InvalidPublicKey, + /// An X25519 value is a low-order point, so the classical half would contribute nothing. + NonContributory, + /// A sealed box was made by a format version this build does not know. + UnsupportedVersion(u8), + /// A sealed box failed authentication: wrong key, wrong associated data, or tampered. + DecryptionFailed, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::InvalidLength { input, expected, actual } => { + write!(f, "{input} has the wrong length: expected {expected} bytes, got {actual}") + } + Error::TooShort { input, minimum, actual } => { + write!(f, "{input} is too short: at least {minimum} bytes, got {actual}") + } + Error::InvalidPublicKey => f.write_str("public key fails the ML-KEM-768 encapsulation key check"), + Error::NonContributory => f.write_str("X25519 value is a low-order point"), + Error::UnsupportedVersion(v) => write!(f, "sealed box version {v} is not supported"), + Error::DecryptionFailed => f.write_str("sealed box could not be opened"), + } + } +} + +impl core::error::Error for Error {} + +pub(crate) fn exact(input: Input, bytes: &[u8]) -> Result<&[u8; N], Error> { + bytes.try_into().map_err(|_| Error::InvalidLength { input, expected: N, actual: bytes.len() }) +} diff --git a/src/exchange.rs b/src/exchange.rs new file mode 100644 index 0000000..5cbd20a --- /dev/null +++ b/src/exchange.rs @@ -0,0 +1,204 @@ +//! A mutual exchange between two peers, and the WireGuard PSK it yields per epoch. +//! +//! Each peer has a hybrid key pair, and each knows the other's public key (authenticated by the +//! caller; for Via, signed with the device's Tessera key). The exchange runs both directions: +//! +//! ```text +//! initiator I responder R +//! (ct_IR, ss_IR) = Encaps(pk_R) ct_IR -> ss_IR = Decaps(sk_R, ct_IR) +//! (ct_RI, ss_RI) = Encaps(pk_I) +//! ss_RI = Decaps(sk_I, ct_RI) <- ct_RI +//! ``` +//! +//! The session is derived from **both** secrets and the whole transcript, so a peer that cannot +//! decapsulate the other direction cannot compute it. A single encapsulation would authenticate +//! only the receiver: anyone who knows `pk_R` can encapsulate to it, so once a quantum computer +//! breaks WireGuard's static X25519 keys, an attacker could impersonate the initiator and choose +//! the responder's PSK (QA finding A-15). Rosenpass is mutual for the same reason. +//! +//! **Forward secrecy between epochs needs one exchange per epoch** (Rosenpass rotates every +//! 120 s), and forward secrecy against a later theft of a static key needs the key pairs to be +//! ephemeral, or an ephemeral exchange added on top (Day 3). + +use alloc::vec::Vec; +use core::fmt; + +use rand_core::CryptoRng; +use zeroize::{ZeroizeOnDrop, Zeroizing}; + +use crate::error::Error; +use crate::schedule::{LABEL_WIREGUARD_PSK, Prk, Transcript, expand, session_prk}; +use crate::xwing::{Ciphertext, ENCAPSULATION_SEED_LEN, PublicKey, SecretKey, SharedSecret}; + +/// Length of a WireGuard pre-shared key. +pub const WIREGUARD_PSK_LEN: usize = 32; + +/// The keys both peers hold after one exchange. Zeroised on drop; never printed. +pub struct Session { + prk: Prk, +} + +impl Session { + /// The WireGuard pre-shared key for `epoch` (see [`crate::epoch_at`]). Deterministic: both + /// peers get the same key for the same epoch, and different epochs give different keys. + #[must_use] + pub fn wireguard_psk(&self, epoch: u64) -> WireGuardPsk { + WireGuardPsk(expand(&self.prk, &[LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()])) + } +} + +impl fmt::Debug for Session { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Session([redacted])") + } +} + +impl ZeroizeOnDrop for Session {} + +/// A 32-byte WireGuard pre-shared key. Zeroised on drop; never printed. +pub struct WireGuardPsk(Zeroizing<[u8; WIREGUARD_PSK_LEN]>); + +impl WireGuardPsk { + /// The raw key, to hand to WireGuard (`wg set ... preshared-key`). + #[must_use] + pub fn as_bytes(&self) -> &[u8; WIREGUARD_PSK_LEN] { + &self.0 + } +} + +impl fmt::Debug for WireGuardPsk { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("WireGuardPsk([redacted])") + } +} + +impl ZeroizeOnDrop for WireGuardPsk {} + +/// The initiator's state between sending its ciphertext and receiving the responder's. +/// Holds the first-direction secret; zeroised on drop. +pub struct Initiation<'a> { + me: &'a SecretKey, + peer: PublicKey, + ct_ir: Ciphertext, + ss_ir: SharedSecret, + context: Zeroizing>, +} + +impl fmt::Debug for Initiation<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Initiation([redacted])") + } +} + +impl Initiation<'_> { + /// The ciphertext to send to the responder. + #[must_use] + pub fn ciphertext(&self) -> &Ciphertext { + &self.ct_ir + } + + /// Finish with the responder's ciphertext. + /// + /// # Errors + /// [`Error::NonContributory`] if its X25519 part is a low-order point. A tampered ML-KEM part + /// is not reported; it yields a session that does not match the responder's, and the + /// WireGuard handshake then fails. + pub fn finish(self, ct_ri: &Ciphertext) -> Result { + let ss_ri = self.me.decapsulate(ct_ri)?; + let t = Transcript { + initiator: self.me.public_key(), + responder: &self.peer, + ct_ir: &self.ct_ir, + ct_ri, + context: &self.context, + }; + Ok(Session { prk: session_prk(&self.ss_ir, &ss_ri, &t) }) + } +} + +/// Start an exchange as the initiator: encapsulate to the responder and keep the state. +/// +/// # Errors +/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point. +pub fn initiate<'a, R: CryptoRng + ?Sized>( + me: &'a SecretKey, + responder: &PublicKey, + context: &[u8], + rng: &mut R, +) -> Result, Error> { + let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]); + rng.fill_bytes(eseed.as_mut_slice()); + initiate_inner(me, responder, context, &eseed) +} + +/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back, +/// and return the ciphertext to send together with the finished session. +/// +/// # Errors +/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519 +/// part. +pub fn respond( + me: &SecretKey, + initiator: &PublicKey, + ct_ir: &Ciphertext, + context: &[u8], + rng: &mut R, +) -> Result<(Ciphertext, Session), Error> { + let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]); + rng.fill_bytes(eseed.as_mut_slice()); + respond_inner(me, initiator, ct_ir, context, &eseed) +} + +/// [`initiate`] with explicit randomness. **Hazmat** (feature `hazmat`), for known-answer tests: +/// reusing an `eseed` reuses the secret. +/// +/// # Errors +/// As [`initiate`]. +#[cfg(feature = "hazmat")] +pub fn initiate_derand<'a>( + me: &'a SecretKey, + responder: &PublicKey, + context: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result, Error> { + initiate_inner(me, responder, context, eseed) +} + +/// [`respond`] with explicit randomness. **Hazmat** (feature `hazmat`), for known-answer tests. +/// +/// # Errors +/// As [`respond`]. +#[cfg(feature = "hazmat")] +pub fn respond_derand( + me: &SecretKey, + initiator: &PublicKey, + ct_ir: &Ciphertext, + context: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result<(Ciphertext, Session), Error> { + respond_inner(me, initiator, ct_ir, context, eseed) +} + +fn initiate_inner<'a>( + me: &'a SecretKey, + responder: &PublicKey, + context: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result, Error> { + let (ct_ir, ss_ir) = responder.encapsulate_inner(eseed)?; + Ok(Initiation { me, peer: responder.clone(), ct_ir, ss_ir, context: Zeroizing::new(context.to_vec()) }) +} + +fn respond_inner( + me: &SecretKey, + initiator: &PublicKey, + ct_ir: &Ciphertext, + context: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result<(Ciphertext, Session), Error> { + let ss_ir = me.decapsulate(ct_ir)?; + let (ct_ri, ss_ri) = initiator.encapsulate_inner(eseed)?; + let t = Transcript { initiator, responder: me.public_key(), ct_ir, ct_ri: &ct_ri, context }; + let session = Session { prk: session_prk(&ss_ir, &ss_ri, &t) }; + Ok((ct_ri, session)) +} diff --git a/src/lib.rs b/src/lib.rs index 8b13789..e1a8651 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,43 @@ +//! # Arcanum +//! +//! The post-quantum crypto core of the Domi ecosystem. **Not audited.** +//! +//! - [`xwing`]: the hybrid KEM ML-KEM-768 + X25519 (X-Wing, draft-connolly-cfrg-xwing-kem-11). +//! - [`exchange`]: a mutual exchange between two peers (each encapsulates to the other), bound to +//! the full transcript and a context, and the WireGuard pre-shared key it yields per epoch. +//! - [`seal`]: a one-shot sealed box to a recipient's hybrid public key. +//! +//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `sha3`, `shake`, +//! `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters. +//! Design, sources and risks: `docs/01_arcanum.md` and `docs/THREAT_MODEL.md`. +//! +//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points used by +//! the known-answer tests. It is off by default and must never be enabled in a release build. +#![no_std] +#![forbid(unsafe_code)] +#![deny(missing_docs)] +extern crate alloc; + +mod error; +pub mod exchange; +mod schedule; +pub mod seal; +pub mod xwing; + +#[cfg(test)] +mod binding_tests; + +pub use error::{Error, Input}; +pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk}; + +/// The recommended rotation interval in seconds. Rosenpass's responder rekeys every 120 s +/// (`REKEY_AFTER_TIME_RESPONDER`), following WireGuard's own two-minute rekey. +pub const RECOMMENDED_EPOCH_SECONDS: u64 = 120; + +/// The epoch number at `unix_seconds`, for [`Session::wireguard_psk`]. Arcanum has no clock; the +/// caller passes the time. +#[must_use] +pub const fn epoch_at(unix_seconds: u64) -> u64 { + unix_seconds / RECOMMENDED_EPOCH_SECONDS +} diff --git a/src/schedule.rs b/src/schedule.rs new file mode 100644 index 0000000..9c04331 --- /dev/null +++ b/src/schedule.rs @@ -0,0 +1,113 @@ +//! The key schedule: HKDF-SHA-256 (RFC 5869) with versioned `domi/arcanum/v1/...` labels. +//! +//! X-Wing is used exactly as specified; its combiner binds `ct_X` and `pk_X` and leaves `ct_M` and +//! `pk_M` to ML-KEM. The roadmap's decided combiner binds both public keys and both ciphertexts, +//! so that is done here, in Arcanum's own derivation (QA decision D-QA-1(a)): +//! +//! ```text +//! exchange: th = SHA-256("domi/arcanum/v1/transcript/exchange" +//! || pk_I || pk_R || ct_IR || ct_RI || u64be(len ctx) || ctx) +//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss_IR || ss_RI || th) +//! seal: th = SHA-256("domi/arcanum/v1/transcript/seal" || pk || ct || u64be(len aad) || aad) +//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th) +//! keys: okm = HKDF-Expand(prk, label || fixed-width fields) +//! ``` +//! +//! Every hashed field before the context is fixed-width and the context is length-prefixed, so +//! the encoding is injective. Roles are bound by position. A v2 schedule gets new labels; these +//! are never reused. + +use hkdf::{Hkdf, HkdfExtract}; +use sha2::{Digest, Sha256}; +use zeroize::{Zeroize, Zeroizing}; + +use crate::xwing::{Ciphertext, PublicKey, SharedSecret}; + +pub(crate) const LABEL_TRANSCRIPT_EXCHANGE: &[u8] = b"domi/arcanum/v1/transcript/exchange"; +pub(crate) const LABEL_TRANSCRIPT_SEAL: &[u8] = b"domi/arcanum/v1/transcript/seal"; +pub(crate) const LABEL_EXTRACT: &[u8] = b"domi/arcanum/v1/extract"; +pub(crate) const LABEL_WIREGUARD_PSK: &[u8] = b"domi/arcanum/v1/wireguard-psk"; +pub(crate) const LABEL_SEAL_KEY: &[u8] = b"domi/arcanum/v1/seal/key"; +pub(crate) const LABEL_SEAL_NONCE: &[u8] = b"domi/arcanum/v1/seal/nonce"; + +/// Every label, for the prefix-freeness test. +#[cfg(test)] +pub(crate) const ALL_LABELS: [&[u8]; 6] = [ + LABEL_TRANSCRIPT_EXCHANGE, + LABEL_TRANSCRIPT_SEAL, + LABEL_EXTRACT, + LABEL_WIREGUARD_PSK, + LABEL_SEAL_KEY, + LABEL_SEAL_NONCE, +]; + +/// Pseudo-random key of one exchange or one seal. +pub(crate) type Prk = Zeroizing<[u8; 32]>; + +/// The transcript of one mutual exchange, in role order. +pub(crate) struct Transcript<'a> { + pub(crate) initiator: &'a PublicKey, + pub(crate) responder: &'a PublicKey, + pub(crate) ct_ir: &'a Ciphertext, + pub(crate) ct_ri: &'a Ciphertext, + pub(crate) context: &'a [u8], +} + +impl Transcript<'_> { + fn hash(&self) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(LABEL_TRANSCRIPT_EXCHANGE); + h.update(self.initiator.as_bytes()); + h.update(self.responder.as_bytes()); + h.update(self.ct_ir.as_bytes()); + h.update(self.ct_ri.as_bytes()); + h.update((self.context.len() as u64).to_be_bytes()); + h.update(self.context); + h.finalize().into() + } +} + +fn extract(secrets: &[&[u8; 32]], th: &[u8; 32]) -> Prk { + let mut ext = HkdfExtract::::new(Some(LABEL_EXTRACT)); + for s in secrets { + ext.input_ikm(s.as_slice()); + } + ext.input_ikm(th); + let (mut prk, _) = ext.finalize(); + let mut out = Zeroizing::new([0u8; 32]); + out.copy_from_slice(prk.as_slice()); + prk.as_mut_slice().zeroize(); + out +} + +/// The PRK of a mutual exchange: both directions' X-Wing secrets and the whole transcript. +pub(crate) fn session_prk(ss_ir: &SharedSecret, ss_ri: &SharedSecret, t: &Transcript<'_>) -> Prk { + extract(&[ss_ir.as_bytes(), ss_ri.as_bytes()], &t.hash()) +} + +/// The same derivation on raw component values, for the in-crate binding tests. +#[cfg(test)] +pub(crate) fn session_prk_raw(ss_ir: &[u8; 32], ss_ri: &[u8; 32], th: &[u8; 32]) -> Prk { + extract(&[ss_ir, ss_ri], th) +} + +/// The PRK of one sealed box: the X-Wing secret, the recipient key, the ciphertext and the aad. +pub(crate) fn seal_prk(ss: &SharedSecret, recipient: &PublicKey, ct: &Ciphertext, aad: &[u8]) -> Prk { + let mut h = Sha256::new(); + h.update(LABEL_TRANSCRIPT_SEAL); + h.update(recipient.as_bytes()); + h.update(ct.as_bytes()); + h.update((aad.len() as u64).to_be_bytes()); + h.update(aad); + let th: [u8; 32] = h.finalize().into(); + extract(&[ss.as_bytes()], &th) +} + +/// HKDF-Expand to `N` bytes with the info parts concatenated. +pub(crate) fn expand(prk: &Prk, info: &[&[u8]]) -> Zeroizing<[u8; N]> { + // Infallible: a 32-byte PRK is the SHA-256 output size, and N <= 32 is far below 255 * 32. + let hk = Hkdf::::from_prk(prk.as_slice()).expect("PRK is 32 bytes"); + let mut out = Zeroizing::new([0u8; N]); + hk.expand_multi_info(info, out.as_mut_slice()).expect("N is at most 255 * 32"); + out +} diff --git a/src/seal.rs b/src/seal.rs new file mode 100644 index 0000000..a8d413c --- /dev/null +++ b/src/seal.rs @@ -0,0 +1,121 @@ +//! One-shot sealed box to a recipient's hybrid public key, for Custos sealing and Tabellarius. +//! +//! ```text +//! sealed = 0x01 || ct (1120 B) || ChaCha20-Poly1305(key, nonce, plaintext, aad = 0x01) || tag +//! th = SHA-256("domi/arcanum/v1/transcript/seal" || pk || ct || u64be(len aad) || aad) +//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th) +//! key = HKDF-Expand(prk, "domi/arcanum/v1/seal/key", 32) +//! nonce = HKDF-Expand(prk, "domi/arcanum/v1/seal/nonce", 12) +//! ``` +//! +//! Every seal runs a fresh encapsulation, so a key and nonce pair is never used twice. +//! +//! **Anyone who knows the recipient's public key can seal.** There is no sender authentication, +//! and ChaCha20-Poly1305 is not key-committing: a successful [`open`] says nothing about who +//! sealed. This is a documented construction, not HPKE (RFC 9180). + +use alloc::vec::Vec; + +use chacha20poly1305::aead::AeadInOut; +use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce}; +use rand_core::CryptoRng; +use zeroize::Zeroizing; + +use crate::error::{Error, Input}; +use crate::schedule::{LABEL_SEAL_KEY, LABEL_SEAL_NONCE, Prk, expand, seal_prk}; +use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, ENCAPSULATION_SEED_LEN, PublicKey, SecretKey}; + +/// The format version written as the first byte. +pub const VERSION: u8 = 1; +const TAG_LEN: usize = 16; +const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN; +/// Bytes a sealed box adds to the plaintext: version, ciphertext and the Poly1305 tag. +pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN; + +fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) { + let key = expand::<32>(prk, &[LABEL_SEAL_KEY]); + let nonce = expand::<12>(prk, &[LABEL_SEAL_NONCE]); + // Infallible: the key is exactly 32 bytes. + let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key"); + (aead, Nonce::from(*nonce)) +} + +/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again +/// to open). +/// +/// # Errors +/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point. +pub fn seal( + recipient: &PublicKey, + plaintext: &[u8], + aad: &[u8], + rng: &mut R, +) -> Result, Error> { + let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]); + rng.fill_bytes(eseed.as_mut_slice()); + seal_inner(recipient, plaintext, aad, &eseed) +} + +/// [`seal`] with explicit randomness. **Hazmat** (feature `hazmat`), for tests: reusing an +/// `eseed` reuses key and nonce. +/// +/// # Errors +/// As [`seal`]. +#[cfg(feature = "hazmat")] +pub fn seal_derand( + recipient: &PublicKey, + plaintext: &[u8], + aad: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result, Error> { + seal_inner(recipient, plaintext, aad, eseed) +} + +fn seal_inner( + recipient: &PublicKey, + plaintext: &[u8], + aad: &[u8], + eseed: &[u8; ENCAPSULATION_SEED_LEN], +) -> Result, Error> { + let (ct, ss) = recipient.encapsulate_inner(eseed)?; + let (aead, nonce) = cipher(&seal_prk(&ss, recipient, &ct, aad)); + + // Allocated once at its final size, so no buffer that held plaintext is ever reallocated. + let mut out = Vec::with_capacity(plaintext.len() + OVERHEAD); + out.push(VERSION); + out.extend_from_slice(ct.as_bytes()); + out.extend_from_slice(plaintext); + // ChaCha20-Poly1305 refuses only messages over 2^38 bytes; that is reported, not a panic. + let tag = aead + .encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into()) + .map_err(|_| Error::DecryptionFailed)?; + out.extend_from_slice(tag.as_slice()); + Ok(out) +} + +/// Open a sealed box with the recipient's secret key and the same `aad`. +/// +/// # Errors +/// [`Error::TooShort`], [`Error::UnsupportedVersion`], [`Error::NonContributory`], or +/// [`Error::DecryptionFailed`] for a wrong key, wrong `aad`, or any tampering. +pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result>, Error> { + if sealed.len() < OVERHEAD { + return Err(Error::TooShort { input: Input::SealedBox, minimum: OVERHEAD, actual: sealed.len() }); + } + let (header, rest) = sealed.split_at(HEADER_LEN); + let (&version, ct) = header.split_first().ok_or(Error::DecryptionFailed)?; + if version != VERSION { + return Err(Error::UnsupportedVersion(version)); + } + let ct = Ciphertext::from_bytes(ct)?; + let ss = recipient.decapsulate(&ct)?; + let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad)); + + let (body, tag) = rest.split_at(rest.len() - TAG_LEN); + let tag = chacha20poly1305::Tag::try_from(tag).map_err(|_| Error::DecryptionFailed)?; + // The tag is checked before anything is decrypted; on failure the buffer holds only ciphertext. + let mut plaintext = Zeroizing::new(body.to_vec()); + aead.decrypt_inout_detached(&nonce, &[VERSION], plaintext.as_mut_slice().into(), &tag) + .map_err(|_| Error::DecryptionFailed)?; + Ok(plaintext) +} diff --git a/src/xwing.rs b/src/xwing.rs new file mode 100644 index 0000000..482f054 --- /dev/null +++ b/src/xwing.rs @@ -0,0 +1,304 @@ +//! X-Wing: the hybrid KEM ML-KEM-768 + X25519, as specified in draft-connolly-cfrg-xwing-kem-11. +//! +//! This module is glue between vetted primitives: ML-KEM-768 from `ml-kem` (FIPS 203), X25519 from +//! `x25519-dalek` (RFC 7748), SHAKE256 from `shake` and SHA3-256 from `sha3` (FIPS 202). It is pinned +//! by the draft's three test vectors and a differential test against RustCrypto's `x-wing` crate. +//! +//! One deliberate difference from the draft: a low-order X25519 public key or ciphertext part is +//! refused with [`Error::NonContributory`]. Honest keys and ciphertexts are never low-order, so no +//! honest exchange and no official vector is affected (docs/01_arcanum.md). + +use core::{array, fmt}; + +use ml_kem::array::Array; +use ml_kem::{B32, Decapsulate, KeyExport, MlKem768, Seed}; +use rand_core::CryptoRng; +use sha3::{Digest, Sha3_256}; +use shake::{ExtendableOutput, Shake256, Update, XofReader}; +use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; + +use crate::error::{Error, Input, exact}; + +type MlKemEncapsulationKey = ml_kem::EncapsulationKey; +type MlKemDecapsulationKey = ml_kem::DecapsulationKey; + +/// Length of a hybrid public key: ML-KEM-768 encapsulation key (1184) + X25519 public key (32). +pub const PUBLIC_KEY_LEN: usize = 1216; +/// Length of a hybrid secret key: a 32-byte seed, expanded with SHAKE256. +pub const SECRET_KEY_LEN: usize = 32; +/// Length of a hybrid ciphertext: ML-KEM-768 ciphertext (1088) + X25519 ephemeral public key (32). +pub const CIPHERTEXT_LEN: usize = 1120; +/// Length of the X-Wing shared secret. +pub const SHARED_SECRET_LEN: usize = 32; +/// Length of the encapsulation randomness: 32 bytes for ML-KEM, 32 for the X25519 ephemeral key. +pub const ENCAPSULATION_SEED_LEN: usize = 64; + +const ML_KEM_PUBLIC_KEY_LEN: usize = 1184; +const ML_KEM_CIPHERTEXT_LEN: usize = 1088; + +/// The X-Wing label, ASCII `\.//^\` (hex 5c2e2f2f5e5c), draft -11 §5.3. +const XWING_LABEL: &[u8; 6] = br"\.//^\"; + +/// X-Wing Combiner (draft -11 §5.3): SHA3-256(ss_M || ss_X || ct_X || pk_X || XWingLabel). +pub(crate) fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x: &[u8; 32]) -> [u8; SHARED_SECRET_LEN] { + let mut h = Sha3_256::new(); + Digest::update(&mut h, ss_m); + Digest::update(&mut h, ss_x); + Digest::update(&mut h, ct_x); + Digest::update(&mut h, pk_x); + Digest::update(&mut h, XWING_LABEL); + h.finalize().into() +} + +/// The X-Wing shared secret. Zeroised on drop; never printed. +pub struct SharedSecret(pub(crate) Zeroizing<[u8; SHARED_SECRET_LEN]>); + +impl SharedSecret { + /// The raw 32 bytes, for interoperating with other X-Wing users. Prefer [`crate::exchange`], + /// which binds the secret to the transcript and a context. + #[must_use] + pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] { + &self.0 + } +} + +impl fmt::Debug for SharedSecret { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SharedSecret([redacted])") + } +} + +impl ZeroizeOnDrop for SharedSecret {} + +/// A hybrid public key (`pk_M || pk_X`), validated on parse. +#[derive(Clone)] +pub struct PublicKey { + bytes: [u8; PUBLIC_KEY_LEN], + pk_m: MlKemEncapsulationKey, + pk_x: X25519Public, +} + +impl PublicKey { + /// Parse a hybrid public key received from somewhere else. + /// + /// # Errors + /// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM + /// part fails the FIPS 203 §7.2 encapsulation key check. + pub fn from_bytes(bytes: &[u8]) -> Result { + let bytes: &[u8; PUBLIC_KEY_LEN] = exact(Input::PublicKey, bytes)?; + let m: [u8; ML_KEM_PUBLIC_KEY_LEN] = array::from_fn(|i| bytes[i]); + let pk_m = MlKemEncapsulationKey::new(&Array::from(m)).map_err(|_| Error::InvalidPublicKey)?; + let x: [u8; 32] = array::from_fn(|i| bytes[ML_KEM_PUBLIC_KEY_LEN + i]); + Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) }) + } + + /// The 1216-byte encoding. + #[must_use] + pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_LEN] { + &self.bytes + } + + /// Encapsulate a fresh shared secret to this key. + /// + /// # Errors + /// [`Error::NonContributory`] if the X25519 part of the key is a low-order point. + pub fn encapsulate(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret), Error> { + let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]); + rng.fill_bytes(eseed.as_mut_slice()); + self.encapsulate_inner(&eseed) + } + + /// X-Wing `EncapsulateDerand` (draft -11 §5.4.1): the randomness is given explicitly. + /// + /// **Hazmat** (feature `hazmat`). For known-answer tests. Using the same `eseed` twice gives + /// the same secret to anyone who sees both ciphertexts. Use [`PublicKey::encapsulate`]. + /// + /// # Errors + /// [`Error::NonContributory`] if the X25519 part of the key is a low-order point. + #[cfg(feature = "hazmat")] + pub fn encapsulate_derand( + &self, + eseed: &[u8; ENCAPSULATION_SEED_LEN], + ) -> Result<(Ciphertext, SharedSecret), Error> { + self.encapsulate_inner(eseed) + } + + pub(crate) fn encapsulate_inner( + &self, + eseed: &[u8; ENCAPSULATION_SEED_LEN], + ) -> Result<(Ciphertext, SharedSecret), Error> { + let mut m = B32::from(array::from_fn::(|i| eseed[i])); + let (ct_m, mut ss_m) = self.pk_m.encapsulate_deterministic(&m); + m.as_mut_slice().zeroize(); + + let ek_x: Zeroizing<[u8; 32]> = Zeroizing::new(array::from_fn(|i| eseed[32 + i])); + let ek_x = StaticSecret::from(*ek_x); + let ct_x = X25519Public::from(&ek_x); + let ss_x = ek_x.diffie_hellman(&self.pk_x); + drop(ek_x); + + let result = if ss_x.was_contributory() { + let ss_m_arr = as32(&ss_m); + Ok(combiner(&ss_m_arr, ss_x.as_bytes(), ct_x.as_bytes(), self.pk_x.as_bytes())) + } else { + Err(Error::NonContributory) + }; + ss_m.as_mut_slice().zeroize(); + let ss = result?; + + let mut ct = [0u8; CIPHERTEXT_LEN]; + ct[..ML_KEM_CIPHERTEXT_LEN].copy_from_slice(ct_m.as_slice()); + ct[ML_KEM_CIPHERTEXT_LEN..].copy_from_slice(ct_x.as_bytes()); + Ok((Ciphertext(ct), SharedSecret(Zeroizing::new(ss)))) + } +} + +impl PartialEq for PublicKey { + fn eq(&self, other: &Self) -> bool { + self.bytes == other.bytes + } +} + +impl Eq for PublicKey {} + +impl fmt::Debug for PublicKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PublicKey").field("len", &PUBLIC_KEY_LEN).finish_non_exhaustive() + } +} + +/// A hybrid ciphertext (`ct_M || ct_X`). Any 1120 bytes parse; a tampered ML-KEM part is handled +/// by implicit rejection, a low-order X25519 part is refused at decapsulation. +#[derive(Clone, PartialEq, Eq)] +pub struct Ciphertext([u8; CIPHERTEXT_LEN]); + +impl Ciphertext { + /// Parse a ciphertext. + /// + /// # Errors + /// [`Error::InvalidLength`] if it is not 1120 bytes. + pub fn from_bytes(bytes: &[u8]) -> Result { + exact(Input::Ciphertext, bytes).map(|b| Self(*b)) + } + + /// The 1120-byte encoding. + #[must_use] + pub fn as_bytes(&self) -> &[u8; CIPHERTEXT_LEN] { + &self.0 + } +} + +impl fmt::Debug for Ciphertext { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Ciphertext").field("len", &CIPHERTEXT_LEN).finish_non_exhaustive() + } +} + +/// A hybrid secret key. Stored as its 32-byte seed plus the expanded keys; all zeroised on drop. +pub struct SecretKey { + seed: Zeroizing<[u8; SECRET_KEY_LEN]>, + dk_m: MlKemDecapsulationKey, + sk_x: StaticSecret, + public: PublicKey, +} + +impl SecretKey { + /// Generate a new key pair from the caller's RNG. + pub fn generate(rng: &mut R) -> Self { + let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]); + rng.fill_bytes(seed.as_mut_slice()); + Self::expand(seed) + } + + /// X-Wing `GenerateKeyPairDerand` (draft -11 §5.2.1): the key from a given 32-byte seed. + /// **Hazmat** (feature `hazmat`), for tests: the caller's copy of `seed` is not wiped. Real + /// code uses [`SecretKey::generate`], or [`SecretKey::from_bytes`] on a buffer it zeroises. + #[cfg(feature = "hazmat")] + #[must_use] + pub fn from_seed(seed: [u8; SECRET_KEY_LEN]) -> Self { + Self::expand(Zeroizing::new(seed)) + } + + /// Parse a stored secret key (its 32-byte seed). + /// + /// # Errors + /// [`Error::InvalidLength`] if it is not 32 bytes. Every 32-byte value is a valid key. + pub fn from_bytes(bytes: &[u8]) -> Result { + let seed: &[u8; SECRET_KEY_LEN] = exact(Input::SecretKey, bytes)?; + Ok(Self::expand(Zeroizing::new(*seed))) + } + + /// The 32-byte seed, for storing in Custos or Tessera. Handle with care. + #[must_use] + pub fn to_seed(&self) -> Zeroizing<[u8; SECRET_KEY_LEN]> { + Zeroizing::new(*self.seed) + } + + /// The matching public key. + #[must_use] + pub fn public_key(&self) -> &PublicKey { + &self.public + } + + /// X-Wing `Decapsulate` (draft -11 §5.5). + /// + /// # Errors + /// [`Error::NonContributory`] if the X25519 part of the ciphertext is a low-order point. A + /// tampered ML-KEM part is not an error: ML-KEM's implicit rejection returns an unrelated secret. + pub fn decapsulate(&self, ct: &Ciphertext) -> Result { + let ct_x: [u8; 32] = array::from_fn(|i| ct.0[ML_KEM_CIPHERTEXT_LEN + i]); + let ss_x = self.sk_x.diffie_hellman(&X25519Public::from(ct_x)); + if !ss_x.was_contributory() { + return Err(Error::NonContributory); + } + let ct_m: [u8; ML_KEM_CIPHERTEXT_LEN] = array::from_fn(|i| ct.0[i]); + let mut ss_m = self.dk_m.decapsulate(&Array::from(ct_m)); + let ss_m_arr = as32(&ss_m); + let ss = combiner(&ss_m_arr, ss_x.as_bytes(), &ct_x, self.public.pk_x.as_bytes()); + ss_m.as_mut_slice().zeroize(); + Ok(SharedSecret(Zeroizing::new(ss))) + } + + /// `expandDecapsulationKey` (draft -11 §5.2): SHAKE256(seed) -> d || z || sk_X. + fn expand(seed: Zeroizing<[u8; SECRET_KEY_LEN]>) -> Self { + let mut expanded = Zeroizing::new([0u8; 96]); + let mut xof = Shake256::default(); + Update::update(&mut xof, seed.as_slice()); + xof.finalize_xof().read(expanded.as_mut_slice()); + + let mut ml_seed = Seed::default(); + ml_seed.as_mut_slice().copy_from_slice(&expanded[..64]); + let dk_m = MlKemDecapsulationKey::from_seed(ml_seed); + ml_seed.as_mut_slice().zeroize(); + + let mut sk_x_bytes = Zeroizing::new([0u8; 32]); + sk_x_bytes.copy_from_slice(&expanded[64..]); + let sk_x = StaticSecret::from(*sk_x_bytes); + let pk_x = X25519Public::from(&sk_x); + + let pk_m = dk_m.encapsulation_key().clone(); + let mut bytes = [0u8; PUBLIC_KEY_LEN]; + bytes[..ML_KEM_PUBLIC_KEY_LEN].copy_from_slice(pk_m.to_bytes().as_slice()); + bytes[ML_KEM_PUBLIC_KEY_LEN..].copy_from_slice(pk_x.as_bytes()); + + Self { seed, dk_m, sk_x, public: PublicKey { bytes, pk_m, pk_x } } + } +} + +impl fmt::Debug for SecretKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("SecretKey([redacted])") + } +} + +// `seed` is `Zeroizing`, and `ml-kem`'s and `x25519-dalek`'s key types wipe themselves on drop +// (their `zeroize` features are enabled in Cargo.toml). +impl ZeroizeOnDrop for SecretKey {} + +/// Copy a 32-byte ML-KEM shared key into a stack array that is wiped on drop. +fn as32(k: &ml_kem::SharedKey) -> Zeroizing<[u8; 32]> { + let mut out = Zeroizing::new([0u8; 32]); + out.copy_from_slice(k.as_slice()); + out +} diff --git a/tests/binding.rs b/tests/binding.rs index 390779e..04c7279 100644 --- a/tests/binding.rs +++ b/tests/binding.rs @@ -1,14 +1,17 @@ //! Mandatory test 3, through the public API: an attacker can force the X25519 half to zero by -//! sending a low-order point. Arcanum must refuse that with a typed error instead of producing a -//! secret that only one half protects. (The combiner-level half of test 3, which zeroes each -//! component directly, is `src/binding_tests.rs`.) +//! sending a low-order point. Arcanum refuses that with a typed error instead of producing a +//! secret that only one half protects (QA A-16, A-17). The combiner-level half of test 3, which +//! zeroes each component directly, is `src/binding_tests.rs`. Also QA A-04 (raw ct_X is hashed). + +mod common; use arcanum::Error; use arcanum::exchange; use arcanum::xwing::{Ciphertext, PublicKey, SecretKey}; +use common::rng; -/// Curve25519 u-coordinates of small order, and non-canonical encodings of them (the list -/// libsodium rejects). X25519 of any of these with any clamped scalar is all zeros. +/// Curve25519 u-coordinates of small order and non-canonical encodings of them (libsodium's +/// blocklist). Each is also used with bit 255 set, which X25519 ignores (RFC 7748 §5). const LOW_ORDER: [&str; 7] = [ "0000000000000000000000000000000000000000000000000000000000000000", "0100000000000000000000000000000000000000000000000000000000000000", @@ -19,40 +22,80 @@ const LOW_ORDER: [&str; 7] = [ "eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", ]; -fn low_order_points() -> impl Iterator { - LOW_ORDER.iter().map(|h| hex::decode(h).unwrap().try_into().unwrap()) +fn low_order_points() -> Vec<[u8; 32]> { + LOW_ORDER + .iter() + .flat_map(|h| { + let p: [u8; 32] = hex::decode(h).unwrap().try_into().unwrap(); + let mut high = p; + high[31] |= 0x80; + [p, high] + }) + .collect() +} + +/// Guards the fixture: if a byte above were mistyped, the point would not be low order. +#[test] +fn the_fixture_points_really_are_low_order() { + let s = x25519_dalek::StaticSecret::from([0x5a; 32]); + for p in low_order_points() { + assert!(!s.diffie_hellman(&p.into()).was_contributory(), "{}", hex::encode(p)); + } } #[test] -fn low_order_x25519_ciphertext_is_refused_by_the_responder() { - let sk = SecretKey::from_seed([0x44; 32]); - let (ct, _) = exchange::initiate_derand(sk.public_key(), b"ctx", &[0x55; 64]).unwrap(); +fn low_order_x25519_ciphertext_is_refused() { + let i = SecretKey::from_seed([0x43; 32]); + let r = SecretKey::from_seed([0x44; 32]); + let init = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap(); + let (ct_ri, _) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), b"ctx", &[0x56; 64]).unwrap(); for point in low_order_points() { - let mut bad = *ct.as_bytes(); + let mut bad = *init.ciphertext().as_bytes(); bad[1088..].copy_from_slice(&point); let bad = Ciphertext::from_bytes(&bad).unwrap(); - assert_eq!(exchange::respond(&sk, &bad, b"ctx").err(), Some(Error::NonContributory)); - assert_eq!(sk.decapsulate(&bad).err(), Some(Error::NonContributory)); + assert_eq!(r.decapsulate(&bad).err(), Some(Error::NonContributory)); + let resp = exchange::respond_derand(&r, i.public_key(), &bad, b"ctx", &[0x56; 64]); + assert_eq!(resp.err(), Some(Error::NonContributory)); + + let mut bad = *ct_ri.as_bytes(); + bad[1088..].copy_from_slice(&point); + let again = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap(); + assert_eq!(again.finish(&Ciphertext::from_bytes(&bad).unwrap()).err(), Some(Error::NonContributory)); } } #[test] -fn low_order_x25519_public_key_is_refused_by_the_initiator() { - let sk = SecretKey::from_seed([0x44; 32]); +fn low_order_x25519_public_key_is_refused() { + let i = SecretKey::from_seed([0x43; 32]); + let r = SecretKey::from_seed([0x44; 32]); for point in low_order_points() { - let mut bad = *sk.public_key().as_bytes(); + let mut bad = *r.public_key().as_bytes(); bad[1184..].copy_from_slice(&point); let pk = PublicKey::from_bytes(&bad).expect("the ML-KEM part is still valid"); - assert_eq!(exchange::initiate_derand(&pk, b"ctx", &[0x55; 64]).err(), Some(Error::NonContributory)); assert_eq!(pk.encapsulate_derand(&[0x55; 64]).err(), Some(Error::NonContributory)); + assert_eq!(exchange::initiate_derand(&i, &pk, b"ctx", &[0x55; 64]).err(), Some(Error::NonContributory)); + assert_eq!(arcanum::seal::seal(&pk, b"x", b"", &mut rng(1)).err(), Some(Error::NonContributory)); } } -/// The honest exchange is not affected by the check: the same keys with honest points still agree. +/// QA A-04: X25519 ignores bit 255 of ct_X, so ct_X and ct_X ^ 0x80 give the same ss_X. The +/// output must still differ, because the combiner hashes the raw bytes. +#[test] +fn the_high_bit_of_ct_x_is_bound() { + let r = SecretKey::from_seed([0x44; 32]); + let (ct, ss) = r.public_key().encapsulate(&mut rng(4)).unwrap(); + let mut b = *ct.as_bytes(); + b[1119] ^= 0x80; + let out = r.decapsulate(&Ciphertext::from_bytes(&b).unwrap()).unwrap(); + assert_ne!(out.as_bytes(), ss.as_bytes()); +} + +/// The honest exchange is not affected by the check. #[test] fn honest_points_pass_the_check() { - let sk = SecretKey::from_seed([0x44; 32]); - let (ct, a) = exchange::initiate_derand(sk.public_key(), b"ctx", &[0x55; 64]).unwrap(); - let b = exchange::respond(&sk, &ct, b"ctx").unwrap(); - assert_eq!(a.wireguard_psk(3).as_bytes(), b.wireguard_psk(3).as_bytes()); + let i = SecretKey::from_seed([0x43; 32]); + let r = SecretKey::from_seed([0x44; 32]); + let init = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap(); + let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), b"ctx", &[0x56; 64]).unwrap(); + assert_eq!(init.finish(&ct_ri).unwrap().wireguard_psk(3).as_bytes(), rs.wireguard_psk(3).as_bytes()); } diff --git a/tests/exchange.rs b/tests/exchange.rs index 6a4647a..be16347 100644 --- a/tests/exchange.rs +++ b/tests/exchange.rs @@ -1,10 +1,10 @@ //! Mandatory test 2: both sides of a hybrid exchange derive the same secret, and changing any -//! single input byte changes it. +//! single input byte changes it. Also QA A-14 (roles bound) and A-15 (both directions needed). //! -//! The inputs of one exchange are: the responder's seed, the initiator's encapsulation seed, the -//! responder's public key (as the initiator received it), the ciphertext (as the responder -//! received it), and the context each side passes. Every byte of the public key, the ciphertext, -//! the seeds and the context is flipped in turn. +//! The exchange is mutual (each peer encapsulates to the other, docs/01_arcanum.md). Its inputs +//! are: both peers' seeds, both encapsulation seeds, both public keys (as the other side received +//! them), both ciphertexts (as the other side received them), and the context. Every byte of the +//! public keys, the ciphertexts, the seeds and the context is flipped in turn. mod common; @@ -13,133 +13,231 @@ use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, Secr use common::rng; use std::collections::HashSet; -const SEED: [u8; 32] = [0x11; 32]; -const ESEED: [u8; 64] = [0x22; 64]; +const SEED_I: [u8; 32] = [0x11; 32]; +const SEED_R: [u8; 32] = [0x12; 32]; +const ESEED_I: [u8; 64] = [0x21; 64]; +const ESEED_R: [u8; 64] = [0x22; 64]; const CONTEXT: &[u8] = b"via/test: device-a <-> device-b"; -fn honest() -> ([u8; 32], Ciphertext) { - let sk = SecretKey::from_seed(SEED); - let (ct, session) = exchange::initiate_derand(sk.public_key(), CONTEXT, &ESEED).unwrap(); - (*session.wireguard_psk(0).as_bytes(), ct) -} - fn psk(session: &Session) -> [u8; 32] { *session.wireguard_psk(0).as_bytes() } +/// The honest exchange: (PSK, ct_IR, ct_RI). +fn honest() -> ([u8; 32], Ciphertext, Ciphertext) { + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); + let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ESEED_I).unwrap(); + let ct_ir = init.ciphertext().clone(); + let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), &ct_ir, CONTEXT, &ESEED_R).unwrap(); + let is = init.finish(&ct_ri).unwrap(); + assert_eq!(psk(&is), psk(&rs)); + (psk(&rs), ct_ir, ct_ri) +} + #[test] fn both_sides_derive_the_same_secret() { - let mut r = rng(1); + let mut g = rng(1); for _ in 0..32 { - let sk = SecretKey::generate(&mut r); - let (ct, initiator) = exchange::initiate(sk.public_key(), CONTEXT, &mut r).unwrap(); - let responder = exchange::respond(&sk, &ct, CONTEXT).unwrap(); + let i = SecretKey::generate(&mut g); + let r = SecretKey::generate(&mut g); + let init = exchange::initiate(&i, r.public_key(), CONTEXT, &mut g).unwrap(); + let (ct_ri, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), CONTEXT, &mut g).unwrap(); + let is = init.finish(&ct_ri).unwrap(); for epoch in [0, 1, 7, u64::MAX] { - assert_eq!(initiator.wireguard_psk(epoch).as_bytes(), responder.wireguard_psk(epoch).as_bytes()); + assert_eq!(is.wireguard_psk(epoch).as_bytes(), rs.wireguard_psk(epoch).as_bytes()); } } } #[test] -fn both_sides_agree_after_the_public_key_and_ciphertext_go_through_bytes() { - let sk = SecretKey::from_seed(SEED); - let pk = PublicKey::from_bytes(sk.public_key().as_bytes()).unwrap(); - let (ct, initiator) = exchange::initiate_derand(&pk, CONTEXT, &ESEED).unwrap(); - let ct = Ciphertext::from_bytes(ct.as_bytes()).unwrap(); - let responder = exchange::respond(&sk, &ct, CONTEXT).unwrap(); - assert_eq!(psk(&initiator), psk(&responder)); +fn both_sides_agree_after_keys_and_ciphertexts_go_through_bytes() { + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); + let r_pk = PublicKey::from_bytes(r.public_key().as_bytes()).unwrap(); + let i_pk = PublicKey::from_bytes(i.public_key().as_bytes()).unwrap(); + let init = exchange::initiate_derand(&i, &r_pk, CONTEXT, &ESEED_I).unwrap(); + let ct_ir = Ciphertext::from_bytes(init.ciphertext().as_bytes()).unwrap(); + let (ct_ri, rs) = exchange::respond_derand(&r, &i_pk, &ct_ir, CONTEXT, &ESEED_R).unwrap(); + let ct_ri = Ciphertext::from_bytes(ct_ri.as_bytes()).unwrap(); + assert_eq!(psk(&init.finish(&ct_ri).unwrap()), psk(&rs)); } #[test] fn fresh_randomness_gives_a_fresh_secret() { - let mut r = rng(2); - let sk = SecretKey::generate(&mut r); + let mut g = rng(2); + let i = SecretKey::generate(&mut g); + let r = SecretKey::generate(&mut g); let mut seen = HashSet::new(); for _ in 0..64 { - let (_, s) = exchange::initiate(sk.public_key(), CONTEXT, &mut r).unwrap(); - assert!(seen.insert(psk(&s)), "two exchanges produced the same secret"); + let init = exchange::initiate(&i, r.public_key(), CONTEXT, &mut g).unwrap(); + let (_, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), CONTEXT, &mut g).unwrap(); + assert!(seen.insert(psk(&rs)), "two exchanges produced the same secret"); } } +/// Flip each byte of ct_IR as the responder receives it: the responder's secret changes. #[test] -fn every_ciphertext_byte_changes_the_responders_secret() { - let (honest_psk, ct) = honest(); - let sk = SecretKey::from_seed(SEED); +fn every_byte_of_the_initiators_ciphertext_changes_the_secret() { + let (honest_psk, ct_ir, _) = honest(); + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); let mut accepted = 0; - for i in 0..CIPHERTEXT_LEN { - let mut bad = *ct.as_bytes(); - bad[i] ^= 0x01; + for n in 0..CIPHERTEXT_LEN { + let mut bad = *ct_ir.as_bytes(); + bad[n] ^= 0x01; let bad = Ciphertext::from_bytes(&bad).unwrap(); // A refusal (a low-order X25519 value) is also "not the honest secret". - if let Ok(s) = exchange::respond(&sk, &bad, CONTEXT) { - assert_ne!(psk(&s), honest_psk, "ciphertext byte {i} did not change the secret"); + if let Ok((_, s)) = exchange::respond_derand(&r, i.public_key(), &bad, CONTEXT, &ESEED_R) { + assert_ne!(psk(&s), honest_psk, "ct_IR byte {n} did not change the secret"); accepted += 1; } } assert!(accepted > CIPHERTEXT_LEN - 32, "flipped ciphertexts must mostly decapsulate (implicit rejection)"); } +/// Flip each byte of ct_RI as the initiator receives it: the initiator's secret changes. #[test] -fn every_public_key_byte_changes_the_initiators_secret() { - let (honest_psk, _) = honest(); - let sk = SecretKey::from_seed(SEED); - let mut refused = 0; - for i in 0..PUBLIC_KEY_LEN { - let mut bad = *sk.public_key().as_bytes(); - bad[i] ^= 0x01; - // A flipped ML-KEM coefficient can fail the FIPS 203 modulus check: refused, not accepted. - let Ok(pk) = PublicKey::from_bytes(&bad) else { - refused += 1; - continue; - }; - match exchange::initiate_derand(&pk, CONTEXT, &ESEED) { - Ok((_, s)) => assert_ne!(psk(&s), honest_psk, "public key byte {i} did not change the secret"), - Err(_) => refused += 1, +fn every_byte_of_the_responders_ciphertext_changes_the_secret() { + let (honest_psk, _, ct_ri) = honest(); + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); + let mut accepted = 0; + for n in 0..CIPHERTEXT_LEN { + let mut bad = *ct_ri.as_bytes(); + bad[n] ^= 0x01; + let bad = Ciphertext::from_bytes(&bad).unwrap(); + let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ESEED_I).unwrap(); + if let Ok(s) = init.finish(&bad) { + assert_ne!(psk(&s), honest_psk, "ct_RI byte {n} did not change the secret"); + accepted += 1; } } - assert!(refused < PUBLIC_KEY_LEN, "most flipped keys still parse; the test must exercise them"); + assert!(accepted > CIPHERTEXT_LEN - 32); +} + +/// Flip each byte of the responder's public key as the initiator received it, and of the +/// initiator's public key as the responder received it. +#[test] +fn every_public_key_byte_changes_the_secret() { + let (honest_psk, ct_ir, _) = honest(); + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); + let mut used = 0; + for n in 0..PUBLIC_KEY_LEN { + // The initiator's view of the responder's key. + let mut bad = *r.public_key().as_bytes(); + bad[n] ^= 0x01; + // A flipped ML-KEM coefficient can fail the FIPS 203 modulus check: refused, not accepted. + if let Ok(pk) = PublicKey::from_bytes(&bad) { + let init = exchange::initiate_derand(&i, &pk, CONTEXT, &ESEED_I).unwrap(); + let (ct_ri, rs) = + exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &ESEED_R).unwrap(); + let is = init.finish(&ct_ri).unwrap(); + assert_ne!(psk(&is), honest_psk, "initiator: responder key byte {n}"); + assert_ne!(psk(&is), psk(&rs), "initiator: responder key byte {n} still agrees"); + used += 1; + } + // The responder's view of the initiator's key. + let mut bad = *i.public_key().as_bytes(); + bad[n] ^= 0x01; + if let Ok(pk) = PublicKey::from_bytes(&bad) { + let (_, rs) = exchange::respond_derand(&r, &pk, &ct_ir, CONTEXT, &ESEED_R).unwrap(); + assert_ne!(psk(&rs), honest_psk, "responder: initiator key byte {n}"); + used += 1; + } + } + assert!(used > PUBLIC_KEY_LEN, "most flipped keys still parse; the test must exercise them"); } #[test] fn every_seed_byte_changes_the_secret() { - let (honest_psk, _) = honest(); - for i in 0..32 { - let mut seed = SEED; - seed[i] ^= 0x01; - let sk = SecretKey::from_seed(seed); - let (_, s) = exchange::initiate_derand(sk.public_key(), CONTEXT, &ESEED).unwrap(); - assert_ne!(psk(&s), honest_psk, "seed byte {i}"); + let (honest_psk, _, _) = honest(); + let run = |si: [u8; 32], sr: [u8; 32], ei: [u8; 64], er: [u8; 64]| { + let i = SecretKey::from_seed(si); + let r = SecretKey::from_seed(sr); + let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ei).unwrap(); + let (_, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &er).unwrap(); + psk(&rs) + }; + for n in 0..32 { + let mut s = SEED_I; + s[n] ^= 1; + assert_ne!(run(s, SEED_R, ESEED_I, ESEED_R), honest_psk, "initiator seed byte {n}"); + let mut s = SEED_R; + s[n] ^= 1; + assert_ne!(run(SEED_I, s, ESEED_I, ESEED_R), honest_psk, "responder seed byte {n}"); } - for i in 0..64 { - let mut eseed = ESEED; - eseed[i] ^= 0x01; - let sk = SecretKey::from_seed(SEED); - let (_, s) = exchange::initiate_derand(sk.public_key(), CONTEXT, &eseed).unwrap(); - assert_ne!(psk(&s), honest_psk, "eseed byte {i}"); + // Bit 4 of each byte: X25519 clamps bits 0-2 of byte 32 and bits 6-7 of byte 63 of the + // ephemeral scalar (RFC 7748 §5), so flipping those bits is, by design, no change at all. + for n in 0..64 { + let mut e = ESEED_I; + e[n] ^= 0x10; + assert_ne!(run(SEED_I, SEED_R, e, ESEED_R), honest_psk, "initiator eseed byte {n}"); + let mut e = ESEED_R; + e[n] ^= 0x10; + assert_ne!(run(SEED_I, SEED_R, ESEED_I, e), honest_psk, "responder eseed byte {n}"); } } #[test] -fn every_context_byte_changes_the_secret_and_a_mismatch_disagrees() { - let (honest_psk, ct) = honest(); - let sk = SecretKey::from_seed(SEED); - for i in 0..CONTEXT.len() { +fn every_context_byte_changes_the_secret() { + let (honest_psk, ct_ir, _) = honest(); + let i = SecretKey::from_seed(SEED_I); + let r = SecretKey::from_seed(SEED_R); + let resp = |ctx: &[u8]| psk(&exchange::respond_derand(&r, i.public_key(), &ct_ir, ctx, &ESEED_R).unwrap().1); + for n in 0..CONTEXT.len() { let mut ctx = CONTEXT.to_vec(); - ctx[i] ^= 0x01; - let s = exchange::respond(&sk, &ct, &ctx).unwrap(); - assert_ne!(psk(&s), honest_psk, "context byte {i}"); + ctx[n] ^= 0x01; + assert_ne!(resp(&ctx), honest_psk, "context byte {n}"); } // Length is bound too: a prefix or an extension of the context is a different context. for ctx in [&CONTEXT[..CONTEXT.len() - 1], b"", &[CONTEXT, b"\0"].concat()[..]] { - let s = exchange::respond(&sk, &ct, ctx).unwrap(); - assert_ne!(psk(&s), honest_psk); + assert_ne!(resp(ctx), honest_psk); } } +/// QA A-15: the attacker knows both public keys and plays the initiator without the initiator's +/// secret key. She can make ct_IR (she knows ss_IR), but she cannot decapsulate ct_RI, which the +/// responder encapsulated to the real initiator. So she cannot compute the responder's PSK. +#[test] +fn an_impersonated_initiator_cannot_compute_the_psk() { + let i = SecretKey::from_seed(SEED_I); // the real initiator, whom the attacker impersonates + let r = SecretKey::from_seed(SEED_R); + let mallory = SecretKey::from_seed([0x66; 32]); + let mut g = rng(3); + + // Mallory encapsulates to the responder (anyone can) and sends it as "from I". + let forged = exchange::initiate(&mallory, r.public_key(), CONTEXT, &mut g).unwrap(); + let (ct_ri, responder_session) = + exchange::respond(&r, i.public_key(), forged.ciphertext(), CONTEXT, &mut g).unwrap(); + // Her best effort: finish with her own key. ct_RI was made for I's key, not hers. + let mallory_session = forged.finish(&ct_ri).unwrap(); + assert_ne!(psk(&mallory_session), psk(&responder_session)); +} + +/// QA A-14: roles are bound by position. Running the exchange with the roles swapped (same two +/// keys, same randomness) gives a different PSK, so a reflected message cannot complete it. +#[test] +fn roles_are_bound() { + let a = SecretKey::from_seed(SEED_I); + let b = SecretKey::from_seed(SEED_R); + let ab = exchange::initiate_derand(&a, b.public_key(), CONTEXT, &ESEED_I).unwrap(); + let (ct, ab_resp) = exchange::respond_derand(&b, a.public_key(), ab.ciphertext(), CONTEXT, &ESEED_R).unwrap(); + let ab_init = ab.finish(&ct).unwrap(); + let ba = exchange::initiate_derand(&b, a.public_key(), CONTEXT, &ESEED_I).unwrap(); + let (ct, ba_resp) = exchange::respond_derand(&a, b.public_key(), ba.ciphertext(), CONTEXT, &ESEED_R).unwrap(); + let ba_init = ba.finish(&ct).unwrap(); + assert_eq!(psk(&ab_init), psk(&ab_resp)); + assert_eq!(psk(&ba_init), psk(&ba_resp)); + assert_ne!(psk(&ab_init), psk(&ba_init)); +} + #[test] fn the_wrong_secret_key_does_not_agree() { - let (honest_psk, ct) = honest(); + let (honest_psk, ct_ir, _) = honest(); + let i = SecretKey::from_seed(SEED_I); let other = SecretKey::from_seed([0x33; 32]); - let s = exchange::respond(&other, &ct, CONTEXT).unwrap(); + let (_, s) = exchange::respond_derand(&other, i.public_key(), &ct_ir, CONTEXT, &ESEED_R).unwrap(); assert_ne!(psk(&s), honest_psk); } diff --git a/tests/feature_hygiene.rs b/tests/feature_hygiene.rs new file mode 100644 index 0000000..2f1aafe --- /dev/null +++ b/tests/feature_hygiene.rs @@ -0,0 +1,34 @@ +//! QA A-35: no test-only feature may reach a normal (release) build through Cargo feature +//! unification. Checks the normal-edge dependency graph that a consumer of Arcanum would get. +//! +//! `arcanum/hazmat` exposes the deterministic entry points; `ml-kem/hazmat` only un-hides docs in +//! 0.3.4 (its `encapsulate_deterministic` is public either way), but is kept out on principle. + +use std::process::Command; + +fn tree(args: &[&str]) -> String { + let out = Command::new(env!("CARGO")) + .current_dir(env!("CARGO_MANIFEST_DIR")) + .args(["tree", "--offline", "--locked", "-e", "features,normal", "--prefix", "none"]) + .args(args) + .output() + .expect("run cargo tree"); + assert!(out.status.success(), "cargo tree failed: {}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8(out.stdout).unwrap() +} + +#[test] +fn hazmat_is_not_in_the_normal_graph() { + let t = tree(&["-p", "arcanum"]); + assert!(t.contains("ml-kem"), "the tree must include ml-kem, or this test checks nothing:\n{t}"); + for line in t.lines() { + assert!(!line.contains("feature \"hazmat\""), "hazmat reached a normal build: {line}\n{t}"); + } +} + +#[test] +fn no_os_rng_in_the_normal_graph() { + // Randomness is a parameter (QA A-36): nothing in the normal graph may pull an OS RNG. + let t = tree(&["-p", "arcanum"]); + assert!(!t.contains("getrandom"), "getrandom reached a normal build:\n{t}"); +} diff --git a/tests/malformed.rs b/tests/malformed.rs index 0e1e588..2db0192 100644 --- a/tests/malformed.rs +++ b/tests/malformed.rs @@ -48,16 +48,20 @@ fn ml_kem_key_failing_the_modulus_check_is_a_typed_error() { fn random_bytes_never_panic() { let mut r = rng(9); let sk = SecretKey::from_seed([0x01; 32]); + let peer = SecretKey::from_seed([0x02; 32]); + let (honest_ct, _) = peer.public_key().encapsulate(&mut r).unwrap(); for round in 0..512 { let len = [PUBLIC_KEY_LEN, CIPHERTEXT_LEN, seal::OVERHEAD, seal::OVERHEAD + 40, 0, 17][round % 6]; let mut buf = vec![0u8; len]; r.fill_bytes(&mut buf); if let Ok(pk) = PublicKey::from_bytes(&buf) { - let _ = exchange::initiate(&pk, b"ctx", &mut r); + let _ = exchange::initiate(&sk, &pk, b"ctx", &mut r); + let _ = exchange::respond(&sk, &pk, &honest_ct, b"ctx", &mut r); } if let Ok(ct) = Ciphertext::from_bytes(&buf) { // Random ML-KEM ciphertexts decapsulate (implicit rejection) to some unrelated secret. - let _ = exchange::respond(&sk, &ct, b"ctx"); + let _ = exchange::respond(&sk, peer.public_key(), &ct, b"ctx", &mut r); + let _ = exchange::initiate(&sk, peer.public_key(), b"ctx", &mut r).unwrap().finish(&ct); } assert!(seal::open(&sk, &buf, b"aad").is_err(), "random bytes must never open"); } @@ -129,3 +133,49 @@ fn errors_display_without_secrets() { assert_eq!(e.to_string(), "ciphertext has the wrong length: expected 1120 bytes, got 3"); let _: &dyn std::error::Error = &e; } + +/// QA A-20: the modulus check is not over-eager. The last 32 bytes of the ML-KEM key are the +/// seed rho, where any value is legal. +#[test] +fn ml_kem_key_check_accepts_any_rho() { + let sk = SecretKey::from_seed([0x03; 32]); + let mut ok = *sk.public_key().as_bytes(); + ok[1183] ^= 1; + assert!(PublicKey::from_bytes(&ok).is_ok()); +} + +/// QA A-21: the only stored private-key form is the 32-byte seed; an expanded ML-KEM key or an +/// X-Wing key plus anything else is refused by length. +#[test] +fn only_the_32_byte_seed_is_a_secret_key() { + for len in [64, 96, 2400, 2432] { + assert!(matches!(SecretKey::from_bytes(&vec![0u8; len]), Err(Error::InvalidLength { .. })), "{len}"); + } +} + +/// QA A-24: a one-byte extension and a splice (header of one box, body of another) are refused. +#[test] +fn sealed_box_extension_and_splice_are_refused() { + let mut r = rng(14); + let sk = SecretKey::generate(&mut r); + let b1 = seal::seal(sk.public_key(), b"one", b"", &mut r).unwrap(); + let b2 = seal::seal(sk.public_key(), b"two", b"", &mut r).unwrap(); + let mut ext = b1.clone(); + ext.push(0); + assert_eq!(seal::open(&sk, &ext, b"").unwrap_err(), Error::DecryptionFailed); + let mut spliced = b1[..1121].to_vec(); + spliced.extend_from_slice(&b2[1121..]); + assert_eq!(seal::open(&sk, &spliced, b"").unwrap_err(), Error::DecryptionFailed); +} + +/// QA A-26: all randomness comes from the RNG parameter: the same seed gives the same box, a +/// different seed a different one. +#[test] +fn seal_randomness_comes_only_from_the_rng() { + let sk = SecretKey::from_seed([0x04; 32]); + let a = seal::seal(sk.public_key(), b"m", b"", &mut rng(1)).unwrap(); + let b = seal::seal(sk.public_key(), b"m", b"", &mut rng(1)).unwrap(); + let c = seal::seal(sk.public_key(), b"m", b"", &mut rng(2)).unwrap(); + assert_eq!(a, b); + assert_ne!(a, c); +} diff --git a/tests/no_unsafe.rs b/tests/no_unsafe.rs index d93b84b..ffc4ab0 100644 --- a/tests/no_unsafe.rs +++ b/tests/no_unsafe.rs @@ -31,7 +31,8 @@ fn no_source_file_contains_unsafe() { let text = fs::read_to_string(&f).unwrap(); for (n, line) in text.lines().enumerate() { let code = line.split("//").next().unwrap_or(""); - assert!(!code.contains("unsafe"), "{}:{}: {line}", f.display(), n + 1); + let opts_in = code.contains("unsafe") && code.trim() != "#![forbid(unsafe_code)]"; + assert!(!opts_in, "{}:{}: {line}", f.display(), n + 1); } } } diff --git a/tests/psk_epochs.rs b/tests/psk_epochs.rs index aa49c15..5131596 100644 --- a/tests/psk_epochs.rs +++ b/tests/psk_epochs.rs @@ -8,11 +8,16 @@ use std::collections::HashSet; const CONTEXT: &[u8] = b"via/test: epochs"; +fn exchange_with(eseed_i: [u8; 64]) -> (exchange::Session, exchange::Session) { + let i = SecretKey::from_seed([0x01; 32]); + let r = SecretKey::from_seed([0x04; 32]); + let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &eseed_i).unwrap(); + let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &[0x05; 64]).unwrap(); + (init.finish(&ct_ri).unwrap(), rs) +} + fn sessions() -> (exchange::Session, exchange::Session) { - let sk = SecretKey::from_seed([0x01; 32]); - let (ct, a) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x02; 64]).unwrap(); - let b = exchange::respond(&sk, &ct, CONTEXT).unwrap(); - (a, b) + exchange_with([0x02; 64]) } #[test] @@ -43,9 +48,8 @@ fn the_same_epoch_is_reproducible_from_the_same_inputs() { #[test] fn a_different_exchange_gives_different_psks_for_the_same_epoch() { - let sk = SecretKey::from_seed([0x01; 32]); - let (_, a) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x02; 64]).unwrap(); - let (_, c) = exchange::initiate_derand(sk.public_key(), CONTEXT, &[0x03; 64]).unwrap(); + let (a, _) = exchange_with([0x02; 64]); + let (c, _) = exchange_with([0x03; 64]); for epoch in 0..16 { assert_ne!(a.wireguard_psk(epoch).as_bytes(), c.wireguard_psk(epoch).as_bytes()); } @@ -83,3 +87,13 @@ fn epoch_helper_uses_two_minute_epochs() { assert_eq!(epoch_at(1_764_000_000), 1_764_000_000 / 120); assert_eq!(epoch_at(u64::MAX), u64::MAX / 120); } + +/// QA A-11: the epoch is encoded at its full 64-bit width; nothing truncates it. +#[test] +fn the_epoch_is_not_truncated() { + let (a, _) = sessions(); + let p = |e: u64| *a.wireguard_psk(e).as_bytes(); + assert_ne!(p(0), p(1 << 32)); + assert_ne!(p(1), p(1 << 8)); + assert_ne!(p(u64::MAX), p(u64::MAX >> 1)); +}