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.
This commit is contained in:
2026-11-25 07:38:55 +01:00
parent c7d050ed65
commit 89b5329f06
15 changed files with 1316 additions and 118 deletions
+92 -9
View File
@@ -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");
}
+83
View File
@@ -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<const N: usize>(input: Input, bytes: &[u8]) -> Result<&[u8; N], Error> {
bytes.try_into().map_err(|_| Error::InvalidLength { input, expected: N, actual: bytes.len() })
}
+204
View File
@@ -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<Vec<u8>>,
}
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<Session, Error> {
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<Initiation<'a>, 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<R: CryptoRng + ?Sized>(
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<Initiation<'a>, 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<Initiation<'a>, 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))
}
+42
View File
@@ -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
}
+113
View File
@@ -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::<Sha256>::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<const N: usize>(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::<Sha256>::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
}
+121
View File
@@ -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<R: CryptoRng + ?Sized>(
recipient: &PublicKey,
plaintext: &[u8],
aad: &[u8],
rng: &mut R,
) -> Result<Vec<u8>, 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<Vec<u8>, Error> {
seal_inner(recipient, plaintext, aad, eseed)
}
fn seal_inner(
recipient: &PublicKey,
plaintext: &[u8],
aad: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<Vec<u8>, 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<Zeroizing<Vec<u8>>, 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)
}
+304
View File
@@ -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<MlKem768>;
type MlKemDecapsulationKey = ml_kem::DecapsulationKey<MlKem768>;
/// 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<Self, Error> {
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<R: CryptoRng + ?Sized>(&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::<u8, 32, _>(|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<Self, Error> {
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<R: CryptoRng + ?Sized>(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<Self, Error> {
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<SharedSecret, Error> {
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
}