fix: QA second review R2-01 to R2-05

R2-01: PublicKey::encapsulate, SecretKey::decapsulate and SharedSecret::as_bytes
are hazmat-only; release consumers reach keys only through exchange and seal.
R2-02: PublicKey::from_bytes refuses a non-canonical X25519 half (bit 255 set,
or a value of at least 2^255 - 19). Honest keys and the draft vectors pass.
R2-03: schedule::expand takes one static label and one fixed-width field, so
its info is injective by signature. v1 bytes unchanged (golden vectors pass).
R2-04: generate, initiate, respond and seal say the RNG must be the OS RNG.
R2-05: Initiation is ZeroizeOnDrop; seal's buffer stays Zeroizing until the
plaintext in it is encrypted, so the MessageTooLong path wipes it.
QA's A-33 case for PublicKey::encapsulate moves to exchange::respond, and its
A-08 test pins the new expand signature to the v1 encoding.
This commit is contained in:
2026-11-25 08:37:11 +01:00
parent f3e17f3d5c
commit 6780abc0c2
8 changed files with 152 additions and 31 deletions
+46 -8
View File
@@ -4,9 +4,16 @@
//! `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).
//! Two deliberate differences from the draft, both stricter and both invisible to honest peers and
//! to the official vectors: a low-order X25519 public key or ciphertext part is refused with
//! [`Error::NonContributory`], and a public key whose X25519 half is not the canonical encoding
//! (bit 255 set, or a value of at least 2^255 - 19) is refused with [`Error::InvalidPublicKey`]
//! (docs/01_arcanum.md).
//!
//! **The raw one-way KEM is not part of the release API** (QA R2-01). Without the `hazmat` feature
//! a consumer can parse keys and ciphertexts and generate a key pair, but cannot encapsulate,
//! decapsulate or read an X-Wing secret: a PSK must come from [`crate::exchange`], which needs both
//! directions and binds the transcript, and sealing goes through [`crate::seal`].
use core::{array, fmt};
@@ -55,12 +62,17 @@ pub(crate) fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x:
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.
/// The raw 32 bytes. **Hazmat** (feature `hazmat`): a one-way X-Wing secret authenticates only
/// the receiver and is bound to no transcript, so it must never be used as a key directly.
#[cfg(feature = "hazmat")]
#[must_use]
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
&self.0
}
pub(crate) fn bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
&self.0
}
}
impl fmt::Debug for SharedSecret {
@@ -84,12 +96,15 @@ impl PublicKey {
///
/// # 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.
/// part fails the FIPS 203 §7.2 encapsulation key check, or the X25519 part is not canonical.
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]);
if !is_canonical_x25519(&x) {
return Err(Error::InvalidPublicKey);
}
Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) })
}
@@ -99,10 +114,12 @@ impl PublicKey {
&self.bytes
}
/// Encapsulate a fresh shared secret to this key.
/// Encapsulate a fresh shared secret to this key. **Hazmat** (feature `hazmat`), see the module
/// docs; release code uses [`crate::exchange`] or [`crate::seal`].
///
/// # Errors
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
#[cfg(feature = "hazmat")]
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());
@@ -205,6 +222,10 @@ pub struct SecretKey {
impl SecretKey {
/// Generate a new key pair from the caller's RNG.
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
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());
@@ -241,12 +262,17 @@ impl SecretKey {
&self.public
}
/// X-Wing `Decapsulate` (draft -11 §5.5).
/// X-Wing `Decapsulate` (draft -11 §5.5). **Hazmat** (feature `hazmat`), see the module docs.
///
/// # 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.
#[cfg(feature = "hazmat")]
pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
self.decapsulate_inner(ct)
}
pub(crate) fn decapsulate_inner(&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() {
@@ -296,6 +322,18 @@ impl fmt::Debug for SecretKey {
// (their `zeroize` features are enabled in Cargo.toml).
impl ZeroizeOnDrop for SecretKey {}
/// RFC 7748 encodes a u-coordinate as 32 little-endian bytes of a value below p = 2^255 - 19, with
/// bit 255 clear; X25519 outputs (every honest public key) are always in that form. Decoders mask
/// bit 255 and reduce mod p, so other encodings alias a canonical key: refuse them (QA R2-02).
fn is_canonical_x25519(u: &[u8; 32]) -> bool {
if u[31] & 0x80 != 0 {
return false;
}
// With bit 255 clear, u >= p only for 2^255 - 19 ..= 2^255 - 1: ed..ff, then 30 x ff, then 7f.
let at_least_p = u[31] == 0x7f && u[1..31].iter().all(|&b| b == 0xff) && u[0] >= 0xed;
!at_least_p
}
/// 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]);