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:
+15
-3
@@ -43,7 +43,7 @@ impl Session {
|
||||
/// 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()]))
|
||||
WireGuardPsk(expand(&self.prk, LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,6 +84,10 @@ pub struct Initiation<'a> {
|
||||
context: Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
// The secret fields wipe themselves: `ss_ir` is a `ZeroizeOnDrop` `SharedSecret` and `context` is
|
||||
// `Zeroizing`; `me` is a borrow and `peer`/`ct_ir` are public (QA R2-05).
|
||||
impl ZeroizeOnDrop for Initiation<'_> {}
|
||||
|
||||
impl fmt::Debug for Initiation<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Initiation([redacted])")
|
||||
@@ -104,7 +108,7 @@ impl Initiation<'_> {
|
||||
/// 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 ss_ri = self.me.decapsulate_inner(ct_ri)?;
|
||||
let t = Transcript {
|
||||
initiator: self.me.public_key(),
|
||||
responder: &self.peer,
|
||||
@@ -118,6 +122,10 @@ impl Initiation<'_> {
|
||||
|
||||
/// Start an exchange as the initiator: encapsulate to the responder and keep the state.
|
||||
///
|
||||
/// **`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).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point.
|
||||
pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
||||
@@ -134,6 +142,10 @@ pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
||||
/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back,
|
||||
/// and return the ciphertext to send together with the finished session.
|
||||
///
|
||||
/// **`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).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519
|
||||
/// part.
|
||||
@@ -196,7 +208,7 @@ fn respond_inner(
|
||||
context: &[u8],
|
||||
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
||||
) -> Result<(Ciphertext, Session), Error> {
|
||||
let ss_ir = me.decapsulate(ct_ir)?;
|
||||
let ss_ir = me.decapsulate_inner(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) };
|
||||
|
||||
+13
-6
@@ -28,9 +28,16 @@ fn psk_info(epoch: u64) -> Vec<u8> {
|
||||
#[test]
|
||||
fn a08_kdf_info_encodings_in_use_are_injective() {
|
||||
let prk: Prk = Zeroizing::new([9u8; 32]);
|
||||
// (1) The helper is raw concatenation. If this ever fails, the helper became length-prefixed:
|
||||
// update this test and the golden vectors together.
|
||||
assert_eq!(*expand::<32>(&prk, &[b"ab", b"c"]), *expand::<32>(&prk, &[b"a", b"bc"]));
|
||||
// (1) Builder fix for R2-03: the helper now takes exactly one label and one fixed-width field,
|
||||
// so the old ["ab","c"] vs ["a","bc"] collision cannot be written any more. Its bytes are still
|
||||
// the v1 encoding, HKDF-Expand(prk, label || field), so the golden vectors did not change.
|
||||
let raw = |info: &[u8]| {
|
||||
let mut o = [0u8; 32];
|
||||
hkdf::Hkdf::<sha2::Sha256>::from_prk(prk.as_slice()).unwrap().expand(info, &mut o).unwrap();
|
||||
o
|
||||
};
|
||||
assert_eq!(*expand::<32, 8>(&prk, LABEL_WIREGUARD_PSK, &7u64.to_be_bytes()), raw(&psk_info(7)));
|
||||
assert_eq!(*expand::<32, 0>(&prk, LABEL_SEAL_KEY, &[]), raw(LABEL_SEAL_KEY));
|
||||
|
||||
// (2) Every info string in use: one fixed length per purpose, and none a prefix of another.
|
||||
let mut infos: Vec<Vec<u8>> = [0u64, 1, 255, 256, 1 << 32, u64::MAX].iter().map(|&e| psk_info(e)).collect();
|
||||
@@ -83,15 +90,15 @@ fn a09_one_secret_never_yields_the_same_key_for_two_purposes() {
|
||||
|
||||
let mut keys: HashSet<[u8; 32]> = HashSet::new();
|
||||
for prk in [&seal, &session] {
|
||||
let key = *expand::<32>(prk, &[LABEL_SEAL_KEY]);
|
||||
let key = *expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
|
||||
assert!(keys.insert(key));
|
||||
let mut nonce = [0u8; 32];
|
||||
nonce[..12].copy_from_slice(&*expand::<12>(prk, &[LABEL_SEAL_NONCE]));
|
||||
nonce[..12].copy_from_slice(&*expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]));
|
||||
// HKDF output is prefix-consistent: a shared label would make the nonce the key's prefix.
|
||||
assert_ne!(nonce[..12], key[..12], "the nonce is a prefix of the key: labels shared");
|
||||
assert!(keys.insert(nonce));
|
||||
for e in 0..1024u64 {
|
||||
assert!(keys.insert(*expand::<32>(prk, &[LABEL_WIREGUARD_PSK, &e.to_be_bytes()])), "epoch {e}");
|
||||
assert!(keys.insert(*expand::<32, 8>(prk, LABEL_WIREGUARD_PSK, &e.to_be_bytes())), "epoch {e}");
|
||||
}
|
||||
}
|
||||
assert_eq!(keys.len(), 2 * (2 + 1024));
|
||||
|
||||
+16
-5
@@ -82,7 +82,7 @@ fn extract(secrets: &[&[u8; 32]], th: &[u8; 32]) -> Prk {
|
||||
|
||||
/// 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())
|
||||
extract(&[ss_ir.bytes(), ss_ri.bytes()], &t.hash())
|
||||
}
|
||||
|
||||
/// The PRK of one sealed box: the X-Wing secret, the recipient key, the ciphertext and the aad.
|
||||
@@ -94,14 +94,25 @@ pub(crate) fn seal_prk(ss: &SharedSecret, recipient: &PublicKey, ct: &Ciphertext
|
||||
h.update((aad.len() as u64).to_be_bytes());
|
||||
h.update(aad);
|
||||
let th: [u8; 32] = h.finalize().into();
|
||||
extract(&[ss.as_bytes()], &th)
|
||||
extract(&[ss.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]> {
|
||||
/// HKDF-Expand to `N` bytes with `info = label || field`.
|
||||
///
|
||||
/// The signature is what makes the encoding injective (QA R2-03): exactly one label, which must be
|
||||
/// one of the `LABEL_*` constants above (unique and prefix-free, tested in `binding_tests`), and
|
||||
/// exactly one fixed-width field. If two calls give the same `info`, their labels are equal (in a
|
||||
/// prefix-free set a label is determined by the string it starts), so their fields are equal too.
|
||||
/// Several values go into one fixed-width array, never into separate parts. This is byte for byte
|
||||
/// the v1 encoding (`tests/golden_v1.rs` is unchanged).
|
||||
pub(crate) fn expand<const N: usize, const K: usize>(
|
||||
prk: &Prk,
|
||||
label: &'static [u8],
|
||||
field: &[u8; K],
|
||||
) -> 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");
|
||||
hk.expand_multi_info(&[label, field.as_slice()], out.as_mut_slice()).expect("N is at most 255 * 32");
|
||||
out
|
||||
}
|
||||
|
||||
+13
-6
@@ -33,8 +33,8 @@ const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN;
|
||||
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]);
|
||||
let key = expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
|
||||
let nonce = expand::<12, 0>(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))
|
||||
@@ -43,6 +43,10 @@ fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
||||
/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again
|
||||
/// to open).
|
||||
///
|
||||
/// **`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).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
|
||||
pub fn seal<R: CryptoRng + ?Sized>(
|
||||
@@ -80,8 +84,10 @@ fn seal_inner(
|
||||
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);
|
||||
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated. It is
|
||||
// `Zeroizing` until the plaintext has been encrypted in place, so an early return (the
|
||||
// `MessageTooLong` path) wipes the copy instead of freeing it unwiped (QA R2-05).
|
||||
let mut out = Zeroizing::new(Vec::with_capacity(plaintext.len() + OVERHEAD));
|
||||
out.push(VERSION);
|
||||
out.extend_from_slice(ct.as_bytes());
|
||||
out.extend_from_slice(plaintext);
|
||||
@@ -90,7 +96,8 @@ fn seal_inner(
|
||||
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
|
||||
.map_err(|_| Error::MessageTooLong)?;
|
||||
out.extend_from_slice(tag.as_slice());
|
||||
Ok(out)
|
||||
// Now only ciphertext: move the buffer out without copying it (the wrapper keeps an empty Vec).
|
||||
Ok(core::mem::take(&mut *out))
|
||||
}
|
||||
|
||||
/// Open a sealed box with the recipient's secret key and the same `aad`.
|
||||
@@ -108,7 +115,7 @@ pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result<Zeroizin
|
||||
return Err(Error::UnsupportedVersion(version));
|
||||
}
|
||||
let ct = Ciphertext::from_bytes(ct)?;
|
||||
let ss = recipient.decapsulate(&ct)?;
|
||||
let ss = recipient.decapsulate_inner(&ct)?;
|
||||
let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad));
|
||||
|
||||
let (body, tag) = rest.split_at(rest.len() - TAG_LEN);
|
||||
|
||||
+46
-8
@@ -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]);
|
||||
|
||||
+42
-1
@@ -68,14 +68,55 @@ fn low_order_x25519_ciphertext_is_refused() {
|
||||
fn low_order_x25519_public_key_is_refused() {
|
||||
let i = SecretKey::from_seed([0x43; 32]);
|
||||
let r = SecretKey::from_seed([0x44; 32]);
|
||||
let mut refused_at_parse = 0;
|
||||
for point in low_order_points() {
|
||||
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");
|
||||
// Non-canonical encodings (bit 255 set, or p and p + 1) are refused when parsed (QA R2-02);
|
||||
// the canonical low-order points parse and are refused when used.
|
||||
let canonical = point[31] & 0x80 == 0 && !(point[31] == 0x7f && point[0] >= 0xed);
|
||||
let pk = match PublicKey::from_bytes(&bad) {
|
||||
Ok(pk) => {
|
||||
assert!(canonical, "a non-canonical pk_X parsed: {}", hex::encode(point));
|
||||
pk
|
||||
}
|
||||
Err(e) => {
|
||||
assert_eq!(e, Error::InvalidPublicKey);
|
||||
assert!(!canonical, "a canonical pk_X was refused: {}", hex::encode(point));
|
||||
refused_at_parse += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
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));
|
||||
}
|
||||
// 7 points with bit 255 set, plus p and p + 1.
|
||||
assert_eq!(refused_at_parse, 9);
|
||||
}
|
||||
|
||||
/// QA R2-02 boundary: p - 1 is the largest canonical u-coordinate (and low order), p is the
|
||||
/// smallest non-canonical one, and an honest key is always canonical.
|
||||
#[test]
|
||||
fn the_canonical_boundary_is_exactly_p() {
|
||||
let r = SecretKey::from_seed([0x44; 32]);
|
||||
let with_x = |x: [u8; 32]| {
|
||||
let mut b = *r.public_key().as_bytes();
|
||||
b[1184..].copy_from_slice(&x);
|
||||
PublicKey::from_bytes(&b)
|
||||
};
|
||||
let mut p_minus_1 = [0xff; 32];
|
||||
p_minus_1[0] = 0xec;
|
||||
p_minus_1[31] = 0x7f;
|
||||
let mut p = p_minus_1;
|
||||
p[0] = 0xed;
|
||||
let mut below = [0xff; 32];
|
||||
below[31] = 0x7f;
|
||||
below[1] = 0xfe; // 2^255 - 1 - 2^8: below p although its first byte is 0xff
|
||||
assert!(with_x(p_minus_1).is_ok());
|
||||
assert_eq!(with_x(p).err(), Some(Error::InvalidPublicKey));
|
||||
assert!(with_x(below).is_ok());
|
||||
assert!(PublicKey::from_bytes(r.public_key().as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
/// QA A-04: X25519 ignores bit 255 of ct_X, so ct_X and ct_X ^ 0x80 give the same ss_X. The
|
||||
|
||||
@@ -116,10 +116,14 @@ fn control_the_safe_api_compiles_without_hazmat() {
|
||||
fn a33_a_non_crypto_rng_does_not_compile() {
|
||||
let calls = [
|
||||
("SecretKey::generate", "let _ = arcanum::xwing::SecretKey::generate(&mut Counter(0));"),
|
||||
// Builder, with the R2-01 fix: `PublicKey::encapsulate` is hazmat-only now, so it no longer
|
||||
// exists for a consumer (qa_r2_01 checks that). Its place is taken by the other release
|
||||
// function that takes an RNG, `exchange::respond`.
|
||||
(
|
||||
"PublicKey::encapsulate",
|
||||
"exchange::respond",
|
||||
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
|
||||
let _ = k.public_key().encapsulate(&mut Counter(0));",
|
||||
let ct = arcanum::xwing::Ciphertext::from_bytes(&[0; 1120]).unwrap(); \
|
||||
let _ = arcanum::exchange::respond(&k, k.public_key(), &ct, b\"\", &mut Counter(0));",
|
||||
),
|
||||
(
|
||||
"exchange::initiate",
|
||||
|
||||
@@ -54,6 +54,7 @@ fn a28_secret_types_are_zeroize_on_drop() {
|
||||
assert_zeroize_on_drop::<SharedSecret>();
|
||||
assert_zeroize_on_drop::<Session>();
|
||||
assert_zeroize_on_drop::<WireGuardPsk>();
|
||||
assert_zeroize_on_drop::<exchange::Initiation<'static>>(); // R2-05, added by the builder with the fix
|
||||
}
|
||||
|
||||
/// QA A-28: `Debug` of every secret type is redacted (the PSK and Session case is already in
|
||||
|
||||
Reference in New Issue
Block a user