From a553da80942632cf9a493c055216494eb5de473d Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 16:26:40 +1100 Subject: [PATCH 01/14] ec: wipe the stack after the Ed25519 and Ed448 fixed-base multiplication scalar_mult_base_encoded runs in a frame of its own and overwrites the stack it used (3072 bytes for Ed25519, 4096 for Ed448), as X448's ladder does. A comparison of two runs over different keys found limbs of the point's coordinates and of the normalizing inversion left after keygen_out, from_bytes_out and every form of signing. Outputs are byte-identical (old-vs-new differential over 300 keys); the ec tests, RFC 8032 vectors and Wycheproof suites pass. Assisted-by: Claude:claude-opus-5-5 --- crypto/ec/src/ed/ed25519/mod.rs | 8 +++++--- crypto/ec/src/ed/ed25519/point.rs | 23 +++++++++++++++++++++++ crypto/ec/src/ed/ed448/mod.rs | 8 +++++--- crypto/ec/src/ed/ed448/point.rs | 23 +++++++++++++++++++++++ 4 files changed, 56 insertions(+), 6 deletions(-) diff --git a/crypto/ec/src/ed/ed25519/mod.rs b/crypto/ec/src/ed/ed25519/mod.rs index ca5f874ec..ac38342e2 100644 --- a/crypto/ec/src/ed/ed25519/mod.rs +++ b/crypto/ec/src/ed/ed25519/mod.rs @@ -164,9 +164,11 @@ //! for `clone` and for the array `encode` returns. Use [`keygen_out`], //! [`Ed25519PrivateKey::from_bytes_out`], `clone_from` and `encode_out` into a key or buffer you //! own where that matters. Signing also overwrites the stack its last step used, where the -//! compiler otherwise leaves limbs of the scalar it held in registers; a scan of the dead stack -//! after each signing call finds none of the key in release builds for x86-64 and arm64, the -//! two scanned. SHA-512 is outside that: its load of the block that holds the private key can +//! compiler otherwise leaves limbs of the scalar it held in registers, and each fixed-base +//! multiplication (key expansion's `[s]B`, signing's `[r]B`) the stack it used, where it leaves +//! limbs of the point's coordinates and of the inversion that normalizes them; a scan of the +//! dead stack after each signing call finds none of the key in release builds for x86-64 and +//! arm64, the two scanned. SHA-512 is outside that: its load of the block that holds the private key can //! leave words of it on the stack, seen as one word after `from_bytes_out` in the arm64 build. //! //! Each fixed-base multiplication checks that its result is a point of the curve before diff --git a/crypto/ec/src/ed/ed25519/point.rs b/crypto/ec/src/ed/ed25519/point.rs index ea812997a..40f8bad23 100644 --- a/crypto/ec/src/ed/ed25519/point.rs +++ b/crypto/ec/src/ed/ed25519/point.rs @@ -12,6 +12,7 @@ use super::scalar; use crate::ed::bits; use crate::ed::curve25519::{FieldElement25519, NormalizedFieldElement25519}; use crate::ed::wnaf; +use crate::stack_wipe::wipe_stack_below; use bouncycastle_utils::ct::Condition; use bouncycastle_utils::secret::Secret; @@ -445,9 +446,31 @@ pub(super) fn scalar_mult_base(k: &[u8; 32], r: &mut PointAccum) { /// Writes the encoding of `[k]B` to `r`, for `k` as [`scalar_mult_base`] takes it, after /// checking that the result is a point of the curve; on failure `r` is cleared. Constant /// time; the outcome of the check is not secret. +/// +/// The coordinates wipe themselves, but the compiler also spills limbs of them, and of the +/// inversion that normalizes the result, to stack slots no wipe in the source reaches, so the +/// computation runs in a frame of its own and the stack it used is overwritten afterwards. pub(super) fn scalar_mult_base_encoded( k: &[u8; 32], r: &mut [u8; 32], +) -> Result<(), ResultCheckFailed> { + let checked = scalar_mult_base_encoded_in_own_frame(k, r); + wipe_stack_below::(); + checked +} + +/// How much stack [`wipe_stack_below`] overwrites, in 64-bit words: 3072 bytes. The check of +/// `dev_scripts/ecdsa_stack_harness` passes with 2176 bytes wiped and fails with 2048 (rustc +/// 1.97, x86-64 release build; 2048 suffice with 1.88). The rest is room for a compiler that +/// lays the frames out less tightly. +const WIPED_STACK_WORDS: usize = 384; + +/// The computation of [`scalar_mult_base_encoded`]. Never inlined, so that what it spills lies +/// below its caller's frame, where [`wipe_stack_below`] reaches it. +#[inline(never)] +fn scalar_mult_base_encoded_in_own_frame( + k: &[u8; 32], + r: &mut [u8; 32], ) -> Result<(), ResultCheckFailed> { let mut p = PointAccum::default(); scalar_mult_base(k, &mut p); diff --git a/crypto/ec/src/ed/ed448/mod.rs b/crypto/ec/src/ed/ed448/mod.rs index b7dea66e8..da27dd799 100644 --- a/crypto/ec/src/ed/ed448/mod.rs +++ b/crypto/ec/src/ed/ed448/mod.rs @@ -175,9 +175,11 @@ //! [`Ed448PrivateKey::from_bytes_out`], `clone_from` and `encode_out` into a key or buffer you //! own where that matters. //! -//! Two computations would leave secrets on the stack that no `Secret` reaches. One is the last -//! step of signing, where the compiler spills limbs of the scalar it held in registers: it -//! runs in a frame of its own whose stack is overwritten afterwards. The other is every +//! Three computations would leave secrets on the stack that no `Secret` reaches. One is the last +//! step of signing, where the compiler spills limbs of the scalar it held in registers, and +//! another each fixed-base multiplication (key expansion's `[s]B`, signing's `[r]B`), which +//! spills limbs of the point's coordinates and of the inversion that normalizes them: each runs +//! in a frame of its own whose stack is overwritten afterwards. The third is every //! SHAKE256 over the private key or the prefix: a sponge that is moved to be squeezed leaves //! the private key and whole Keccak states of the prefix's hash behind, so each is finished //! where it sits, and `bouncycastle_digest::sha3` overwrites the frame of each Keccak permutation, diff --git a/crypto/ec/src/ed/ed448/point.rs b/crypto/ec/src/ed/ed448/point.rs index c22d92b91..8357d4f47 100644 --- a/crypto/ec/src/ed/ed448/point.rs +++ b/crypto/ec/src/ed/ed448/point.rs @@ -16,6 +16,7 @@ use super::precomp::{COMB_BASE, WNAF_BASE, WNAF_BASE_225}; use super::scalar::{self, SCALAR_LEN, SIGNED_DIGITS}; use crate::ed::curve448::{FieldElement448, NormalizedFieldElement448}; use crate::ed::wnaf; +use crate::stack_wipe::wipe_stack_below; use bouncycastle_utils::ct::Condition; use bouncycastle_utils::secret::Secret; @@ -369,9 +370,31 @@ pub(super) fn scalar_mult_base(k: &[u8; SCALAR_LEN], r: &mut PointProjective) { /// Writes the encoding of `[k]B` to `r`, for `k` as [`scalar_mult_base`] takes it, after /// checking that the result is a point of the curve; on failure `r` is cleared. Constant /// time; the outcome of the check is not secret. +/// +/// The coordinates wipe themselves, but the compiler also spills limbs of them, and of the +/// inversion that normalizes the result, to stack slots no wipe in the source reaches, so the +/// computation runs in a frame of its own and the stack it used is overwritten afterwards. pub(super) fn scalar_mult_base_encoded( k: &[u8; SCALAR_LEN], r: &mut [u8; POINT_LEN], +) -> Result<(), ResultCheckFailed> { + let checked = scalar_mult_base_encoded_in_own_frame(k, r); + wipe_stack_below::(); + checked +} + +/// How much stack [`wipe_stack_below`] overwrites, in 64-bit words: 4096 bytes. The check of +/// `dev_scripts/ecdsa_stack_harness` passes with 2816 bytes wiped and fails with 2752 (rustc +/// 1.97, x86-64 release build), and passes with 2944 and fails with 2816 with rustc 1.88. The +/// rest is room for a compiler that lays the frames out less tightly. +const WIPED_STACK_WORDS: usize = 512; + +/// The computation of [`scalar_mult_base_encoded`]. Never inlined, so that what it spills lies +/// below its caller's frame, where [`wipe_stack_below`] reaches it. +#[inline(never)] +fn scalar_mult_base_encoded_in_own_frame( + k: &[u8; SCALAR_LEN], + r: &mut [u8; POINT_LEN], ) -> Result<(), ResultCheckFailed> { let mut p = PointProjective::neutral(); scalar_mult_base(k, &mut p); From c8c74cfe31e694d05b08314d9f023253be2775b0 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 16:40:37 +1100 Subject: [PATCH 02/14] ec: Ed25519, Ed448, X25519 and X448 by-value keys built in wiped frames keygen, keygen_from_seed, the trait's from_bytes and clone build the key in a frame of their own whose stack is overwritten afterwards, as the ECDSA and ECC CDH keys do; the move out of that frame left whole copies of the private key, its digest, s and prefix behind. The Ed keygen wipe also covers the public key's decoding, so that two runs over different keys leave the same stack. Outputs are byte-identical; the ec tests, RFC 8032 / RFC 7748 vectors and Wycheproof suites pass. Assisted-by: Claude:claude-opus-5-5 --- crypto/ec/src/ed/ed25519/keys.rs | 43 +++++++++++++++++-------- crypto/ec/src/ed/ed25519/mod.rs | 4 ++- crypto/ec/src/ed/ed448/keys.rs | 43 +++++++++++++++++-------- crypto/ec/src/ed/ed448/mod.rs | 4 ++- crypto/ec/src/ed/x25519.rs | 55 +++++++++++++++++++------------- crypto/ec/src/ed/x448.rs | 54 ++++++++++++++++++------------- 6 files changed, 131 insertions(+), 72 deletions(-) diff --git a/crypto/ec/src/ed/ed25519/keys.rs b/crypto/ec/src/ed/ed25519/keys.rs index 39e1ce0e8..b355221b7 100644 --- a/crypto/ec/src/ed/ed25519/keys.rs +++ b/crypto/ec/src/ed/ed25519/keys.rs @@ -5,6 +5,7 @@ use super::point::PublicPoint; use super::scheme::{ self, CONTEXT_MAX_LEN, ExpandedKey, PREHASH_LEN, PRIVATE_KEY_LEN, PUBLIC_KEY_LEN, SIGNATURE_LEN, }; +use crate::stack_wipe::in_wiped_frame; use bouncycastle_core::errors::{KeyDecodingError, KeyMaterialError, RNGError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{ @@ -71,6 +72,19 @@ impl Algorithm for Ed25519ph { impl SignatureAlgorithm for Ed25519ph {} +/// What the stack wipe overwrites, in 64-bit words, after the trait's `from_bytes` and `clone` +/// build a key in a frame of their own, which the move out of it would otherwise leave holding +/// a copy: 512 bytes. `dev_scripts/ecdsa_stack_harness` passes with 192 bytes wiped and fails +/// with 128 (x86-64 release builds, rustc 1.97 and 1.88). +const BY_VALUE_STACK_WORDS: usize = 64; + +/// The same after [`keygen`], whose frame also decodes the public key: 3072 bytes. The harness +/// finds no copy of the key with 1024 bytes wiped, but the public key's decoding leaves values +/// that differ from key to key down to 2304 bytes below the call; they are public, and +/// wiping them too lets the harness compare two runs over different keys. It passes with +/// 2304 bytes and fails with 2048, measured the same way. +const KEYGEN_STACK_WORDS: usize = 384; + /// Generates a key pair from `rng`, which must offer Ed25519's 128 bits: the 32 octets it /// draws are the private key (RFC 8032 Section 5.1.5). /// @@ -81,14 +95,13 @@ impl SignatureAlgorithm for Ed25519ph {} /// [`SignatureError::RNGError`] if the RNG is weaker than the algorithm or fails to deliver; /// [`SignatureError::ComputationFault`] if the computed public key fails its check, which no input /// causes. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen(rng: &mut dyn RNG) -> Result<(Ed25519PublicKey, Ed25519PrivateKey), SignatureError> { - let mut sk = Ed25519PrivateKey::zeroized(); - keygen_out(rng, &mut sk)?; - let pk = sk.pk()?; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = Ed25519PrivateKey::zeroized(); + keygen_out(rng, &mut sk)?; + let pk = sk.pk()?; + Ok((pk, sk)) + }) } /// Generates a private key into `sk`, a key you hold: the RNG, which must offer Ed25519's 128 @@ -255,9 +268,11 @@ impl PrivateKey for Ed25519PrivateKey { /// [`KeyDecodingError`] if `bytes` is not 32 octets, or if the computed public key fails /// its check, which no input causes. fn from_bytes(bytes: &[u8]) -> Result { - let mut sk = Self::zeroized(); - Self::from_bytes_out(bytes, &mut sk)?; - Ok(sk) + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + Self::from_bytes_out(bytes, &mut sk)?; + Ok(sk) + }) } } @@ -265,9 +280,11 @@ impl PrivateKey for Ed25519PrivateKey { /// Considerations); `clone_from` copies field by field into a key you hold. impl Clone for Ed25519PrivateKey { fn clone(&self) -> Self { - let mut sk = Self::zeroized(); - sk.clone_from(self); - sk + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + sk.clone_from(self); + sk + }) } fn clone_from(&mut self, source: &Self) { diff --git a/crypto/ec/src/ed/ed25519/mod.rs b/crypto/ec/src/ed/ed25519/mod.rs index ac38342e2..ef3c2f9ff 100644 --- a/crypto/ec/src/ed/ed25519/mod.rs +++ b/crypto/ec/src/ed/ed25519/mod.rs @@ -163,7 +163,9 @@ //! not wipe its source: that holds for the key pair of [`keygen`], for the trait's `from_bytes`, //! for `clone` and for the array `encode` returns. Use [`keygen_out`], //! [`Ed25519PrivateKey::from_bytes_out`], `clone_from` and `encode_out` into a key or buffer you -//! own where that matters. Signing also overwrites the stack its last step used, where the +//! own where that matters. [`keygen`], `from_bytes` and `clone` build the key in a frame of their +//! own whose stack is overwritten afterwards, so the copies left are those of the caller's +//! moves, not of theirs. Signing also overwrites the stack its last step used, where the //! compiler otherwise leaves limbs of the scalar it held in registers, and each fixed-base //! multiplication (key expansion's `[s]B`, signing's `[r]B`) the stack it used, where it leaves //! limbs of the point's coordinates and of the inversion that normalizes them; a scan of the diff --git a/crypto/ec/src/ed/ed448/keys.rs b/crypto/ec/src/ed/ed448/keys.rs index f177f0f9b..b05fde1f9 100644 --- a/crypto/ec/src/ed/ed448/keys.rs +++ b/crypto/ec/src/ed/ed448/keys.rs @@ -5,6 +5,7 @@ use super::point::PublicPoint; use super::scheme::{ self, CONTEXT_MAX_LEN, ExpandedKey, PREHASH_LEN, PRIVATE_KEY_LEN, PUBLIC_KEY_LEN, SIGNATURE_LEN, }; +use crate::stack_wipe::in_wiped_frame; use bouncycastle_core::errors::{KeyDecodingError, KeyMaterialError, RNGError, SignatureError}; use bouncycastle_core::security_strength::SecurityStrength; use bouncycastle_core::signature_key::{ @@ -75,6 +76,19 @@ impl Algorithm for Ed448ph { impl SignatureAlgorithm for Ed448ph {} +/// What the stack wipe overwrites, in 64-bit words, after the trait's `from_bytes` and `clone` +/// build a key in a frame of their own, which the move out of it would otherwise leave holding +/// a copy: 768 bytes. `dev_scripts/ecdsa_stack_harness` passes with 256 bytes wiped and fails +/// with 192 (x86-64 release builds, rustc 1.97 and 1.88). +const BY_VALUE_STACK_WORDS: usize = 96; + +/// The same after [`keygen`], whose frame also decodes the public key: 5120 bytes. The harness +/// finds no copy of the key with 1024 bytes wiped, but the public key's decoding leaves values +/// that differ from key to key down to 4096 bytes below the call; they are public, and +/// wiping them too lets the harness compare two runs over different keys. It passes with +/// 4096 bytes and fails with 3584, measured the same way. +const KEYGEN_STACK_WORDS: usize = 640; + /// Generates a key pair from `rng`, which must offer the 192 bits Ed448 is classed at: the 57 /// octets it draws are the private key (RFC 8032 Section 5.2.5). /// @@ -86,14 +100,13 @@ impl SignatureAlgorithm for Ed448ph {} /// [`SignatureError::ComputationFault`] if the computed public key fails its check, which no input /// causes; [`SignatureError::KeyGenError`] if the octets drawn are a private key this module /// refuses ([`Ed448PrivateKey`]), which is not known to happen. The generation is not retried. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen(rng: &mut dyn RNG) -> Result<(Ed448PublicKey, Ed448PrivateKey), SignatureError> { - let mut sk = Ed448PrivateKey::zeroized(); - keygen_out(rng, &mut sk)?; - let pk = sk.pk()?; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = Ed448PrivateKey::zeroized(); + keygen_out(rng, &mut sk)?; + let pk = sk.pk()?; + Ok((pk, sk)) + }) } /// Generates a private key into `sk`, a key you hold: the RNG, which must offer the 192 bits @@ -272,9 +285,11 @@ impl PrivateKey for Ed448PrivateKey { /// (see the type), which no known octets are; or if the computed public key fails its /// check, which no input causes. fn from_bytes(bytes: &[u8]) -> Result { - let mut sk = Self::zeroized(); - Self::from_bytes_out(bytes, &mut sk)?; - Ok(sk) + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + Self::from_bytes_out(bytes, &mut sk)?; + Ok(sk) + }) } } @@ -282,9 +297,11 @@ impl PrivateKey for Ed448PrivateKey { /// Considerations); `clone_from` copies field by field into a key you hold. impl Clone for Ed448PrivateKey { fn clone(&self) -> Self { - let mut sk = Self::zeroized(); - sk.clone_from(self); - sk + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + sk.clone_from(self); + sk + }) } fn clone_from(&mut self, source: &Self) { diff --git a/crypto/ec/src/ed/ed448/mod.rs b/crypto/ec/src/ed/ed448/mod.rs index da27dd799..235b92f9f 100644 --- a/crypto/ec/src/ed/ed448/mod.rs +++ b/crypto/ec/src/ed/ed448/mod.rs @@ -173,7 +173,9 @@ //! not wipe its source: that holds for the key pair of [`keygen`], for the trait's `from_bytes`, //! for `clone` and for the array `encode` returns. Use [`keygen_out`], //! [`Ed448PrivateKey::from_bytes_out`], `clone_from` and `encode_out` into a key or buffer you -//! own where that matters. +//! own where that matters. [`keygen`], `from_bytes` and `clone` build the key in a frame of their +//! own whose stack is overwritten afterwards, so the copies left are those of the caller's +//! moves, not of theirs. //! //! Three computations would leave secrets on the stack that no `Secret` reaches. One is the last //! step of signing, where the compiler spills limbs of the scalar it held in registers, and diff --git a/crypto/ec/src/ed/x25519.rs b/crypto/ec/src/ed/x25519.rs index d61de9ce3..17e11daf1 100644 --- a/crypto/ec/src/ed/x25519.rs +++ b/crypto/ec/src/ed/x25519.rs @@ -172,8 +172,10 @@ //! trait's `from_bytes` and `DeriveKeyPair`, for `clone`, for the clamped scalar `encode` //! returns, and for the results of `core`'s by-value `agree`, `encaps` and `decaps`. Use the //! `_out` forms, [`X25519PrivateKey::from_bytes_out`] and `clone_from`, into a buffer or key you -//! own where that matters. What HKDF's own frames keep is in `crate::dhkem`'s Security -//! Considerations. +//! own where that matters. [`keygen`], [`keygen_from_seed`], `from_bytes` and `clone` build the +//! key in a frame of their own whose stack is overwritten afterwards, so the copies left are +//! those of the caller's moves, not of theirs. What HKDF's own frames keep is in +//! `crate::dhkem`'s Security Considerations. //! //! These wipes are made in the source, and a copy the compiler makes on its own is beyond them. //! A stack probe of this module found, below the frame after every operation that multiplies by @@ -216,6 +218,7 @@ use bouncycastle_utils::secret::{Secret, zeroize_in_place}; use core::fmt::{self, Display, Formatter}; use crate::ed::curve25519::FieldElement25519; +use crate::stack_wipe::in_wiped_frame; // Only the field arithmetic (`FieldElement25519` in curve25519.rs) is shared with Ed25519. The // scalar and point types below are X25519's own: an Ed25519 scalar is reduced mod the group order @@ -271,6 +274,12 @@ impl AlgorithmOID for X25519 { const OID_DER: &'static [u8] = &[0x06, 0x03, 0x2B, 0x65, 0x6E]; } +/// What the stack wipe overwrites, in 64-bit words, after [`keygen`], [`keygen_from_seed`], the +/// trait's `from_bytes` and `clone` build a key in a frame of their own, which the move out of +/// it would otherwise leave holding a copy: 512 bytes. `dev_scripts/ecdsa_stack_harness` passes +/// with 192 bytes wiped and fails with 128 (x86-64 release builds, rustc 1.97 and 1.88). +const BY_VALUE_STACK_WORDS: usize = 64; + /// Generates a key pair from `rng`, which must offer X25519's 128 bits: the 32 bytes it draws /// are the private key (RFC 7748 Section 6.1: "Alice generates 32 random bytes in a\[0\] to /// a\[31\]"). @@ -280,14 +289,13 @@ impl AlgorithmOID for X25519 { /// /// # Errors /// [`KeyAgreementError::RNGError`] if the RNG is weaker than the algorithm or fails to deliver. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen(rng: &mut dyn RNG) -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { - let mut sk = X25519PrivateKey::zeroized(); - keygen_out(rng, &mut sk)?; - let pk = sk.pk; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = X25519PrivateKey::zeroized(); + keygen_out(rng, &mut sk)?; + let pk = sk.pk; + Ok((pk, sk)) + }) } /// Generates a private key into `sk`, a key you hold: the RNG, which must offer X25519's 128 @@ -322,16 +330,15 @@ pub fn keygen_out(rng: &mut dyn RNG, sk: &mut X25519PrivateKey) -> Result<(), Ke /// # Errors /// [`KeyAgreementError::KeyMaterialError`] for a seed of another type or length, or of too /// little strength. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen_from_seed( seed: &KeyMaterial256, ) -> Result<(X25519PublicKey, X25519PrivateKey), KeyAgreementError> { - let mut sk = X25519PrivateKey::zeroized(); - keygen_from_seed_out(seed, &mut sk)?; - let pk = sk.pk; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = X25519PrivateKey::zeroized(); + keygen_from_seed_out(seed, &mut sk)?; + let pk = sk.pk; + Ok((pk, sk)) + }) } /// The private key whose scalar is `seed`'s 32 bytes, into `sk`, a key you hold: the seed's @@ -656,9 +663,11 @@ impl PrivateKey for X25519PrivateKey { /// /// [`KeyDecodingError`] if `bytes` is not 32 bytes. fn from_bytes(bytes: &[u8]) -> Result { - let mut sk = Self::zeroized(); - Self::from_bytes_out(bytes, &mut sk)?; - Ok(sk) + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + Self::from_bytes_out(bytes, &mut sk)?; + Ok(sk) + }) } } @@ -666,9 +675,11 @@ impl PrivateKey for X25519PrivateKey { /// Considerations); `clone_from` copies field by field into a key you hold. impl Clone for X25519PrivateKey { fn clone(&self) -> Self { - let mut sk = Self::zeroized(); - sk.clone_from(self); - sk + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + sk.clone_from(self); + sk + }) } fn clone_from(&mut self, source: &Self) { diff --git a/crypto/ec/src/ed/x448.rs b/crypto/ec/src/ed/x448.rs index d32bf7b6d..8ac7625a8 100644 --- a/crypto/ec/src/ed/x448.rs +++ b/crypto/ec/src/ed/x448.rs @@ -171,7 +171,9 @@ //! `DeriveKeyPair`, for `clone`, for the clamped scalar `encode` returns, and for the results //! of `core`'s by-value `agree`, `encaps` and `decaps`. Use the `_out` forms, //! [`X448PrivateKey::from_bytes_out`] and `clone_from`, into a buffer or key you own where that -//! matters. +//! matters. [`keygen`], [`keygen_from_seed`], `from_bytes` and `clone` build the key in a frame +//! of their own whose stack is overwritten afterwards, so the copies left are those of the +//! caller's moves, not of theirs. //! //! These wipes are made in the source, and a copy the compiler makes on its own is beyond them. //! A stack probe of this module (one release build, x86-64) found register spills left below @@ -195,7 +197,7 @@ use crate::dhkem::{ AuthDecapsulatingKey, AuthEncapsulatingKey, DHKEM, DHKEMParams, DeriveKeyPairForm, HpkeKem, }; -use crate::stack_wipe::wipe_stack_below; +use crate::stack_wipe::{in_wiped_frame, wipe_stack_below}; use bouncycastle_core::agreement_key::{AgreementKey, KeyAgreementAlgorithm}; use bouncycastle_core::errors::{ KEMError, KeyAgreementError, KeyDecodingError, KeyMaterialError, RNGError, @@ -264,6 +266,12 @@ impl AlgorithmOID for X448 { const OID_DER: &'static [u8] = &[0x06, 0x03, 0x2B, 0x65, 0x6F]; } +/// What the stack wipe overwrites, in 64-bit words, after [`keygen`], [`keygen_from_seed`], the +/// trait's `from_bytes` and `clone` build a key in a frame of their own, which the move out of +/// it would otherwise leave holding a copy: 1024 bytes. `dev_scripts/ecdsa_stack_harness` passes +/// with 320 bytes wiped and fails with 256 (x86-64 release builds, rustc 1.97 and 1.88). +const BY_VALUE_STACK_WORDS: usize = 128; + /// Generates a key pair from `rng`, which must offer X448's 192 bits: the 56 bytes it draws are /// the private key (RFC 7748 Section 6.2: "Alice and Bob generate 56 random bytes"). /// @@ -272,14 +280,13 @@ impl AlgorithmOID for X448 { /// /// # Errors /// [`KeyAgreementError::RNGError`] if the RNG is weaker than the algorithm or fails to deliver. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen(rng: &mut dyn RNG) -> Result<(X448PublicKey, X448PrivateKey), KeyAgreementError> { - let mut sk = X448PrivateKey::zeroized(); - keygen_out(rng, &mut sk)?; - let pk = sk.pk; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = X448PrivateKey::zeroized(); + keygen_out(rng, &mut sk)?; + let pk = sk.pk; + Ok((pk, sk)) + }) } /// Generates a private key into `sk`, a key you hold: the RNG, which must offer X448's 192 bits, @@ -314,16 +321,15 @@ pub fn keygen_out(rng: &mut dyn RNG, sk: &mut X448PrivateKey) -> Result<(), KeyA /// # Errors /// [`KeyAgreementError::KeyMaterialError`] for a seed of another type or length, or of too /// little strength. -// Inlined so that the key is built in the caller's frame and moved into the pair once; out of -// line, LLVM stages a further copy of it, which the stack harness's keygen rows show. -#[inline(always)] pub fn keygen_from_seed( seed: &KeyMaterial, ) -> Result<(X448PublicKey, X448PrivateKey), KeyAgreementError> { - let mut sk = X448PrivateKey::zeroized(); - keygen_from_seed_out(seed, &mut sk)?; - let pk = sk.pk; - Ok((pk, sk)) + in_wiped_frame::(|| { + let mut sk = X448PrivateKey::zeroized(); + keygen_from_seed_out(seed, &mut sk)?; + let pk = sk.pk; + Ok((pk, sk)) + }) } /// The private key whose scalar is `seed`'s 56 bytes, into `sk`, a key you hold: the seed's @@ -662,9 +668,11 @@ impl PrivateKey for X448PrivateKey { /// /// [`KeyDecodingError`] if `bytes` is not 56 bytes. fn from_bytes(bytes: &[u8]) -> Result { - let mut sk = Self::zeroized(); - Self::from_bytes_out(bytes, &mut sk)?; - Ok(sk) + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + Self::from_bytes_out(bytes, &mut sk)?; + Ok(sk) + }) } } @@ -672,9 +680,11 @@ impl PrivateKey for X448PrivateKey { /// Considerations); `clone_from` copies field by field into a key you hold. impl Clone for X448PrivateKey { fn clone(&self) -> Self { - let mut sk = Self::zeroized(); - sk.clone_from(self); - sk + in_wiped_frame::(|| { + let mut sk = Self::zeroized(); + sk.clone_from(self); + sk + }) } fn clone_from(&mut self, source: &Self) { From 6f6181f014cb1e9c9c32eb43b27d26a82f9624de Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 16:44:15 +1100 Subject: [PATCH 03/14] ci: check_ecdsa_stack.sh covers Ed25519, Ed448, X25519 and X448 The ECDSA stack harness gains an ed module: EdDSA key generation, decoding, copies, encodings, pk and every form of signing (one-shots, pre-hash one-shots and streaming final), and X25519 and X448 keys and agreement, searched for the private key, its digest, s, prefix, the nonce digest, r and K, each checked against a real output (RFC 8032 and RFC 7748 vectors, S = r + k s mod L, encode == seed, the peer's K), and compared over two keys. X25519's scalar-multiplication residue is reported as left, by decision. 792 ok on rustc 1.97 and 1.88; with the ed wipes zeroed, 61 rows fail on both. CLAUDE.md names the constants. Assisted-by: Claude:claude-opus-5-5 --- .gitea/workflows/ecdsa-stack.yml | 2 +- .github/workflows/ecdsa-stack.yml | 2 +- CLAUDE.md | 15 +- dev_scripts/check_ecdsa_stack.sh | 18 +- dev_scripts/ecdsa_stack_harness/Cargo.toml | 7 +- dev_scripts/ecdsa_stack_harness/src/ed.rs | 934 ++++++++++++++++++++ dev_scripts/ecdsa_stack_harness/src/main.rs | 20 +- 7 files changed, 977 insertions(+), 21 deletions(-) create mode 100644 dev_scripts/ecdsa_stack_harness/src/ed.rs diff --git a/.gitea/workflows/ecdsa-stack.yml b/.gitea/workflows/ecdsa-stack.yml index b2c5101c3..5fa4d4d5d 100644 --- a/.gitea/workflows/ecdsa-stack.yml +++ b/.gitea/workflows/ecdsa-stack.yml @@ -29,5 +29,5 @@ jobs: rustup toolchain install stable --profile minimal rustup default stable - - name: Search the stack ECDSA signing and EC key handling used for what they handled + - name: Search the stack ECDSA, ECC CDH, DHKEM and EdDSA/XDH used for what they handled run: ./dev_scripts/check_ecdsa_stack.sh diff --git a/.github/workflows/ecdsa-stack.yml b/.github/workflows/ecdsa-stack.yml index 3d2f58c4d..7c338d521 100644 --- a/.github/workflows/ecdsa-stack.yml +++ b/.github/workflows/ecdsa-stack.yml @@ -27,5 +27,5 @@ jobs: - name: Install Rust toolchain uses: dtolnay/rust-toolchain@stable - - name: Search the stack ECDSA, ECC CDH and DHKEM used for what they handled + - name: Search the stack ECDSA, ECC CDH, DHKEM and EdDSA/XDH used for what they handled run: ./dev_scripts/check_ecdsa_stack.sh diff --git a/CLAUDE.md b/CLAUDE.md index 44772ea1e..949b9b1cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -549,12 +549,17 @@ Eleven workflows under `.github/workflows/`, all triggered by pull requests: - `ecdsa-stack.yml`: `dev_scripts/check_ecdsa_stack.sh`, the same shape and matrix over `dev_scripts/ecdsa_stack_harness`, which runs ECDSA's and ECC CDH's key decoding, encoding, generation and `derive_pk`, the drawing of `k`, the one-shots and the signers' finals, on all seven curves, ECC CDH's agreement - (raw and through its KDFs), and DHKEM over the NIST curves and X448 with its labeled HKDF steps (X25519's DHKEM - is reported, not failed), searching for the keys, `k`, the RNG's output, the DH products and the derived secrets - and comparing two runs over different keys. Its wipes scale with the curve's limb count: re-measure - `DECODE_STACK_*`, `ENCODE_STACK_*`, `DERIVE_STACK_*`, `AGREE_STACK_*` and `KEYGEN_STACK_*` in + (raw and through its KDFs), DHKEM over the NIST curves and X448 with its labeled HKDF steps, and, in its `ed` + module, Ed25519's and Ed448's key generation, decoding, copies, encodings and every form of signing and X25519's + and X448's keys and agreement (X25519's DHKEM, and the comparison of its scalar multiplications, are reported, + not failed), searching for the keys, `k` or EdDSA's `r` and prefix, the RNG's output, the DH products and the + derived secrets and comparing two runs over different keys. Its wipes scale with the curve's limb count: + re-measure `DECODE_STACK_*`, `ENCODE_STACK_*`, `DERIVE_STACK_*`, `AGREE_STACK_*` and `KEYGEN_STACK_*` in `crypto/ec/src/curve.rs`, `SIGN_STACK_*` in `crypto/ec/src/ecdsa/ecdsa.rs`, and the fixed - `LABELED_STACK_WORDS` and `DERIVE_KEY_PAIR_STACK_WORDS` in `crypto/ec/src/dhkem/`. + `LABELED_STACK_WORDS` and `DERIVE_KEY_PAIR_STACK_WORDS` in `crypto/ec/src/dhkem/`, `WIPED_STACK_WORDS` in + `crypto/ec/src/ed/{ed25519,ed448}/{point,scalar}.rs` and `x448.rs`, `BY_VALUE_STACK_WORDS` in + `crypto/ec/src/ed/{ed25519,ed448}/keys.rs`, `x25519.rs` and `x448.rs`, and `KEYGEN_STACK_WORDS` in the two + `keys.rs`. - `publish_doc_benches_to_ghpages.yaml`: builds rustdoc and runs `quality_stats.sh`; on `main` it also publishes docs and code stats to GitHub Pages (`https://bcgit.github.io/bc-rust/`). Its bench step is commented out because the benches are too slow on the hosted runner, so benchmark figures come from a diff --git a/dev_scripts/check_ecdsa_stack.sh b/dev_scripts/check_ecdsa_stack.sh index f00099439..3750a534c 100755 --- a/dev_scripts/check_ecdsa_stack.sh +++ b/dev_scripts/check_ecdsa_stack.sh @@ -1,17 +1,23 @@ #!/usr/bin/env bash # Checks that ECDSA signing and the handling of its private keys (bouncycastle_ec::ecdsa), ECC -# CDH's private keys and agreement (bouncycastle_ec::eccdh), and DHKEM over the NIST curves and -# X448 with its labeled HKDF steps (bouncycastle_ec::dhkem) leave nothing of what they handled on -# the stack they used, over each of the seven curves, over dev_scripts/ecdsa_stack_harness: for -# each operation it paints the stack, runs the operation, copies the dead stack out and searches +# CDH's private keys and agreement (bouncycastle_ec::eccdh), DHKEM over the NIST curves and +# X448 with its labeled HKDF steps (bouncycastle_ec::dhkem), and Ed25519, Ed448, X25519 and X448 +# (bouncycastle_ec::ed) leave nothing of what they handled on the stack they used, the first two +# over each of the seven curves, over dev_scripts/ecdsa_stack_harness: for each operation it +# paints the stack, runs the operation, copies the dead stack out and searches # the copy for the words of every secret the operation handled (the private keys, the RNG's # output, k, the Diffie-Hellman products, the DHKEM's PRK and shared secret and what a KDF # derived, as bytes and as limbs). The operations are the decoding, encoding, copying, # re-pairing and generation of a private key and the derivation of its public key, the drawing # of k (create_signer), the random and the deterministic one-shots and the streaming finals, the # agreement, and the DHKEM's private-key decoding, DeriveKeyPair, Encap, Decap, AuthEncap and -# AuthDecap. DHKEM over X25519 is run and reported, and does not fail the check: its scalar -# multiplication leaves part of its field inversion, by decision. +# AuthDecap. EdDSA's keys are generated, decoded, copied and encoded, their public keys read, and +# each signs through the one-shots and the pre-hash variant's streaming final, searched for the +# private key, its digest, s, prefix, the digest of the nonce and r; X25519's and X448's keys go +# through the same and agree, searched for the key as given and clamped and for K. DHKEM over +# X25519, and the comparison of two runs of X25519's scalar multiplications, are run and +# reported, and do not fail the check: its scalar multiplication leaves part of its field +# inversion, by decision. # # Each operation is also run twice at the same addresses over different secrets (two keys, two # draws of the RNG), and the two copies of the stack compared: but for the signature, the public diff --git a/dev_scripts/ecdsa_stack_harness/Cargo.toml b/dev_scripts/ecdsa_stack_harness/Cargo.toml index 2b3e015d8..17cdc6955 100644 --- a/dev_scripts/ecdsa_stack_harness/Cargo.toml +++ b/dev_scripts/ecdsa_stack_harness/Cargo.toml @@ -1,7 +1,8 @@ # ECDSA signing and the handling of its private keys (bouncycastle_ec::ecdsa), ECC CDH's private -# keys and agreement (bouncycastle_ec::eccdh) and DHKEM (bouncycastle_ec::dhkem), each run over a -# painted stack that is then searched for what the operation handled, for `../check_ecdsa_stack.sh`. Its own workspace, -# so the root `cargo build --workspace` never builds it. +# keys and agreement (bouncycastle_ec::eccdh), DHKEM (bouncycastle_ec::dhkem) and Ed25519, Ed448, +# X25519 and X448 (bouncycastle_ec::ed), each run over a painted stack that is then searched for +# what the operation handled, for `../check_ecdsa_stack.sh`. Its own workspace, so the root +# `cargo build --workspace` never builds it. [package] name = "ecdsa_stack_harness" version = "0.0.0" diff --git a/dev_scripts/ecdsa_stack_harness/src/ed.rs b/dev_scripts/ecdsa_stack_harness/src/ed.rs new file mode 100644 index 000000000..333101398 --- /dev/null +++ b/dev_scripts/ecdsa_stack_harness/src/ed.rs @@ -0,0 +1,934 @@ +//! Ed25519 and Ed448 (`bouncycastle_ec::ed::{ed25519, ed448}`), and X25519 and X448 agreement +//! (`bouncycastle_ec::ed::{x25519, x448}`), run over the painted stack as the rest of the harness +//! runs ECDSA. An EdDSA key is searched for its private key, the digest it is expanded from and +//! the scalar `s` and `prefix` taken from that, and a signature also for the digest of step 2 and +//! the nonce `r` (RFC 8032 Sections 5.1.6 and 5.2.6), each computed here and checked against the +//! signature, `S = r + k s mod L`, before it is searched for. An X25519 or X448 key is searched +//! for its bytes as given and clamped, and an agreement also for `K`. +use crate::{Scan, Values, bytes_of, message, rng_of}; +use bouncycastle_core::agreement_key::AgreementKey; +use bouncycastle_core::errors::{KeyAgreementError, KeyDecodingError, SignatureError}; +use bouncycastle_core::key_material::{KeyMaterial, KeyMaterialTrait, KeyType}; +use bouncycastle_core::signature_key::{ + DeterministicOneShotSigningKey, DeterministicSigningKey, OneShotVerifyingKey, +}; +use bouncycastle_core::traits::{ + Hash, PrivateKey, PublicKey, RNG, SignatureSigner, Suspendable, XOF, XOFSqueezer, +}; +use bouncycastle_digest::sha2::SHA512; +use bouncycastle_digest::sha3::SHAKE256; +use bouncycastle_ec::ed::ed448::{self, Ed448, Ed448PrivateKey, Ed448PublicKey, Ed448ph}; +use bouncycastle_ec::ed::ed25519::{self, Ed25519, Ed25519PrivateKey, Ed25519PublicKey, Ed25519ph}; +use bouncycastle_ec::ed::x448::{self, X448PrivateKey, X448PublicKey}; +use bouncycastle_ec::ed::x25519::{self, X25519PrivateKey, X25519PublicKey}; + +/// Hexadecimal, for the RFC vectors. +fn hex(s: &str) -> Vec { + (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect() +} + +/// A value as a SHA-512 state or message schedule holds it: 64-bit big-endian words, each in +/// the other byte order in memory. +fn word_swapped(bytes: &[u8]) -> Vec { + bytes.chunks(8).flat_map(|w| w.iter().rev().copied()).collect() +} + +/// The little-endian integer `le` as `count` limbs of `bits` bits, each in a 64-bit word: a +/// field element of the curve25519 (51) or curve448 (56) arithmetic. +fn radix_limbs(le: &[u8], bits: usize, count: usize) -> Vec { + let bit = |i: usize| i / 8 < le.len() && le[i / 8] >> (i % 8) & 1 == 1; + (0..count) + .flat_map(|l| { + let limb = (0..bits).fold(0u64, |acc, j| acc | (u64::from(bit(l * bits + j)) << j)); + limb.to_le_bytes() + }) + .collect() +} + +/// Unsigned integers as 32-bit limbs, least significant first: only what the checks need. +type Big = Vec; + +fn big(le: &[u8]) -> Big { + let mut b: Big = le + .chunks(4) + .map(|c| c.iter().rev().fold(0u32, |acc, byte| acc << 8 | u32::from(*byte))) + .collect(); + trim(&mut b); + b +} + +fn trim(b: &mut Big) { + while b.last() == Some(&0) { + b.pop(); + } +} + +fn le_bytes(b: &Big, len: usize) -> Vec { + let mut out: Vec = b.iter().flat_map(|l| l.to_le_bytes()).collect(); + assert!(out.iter().skip(len).all(|byte| *byte == 0)); + out.resize(len, 0); + out +} + +fn big_cmp(a: &Big, b: &Big) -> std::cmp::Ordering { + a.len().cmp(&b.len()).then_with(|| a.iter().rev().cmp(b.iter().rev())) +} + +fn big_add(a: &Big, b: &Big) -> Big { + let mut out = Big::new(); + let mut carry = 0u64; + for i in 0..a.len().max(b.len()) { + let sum = u64::from(*a.get(i).unwrap_or(&0)) + u64::from(*b.get(i).unwrap_or(&0)) + carry; + out.push(sum as u32); + carry = sum >> 32; + } + out.push(carry as u32); + trim(&mut out); + out +} + +/// `a - b`, for `a >= b`. +fn big_sub(a: &Big, b: &Big) -> Big { + let mut out = Big::new(); + let mut borrow = 0i64; + for i in 0..a.len() { + let diff = i64::from(a[i]) - i64::from(*b.get(i).unwrap_or(&0)) - borrow; + out.push(diff.rem_euclid(1 << 32) as u32); + borrow = i64::from(diff < 0); + } + assert_eq!(borrow, 0); + trim(&mut out); + out +} + +fn big_mul(a: &Big, b: &Big) -> Big { + let mut out = vec![0u32; a.len() + b.len() + 1]; + for (i, x) in a.iter().enumerate() { + let mut carry = 0u64; + for (j, y) in b.iter().enumerate() { + let t = u64::from(*x) * u64::from(*y) + u64::from(out[i + j]) + carry; + out[i + j] = t as u32; + carry = t >> 32; + } + out[i + b.len()] = carry as u32; + } + trim(&mut out); + out +} + +/// `a mod m`, a bit at a time. +fn big_mod(a: &Big, m: &Big) -> Big { + let mut r = Big::new(); + for i in (0..32 * a.len()).rev() { + r = big_add(&r, &r); + if a[i / 32] >> (i % 32) & 1 == 1 { + r = big_add(&r, &vec![1]); + } + if big_cmp(&r, m).is_ge() { + r = big_sub(&r, m); + } + } + r +} + +fn big_dec(s: &str) -> Big { + s.bytes() + .fold(Big::new(), |acc, d| big_add(&big_mul(&acc, &vec![10]), &vec![u32::from(d - b'0')])) +} + +fn big_pow2(e: usize) -> Big { + let mut b = vec![0u32; e / 32 + 1]; + b[e / 32] = 1 << (e % 32); + b +} + +/// What the harness needs of an EdDSA scheme over and above the key traits: its keys' +/// inherent functions and roles, and the reference computation of RFC 8032. +pub(crate) trait EdScheme: + PrivateKey + Clone + PartialEq +{ + type Pk: PublicKey; + const NAME: &'static str; + /// The length of the scalar and of the prefix. + const HALF: usize; + /// The bits of a field element's limbs, and how many there are. + const LIMB_BITS: usize; + const LIMBS: usize; + /// RFC 8032's first test vector of the scheme: private key, public key, message, context, + /// signature. + const VECTOR: [&'static str; 5]; + /// The context the scheme itself signs with: none for Ed25519 (RFC 8032 Section 5.1). + const CONTEXT: &'static [u8]; + + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), SignatureError>; + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), SignatureError>; + fn zeroized() -> Self; + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError>; + fn pk(&self) -> Self::Pk; + fn consistent(pk: &Self::Pk, sk: &Self) -> bool; + fn sign_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; SIG]) -> usize; + fn sign(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; SIG]; + fn sign_ph_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; SIG]) -> usize; + fn sign_ph(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; SIG]; + fn ph_signer<'a>(&'a self, ctx: Option<&[u8]>) -> Box + 'a>; + fn verifies(pk: &Self::Pk, msg: &[u8], ctx: Option<&[u8]>, sig: &[u8], ph: bool) -> bool; + + /// `H(x)` of the scheme, over the concatenation of `parts`, without `dom`. + fn hash(parts: &[&[u8]]) -> Vec; + /// The images of a digest as the hash holds it. + fn digest_images(name: &str, digest: &[u8], values: &mut Values); + /// The chaining values the hash passes through over `input`, as they lie in memory. + fn chaining_values(input: &[u8]) -> Vec; + /// `PH(M)` of the pre-hash variant. + fn prehash(msg: &[u8]) -> Vec; + /// `dom2(F, C)` or `dom4(F, C)`. + fn dom(ph: bool, ctx: &[u8]) -> Vec; + /// RFC 8032 Section 5.1.5 or 5.2.5, step 2. + fn prune(s: &mut [u8]); + fn order() -> Big; +} + +impl EdScheme<32, 32, 64> for Ed25519PrivateKey { + type Pk = Ed25519PublicKey; + const NAME: &'static str = "Ed25519"; + const HALF: usize = 32; + const LIMB_BITS: usize = 51; + const LIMBS: usize = 5; + const CONTEXT: &'static [u8] = b""; + // RFC 8032 Section 7.1, TEST 1. + const VECTOR: [&'static str; 5] = [ + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + "", + "", + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bac\ + c61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + ]; + + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), SignatureError> { + ed25519::keygen(rng) + } + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), SignatureError> { + ed25519::keygen_out(rng, sk) + } + fn zeroized() -> Self { + Ed25519PrivateKey::zeroized() + } + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError> { + Ed25519PrivateKey::from_bytes_out(bytes, sk) + } + fn pk(&self) -> Self::Pk { + Ed25519PrivateKey::pk(self).unwrap() + } + fn consistent(pk: &Self::Pk, sk: &Self) -> bool { + ed25519::keypair_consistency_check(pk, sk).is_ok() + } + fn sign_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; 64]) -> usize { + DeterministicOneShotSigningKey::::sign_deterministic_out(self, msg, ctx, sig) + .unwrap() + } + fn sign(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; 64] { + DeterministicOneShotSigningKey::::sign_deterministic(self, msg, ctx).unwrap() + } + fn sign_ph_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; 64]) -> usize { + DeterministicOneShotSigningKey::::sign_deterministic_out( + &self.as_prehash(), + msg, + ctx, + sig, + ) + .unwrap() + } + fn sign_ph(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; 64] { + DeterministicOneShotSigningKey::::sign_deterministic( + &self.as_prehash(), + msg, + ctx, + ) + .unwrap() + } + fn ph_signer<'a>(&'a self, ctx: Option<&[u8]>) -> Box + 'a> { + Box::new(self.as_prehash().create_signer_deterministic(ctx).unwrap()) + } + fn verifies(pk: &Self::Pk, msg: &[u8], ctx: Option<&[u8]>, sig: &[u8], ph: bool) -> bool { + if ph { + OneShotVerifyingKey::::verify(&pk.as_prehash(), msg, ctx, sig).is_ok() + } else { + OneShotVerifyingKey::::verify(pk, msg, ctx, sig).is_ok() + } + } + + fn hash(parts: &[&[u8]]) -> Vec { + let mut hash = SHA512::default(); + for part in parts { + hash.do_update(part); + } + let mut digest = vec![0u8; 64]; + hash.do_final_out(&mut digest); + digest + } + fn digest_images(name: &str, digest: &[u8], values: &mut Values) { + values.push((name.to_string(), digest.to_vec())); + values.push((format!("{name} (SHA-512 state)"), word_swapped(digest))); + } + fn chaining_values(input: &[u8]) -> Vec { + // After each whole block but the last, from the suspended state: after its three-byte + // version prefix, the state words in little-endian order. + (1..input.len().div_ceil(128)) + .flat_map(|blocks| { + let mut hash = SHA512::default(); + hash.do_update(&input[..128 * blocks]); + hash.suspend()[3..3 + 64].to_vec() + }) + .collect() + } + fn prehash(msg: &[u8]) -> Vec { + Self::hash(&[msg]) + } + fn dom(ph: bool, ctx: &[u8]) -> Vec { + // RFC 8032 Section 2: dom2 is blank for Ed25519, and for Ed25519ph "SigEd25519 no + // Ed25519 collisions" || octet(x) || octet(OLEN(y)) || y. + if ph { + [b"SigEd25519 no Ed25519 collisions".as_slice(), &[1, ctx.len() as u8], ctx].concat() + } else { + Vec::new() + } + } + fn prune(s: &mut [u8]) { + // RFC 8032 Section 5.1.5, step 2. + s[0] &= 0xF8; + s[31] &= 0x7F; + s[31] |= 0x40; + } + fn order() -> Big { + // RFC 8032 Section 5.1, Table 1. + big_add(&big_pow2(252), &big_dec("27742317777372353535851937790883648493")) + } +} + +impl EdScheme<57, 57, 114> for Ed448PrivateKey { + type Pk = Ed448PublicKey; + const NAME: &'static str = "Ed448"; + const HALF: usize = 57; + const LIMB_BITS: usize = 56; + const LIMBS: usize = 8; + const CONTEXT: &'static [u8] = b"stack harness"; + // RFC 8032 Section 7.4, "1 octet (with context)". + const VECTOR: [&'static str; 5] = [ + "c4eab05d357007c632f3dbb48489924d552b08fe0c353a0d4a1f00acda2c463afbea67c5e8d2877c5e3bc397\ + a659949ef8021e954e0a12274e", + "43ba28f430cdff456ae531545f7ecd0ac834a55d9358c0372bfa0c6c6798c0866aea01eb00742802b8438ea4\ + cb82169c235160627b4c3a9480", + "03", + "666f6f", + "d4f8f6131770dd46f40867d6fd5d5055de43541f8c5e35abbcd001b32a89f7d2151f7647f11d8ca2ae279fb8\ + 42d607217fce6e042f6815ea000c85741de5c8da1144a6a1aba7f96de42505d7a7298524fda538fccbbb754f\ + 578c1cad10d54d0d5428407e85dcbc98a49155c13764e66c3c00", + ]; + + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), SignatureError> { + ed448::keygen(rng) + } + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), SignatureError> { + ed448::keygen_out(rng, sk) + } + fn zeroized() -> Self { + Ed448PrivateKey::zeroized() + } + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError> { + Ed448PrivateKey::from_bytes_out(bytes, sk) + } + fn pk(&self) -> Self::Pk { + Ed448PrivateKey::pk(self).unwrap() + } + fn consistent(pk: &Self::Pk, sk: &Self) -> bool { + ed448::keypair_consistency_check(pk, sk).is_ok() + } + fn sign_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; 114]) -> usize { + DeterministicOneShotSigningKey::::sign_deterministic_out(self, msg, ctx, sig) + .unwrap() + } + fn sign(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; 114] { + DeterministicOneShotSigningKey::::sign_deterministic(self, msg, ctx).unwrap() + } + fn sign_ph_out(&self, msg: &[u8], ctx: Option<&[u8]>, sig: &mut [u8; 114]) -> usize { + DeterministicOneShotSigningKey::::sign_deterministic_out( + &self.as_prehash(), + msg, + ctx, + sig, + ) + .unwrap() + } + fn sign_ph(&self, msg: &[u8], ctx: Option<&[u8]>) -> [u8; 114] { + DeterministicOneShotSigningKey::::sign_deterministic( + &self.as_prehash(), + msg, + ctx, + ) + .unwrap() + } + fn ph_signer<'a>(&'a self, ctx: Option<&[u8]>) -> Box + 'a> { + Box::new(self.as_prehash().create_signer_deterministic(ctx).unwrap()) + } + fn verifies(pk: &Self::Pk, msg: &[u8], ctx: Option<&[u8]>, sig: &[u8], ph: bool) -> bool { + if ph { + OneShotVerifyingKey::::verify(&pk.as_prehash(), msg, ctx, sig).is_ok() + } else { + OneShotVerifyingKey::::verify(pk, msg, ctx, sig).is_ok() + } + } + + fn hash(parts: &[&[u8]]) -> Vec { + shake256(parts, 114) + } + fn digest_images(name: &str, digest: &[u8], values: &mut Values) { + // The sponge's lanes are little-endian: the digest is its own image. + values.push((name.to_string(), digest.to_vec())); + } + fn chaining_values(_: &[u8]) -> Vec { + // The Keccak state is wiped by `bouncycastle_digest::sha3` at each permutation. + Vec::new() + } + fn prehash(msg: &[u8]) -> Vec { + // RFC 8032 Section 5.2: "PH being SHAKE256(x, 64)". + shake256(&[msg], 64) + } + fn dom(ph: bool, ctx: &[u8]) -> Vec { + // RFC 8032 Section 2: "SigEd448" || octet(x) || octet(OLEN(y)) || y. + [b"SigEd448".as_slice(), &[u8::from(ph), ctx.len() as u8], ctx].concat() + } + fn prune(s: &mut [u8]) { + // RFC 8032 Section 5.2.5, step 2. + s[0] &= 0xFC; + s[56] = 0; + s[55] |= 0x80; + } + fn order() -> Big { + // RFC 8032 Section 5.2, Table 2. + big_sub( + &big_pow2(446), + &big_dec("13818066809895115352007386748515426880336692474882178609894547503885"), + ) + } +} + +fn shake256(parts: &[&[u8]], len: usize) -> Vec { + let mut xof = SHAKE256::default(); + for part in parts { + xof.do_update(part); + } + xof.into_squeezer().do_output(len) +} + +/// The expansion of an EdDSA private key (RFC 8032 Section 5.1.5 or 5.2.5). +struct Expanded { + seed: Vec, + h: Vec, + s: Vec, + prefix: Vec, +} + +impl Expanded { + fn of, const SK: usize, const PK: usize, const SIG: usize>( + seed: &[u8], + ) -> Self { + let h = E::hash(&[seed]); + let mut s = h[..E::HALF].to_vec(); + E::prune(&mut s); + Self { seed: seed.to_vec(), prefix: h[E::HALF..].to_vec(), h, s } + } + + /// What a key is searched for: the private key, as bytes and as the SHA-512 words it is + /// absorbed as, its digest, `s` and `prefix`. + fn values, const SK: usize, const PK: usize, const SIG: usize>( + &self, + ) -> Values { + let mut values = vec![ + ("private key".to_string(), self.seed.clone()), + ("private key (SHA-512 words)".to_string(), word_swapped(&self.seed)), + ("s".to_string(), self.s.clone()), + ("prefix".to_string(), self.prefix.clone()), + ]; + E::digest_images("h", &self.h, &mut values); + values + } +} + +/// The digest of step 2 and `r`, of the signature `sig` over `msg` under `key`, checked against +/// it: `S = r + k s mod L` (steps 4 and 5), with `k` from `R` and the public key `a`. Returned +/// with the key's values, and with the public values `k` and its digest as an image for the +/// comparison of two runs. +fn signing_values, const SK: usize, const PK: usize, const SIG: usize>( + key: &Expanded, + a: &[u8], + msg: &[u8], + ctx: &[u8], + ph: bool, + sig: &[u8], +) -> (Values, Vec) { + let phm = if ph { E::prehash(msg) } else { msg.to_vec() }; + let dom = E::dom(ph, ctx); + let l = E::order(); + let r_digest = E::hash(&[&dom, &key.prefix, &phm]); + let r = big_mod(&big(&r_digest), &l); + let (big_r, big_s) = sig.split_at(SIG / 2); + let k_input = [&dom, big_r, a, &phm].concat(); + let k_digest = E::hash(&[&k_input]); + let k = big_mod(&big(&k_digest), &l); + let s = big_mod(&big_add(&r, &big_mul(&k, &big(&key.s))), &l); + assert_eq!(le_bytes(&s, SIG / 2), big_s, "not the signature's r and s"); + let mut values = key.values::(); + E::digest_images("r digest", &r_digest, &mut values); + values.push(("r".to_string(), le_bytes(&r, SIG / 2))); + // `k`, its digest and the hash's states on the way are public, and differ with `R` and `A`. + let k = le_bytes(&k, SIG / 2); + let image = + [sig, &k, &k_digest, &word_swapped(&k_digest), &E::chaining_values(&k_input)].concat(); + (values, image) +} + +/// A public key as what the comparison of two runs lets differ: its encoding and its `y` in the +/// field arithmetic's limbs. +fn ed_public_image, const SK: usize, const PK: usize, const SIG: usize>( + encoded: &[u8], +) -> Vec { + let mut y = encoded.to_vec(); + *y.last_mut().unwrap() &= 0x7F; + [encoded, &radix_limbs(&y, E::LIMB_BITS, E::LIMBS)].concat() +} + +/// The EdDSA private key of `E`: generated, loaded, copied, encoded, its public key read, and +/// signing with it, through the one-shots and the pre-hash variant's streaming final. +pub(crate) fn eddsa(scan: &mut Scan) +where + E: EdScheme, +{ + let name = E::NAME; + let op = |what: &str| format!("{name} {what}"); + + // The reference computation against RFC 8032's vector, before it is relied on. + let [seed, pk, msg, ctx, sig] = E::VECTOR.map(hex); + let sk = E::from_bytes(&seed).unwrap(); + assert_eq!(&sk.pk().encode()[..], &pk[..], "not the RFC's public key"); + assert_eq!(&sk.sign(&msg, Some(&ctx))[..], &sig[..], "not the RFC's signature"); + signing_values::( + &Expanded::of::(&seed), + &pk, + &msg, + &ctx, + false, + &sig, + ); + + let seeds = [0, 1].map(|i| bytes_of(&format!("{name} key {i}"), SK)); + let keys = seeds.clone().map(|s| Expanded::of::(&s)); + let pks: Vec<[u8; PK]> = + seeds.iter().map(|s| E::from_bytes(s).unwrap().pk().encode()).collect(); + let publics: Vec> = pks.iter().map(|p| ed_public_image::(p)).collect(); + let mut sk = Box::new(E::zeroized()); + let mut other = Box::new(E::zeroized()); + let mut encoded = Box::new([0u8; SK]); + let mut rng = Box::new(rng_of(&seeds[0])); + + for (i, key) in keys.iter().enumerate() { + scan.keep(); + *rng = rng_of(&key.seed); + let (generated_pk, generated_sk) = scan.run(|| E::keygen(&mut *rng)).unwrap(); + assert_eq!(&generated_sk.encode()[..], &key.seed[..], "not the RNG's draw"); + assert_eq!(generated_pk.encode(), pks[i]); + scan.clean(&op("keygen"), &key.values::()); + } + scan.same(&op("keygen"), &publics[0], &publics[1]); + for (i, key) in keys.iter().enumerate() { + scan.keep(); + *rng = rng_of(&key.seed); + scan.run(|| E::keygen_out(&mut *rng, &mut sk)).unwrap(); + assert_eq!(&sk.encode()[..], &key.seed[..], "not the RNG's draw"); + assert_eq!(sk.pk().encode(), pks[i]); + scan.clean(&op("keygen_out"), &key.values::()); + } + scan.same(&op("keygen_out"), &publics[0], &publics[1]); + + for (i, key) in keys.iter().enumerate() { + scan.keep(); + encoded.copy_from_slice(&key.seed); + let loaded = scan.run(|| E::from_bytes(&encoded[..])).unwrap(); + assert_eq!(loaded.pk().encode(), pks[i]); + scan.clean(&op("from_bytes"), &key.values::()); + } + scan.same(&op("from_bytes"), &publics[0], &publics[1]); + for (i, key) in keys.iter().enumerate() { + scan.keep(); + encoded.copy_from_slice(&key.seed); + scan.run(|| E::from_bytes_out(&encoded[..], &mut sk)).unwrap(); + assert_eq!(sk.pk().encode(), pks[i]); + scan.clean(&op("from_bytes_out"), &key.values::()); + } + scan.same(&op("from_bytes_out"), &publics[0], &publics[1]); + + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + let copy = scan.run(|| (*sk).clone()); + assert!(copy == *sk); + scan.clean(&op("clone"), &key.values::()); + } + scan.same(&op("clone"), &[], &[]); + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + scan.run(|| other.clone_from(&sk)); + assert!(*other == *sk); + scan.clean(&op("clone_from"), &key.values::()); + } + scan.same(&op("clone_from"), &[], &[]); + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + other.clone_from(&sk); + scan.keep(); + assert!(scan.run(|| *sk == *other)); + scan.clean(&op("=="), &key.values::()); + } + scan.same(&op("=="), &[], &[]); + + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + *encoded = scan.run(|| sk.encode()); + assert_eq!(&encoded[..], &key.seed[..]); + scan.clean(&op("encode"), &key.values::()); + } + scan.same(&op("encode"), &[], &[]); + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + assert_eq!(scan.run(|| sk.encode_out(&mut encoded)), SK); + assert_eq!(&encoded[..], &key.seed[..]); + scan.clean(&op("encode_out"), &key.values::()); + } + scan.same(&op("encode_out"), &[], &[]); + for (i, key) in keys.iter().enumerate() { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + let pk = scan.run(|| sk.pk()); + assert_eq!(pk.encode(), pks[i]); + scan.clean(&op("pk"), &key.values::()); + } + // `pk` decodes the stored public key and reads nothing secret, so two keys' runs differ in + // public values alone and are not compared: the search is the check. + for key in &keys { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + let pk = Box::new(sk.pk()); + scan.keep(); + assert!(scan.run(|| E::consistent(&pk, &sk))); + scan.clean(&op("keypair_consistency_check"), &key.values::()); + } + scan.same(&op("keypair_consistency_check"), &[], &[]); + + // Signing, under two keys. Ed25519 takes no context; Ed448 and the pre-hash variants are + // given one. + let msg = message(100); + let ctx = E::CONTEXT; + let ph_ctx: &[u8] = b"stack harness"; + let mut sig = Box::new([0u8; SIG]); + let sign_values = |i: usize, sig: &[u8; SIG], ph: bool| { + let pk = E::from_bytes(&keys[i].seed).unwrap().pk(); + let c = if ph { ph_ctx } else { ctx }; + assert!(E::verifies(&pk, &msg, Some(c), sig, ph), "does not verify"); + signing_values::(&keys[i], &pks[i], &msg, c, ph, sig) + }; + let forms: [(&str, bool, fn(&E, &[u8], &[u8], &mut [u8; SIG])); 4] = [ + ("sign_deterministic_out", false, |sk, m, c, sig| { + sk.sign_out(m, Some(c), sig); + }), + ("sign_deterministic", false, |sk, m, c, sig| *sig = sk.sign(m, Some(c))), + ("ph sign_deterministic_out", true, |sk, m, c, sig| { + sk.sign_ph_out(m, Some(c), sig); + }), + ("ph sign_deterministic", true, |sk, m, c, sig| *sig = sk.sign_ph(m, Some(c))), + ]; + for (what, ph, form) in forms { + let c = if ph { ph_ctx } else { ctx }; + let mut images = Vec::new(); + for (i, key) in keys.iter().enumerate() { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + scan.keep(); + scan.run(|| form(&sk, &msg, c, &mut sig)); + let (values, image) = sign_values(i, &sig, ph); + scan.clean(&op(what), &values); + images.push(image); + } + scan.same(&op(what), &images[0], &images[1]); + } + // The pre-hash variant's streaming final, on a signer in a box. + let mut images = Vec::new(); + for (i, key) in keys.iter().enumerate() { + E::from_bytes_out(&key.seed, &mut sk).unwrap(); + let mut signer = sk.ph_signer(Some(ph_ctx)); + signer.do_update(&msg); + scan.keep(); + assert_eq!(scan.run(|| signer.do_final_out_boxed(&mut sig)), Ok(SIG)); + let (values, image) = sign_values(i, &sig, true); + scan.clean(&op("ph final (boxed)"), &values); + images.push(image); + } + scan.same(&op("ph final (boxed)"), &images[0], &images[1]); +} + +/// What the harness needs of an XDH scheme over and above the key traits. +pub(crate) trait XScheme: + PrivateKey + Clone + PartialEq + AgreementKey<(), N, PublicKey = Self::Pk> +{ + type Pk: PublicKey + Copy; + const NAME: &'static str; + /// RFC 7748 Section 6's test vector: Alice's private key, Bob's public key, `K`. + const VECTOR: [&'static str; 3]; + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), KeyAgreementError>; + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), KeyAgreementError>; + fn keygen_from_seed(seed: &KeyMaterial) -> Result<(Self::Pk, Self), KeyAgreementError>; + fn keygen_from_seed_out(seed: &KeyMaterial, sk: &mut Self) -> Result<(), KeyAgreementError>; + fn zeroized() -> Self; + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError>; + fn pk(&self) -> Self::Pk; + fn clamp(k: &mut [u8; N]); +} + +impl XScheme<32> for X25519PrivateKey { + type Pk = X25519PublicKey; + const NAME: &'static str = "X25519"; + const VECTOR: [&'static str; 3] = [ + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", + "4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742", + ]; + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), KeyAgreementError> { + x25519::keygen(rng) + } + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), KeyAgreementError> { + x25519::keygen_out(rng, sk) + } + fn keygen_from_seed(seed: &KeyMaterial<32>) -> Result<(Self::Pk, Self), KeyAgreementError> { + x25519::keygen_from_seed(seed) + } + fn keygen_from_seed_out( + seed: &KeyMaterial<32>, + sk: &mut Self, + ) -> Result<(), KeyAgreementError> { + x25519::keygen_from_seed_out(seed, sk) + } + fn zeroized() -> Self { + X25519PrivateKey::zeroized() + } + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError> { + X25519PrivateKey::from_bytes_out(bytes, sk) + } + fn pk(&self) -> Self::Pk { + X25519PrivateKey::pk(self).unwrap() + } + fn clamp(k: &mut [u8; 32]) { + // RFC 7748 Section 5, decodeScalar25519. + k[0] &= 248; + k[31] &= 127; + k[31] |= 64; + } +} + +impl XScheme<56> for X448PrivateKey { + type Pk = X448PublicKey; + const NAME: &'static str = "X448"; + const VECTOR: [&'static str; 3] = [ + "9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f\ + 127ab1d9ac2d8c0a598726b", + "3eb7a829b0cd20f5bcfc0b599b6feccf6da4627107bdb0d4f345b43027d8b972fc3e34fb4232a13ca706dcb57\ + aec3dae07bdc1c67bf33609", + "07fff4181ac6cc95ec1c16a94a0f74d12da232ce40a77552281d282bb60c0b56fd2464c335543936521c24403\ + 085d59a449a5037514a879d", + ]; + fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), KeyAgreementError> { + x448::keygen(rng) + } + fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), KeyAgreementError> { + x448::keygen_out(rng, sk) + } + fn keygen_from_seed(seed: &KeyMaterial<56>) -> Result<(Self::Pk, Self), KeyAgreementError> { + x448::keygen_from_seed(seed) + } + fn keygen_from_seed_out( + seed: &KeyMaterial<56>, + sk: &mut Self, + ) -> Result<(), KeyAgreementError> { + x448::keygen_from_seed_out(seed, sk) + } + fn zeroized() -> Self { + X448PrivateKey::zeroized() + } + fn from_bytes_out(bytes: &[u8], sk: &mut Self) -> Result<(), KeyDecodingError> { + X448PrivateKey::from_bytes_out(bytes, sk) + } + fn pk(&self) -> Self::Pk { + X448PrivateKey::pk(self).unwrap() + } + fn clamp(k: &mut [u8; 56]) { + // RFC 7748 Section 5, decodeScalar448. + k[0] &= 252; + k[55] |= 128; + } +} + +/// The XDH private key of `X`: generated, from an RNG and from a seed, loaded, encoded, its +/// public key read, and agreeing. `scalar_mult_left` reports, without failing, the comparison +/// of two runs over the operations that multiply by the scalar, for X25519, whose field +/// inversion is left on the stack by decision (its Security Considerations); the search for the +/// key and `K` still fails. +pub(crate) fn xdh, const N: usize>(scan: &mut Scan, scalar_mult_left: bool) { + let name = X::NAME; + let op = |what: &str| format!("{name} {what}"); + let clamped = |raw: &[u8]| { + let mut k: [u8; N] = raw.try_into().unwrap(); + X::clamp(&mut k); + k + }; + let key_values = |raw: &[u8]| -> Values { + vec![ + ("private key (bytes)".to_string(), raw.to_vec()), + ("private key (clamped)".to_string(), clamped(raw).to_vec()), + ] + }; + // The comparison of two runs over an operation that multiplies by the scalar. + let same_scalar_mult = |scan: &mut Scan, what: &str, before: &[u8], after: &[u8]| { + let report_only = scan.report_only; + scan.report_only = scalar_mult_left; + scan.same(&op(what), before, after); + scan.report_only = report_only; + }; + + // The agreement against RFC 7748's vector, before it is relied on. + let [alice, bob, k] = X::VECTOR.map(hex); + let mut z = KeyMaterial::::new(); + let bob = X::Pk::from_bytes(&bob).unwrap(); + X::from_bytes(&alice).unwrap().agree_out(&bob, (), &mut z).unwrap(); + assert_eq!(z.ref_to_bytes(), &k[..], "not the RFC's shared secret"); + + let raws = [0, 1].map(|i| bytes_of(&format!("{name} key {i}"), N)); + let pks: Vec = raws.iter().map(|r| X::from_bytes(r).unwrap().pk()).collect(); + let publics: Vec> = pks.iter().map(|p| p.encode().to_vec()).collect(); + let mut sk = Box::new(X::zeroized()); + let mut encoded = Box::new([0u8; N]); + let mut rng = Box::new(rng_of(&raws[0])); + + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + *rng = rng_of(raw); + let (pk, generated) = scan.run(|| X::keygen(&mut *rng)).unwrap(); + assert_eq!(generated.encode(), clamped(raw), "not the RNG's draw"); + assert_eq!(pk.encode(), pks[i].encode()); + scan.clean(&op("keygen"), &key_values(raw)); + } + same_scalar_mult(scan, "keygen", &publics[0], &publics[1]); + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + *rng = rng_of(raw); + scan.run(|| X::keygen_out(&mut *rng, &mut sk)).unwrap(); + assert_eq!(sk.encode(), clamped(raw), "not the RNG's draw"); + assert_eq!(sk.pk().encode(), pks[i].encode()); + scan.clean(&op("keygen_out"), &key_values(raw)); + } + same_scalar_mult(scan, "keygen_out", &publics[0], &publics[1]); + let seeds = raws + .clone() + .map(|r| Box::new(KeyMaterial::::from_bytes_as_type(&r, KeyType::Seed).unwrap())); + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + let (pk, generated) = scan.run(|| X::keygen_from_seed(&seeds[i])).unwrap(); + assert_eq!(generated.encode(), clamped(raw)); + assert_eq!(pk.encode(), pks[i].encode()); + scan.clean(&op("keygen_from_seed"), &key_values(raw)); + } + same_scalar_mult(scan, "keygen_from_seed", &publics[0], &publics[1]); + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + scan.run(|| X::keygen_from_seed_out(&seeds[i], &mut sk)).unwrap(); + assert_eq!(sk.encode(), clamped(raw)); + assert_eq!(sk.pk().encode(), pks[i].encode()); + scan.clean(&op("keygen_from_seed_out"), &key_values(raw)); + } + same_scalar_mult(scan, "keygen_from_seed_out", &publics[0], &publics[1]); + + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + encoded.copy_from_slice(raw); + let loaded = scan.run(|| X::from_bytes(&encoded[..])).unwrap(); + assert_eq!(loaded.pk().encode(), pks[i].encode()); + scan.clean(&op("from_bytes"), &key_values(raw)); + } + same_scalar_mult(scan, "from_bytes", &publics[0], &publics[1]); + for (i, raw) in raws.iter().enumerate() { + scan.keep(); + encoded.copy_from_slice(raw); + scan.run(|| X::from_bytes_out(&encoded[..], &mut sk)).unwrap(); + assert_eq!(sk.pk().encode(), pks[i].encode()); + scan.clean(&op("from_bytes_out"), &key_values(raw)); + } + same_scalar_mult(scan, "from_bytes_out", &publics[0], &publics[1]); + + let mut other = Box::new(X::zeroized()); + for raw in &raws { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + let copy = scan.run(|| (*sk).clone()); + assert!(copy == *sk); + scan.clean(&op("clone"), &key_values(raw)); + } + scan.same(&op("clone"), &[], &[]); + for raw in &raws { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + scan.run(|| other.clone_from(&sk)); + assert!(*other == *sk); + scan.clean(&op("clone_from"), &key_values(raw)); + } + scan.same(&op("clone_from"), &[], &[]); + for raw in &raws { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + *encoded = scan.run(|| sk.encode()); + assert_eq!(*encoded, clamped(raw)); + scan.clean(&op("encode"), &key_values(raw)); + } + scan.same(&op("encode"), &[], &[]); + for raw in &raws { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + assert_eq!(scan.run(|| sk.encode_out(&mut encoded)), N); + assert_eq!(*encoded, clamped(raw)); + scan.clean(&op("encode_out"), &key_values(raw)); + } + scan.same(&op("encode_out"), &[], &[]); + for (i, raw) in raws.iter().enumerate() { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + let pk = scan.run(|| sk.pk()); + assert_eq!(pk.encode(), pks[i].encode()); + scan.clean(&op("pk"), &key_values(raw)); + } + scan.same(&op("pk"), &publics[0], &publics[1]); + + // Agreement: under two keys, with one peer. `K` is checked by the peer's agreement. + let peer_raw = bytes_of(&format!("{name} peer"), N); + let peer_sk = X::from_bytes(&peer_raw).unwrap(); + let peer = Box::new(peer_sk.pk()); + let mut z = Box::new(KeyMaterial::::new()); + for (i, raw) in raws.iter().enumerate() { + X::from_bytes_out(raw, &mut sk).unwrap(); + scan.keep(); + assert_eq!(scan.run(|| sk.agree_out(&peer, (), &mut z)), Ok(N)); + let mut theirs = KeyMaterial::::new(); + peer_sk.agree_out(&pks[i], (), &mut theirs).unwrap(); + assert_eq!(z.ref_to_bytes(), theirs.ref_to_bytes(), "not their K"); + let mut values = key_values(raw); + values.push(("K".to_string(), z.ref_to_bytes().to_vec())); + scan.clean(&op("agree_out"), &values); + } + same_scalar_mult(scan, "agree_out", &[], &[]); +} diff --git a/dev_scripts/ecdsa_stack_harness/src/main.rs b/dev_scripts/ecdsa_stack_harness/src/main.rs index 38a2197b4..94ef88770 100644 --- a/dev_scripts/ecdsa_stack_harness/src/main.rs +++ b/dev_scripts/ecdsa_stack_harness/src/main.rs @@ -1,6 +1,7 @@ //! What ECDSA signing and the handling of its private keys (bouncycastle_ec::ecdsa), ECC CDH's -//! private keys and agreement (bouncycastle_ec::eccdh), and DHKEM over the NIST curves, X448 and -//! X25519 with its labeled HKDF steps (bouncycastle_ec::dhkem) leave on the dead stack, for +//! private keys and agreement (bouncycastle_ec::eccdh), DHKEM over the NIST curves, X448 and +//! X25519 with its labeled HKDF steps (bouncycastle_ec::dhkem), and Ed25519, Ed448, X25519 and +//! X448 with their keys (bouncycastle_ec::ed, in [`ed`]) leave on the dead stack, for //! `../check_ecdsa_stack.sh`. For each operation the stack below the call is painted, the //! operation run with its results going to the heap or to a live frame above, the dead stack //! copied out, and the copy searched for the 8-byte words of every secret the operation handled: @@ -17,9 +18,9 @@ //! Controls: nothing run must leave nothing, and the same stack twice; a copy of `d` left in a //! frame must be found, and copies of two keys must differ. //! -//! Reported and not failed: DHKEM over X25519, whose scalar multiplication leaves part of its -//! field inversion (`bouncycastle_ec::ed::x25519`'s Security Considerations), lines marked -//! `left`. +//! Reported and not failed: DHKEM over X25519, and the comparison of two runs of every X25519 +//! operation that multiplies by the scalar, whose scalar multiplication leaves part of its field +//! inversion (`bouncycastle_ec::ed::x25519`'s Security Considerations), lines marked `left`. //! //! target/release/ecdsa_stack_harness //! @@ -55,11 +56,14 @@ use bouncycastle_ec::ecdsa::keys::{ECDSAPrivateKey, ECDSAPublicKey}; use bouncycastle_ec::ecdsa::keys_common::{DerivePublicKey, SignatureKeyPair}; use bouncycastle_ec::ed::x448::{self, X448PrivateKey, X448PublicKey}; use bouncycastle_ec::ed::x25519::{self, X25519PrivateKey, X25519PublicKey}; +use bouncycastle_ec::ed::{ed448, ed25519}; use bouncycastle_ec::{Bp256r1, Bp384r1, Bp512r1, P256, P384, P521, Secp256K1}; use bouncycastle_utils::secret::ZeroizablePrimitive; use std::collections::HashSet; use std::hint::black_box; +mod ed; + /// How far below the call the stack is painted and searched. The deepest operation here uses /// under 16 KiB. const DEPTH: usize = 256 * 1024; @@ -457,6 +461,12 @@ fn main() { ); scan.report_only = false; + ed::eddsa::(&mut scan); + ed::eddsa::(&mut scan); + ed::xdh::(&mut scan, false); + // X25519's scalar multiplication leaves part of its inversion, by decision: reported. + ed::xdh::(&mut scan, true); + std::process::exit(if scan.failures == 0 { 0 } else { 1 }); } From 03de292f79c638eaaa97314803bd434ec977dd93 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 16:45:47 +1100 Subject: [PATCH 04/14] ec: Ed25519, Ed448, X25519 and X448 stack tables re-measured The new wipes deepen key generation, private-key decoding and signing: by 1136 to 1680 bytes for Ed25519, 1416 to 2280 for Ed448, and by up to 416 bytes for the by-value XDH keys. Measured as before (deepest frame chain below the mem bench's measure wrapper, rustc 1.97 nightly, x86-64); the base commit reproduces the old figures exactly. Assisted-by: Claude:claude-opus-5-5 --- crypto/ec/src/ed/ed25519/mod.rs | 18 ++++++++++-------- crypto/ec/src/ed/ed448/mod.rs | 17 +++++++++-------- crypto/ec/src/ed/x25519.rs | 8 ++++---- crypto/ec/src/ed/x448.rs | 8 ++++---- 4 files changed, 27 insertions(+), 24 deletions(-) diff --git a/crypto/ec/src/ed/ed25519/mod.rs b/crypto/ec/src/ed/ed25519/mod.rs index ef3c2f9ff..b57591f2b 100644 --- a/crypto/ec/src/ed/ed25519/mod.rs +++ b/crypto/ec/src/ed/ed25519/mod.rs @@ -99,19 +99,21 @@ //! //! | Entry point | Stack | //! |--------------------------------------|--------| -//! | `keygen` | 2680 B | -//! | `keygen_out` | 2488 B | -//! | `Ed25519PrivateKey::from_bytes` | 2680 B | -//! | `Ed25519PrivateKey::from_bytes_out` | 2344 B | +//! | `keygen` | 4360 B | +//! | `keygen_out` | 3624 B | +//! | `Ed25519PrivateKey::from_bytes` | 3896 B | +//! | `Ed25519PrivateKey::from_bytes_out` | 3480 B | //! | `Ed25519PublicKey::from_bytes` | 4376 B | //! | `Ed25519PrivateKey::pk` | 1944 B | -//! | Ed25519 sign | 3096 B | +//! | Ed25519 sign | 4232 B | //! | Ed25519 verify | 5896 B | -//! | Ed25519ph sign | 4184 B | +//! | Ed25519ph sign | 5320 B | //! | Ed25519ph verify | 7080 B | //! -//! The key generation figures leave out the RNG. The Ed25519ph figures are for the streaming -//! signer and verifier, and include the worker: a SHA-512 state and the context. +//! Key generation, decoding a private key and signing peak in the 3 KiB stack wipe that follows the +//! fixed-base multiplication. The key generation figures leave out the RNG. The Ed25519ph figures +//! are for the streaming signer and verifier, and include the worker: a SHA-512 state and the +//! context. //! //! # ๐Ÿšจ Security Considerations ๐Ÿšจ //! diff --git a/crypto/ec/src/ed/ed448/mod.rs b/crypto/ec/src/ed/ed448/mod.rs index 235b92f9f..266672c47 100644 --- a/crypto/ec/src/ed/ed448/mod.rs +++ b/crypto/ec/src/ed/ed448/mod.rs @@ -104,19 +104,20 @@ //! //! | Entry point | Stack | //! |------------------------------------|---------| -//! | `keygen` | 4192 B | -//! | `keygen_out` | 3728 B | -//! | `Ed448PrivateKey::from_bytes` | 4064 B | -//! | `Ed448PrivateKey::from_bytes_out` | 3392 B | +//! | `keygen` | 6472 B | +//! | `keygen_out` | 5144 B | +//! | `Ed448PrivateKey::from_bytes` | 5512 B | +//! | `Ed448PrivateKey::from_bytes_out` | 4808 B | //! | `Ed448PublicKey::from_bytes` | 7232 B | //! | `Ed448PrivateKey::pk` | 3136 B | -//! | Ed448 sign | 4144 B | +//! | Ed448 sign | 5560 B | //! | Ed448 verify | 10320 B | -//! | Ed448ph sign | 5888 B | +//! | Ed448ph sign | 7304 B | //! | Ed448ph verify | 12352 B | //! -//! The key generation figures leave out the RNG. The Ed448ph figures are for the streaming -//! signer and verifier, and include the worker: a SHAKE256 state and the context. +//! Key generation, decoding a private key and signing peak in the 4 KiB stack wipe that follows the +//! fixed-base multiplication. The key generation figures leave out the RNG. The Ed448ph figures are +//! for the streaming signer and verifier, and include the worker: a SHAKE256 state and the context. //! //! # ๐Ÿšจ Security Considerations ๐Ÿšจ //! diff --git a/crypto/ec/src/ed/x25519.rs b/crypto/ec/src/ed/x25519.rs index 17e11daf1..d42e11801 100644 --- a/crypto/ec/src/ed/x25519.rs +++ b/crypto/ec/src/ed/x25519.rs @@ -126,13 +126,13 @@ //! //! | Entry point | Stack | //! |-------------------------------------|--------| -//! | `keygen_from_seed` | 1368 B | +//! | `keygen_from_seed` | 1608 B | //! | `keygen_out` | 1272 B | -//! | `X25519PrivateKey::from_bytes` | 1368 B | +//! | `X25519PrivateKey::from_bytes` | 1464 B | //! | `X25519PrivateKey::from_bytes_out` | 1256 B | //! | `agree` on the private key | 1400 B | -//! | `encaps` on the public key | 4760 B | -//! | `decaps` on the private key | 4136 B | +//! | `encaps` on the public key | 4680 B | +//! | `decaps` on the private key | 4088 B | //! //! Key generation, decoding a private key, and key agreement each run one Montgomery ladder plus //! the field inversion: the chain is the in-place scalar multiplication, the field inversion and diff --git a/crypto/ec/src/ed/x448.rs b/crypto/ec/src/ed/x448.rs index 8ac7625a8..ccde89c91 100644 --- a/crypto/ec/src/ed/x448.rs +++ b/crypto/ec/src/ed/x448.rs @@ -116,13 +116,13 @@ //! //! | Entry point | Stack | //! |-----------------------------------|--------| -//! | `keygen_from_seed` | 2936 B | +//! | `keygen_from_seed` | 3352 B | //! | `keygen_out` | 2728 B | -//! | `X448PrivateKey::from_bytes` | 2872 B | +//! | `X448PrivateKey::from_bytes` | 3064 B | //! | `X448PrivateKey::from_bytes_out` | 2728 B | //! | `agree` on the private key | 2856 B | -//! | `encaps` on the public key | 5768 B | -//! | `decaps` on the private key | 5208 B | +//! | `encaps` on the public key | 5720 B | +//! | `decaps` on the private key | 5224 B | //! //! The first five each run one Montgomery ladder plus the field inversion, which use 1800 B //! below the entry point's own frame; the peak is the 2584 B frame that then overwrites that From b96d74f7fe5e262b8c1f7144302aea9d456cb4f4 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 17:09:43 +1100 Subject: [PATCH 05/14] ci: ed stack harness searches XDH limbs, skips the keygen comparison X25519's and X448's K and clamped scalar are also searched as field limbs (radix 51, radix 56); with X448's ladder wipe zeroed the search finds two limbs of K. EdDSA keygen is keygen_out, still compared, then pk's decoding of the public key, whose square-root intermediates are public and differ by key; adding the decoded x to the public image did not explain them (407 to 372 bytes), so keygen is searched, not compared, as pk already was. Assisted-by: Claude:claude-opus-5-5 --- dev_scripts/ecdsa_stack_harness/src/ed.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/dev_scripts/ecdsa_stack_harness/src/ed.rs b/dev_scripts/ecdsa_stack_harness/src/ed.rs index 333101398..1002420d1 100644 --- a/dev_scripts/ecdsa_stack_harness/src/ed.rs +++ b/dev_scripts/ecdsa_stack_harness/src/ed.rs @@ -539,7 +539,10 @@ where assert_eq!(generated_pk.encode(), pks[i]); scan.clean(&op("keygen"), &key.values::()); } - scan.same(&op("keygen"), &publics[0], &publics[1]); + // `keygen` is `keygen_out`, compared below, then `pk`, which decodes the public key: the + // field elements of its square root are public but differ from key to key, and no image of + // them is computed here, so two runs are not compared and the search is the check. + for (i, key) in keys.iter().enumerate() { scan.keep(); *rng = rng_of(&key.seed); @@ -684,6 +687,9 @@ pub(crate) trait XScheme: const NAME: &'static str; /// RFC 7748 Section 6's test vector: Alice's private key, Bob's public key, `K`. const VECTOR: [&'static str; 3]; + /// The bits of a field element's limbs, and how many there are. + const LIMB_BITS: usize; + const LIMBS: usize; fn keygen(rng: &mut dyn RNG) -> Result<(Self::Pk, Self), KeyAgreementError>; fn keygen_out(rng: &mut dyn RNG, sk: &mut Self) -> Result<(), KeyAgreementError>; fn keygen_from_seed(seed: &KeyMaterial) -> Result<(Self::Pk, Self), KeyAgreementError>; @@ -697,6 +703,8 @@ pub(crate) trait XScheme: impl XScheme<32> for X25519PrivateKey { type Pk = X25519PublicKey; const NAME: &'static str = "X25519"; + const LIMB_BITS: usize = 51; + const LIMBS: usize = 5; const VECTOR: [&'static str; 3] = [ "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", "de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f", @@ -737,6 +745,8 @@ impl XScheme<32> for X25519PrivateKey { impl XScheme<56> for X448PrivateKey { type Pk = X448PublicKey; const NAME: &'static str = "X448"; + const LIMB_BITS: usize = 56; + const LIMBS: usize = 8; const VECTOR: [&'static str; 3] = [ "9a8f4925d1519f5775cf46b04b5800d4ee9ee8bae8bc5565d498c28dd9c9baf574a9419744897391006382a6f\ 127ab1d9ac2d8c0a598726b", @@ -789,10 +799,14 @@ pub(crate) fn xdh, const N: usize>(scan: &mut Scan, scalar_mult_le X::clamp(&mut k); k }; + // The field arithmetic's limbs of a value: the ladder's, for `K`, and of the clamped scalar, + // should it pass through a field element. + let limbs = |v: &[u8]| radix_limbs(v, X::LIMB_BITS, X::LIMBS); let key_values = |raw: &[u8]| -> Values { vec![ ("private key (bytes)".to_string(), raw.to_vec()), ("private key (clamped)".to_string(), clamped(raw).to_vec()), + ("private key (clamped, limbs)".to_string(), limbs(&clamped(raw))), ] }; // The comparison of two runs over an operation that multiplies by the scalar. @@ -928,6 +942,7 @@ pub(crate) fn xdh, const N: usize>(scan: &mut Scan, scalar_mult_le assert_eq!(z.ref_to_bytes(), theirs.ref_to_bytes(), "not their K"); let mut values = key_values(raw); values.push(("K".to_string(), z.ref_to_bytes().to_vec())); + values.push(("K (limbs)".to_string(), limbs(z.ref_to_bytes()))); scan.clean(&op("agree_out"), &values); } same_scalar_mult(scan, "agree_out", &[], &[]); From bad49cff95961d55ebeffdc30bd6f9b2bd349919 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 17:09:43 +1100 Subject: [PATCH 06/14] ec: size the EdDSA keygen wipe by the key pair alone KEYGEN_STACK_WORDS was sized to also erase the public key's decoding, which is public. Sized by the copies of the key pair it removes: 1024 bytes for Ed25519 (384 needed, 320 too few, rustc 1.97 and 1.88) and 1536 for Ed448 (768 and 640 on 1.97, 640 and 512 on 1.88). The stack tables do not move; keygen peaks in the multiplication's wipe. The Ed25519 docs say the check was measured on x86-64, not yet arm64. Assisted-by: Claude:claude-opus-5-5 --- crypto/ec/src/ed/ed25519/keys.rs | 9 +++------ crypto/ec/src/ed/ed25519/mod.rs | 10 ++++++---- crypto/ec/src/ed/ed448/keys.rs | 9 +++------ 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/crypto/ec/src/ed/ed25519/keys.rs b/crypto/ec/src/ed/ed25519/keys.rs index b355221b7..79e87e9c8 100644 --- a/crypto/ec/src/ed/ed25519/keys.rs +++ b/crypto/ec/src/ed/ed25519/keys.rs @@ -78,12 +78,9 @@ impl SignatureAlgorithm for Ed25519ph {} /// with 128 (x86-64 release builds, rustc 1.97 and 1.88). const BY_VALUE_STACK_WORDS: usize = 64; -/// The same after [`keygen`], whose frame also decodes the public key: 3072 bytes. The harness -/// finds no copy of the key with 1024 bytes wiped, but the public key's decoding leaves values -/// that differ from key to key down to 2304 bytes below the call; they are public, and -/// wiping them too lets the harness compare two runs over different keys. It passes with -/// 2304 bytes and fails with 2048, measured the same way. -const KEYGEN_STACK_WORDS: usize = 384; +/// The same after [`keygen`], whose frame holds the key pair: 1024 bytes. The harness passes +/// with 384 bytes wiped and fails with 320, measured the same way. +const KEYGEN_STACK_WORDS: usize = 128; /// Generates a key pair from `rng`, which must offer Ed25519's 128 bits: the 32 octets it /// draws are the private key (RFC 8032 Section 5.1.5). diff --git a/crypto/ec/src/ed/ed25519/mod.rs b/crypto/ec/src/ed/ed25519/mod.rs index b57591f2b..97220ebfc 100644 --- a/crypto/ec/src/ed/ed25519/mod.rs +++ b/crypto/ec/src/ed/ed25519/mod.rs @@ -170,10 +170,12 @@ //! moves, not of theirs. Signing also overwrites the stack its last step used, where the //! compiler otherwise leaves limbs of the scalar it held in registers, and each fixed-base //! multiplication (key expansion's `[s]B`, signing's `[r]B`) the stack it used, where it leaves -//! limbs of the point's coordinates and of the inversion that normalizes them; a scan of the -//! dead stack after each signing call finds none of the key in release builds for x86-64 and -//! arm64, the two scanned. SHA-512 is outside that: its load of the block that holds the private key can -//! leave words of it on the stack, seen as one word after `from_bytes_out` in the arm64 build. +//! limbs of the point's coordinates and of the inversion that normalizes them. +//! `dev_scripts/check_ecdsa_stack.sh` finds none of the key after key generation, decoding and +//! every form of signing in release builds for x86-64 (rustc 1.97 and 1.88); arm64 is not yet +//! measured with these wipes. SHA-512 is outside that: its load of the block that holds the +//! private key can leave words of it on the stack, seen as one word after `from_bytes_out` in +//! an arm64 build. //! //! Each fixed-base multiplication checks that its result is a point of the curve before //! anything is released, and a failure is reported as an error; no input causes one. diff --git a/crypto/ec/src/ed/ed448/keys.rs b/crypto/ec/src/ed/ed448/keys.rs index b05fde1f9..5e73d1cc2 100644 --- a/crypto/ec/src/ed/ed448/keys.rs +++ b/crypto/ec/src/ed/ed448/keys.rs @@ -82,12 +82,9 @@ impl SignatureAlgorithm for Ed448ph {} /// with 192 (x86-64 release builds, rustc 1.97 and 1.88). const BY_VALUE_STACK_WORDS: usize = 96; -/// The same after [`keygen`], whose frame also decodes the public key: 5120 bytes. The harness -/// finds no copy of the key with 1024 bytes wiped, but the public key's decoding leaves values -/// that differ from key to key down to 4096 bytes below the call; they are public, and -/// wiping them too lets the harness compare two runs over different keys. It passes with -/// 4096 bytes and fails with 3584, measured the same way. -const KEYGEN_STACK_WORDS: usize = 640; +/// The same after [`keygen`], whose frame holds the key pair: 1536 bytes. The harness passes +/// with 768 bytes wiped and fails with 640 (640 and 512 with 1.88), measured the same way. +const KEYGEN_STACK_WORDS: usize = 192; /// Generates a key pair from `rng`, which must offer the 192 bits Ed448 is classed at: the 57 /// octets it draws are the private key (RFC 8032 Section 5.2.5). From 11a24e94f49c76e7a22a1bb0995e9fdc9ddfb021 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 17:09:43 +1100 Subject: [PATCH 07/14] Release notes: Ed25519, Ed448, X25519 and X448 stack wipes Assisted-by: Claude:claude-opus-5-5 --- alpha_0.1.4_release_notes.md | 1 + 1 file changed, 1 insertion(+) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 65f08ef03..fd2f1cd2e 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -425,5 +425,6 @@ * ECDSA and ECC CDH private keys' `encode`, `encode_out` and `derive_pk` run in a frame whose stack is then overwritten, on all seven curves: the encodings left the bytes of `d` on P-521 and brainpoolP512r1, and `derive_pk` left `d`-dependent intermediates of the fixed-base multiplication (up to 5 kB) on every curve. About 150 more instructions per encoding and 0.1 to 0.5% per `derive_pk`; outputs are unchanged. * ECC CDH agreement and DHKEM over P-256, P-384 and P-521 (each DH product, `pk(skR)`, the private-key test of `DeriveKeyPair`) run their scalar multiplications in a frame whose stack is then overwritten, so a limb of `d`, limbs of `Z` and the multiplier's intermediates are not left on the dead stack, and an encapsulation no longer moves its ephemeral key out of key generation's `Result`, which left a limb of it and of the RNG's draw on P-521. `agree` takes 0.1 to 0.4% more instructions and an encapsulation or decapsulation 0.04 to 0.4%; their stack rows rise by 1.4 to 3.3 kB. Outputs are unchanged. * `dhkem::hazmat`'s `salt_key`, `labeled_extract_out` and `labeled_expand` (every DHKEM's KDF, X25519's and X448's included, and HPKE's key schedule, whose salt key is keyed by the KEM's shared secret) and `DHKEM::derive_key_pair` run in a frame whose stack is then overwritten, so copies of the HMAC pad states keyed by a salt or a PRK, and the moved copies of a derived private key, are not left on the dead stack; `dev_scripts/check_ecdsa_stack.sh` now covers the encodings, `derive_pk`, ECC CDH agreement and the DHKEMs (X25519's reported, not failed). Measured against 65625f5e built the same way, the X25519 and X448 KEM rows rise by 144 bytes, HPKE's `export_out` by 112 and its other rows move by -672 to +32 bytes (the table now reads what that build gives); outputs are unchanged. +* Ed25519 and Ed448 run each fixed-base multiplication (key expansion's `[s]B`, signing's `[r]B`) in a frame whose stack is then overwritten (3 KiB and 4 KiB), so limbs of the point and of its normalising inversion are not left on the dead stack after key generation, decoding or signing; and `keygen`, `keygen_from_seed`, the trait's `from_bytes` and `clone` of the Ed25519, Ed448, X25519 and X448 private keys build the key in a wiped frame, so the move out of it leaves no copy of the key, its digest, `s` or the prefix. `dev_scripts/check_ecdsa_stack.sh` covers these keys and every form of EdDSA signing and XDH agreement (X25519's documented inversion residue is reported, not failed). Sized on x86-64; arm64 is not yet measured. Outputs are unchanged; about 0.3% more instructions over a mix of decoding, signing and agreement. Key generation, private-key decoding and signing reach 1.1 to 1.7 kB (Ed25519) and 1.4 to 2.3 kB (Ed448) deeper into the stack, the by-value XDH key rows up to 416 bytes; the four memory tables are re-measured. * `bouncycastle-digest`: SHA-384/SHA-512/SHA-512/t compression keeps a 16-word rolling message schedule, zeroized on return, in place of the 80-word array, and needs fewer operations per round: about 11% fewer instructions and 19 to 21% faster on x86-64, with the compression using 320 rather than 800 bytes of stack (368 rather than 852 on thumbv6m) and a 640-byte rather than 1280-byte wipe after it. Outputs are unchanged. * The Ascon stack table in `bouncycastle-symmetric`, the BLAKE2 one in `bouncycastle-digest` and both ML-KEM memory tables in `bouncycastle-pqc` re-measured, each by the method its prose now states in full (the earlier figures did not reproduce): Ascon rows move by -184 to +112 bytes, the BLAKE2 hash one-shot reads 696 bytes where one-shot and streaming shared 1,120, and ML-KEM Encaps is up to 15% lower (ML-KEM-1024 26,776 to 22,872 bytes) and expanded-key Encaps up to 20% higher. From 70f36052ff116c7bc084ad723bb0b50a1887b2bd Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:13:40 +1100 Subject: [PATCH 08/14] ci: SM2 and ECDSA stack harnesses run each operation with callee-saved registers zeroed On arm64 (the first run of PR #196's arm64 legs) both harnesses found words of the key in frames the library does not own: SM2 encode, encode_out, clone and derive_pk (dB and dA), the encryptions (k), and a word of k or a key in the register saves of the operation's first frames, which also made two runs differ past SAVED_REGISTERS (SM2 decryption with C2 changed, ECDSA P-384 and brainpoolP384r1 final, the DHKEM encaps and decaps rows, Ed448 from_bytes, from_bytes_out and ph signing). The disassembly shows the source: main holds a word of the secret it just computed with in x28 or x22, and run_deep, measure or a library frame saves it. arm64 has ten callee-saved registers to x86-64's six, so main keeps more there. scrubbed.rs is a small assembly trampoline (aarch64 and x86-64) that saves the callee-saved registers in its own frame, above everything searched, zeroes them and makes the call. Scan::run also paints from that frame, so the slot measure's 64-byte frame leaves unwritten holds paint rather than an earlier setup call's residue (the ECDSA create_signer finding, a limb from the from_bytes before it). STACK_DETAIL=1 prints where each finding lies, as the symmetric harness does. With this alone every SM2 row passes on arm64 (rustc 1.100 under qemu-user, which reproduces CI's arm64 output); the ECDSA harness still finds the from_bytes limb and the Ed25519 signing comparison, fixed in the next two commits. x86-64 passes with rustc 1.97, 1.88 and 1.100. Assisted-by: Claude:claude-opus-5-5 --- CLAUDE.md | 5 +- dev_scripts/ecdsa_stack_harness/src/main.rs | 48 ++++++- .../ecdsa_stack_harness/src/scrubbed.rs | 121 ++++++++++++++++++ dev_scripts/sm2_stack_harness/src/main.rs | 48 ++++++- dev_scripts/sm2_stack_harness/src/scrubbed.rs | 121 ++++++++++++++++++ 5 files changed, 338 insertions(+), 5 deletions(-) create mode 100644 dev_scripts/ecdsa_stack_harness/src/scrubbed.rs create mode 100644 dev_scripts/sm2_stack_harness/src/scrubbed.rs diff --git a/CLAUDE.md b/CLAUDE.md index 9786e97b4..ab7dd5195 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -582,7 +582,10 @@ A stack check's pass on x86-64 does not carry to another target: a wipe takes a over the stack below its caller, but never clears the registers that frame saves or the padding above its array, and the size of both, like the depth of the frames it wipes, is the target's. That is why the SM2, ECDSA and symmetric stack checks run on arm64 as well, and why a target -they do not run on is not covered by them. +they do not run on is not covered by them. The SM2 and ECDSA harnesses run each operation with +the callee-saved registers zeroed (`src/scrubbed.rs`): arm64 has ten, and the harness's own +copies of a key otherwise reached the stack through a library frame's register saves. Their +`STACK_DETAIL=1` prints how far below the call each finding lies. `cargo test --all` is the workspace run, so a failing test does block a PR; what CI does not run is `cargo mutants`, the CLI shell tests under `cli/tests/`, or rustdoc with warnings denied. diff --git a/dev_scripts/ecdsa_stack_harness/src/main.rs b/dev_scripts/ecdsa_stack_harness/src/main.rs index 94ef88770..d490017a9 100644 --- a/dev_scripts/ecdsa_stack_harness/src/main.rs +++ b/dev_scripts/ecdsa_stack_harness/src/main.rs @@ -15,6 +15,12 @@ //! for the random operations two draws of the RNG), and the two copies compared: but for what the //! operation hands out and the registers the call's first frames saved, they must be the same. //! +//! Each operation runs with the callee-saved registers zero ([`scrubbed`]): a word of a secret +//! this program computed with, waiting in one of them, would otherwise be saved to the stack by +//! the operation's first frames and found there, as on arm64 it was. With `STACK_DETAIL` set, +//! each finding is also printed with how far below the call it lies (negative above it, in this +//! program's frames), which is what a wipe is sized from. +//! //! Controls: nothing run must leave nothing, and the same stack twice; a copy of `d` left in a //! frame must be found, and copies of two keys must differ. //! @@ -63,6 +69,7 @@ use std::collections::HashSet; use std::hint::black_box; mod ed; +mod scrubbed; /// How far below the call the stack is painted and searched. The deepest operation here uses /// under 16 KiB. @@ -164,9 +171,18 @@ impl Scan { Self { buf: vec![0u8; DEPTH], before: vec![0u8; DEPTH], failures: 0, report_only: false } } - /// Paints, runs `f` and copies the stack out. What `f` returns comes back by value. + /// Paints, runs `f` and copies the stack out. What `f` returns comes back by value. Run with + /// the callee-saved registers zero ([`scrubbed`]), and painted from that frame down as well + /// as from [`measure`]'s, so that the slots `measure`'s own frame leaves unwritten hold the + /// paint and not what an earlier call of this program's left there. fn run(&mut self, f: impl FnOnce() -> T) -> T { - measure(&mut self.buf, f) + let mut result = None; + let buf = &mut self.buf; + scrubbed::call(|| { + paint(); + result = Some(measure(buf, f)); + }); + result.unwrap() } /// The bytes of stack the last run used, and for each of `values`, how many of its words @@ -202,6 +218,9 @@ impl Scan { .filter(|(_, hits, _)| *hits > 0) .map(|(name, hits, words)| format!("{name}: {hits} of {words} words")) .collect(); + if detail() { + self.where_found(values); + } if found.is_empty() { println!("ok {operation}: none of its secrets in the {used} bytes of stack it used"); } else { @@ -214,6 +233,19 @@ impl Scan { } } + /// With `STACK_DETAIL` set: how far below the call each word of `values` that was found lies, + /// negative for a word above it, in the frames of this program that run the operation. + fn where_found(&self, values: &Values) { + for (name, image) in values { + for word in image.chunks_exact(8).filter(|w| w.iter().any(|b| *b != w[0])) { + for at in (0..DEPTH - 7).filter(|at| self.buf[*at..at + 8] == *word) { + let below = (DEPTH - PAD) as isize - at as isize; + println!(" {name}: a word {below} bytes below the call"); + } + } + } + } + /// After the leak control: every word of `values` must be found. fn leaked(&mut self, operation: &str, values: &Values) { let (_, counts) = self.search(values); @@ -270,6 +302,13 @@ impl Scan { // within SAVED_REGISTERS of the call are put down to that. let deep_end = end.min((DEPTH - PAD).saturating_sub(SAVED_REGISTERS)); if !explained && deep_end > i { + if detail() { + println!( + " {} bytes differ {} bytes below the call", + deep_end - i, + (DEPTH - i).saturating_sub(PAD) + ); + } count += deep_end - i; furthest = furthest.max((DEPTH - i).saturating_sub(PAD)); } @@ -311,6 +350,11 @@ impl Scan { } } +/// Whether `STACK_DETAIL` is set: then where each finding lies is printed too, for sizing a wipe. +fn detail() -> bool { + std::env::var_os("STACK_DETAIL").is_some() +} + /// `len` bytes of SHA-512 in counter mode over `label`: the harness's own source of distinct, /// fixed secrets. fn bytes_of(label: &str, len: usize) -> Vec { diff --git a/dev_scripts/ecdsa_stack_harness/src/scrubbed.rs b/dev_scripts/ecdsa_stack_harness/src/scrubbed.rs new file mode 100644 index 000000000..56550d18d --- /dev/null +++ b/dev_scripts/ecdsa_stack_harness/src/scrubbed.rs @@ -0,0 +1,121 @@ +//! A call made with every callee-saved register zero. This program computes with the secrets it +//! searches for (to know what to search for, and to check the operation's output), and a word +//! of one can wait in a callee-saved register of `main` across the call that runs the operation; +//! the first frame below that uses the register saves it, a copy the search then finds, which is +//! this program's and not the operation's. A Rust function cannot clear those registers, so this +//! is a few lines of assembly: it saves them in its own frame, above every frame searched, zeroes +//! them, makes the call and restores them. +//! +//! aarch64 (AAPCS64): x19-x28 and the low halves of v8-v15. x86-64 (System V): rbx, rbp and +//! r12-r15. The caller-saved registers are not touched: no callee saves those. + +#[cfg(target_arch = "aarch64")] +core::arch::global_asm!( + ".text", + ".globl stack_harness_scrubbed_call", + ".type stack_harness_scrubbed_call, %function", + ".p2align 2", + "stack_harness_scrubbed_call:", + "stp x29, x30, [sp, #-160]!", + "mov x29, sp", + "stp x19, x20, [sp, #16]", + "stp x21, x22, [sp, #32]", + "stp x23, x24, [sp, #48]", + "stp x25, x26, [sp, #64]", + "stp x27, x28, [sp, #80]", + "stp d8, d9, [sp, #96]", + "stp d10, d11, [sp, #112]", + "stp d12, d13, [sp, #128]", + "stp d14, d15, [sp, #144]", + "mov x16, x0", + "mov x0, x1", + "mov x19, xzr", + "mov x20, xzr", + "mov x21, xzr", + "mov x22, xzr", + "mov x23, xzr", + "mov x24, xzr", + "mov x25, xzr", + "mov x26, xzr", + "mov x27, xzr", + "mov x28, xzr", + "movi v8.16b, #0", + "movi v9.16b, #0", + "movi v10.16b, #0", + "movi v11.16b, #0", + "movi v12.16b, #0", + "movi v13.16b, #0", + "movi v14.16b, #0", + "movi v15.16b, #0", + "blr x16", + "ldp d14, d15, [sp, #144]", + "ldp d12, d13, [sp, #128]", + "ldp d10, d11, [sp, #112]", + "ldp d8, d9, [sp, #96]", + "ldp x27, x28, [sp, #80]", + "ldp x25, x26, [sp, #64]", + "ldp x23, x24, [sp, #48]", + "ldp x21, x22, [sp, #32]", + "ldp x19, x20, [sp, #16]", + "ldp x29, x30, [sp], #160", + "ret", + ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", +); + +#[cfg(target_arch = "x86_64")] +core::arch::global_asm!( + ".text", + ".globl stack_harness_scrubbed_call", + ".type stack_harness_scrubbed_call, @function", + ".p2align 4", + "stack_harness_scrubbed_call:", + "push rbp", + "push rbx", + "push r12", + "push r13", + "push r14", + "push r15", + // Six pushes and the return address: 8 more aligns the stack to 16 at the call. + "sub rsp, 8", + "mov rax, rdi", + "mov rdi, rsi", + "xor ebp, ebp", + "xor ebx, ebx", + "xor r12d, r12d", + "xor r13d, r13d", + "xor r14d, r14d", + "xor r15d, r15d", + "call rax", + "add rsp, 8", + "pop r15", + "pop r14", + "pop r13", + "pop r12", + "pop rbx", + "pop rbp", + "ret", + ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", +); + +#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] +compile_error!("the stack harness clears the callee-saved registers on aarch64 and x86-64 only"); + +unsafe extern "C" { + /// Calls `job(arg)` with the callee-saved registers zero, and restores them. + fn stack_harness_scrubbed_call(job: extern "C" fn(*mut u8), arg: *mut u8); +} + +/// Runs `f` with every callee-saved register zero, its frames below one of this module's that +/// holds what those registers held. +pub fn call(f: F) { + extern "C" fn job(arg: *mut u8) { + // SAFETY: `arg` is the `Option` of `call`, alive and borrowed by nothing else until + // the call returns. A panic here aborts, as a panic out of an `extern "C"` function does. + let f = unsafe { &mut *arg.cast::>() }; + (f.take().unwrap())(); + } + let mut f = Some(f); + // SAFETY: the assembly above follows the C calling convention, restores every register it + // changes that the convention asks it to keep, and passes `arg` on unchanged. + unsafe { stack_harness_scrubbed_call(job::, (&raw mut f).cast()) } +} diff --git a/dev_scripts/sm2_stack_harness/src/main.rs b/dev_scripts/sm2_stack_harness/src/main.rs index bff347337..ea11fd736 100644 --- a/dev_scripts/sm2_stack_harness/src/main.rs +++ b/dev_scripts/sm2_stack_harness/src/main.rs @@ -14,6 +14,12 @@ //! copies compared: but for the ciphertext and the registers the call's first frames saved, //! they must be the same. //! +//! Each operation runs with the callee-saved registers zero ([`scrubbed`]): a word of a secret +//! this program computed with, waiting in one of them, would otherwise be saved to the stack by +//! the operation's first frames and found there, as on arm64 it was. With `STACK_DETAIL` set, +//! each finding is also printed with how far below the call it lies (negative above it, in this +//! program's frames), which is what a wipe is sized from. +//! //! Controls: nothing run must leave nothing, and the same stack twice; a copy of `dB` left in a //! frame must be found, and copies of two keys must differ. //! @@ -40,6 +46,8 @@ use bouncycastle_ec::sm2::sm2::SIG_LEN; use std::collections::HashSet; use std::hint::black_box; +mod scrubbed; + /// How far below the call the stack is painted and searched. The deepest operation here uses /// under 8 KiB. const DEPTH: usize = 256 * 1024; @@ -256,9 +264,18 @@ impl Scan { Self { buf: vec![0u8; DEPTH], before: vec![0u8; DEPTH], failures: 0 } } - /// Paints, runs `f` and copies the stack out. What `f` returns comes back by value. + /// Paints, runs `f` and copies the stack out. What `f` returns comes back by value. Run with + /// the callee-saved registers zero ([`scrubbed`]), and painted from that frame down as well + /// as from [`measure`]'s, so that the slots `measure`'s own frame leaves unwritten hold the + /// paint and not what an earlier call of this program's left there. fn run(&mut self, f: impl FnOnce() -> T) -> T { - measure(&mut self.buf, f) + let mut result = None; + let buf = &mut self.buf; + scrubbed::call(|| { + paint(); + result = Some(measure(buf, f)); + }); + result.unwrap() } /// The bytes of stack the last run used, and for each of `values`, how many of its words @@ -294,6 +311,9 @@ impl Scan { .filter(|(_, hits, _)| *hits > 0) .map(|(name, hits, words)| format!("{name}: {hits} of {words} words")) .collect(); + if detail() { + self.where_found(values); + } if found.is_empty() { println!("ok {operation}: none of its secrets in the {used} bytes of stack it used"); } else { @@ -305,6 +325,19 @@ impl Scan { } } + /// With `STACK_DETAIL` set: how far below the call each word of `values` that was found lies, + /// negative for a word above it, in the frames of this program that run the operation. + fn where_found(&self, values: &Values) { + for (name, image) in values { + for word in image.chunks_exact(8).filter(|w| w.iter().any(|b| *b != w[0])) { + for at in (0..DEPTH - 7).filter(|at| self.buf[*at..at + 8] == *word) { + let below = (DEPTH - PAD) as isize - at as isize; + println!(" {name}: a word {below} bytes below the call"); + } + } + } + } + /// After the leak control: every word of `values` must be found. fn leaked(&mut self, operation: &str, values: &Values) { let (_, counts) = self.search(values); @@ -349,6 +382,12 @@ impl Scan { // held is this program's own: a loop's pointer, a length. let below_the_call = (DEPTH - end).saturating_sub(PAD); if !explained && below_the_call >= SAVED_REGISTERS { + if detail() { + println!( + " {len} bytes differ {} bytes below the call", + (DEPTH - i).saturating_sub(PAD) + ); + } count += len; furthest = furthest.max((DEPTH - i).saturating_sub(PAD)); } @@ -389,6 +428,11 @@ impl Scan { } } +/// Whether `STACK_DETAIL` is set: then where each finding lies is printed too, for sizing a wipe. +fn detail() -> bool { + std::env::var_os("STACK_DETAIL").is_some() +} + /// A message of `len` bytes with no 8-byte word of one repeated byte. fn message(len: usize) -> Box<[u8]> { (0..len).map(|i| (i * 37 + 11) as u8).collect() diff --git a/dev_scripts/sm2_stack_harness/src/scrubbed.rs b/dev_scripts/sm2_stack_harness/src/scrubbed.rs new file mode 100644 index 000000000..56550d18d --- /dev/null +++ b/dev_scripts/sm2_stack_harness/src/scrubbed.rs @@ -0,0 +1,121 @@ +//! A call made with every callee-saved register zero. This program computes with the secrets it +//! searches for (to know what to search for, and to check the operation's output), and a word +//! of one can wait in a callee-saved register of `main` across the call that runs the operation; +//! the first frame below that uses the register saves it, a copy the search then finds, which is +//! this program's and not the operation's. A Rust function cannot clear those registers, so this +//! is a few lines of assembly: it saves them in its own frame, above every frame searched, zeroes +//! them, makes the call and restores them. +//! +//! aarch64 (AAPCS64): x19-x28 and the low halves of v8-v15. x86-64 (System V): rbx, rbp and +//! r12-r15. The caller-saved registers are not touched: no callee saves those. + +#[cfg(target_arch = "aarch64")] +core::arch::global_asm!( + ".text", + ".globl stack_harness_scrubbed_call", + ".type stack_harness_scrubbed_call, %function", + ".p2align 2", + "stack_harness_scrubbed_call:", + "stp x29, x30, [sp, #-160]!", + "mov x29, sp", + "stp x19, x20, [sp, #16]", + "stp x21, x22, [sp, #32]", + "stp x23, x24, [sp, #48]", + "stp x25, x26, [sp, #64]", + "stp x27, x28, [sp, #80]", + "stp d8, d9, [sp, #96]", + "stp d10, d11, [sp, #112]", + "stp d12, d13, [sp, #128]", + "stp d14, d15, [sp, #144]", + "mov x16, x0", + "mov x0, x1", + "mov x19, xzr", + "mov x20, xzr", + "mov x21, xzr", + "mov x22, xzr", + "mov x23, xzr", + "mov x24, xzr", + "mov x25, xzr", + "mov x26, xzr", + "mov x27, xzr", + "mov x28, xzr", + "movi v8.16b, #0", + "movi v9.16b, #0", + "movi v10.16b, #0", + "movi v11.16b, #0", + "movi v12.16b, #0", + "movi v13.16b, #0", + "movi v14.16b, #0", + "movi v15.16b, #0", + "blr x16", + "ldp d14, d15, [sp, #144]", + "ldp d12, d13, [sp, #128]", + "ldp d10, d11, [sp, #112]", + "ldp d8, d9, [sp, #96]", + "ldp x27, x28, [sp, #80]", + "ldp x25, x26, [sp, #64]", + "ldp x23, x24, [sp, #48]", + "ldp x21, x22, [sp, #32]", + "ldp x19, x20, [sp, #16]", + "ldp x29, x30, [sp], #160", + "ret", + ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", +); + +#[cfg(target_arch = "x86_64")] +core::arch::global_asm!( + ".text", + ".globl stack_harness_scrubbed_call", + ".type stack_harness_scrubbed_call, @function", + ".p2align 4", + "stack_harness_scrubbed_call:", + "push rbp", + "push rbx", + "push r12", + "push r13", + "push r14", + "push r15", + // Six pushes and the return address: 8 more aligns the stack to 16 at the call. + "sub rsp, 8", + "mov rax, rdi", + "mov rdi, rsi", + "xor ebp, ebp", + "xor ebx, ebx", + "xor r12d, r12d", + "xor r13d, r13d", + "xor r14d, r14d", + "xor r15d, r15d", + "call rax", + "add rsp, 8", + "pop r15", + "pop r14", + "pop r13", + "pop r12", + "pop rbx", + "pop rbp", + "ret", + ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", +); + +#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] +compile_error!("the stack harness clears the callee-saved registers on aarch64 and x86-64 only"); + +unsafe extern "C" { + /// Calls `job(arg)` with the callee-saved registers zero, and restores them. + fn stack_harness_scrubbed_call(job: extern "C" fn(*mut u8), arg: *mut u8); +} + +/// Runs `f` with every callee-saved register zero, its frames below one of this module's that +/// holds what those registers held. +pub fn call(f: F) { + extern "C" fn job(arg: *mut u8) { + // SAFETY: `arg` is the `Option` of `call`, alive and borrowed by nothing else until + // the call returns. A panic here aborts, as a panic out of an `extern "C"` function does. + let f = unsafe { &mut *arg.cast::>() }; + (f.take().unwrap())(); + } + let mut f = Some(f); + // SAFETY: the assembly above follows the C calling convention, restores every register it + // changes that the convention asks it to keep, and passes `arg` on unchanged. + unsafe { stack_harness_scrubbed_call(job::, (&raw mut f).cast()) } +} From b0fc413a2484b1bc2c12eee5634570dd673b6d7d Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:13:40 +1100 Subject: [PATCH 09/14] ci: ECDSA harness accepts public values lying side by side in either order The comparison of two runs counted a differing run as public only when it was one substring of the image it was given. On arm64 Ed25519 signing (sign_deterministic, sign_deterministic_out, both ph forms and the ph final) left R and k's 64-byte digest next to each other, both public, in the other order from the image, and failed with 96 bytes differing. A run is now public when it is a sequence of pieces of the image, each a word or longer but the last, at the same places in both runs. Assisted-by: Claude:claude-opus-5-5 --- dev_scripts/ecdsa_stack_harness/src/main.rs | 31 +++++++++++++++++---- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/dev_scripts/ecdsa_stack_harness/src/main.rs b/dev_scripts/ecdsa_stack_harness/src/main.rs index d490017a9..bfcfd1eed 100644 --- a/dev_scripts/ecdsa_stack_harness/src/main.rs +++ b/dev_scripts/ecdsa_stack_harness/src/main.rs @@ -292,11 +292,7 @@ impl Scan { while end < DEPTH && self.before[end] != self.buf[end] { end += 1; } - let len = end - i; - let explained = (0..public.len().saturating_sub(len - 1)).any(|at| { - public_before[at..at + len] == self.before[i..end] - && public[at..at + len] == self.buf[i..end] - }); + let explained = self.public_run(i, end, public_before, public); // The first frames of a call save the registers they go on to use, and what those // held is this program's own: a loop's pointer, a length. Only the bytes of the run // within SAVED_REGISTERS of the call are put down to that. @@ -317,6 +313,31 @@ impl Scan { (count, furthest) } + /// Whether the bytes `i..end`, in which the two runs differ, are pieces of `public_before` in + /// the kept run and the same pieces of `public` in the last, one after another: two public + /// values can lie side by side, in any order. Each piece but the last is at least a word. + fn public_run(&self, i: usize, end: usize, public_before: &[u8], public: &[u8]) -> bool { + let mut p = i; + while p < end { + let piece = (0..public.len()) + .map(|at| { + (0..(end - p).min(public.len() - at)) + .take_while(|l| { + public_before[at + l] == self.before[p + l] + && public[at + l] == self.buf[p + l] + }) + .count() + }) + .max() + .unwrap_or(0); + if piece < 8.min(end - p) { + return false; + } + p += piece; + } + true + } + /// After the same operation run twice, at the same addresses, over different secrets: the /// stack it used must be the same both times, but for what it handed out, `public_before` /// the first time and `public` the second. A known value is not needed for this, so it From 6ae975c93ac44a562609114d9672441cc3e54df4 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:13:51 +1100 Subject: [PATCH 10/14] ec: private-key decoding wipes the scalar it reduced into ECDSA, ECC CDH and DHKEM from_bytes built the key from from_borrowed_limbs, whose scalar was moved into the Result: the memory it was reduced into stayed in the decoding closure's frame, unwiped. On arm64 that frame's top slot lies under the 8-byte padding of the wipe's own frame (between its saved registers and its array), which the wipe never writes, so check_ecdsa_stack.sh found one limb of d 136 bytes below the call on P-256, P-384, secp256k1 and the brainpool curves; on x86-64 the slot fell inside the array. SecretScalar gains from_borrowed_limbs_into, which reduces into a scalar the caller holds, and the decodings go through curve::private_key_from_be_bytes: it reduces into a local that is wiped when dropped and hands the key a copy, so the result does not depend on where the compiler puts a moved-from temporary. Outputs are byte-identical: decoding, re-encoding, deterministic signing and the DHKEM decode over 3003 inputs per curve (2144 to 441 accepted) hash the same before and after on all seven curves; the ec test suite passes. Assisted-by: Claude:claude-opus-5-5 --- alpha_0.1.4_release_notes.md | 1 + crypto/ec/src/curve.rs | 24 ++++++++++++++++++++++++ crypto/ec/src/eccdh/dhkem.rs | 8 ++++++-- crypto/ec/src/eccdh/keys.rs | 17 ++++++++++------- crypto/ec/src/ecdsa/keys.rs | 14 +++++++++----- crypto/ec/src/hazmat/bp256r1_scalar.rs | 4 ++++ crypto/ec/src/hazmat/bp384r1_scalar.rs | 4 ++++ crypto/ec/src/hazmat/bp512r1_scalar.rs | 4 ++++ crypto/ec/src/hazmat/p256_scalar.rs | 4 ++++ crypto/ec/src/hazmat/p256k1_scalar.rs | 4 ++++ crypto/ec/src/hazmat/p384_scalar.rs | 4 ++++ crypto/ec/src/hazmat/p521_scalar.rs | 4 ++++ 12 files changed, 78 insertions(+), 14 deletions(-) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 1c3e825ac..8eb73d5dd 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -427,5 +427,6 @@ * ECC CDH agreement and DHKEM over P-256, P-384 and P-521 (each DH product, `pk(skR)`, the private-key test of `DeriveKeyPair`) run their scalar multiplications in a frame whose stack is then overwritten, so a limb of `d`, limbs of `Z` and the multiplier's intermediates are not left on the dead stack, and an encapsulation no longer moves its ephemeral key out of key generation's `Result`, which left a limb of it and of the RNG's draw on P-521. `agree` takes 0.1 to 0.4% more instructions and an encapsulation or decapsulation 0.04 to 0.4%; their stack rows rise by 1.4 to 3.3 kB. Outputs are unchanged. * `dhkem::hazmat`'s `salt_key`, `labeled_extract_out` and `labeled_expand` (every DHKEM's KDF, X25519's and X448's included, and HPKE's key schedule, whose salt key is keyed by the KEM's shared secret) and `DHKEM::derive_key_pair` run in a frame whose stack is then overwritten, so copies of the HMAC pad states keyed by a salt or a PRK, and the moved copies of a derived private key, are not left on the dead stack; `dev_scripts/check_ecdsa_stack.sh` now covers the encodings, `derive_pk`, ECC CDH agreement and the DHKEMs (X25519's reported, not failed). Measured against 65625f5e built the same way, the X25519 and X448 KEM rows rise by 144 bytes, HPKE's `export_out` by 112 and its other rows move by -672 to +32 bytes (the table now reads what that build gives); outputs are unchanged. * Ed25519 and Ed448 run each fixed-base multiplication (key expansion's `[s]B`, signing's `[r]B`) in a frame whose stack is then overwritten (3 KiB and 4 KiB), so limbs of the point and of its normalising inversion are not left on the dead stack after key generation, decoding or signing; and `keygen`, `keygen_from_seed`, the trait's `from_bytes` and `clone` of the Ed25519, Ed448, X25519 and X448 private keys build the key in a wiped frame, so the move out of it leaves no copy of the key, its digest, `s` or the prefix. `dev_scripts/check_ecdsa_stack.sh` covers these keys and every form of EdDSA signing and XDH agreement (X25519's documented inversion residue is reported, not failed). Sized on x86-64; arm64 is not yet measured. Outputs are unchanged; about 0.3% more instructions over a mix of decoding, signing and agreement. Key generation, private-key decoding and signing reach 1.1 to 1.7 kB (Ed25519) and 1.4 to 2.3 kB (Ed448) deeper into the stack, the by-value XDH key rows up to 416 bytes; the four memory tables are re-measured. +* ECDSA, ECC CDH and DHKEM private-key decoding (`from_bytes`, `DHKEMParams::private_key_from_bytes`) reduces the key into a scalar that is wiped when dropped, and keeps a copy of it, through the new `SecretScalar::from_borrowed_limbs_into`: the scalar it moved out instead left a limb of `d` at the top of the decoding's frame, which on arm64 the stack wipe after it does not reach (P-256, P-384, secp256k1 and the brainpool curves). Outputs are unchanged. * `bouncycastle-digest`: SHA-384/SHA-512/SHA-512/t compression keeps a 16-word rolling message schedule, zeroized on return, in place of the 80-word array, and needs fewer operations per round: about 11% fewer instructions and 19 to 21% faster on x86-64, with the compression using 320 rather than 800 bytes of stack (368 rather than 852 on thumbv6m) and a 640-byte rather than 1280-byte wipe after it. Outputs are unchanged. * The Ascon stack table in `bouncycastle-symmetric`, the BLAKE2 one in `bouncycastle-digest` and both ML-KEM memory tables in `bouncycastle-pqc` re-measured, each by the method its prose now states in full (the earlier figures did not reproduce): Ascon rows move by -184 to +112 bytes, the BLAKE2 hash one-shot reads 696 bytes where one-shot and streaming shared 1,120, and ML-KEM Encaps is up to 15% lower (ML-KEM-1024 26,776 to 22,872 bytes) and expanded-key Encaps up to 20% higher. diff --git a/crypto/ec/src/curve.rs b/crypto/ec/src/curve.rs index 4765de13b..36d4d69db 100644 --- a/crypto/ec/src/curve.rs +++ b/crypto/ec/src/curve.rs @@ -122,6 +122,9 @@ pub trait SecretScalar: Clone + Debug + PartialEq + Eq + 'static { fn from_limbs(limbs: Self::Limbs) -> Self; /// From borrowed limbs, reduced mod `n`, leaving the caller's copy to the caller. fn from_borrowed_limbs(limbs: &Self::Limbs) -> Self; + /// As [`from_borrowed_limbs`](Self::from_borrowed_limbs), reduced into `out`, which is + /// wiped when it is dropped, rather than into a scalar that is returned by a move. + fn from_borrowed_limbs_into(limbs: &Self::Limbs, out: &mut Self); /// From the big-endian encoding, reduced mod `n`. fn from_be_bytes(bytes: &Self::Bytes) -> Self; /// The big-endian encoding, as a plain array the caller asked for. @@ -331,6 +334,27 @@ pub fn private_scalar_from_be_bytes(bytes: &C::ScalarBytes) -> Option< Some(C::Scalar::from_borrowed_limbs(&limbs)) } +/// [`private_scalar_from_be_bytes`] for a key's decoding in a wiped frame: `key` of the scalar, +/// or `refused()`. The scalar is reduced into a local that is wiped when it is dropped, and `key` +/// is given a copy of it. Returned by a move, as [`SecretScalar::from_borrowed_limbs`] returns +/// it, the scalar would leave the memory it was reduced into unwiped in the frame of the closure +/// that runs this, at the top, which the wipe after that frame does not reach (on aarch64 its +/// own saved registers and padding lie over those slots). +pub(crate) fn private_key_from_be_bytes( + bytes: &C::ScalarBytes, + key: impl FnOnce(C::Scalar) -> R, + refused: impl FnOnce() -> R, +) -> R { + let mut limbs = Secret::::new(); + C::limbs_from_be_bytes_into(bytes, &mut limbs); + if !C::scalar_in_range(&limbs).to_bool() { + return refused(); + } + let mut d = C::Scalar::from_limbs(C::Limbs::ZEROED); + C::Scalar::from_borrowed_limbs_into(&limbs, &mut d); + key(d.clone()) +} + /// What the stack wipe overwrites after an ECDSA or ECC CDH private key is decoded: this many of /// the curve's limb arrays and this many words, 1536 bytes. Unwiped, `from_bytes` writes to at /// most 808 bytes below the call (P-521; 376 on the other curves; x86-64, rustc 1.97 and 1.88, diff --git a/crypto/ec/src/eccdh/dhkem.rs b/crypto/ec/src/eccdh/dhkem.rs index 629cf91ee..cf3cafdf9 100644 --- a/crypto/ec/src/eccdh/dhkem.rs +++ b/crypto/ec/src/eccdh/dhkem.rs @@ -42,7 +42,7 @@ use crate::curve::{ AGREE_STACK_FIXED, AGREE_STACK_PER_LIMB, Curve, DECODE_STACK_FIXED, DECODE_STACK_PER_LIMB, - JacobianPoint, private_scalar_from_be_bytes, public_point_wiped, + JacobianPoint, private_key_from_be_bytes, public_point_wiped, }; use crate::dhkem::{ AuthDecapsulatingKey, AuthEncapsulatingKey, DHKEM, DHKEMParams, DeriveKeyPairForm, HpkeKem, @@ -352,7 +352,11 @@ where // The key is built in a wiped frame, as the private key's `from_bytes` builds it. fn private_key_from_bytes(sk: &[u8; N_SK]) -> Option> { in_wiped_frame::(|| { - private_scalar_from_be_bytes::(sk).map(ECCDHPrivateKey::from_scalar) + private_key_from_be_bytes::( + sk, + |d| Some(ECCDHPrivateKey::from_scalar(d)), + || None, + ) }) } diff --git a/crypto/ec/src/eccdh/keys.rs b/crypto/ec/src/eccdh/keys.rs index 177457901..51507cf1a 100644 --- a/crypto/ec/src/eccdh/keys.rs +++ b/crypto/ec/src/eccdh/keys.rs @@ -3,7 +3,7 @@ use crate::curve::{ Curve, DECODE_STACK_FIXED, DECODE_STACK_PER_LIMB, ENCODE_STACK_FIXED, ENCODE_STACK_PER_LIMB, - KEYGEN_STACK_FIXED, KEYGEN_STACK_PER_LIMB, SecretScalar, private_scalar_from_be_bytes, + KEYGEN_STACK_FIXED, KEYGEN_STACK_PER_LIMB, SecretScalar, private_key_from_be_bytes, public_point_wiped, }; use crate::eccdh::keys_common::{AgreementKeyPair, DerivePublicKey}; @@ -63,9 +63,10 @@ where /// `d` must be in `[1, n-1]` (SP 800-56A Rev. 3 Section 5.6.2.1.2), checked on the raw /// big-endian value before any reduction, so that `d = n + 1` is refused rather than loaded - /// as `d = 1`; the check and the load are - /// [`private_scalar_from_be_bytes`], - /// which stages the candidate in a `Secret` and reveals only whether the key loaded. + /// as `d = 1`; the check and the load are those of [`private_scalar_from_be_bytes`], which + /// stages the candidate in a `Secret` and reveals only whether the key loaded. + /// + /// [`private_scalar_from_be_bytes`]: crate::curve::private_scalar_from_be_bytes fn from_bytes(bytes: &[u8]) -> Result { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -73,9 +74,11 @@ where // The key is built in the wiped frame, `Result` and all: the temporaries of the // conversion would otherwise hold a copy of `d` in this frame. in_wiped_frame::(|| { - private_scalar_from_be_bytes::(bytes) - .map(Self) - .ok_or(KeyDecodingError("ECC CDH private key must be in [1, n-1]")) + private_key_from_be_bytes::( + bytes, + |d| Ok(Self(d)), + || Err(KeyDecodingError("ECC CDH private key must be in [1, n-1]")), + ) }) } } diff --git a/crypto/ec/src/ecdsa/keys.rs b/crypto/ec/src/ecdsa/keys.rs index 0ee800ba7..9b20a1bde 100644 --- a/crypto/ec/src/ecdsa/keys.rs +++ b/crypto/ec/src/ecdsa/keys.rs @@ -7,7 +7,7 @@ use crate::curve::{ Curve, DECODE_STACK_FIXED, DECODE_STACK_PER_LIMB, ENCODE_STACK_FIXED, ENCODE_STACK_PER_LIMB, - KEYGEN_STACK_FIXED, KEYGEN_STACK_PER_LIMB, SecretScalar, private_scalar_from_be_bytes, + KEYGEN_STACK_FIXED, KEYGEN_STACK_PER_LIMB, SecretScalar, private_key_from_be_bytes, public_point_wiped, }; use crate::ecdsa::ecdsa::EcdsaHash; @@ -76,9 +76,11 @@ where /// FIPS 186-5 Section 6.2: `d` is in `[1, n-1]`, checked on the raw big-endian value before /// any reduction, so that `d = n + 1` is refused rather than loaded as `d = 1` (one key would - /// otherwise have unboundedly many encodings); the check and the load are + /// otherwise have unboundedly many encodings); the check and the load are those of /// [`private_scalar_from_be_bytes`], which stages the candidate in a `Secret` and reveals only /// whether the key loaded. + /// + /// [`private_scalar_from_be_bytes`]: crate::curve::private_scalar_from_be_bytes fn from_bytes(bytes: &[u8]) -> Result { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -86,9 +88,11 @@ where // The key is built in the wiped frame, `Result` and all: the temporaries of the // conversion would otherwise hold a copy of `d` in this frame. in_wiped_frame::(|| { - private_scalar_from_be_bytes::(bytes) - .map(|d| Self { d, _hash: PhantomData }) - .ok_or(KeyDecodingError("ECDSA private key must be in [1, n-1]")) + private_key_from_be_bytes::( + bytes, + |d| Ok(Self { d, _hash: PhantomData }), + || Err(KeyDecodingError("ECDSA private key must be in [1, n-1]")), + ) }) } } diff --git a/crypto/ec/src/hazmat/bp256r1_scalar.rs b/crypto/ec/src/hazmat/bp256r1_scalar.rs index 9e66a3642..45312b0fa 100644 --- a/crypto/ec/src/hazmat/bp256r1_scalar.rs +++ b/crypto/ec/src/hazmat/bp256r1_scalar.rs @@ -306,6 +306,10 @@ impl SecretScalar for Bp256r1Scalar { Bp256r1Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 4], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 32]) -> Self { Bp256r1Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/bp384r1_scalar.rs b/crypto/ec/src/hazmat/bp384r1_scalar.rs index 8b4a5d733..c7e06a00e 100644 --- a/crypto/ec/src/hazmat/bp384r1_scalar.rs +++ b/crypto/ec/src/hazmat/bp384r1_scalar.rs @@ -314,6 +314,10 @@ impl SecretScalar for Bp384r1Scalar { Bp384r1Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 6], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 48]) -> Self { Bp384r1Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/bp512r1_scalar.rs b/crypto/ec/src/hazmat/bp512r1_scalar.rs index a92b06579..c998a6bd4 100644 --- a/crypto/ec/src/hazmat/bp512r1_scalar.rs +++ b/crypto/ec/src/hazmat/bp512r1_scalar.rs @@ -314,6 +314,10 @@ impl SecretScalar for Bp512r1Scalar { Bp512r1Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 8], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 64]) -> Self { Bp512r1Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/p256_scalar.rs b/crypto/ec/src/hazmat/p256_scalar.rs index 495eb5017..9392ade0c 100644 --- a/crypto/ec/src/hazmat/p256_scalar.rs +++ b/crypto/ec/src/hazmat/p256_scalar.rs @@ -507,6 +507,10 @@ impl SecretScalar for P256Scalar { P256Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 4], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 32]) -> Self { P256Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/p256k1_scalar.rs b/crypto/ec/src/hazmat/p256k1_scalar.rs index 497553e40..1f7f4aeec 100644 --- a/crypto/ec/src/hazmat/p256k1_scalar.rs +++ b/crypto/ec/src/hazmat/p256k1_scalar.rs @@ -446,6 +446,10 @@ impl SecretScalar for P256K1Scalar { P256K1Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 4], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 32]) -> Self { P256K1Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/p384_scalar.rs b/crypto/ec/src/hazmat/p384_scalar.rs index fec03837c..d3c34fb91 100644 --- a/crypto/ec/src/hazmat/p384_scalar.rs +++ b/crypto/ec/src/hazmat/p384_scalar.rs @@ -450,6 +450,10 @@ impl SecretScalar for P384Scalar { P384Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 6], out: &mut Self) { + reduce_once_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 48]) -> Self { P384Scalar::from_be_bytes(bytes) } diff --git a/crypto/ec/src/hazmat/p521_scalar.rs b/crypto/ec/src/hazmat/p521_scalar.rs index 94621e7c0..1396d33b6 100644 --- a/crypto/ec/src/hazmat/p521_scalar.rs +++ b/crypto/ec/src/hazmat/p521_scalar.rs @@ -551,6 +551,10 @@ impl SecretScalar for P521Scalar { P521Scalar::from_borrowed_limbs(limbs) } + fn from_borrowed_limbs_into(limbs: &[u64; 9], out: &mut Self) { + reduce_wide_into(limbs, &mut out.0); + } + fn from_be_bytes(bytes: &[u8; 66]) -> Self { P521Scalar::from_be_bytes(bytes) } From 0759b62f212e13ab4ceb939cfc7048e4945f7f58 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:13:57 +1100 Subject: [PATCH 11/14] ec: arm64 status of the SM2 and EdDSA stack wipes With the harness and decoding fixes, check_ecdsa_stack.sh and check_sm2_stack.sh pass on arm64 Linux (rustc 1.100, and nightly 1.97). The SM2 signing wipes, which said they were not measured on arm64, now give the depth there with their body taken out: 1504, 3240 and 2904 bytes for create_signer, sign_out and the final (4096 wiped), 2760 and 3064 for from_bytes and keygen (5120 wiped). The Ed25519 docs no longer predict a SHA-512 word after from_bytes_out on arm64: since the SHA-512 rewrite none is found there. The Ed448 docs and the release notes say the same of arm64. Assisted-by: Claude:claude-opus-5-5 --- alpha_0.1.4_release_notes.md | 2 +- crypto/ec/src/ed/ed25519/mod.rs | 6 ++---- crypto/ec/src/ed/ed448/mod.rs | 4 ++-- crypto/ec/src/sm2/keys.rs | 4 ++-- crypto/ec/src/sm2/mod.rs | 4 ++-- crypto/ec/src/sm2/sm2.rs | 4 ++-- dev_scripts/check_sm2_stack.sh | 8 ++++---- 7 files changed, 15 insertions(+), 17 deletions(-) diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 8eb73d5dd..b9234cca7 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -426,7 +426,7 @@ * ECDSA and ECC CDH private keys' `encode`, `encode_out` and `derive_pk` run in a frame whose stack is then overwritten, on all seven curves: the encodings left the bytes of `d` on P-521 and brainpoolP512r1, and `derive_pk` left `d`-dependent intermediates of the fixed-base multiplication (up to 5 kB) on every curve. About 150 more instructions per encoding and 0.1 to 0.5% per `derive_pk`; outputs are unchanged. * ECC CDH agreement and DHKEM over P-256, P-384 and P-521 (each DH product, `pk(skR)`, the private-key test of `DeriveKeyPair`) run their scalar multiplications in a frame whose stack is then overwritten, so a limb of `d`, limbs of `Z` and the multiplier's intermediates are not left on the dead stack, and an encapsulation no longer moves its ephemeral key out of key generation's `Result`, which left a limb of it and of the RNG's draw on P-521. `agree` takes 0.1 to 0.4% more instructions and an encapsulation or decapsulation 0.04 to 0.4%; their stack rows rise by 1.4 to 3.3 kB. Outputs are unchanged. * `dhkem::hazmat`'s `salt_key`, `labeled_extract_out` and `labeled_expand` (every DHKEM's KDF, X25519's and X448's included, and HPKE's key schedule, whose salt key is keyed by the KEM's shared secret) and `DHKEM::derive_key_pair` run in a frame whose stack is then overwritten, so copies of the HMAC pad states keyed by a salt or a PRK, and the moved copies of a derived private key, are not left on the dead stack; `dev_scripts/check_ecdsa_stack.sh` now covers the encodings, `derive_pk`, ECC CDH agreement and the DHKEMs (X25519's reported, not failed). Measured against 65625f5e built the same way, the X25519 and X448 KEM rows rise by 144 bytes, HPKE's `export_out` by 112 and its other rows move by -672 to +32 bytes (the table now reads what that build gives); outputs are unchanged. -* Ed25519 and Ed448 run each fixed-base multiplication (key expansion's `[s]B`, signing's `[r]B`) in a frame whose stack is then overwritten (3 KiB and 4 KiB), so limbs of the point and of its normalising inversion are not left on the dead stack after key generation, decoding or signing; and `keygen`, `keygen_from_seed`, the trait's `from_bytes` and `clone` of the Ed25519, Ed448, X25519 and X448 private keys build the key in a wiped frame, so the move out of it leaves no copy of the key, its digest, `s` or the prefix. `dev_scripts/check_ecdsa_stack.sh` covers these keys and every form of EdDSA signing and XDH agreement (X25519's documented inversion residue is reported, not failed). Sized on x86-64; arm64 is not yet measured. Outputs are unchanged; about 0.3% more instructions over a mix of decoding, signing and agreement. Key generation, private-key decoding and signing reach 1.1 to 1.7 kB (Ed25519) and 1.4 to 2.3 kB (Ed448) deeper into the stack, the by-value XDH key rows up to 416 bytes; the four memory tables are re-measured. +* Ed25519 and Ed448 run each fixed-base multiplication (key expansion's `[s]B`, signing's `[r]B`) in a frame whose stack is then overwritten (3 KiB and 4 KiB), so limbs of the point and of its normalising inversion are not left on the dead stack after key generation, decoding or signing; and `keygen`, `keygen_from_seed`, the trait's `from_bytes` and `clone` of the Ed25519, Ed448, X25519 and X448 private keys build the key in a wiped frame, so the move out of it leaves no copy of the key, its digest, `s` or the prefix. `dev_scripts/check_ecdsa_stack.sh` covers these keys and every form of EdDSA signing and XDH agreement (X25519's documented inversion residue is reported, not failed). Sized on x86-64; the check passes on arm64 as well. Outputs are unchanged; about 0.3% more instructions over a mix of decoding, signing and agreement. Key generation, private-key decoding and signing reach 1.1 to 1.7 kB (Ed25519) and 1.4 to 2.3 kB (Ed448) deeper into the stack, the by-value XDH key rows up to 416 bytes; the four memory tables are re-measured. * ECDSA, ECC CDH and DHKEM private-key decoding (`from_bytes`, `DHKEMParams::private_key_from_bytes`) reduces the key into a scalar that is wiped when dropped, and keeps a copy of it, through the new `SecretScalar::from_borrowed_limbs_into`: the scalar it moved out instead left a limb of `d` at the top of the decoding's frame, which on arm64 the stack wipe after it does not reach (P-256, P-384, secp256k1 and the brainpool curves). Outputs are unchanged. * `bouncycastle-digest`: SHA-384/SHA-512/SHA-512/t compression keeps a 16-word rolling message schedule, zeroized on return, in place of the 80-word array, and needs fewer operations per round: about 11% fewer instructions and 19 to 21% faster on x86-64, with the compression using 320 rather than 800 bytes of stack (368 rather than 852 on thumbv6m) and a 640-byte rather than 1280-byte wipe after it. Outputs are unchanged. * The Ascon stack table in `bouncycastle-symmetric`, the BLAKE2 one in `bouncycastle-digest` and both ML-KEM memory tables in `bouncycastle-pqc` re-measured, each by the method its prose now states in full (the earlier figures did not reproduce): Ascon rows move by -184 to +112 bytes, the BLAKE2 hash one-shot reads 696 bytes where one-shot and streaming shared 1,120, and ML-KEM Encaps is up to 15% lower (ML-KEM-1024 26,776 to 22,872 bytes) and expanded-key Encaps up to 20% higher. diff --git a/crypto/ec/src/ed/ed25519/mod.rs b/crypto/ec/src/ed/ed25519/mod.rs index 97220ebfc..22246e4cd 100644 --- a/crypto/ec/src/ed/ed25519/mod.rs +++ b/crypto/ec/src/ed/ed25519/mod.rs @@ -172,10 +172,8 @@ //! multiplication (key expansion's `[s]B`, signing's `[r]B`) the stack it used, where it leaves //! limbs of the point's coordinates and of the inversion that normalizes them. //! `dev_scripts/check_ecdsa_stack.sh` finds none of the key after key generation, decoding and -//! every form of signing in release builds for x86-64 (rustc 1.97 and 1.88); arm64 is not yet -//! measured with these wipes. SHA-512 is outside that: its load of the block that holds the -//! private key can leave words of it on the stack, seen as one word after `from_bytes_out` in -//! an arm64 build. +//! every form of signing in release builds for x86-64 (rustc 1.97 and 1.88) and arm64 (rustc +//! 1.100), the wipes being sized on x86-64. //! //! Each fixed-base multiplication checks that its result is a point of the curve before //! anything is released, and a failure is reported as an error; no input causes one. diff --git a/crypto/ec/src/ed/ed448/mod.rs b/crypto/ec/src/ed/ed448/mod.rs index 266672c47..f00c70bd9 100644 --- a/crypto/ec/src/ed/ed448/mod.rs +++ b/crypto/ec/src/ed/ed448/mod.rs @@ -190,8 +190,8 @@ //! after each operation finds none of the private key, the scalar, the prefix, the digests, //! the nonce `r`, `r + k s` or those Keccak states after `keygen_out`, `from_bytes_out`, //! `clone_from`, `encode_out`, `pk`, `==`, `keypair_consistency_check` and every form of -//! signing, in the release build for x86-64 Linux (rustc 1.97.0-nightly), the one build -//! scanned. The by-value forms leave what a move leaves, as above. +//! signing, in release builds for x86-64 Linux (rustc 1.97.0-nightly) and arm64 Linux (rustc +//! 1.100). The by-value forms leave what a move leaves, as above. //! //! Each fixed-base multiplication checks that its result is a point of the curve before //! anything is released, and a failure is reported as an error; no input causes one. diff --git a/crypto/ec/src/sm2/keys.rs b/crypto/ec/src/sm2/keys.rs index fc389d2f1..592d4c152 100644 --- a/crypto/ec/src/sm2/keys.rs +++ b/crypto/ec/src/sm2/keys.rs @@ -40,8 +40,8 @@ pub(in crate::sm2) const EXTRA_BITS_DRBG_OUTPUT_LEN: usize = 40; /// taken out, `dev_scripts/sm2_stack_harness` reports the stack written to 2664 bytes below a /// call of `from_bytes` and 2968 below one of [`keygen`] with rustc 1.97 (nightly), and 2384 and /// 2688 with rustc 1.88; with 2816 bytes wiped `dev_scripts/check_sm2_stack.sh` fails with rustc -/// 1.88, and with 2560 with either. The rest is room for a compiler that lays the frames out -/// less tightly; it has not been measured on arm64. +/// 1.88, and with 2560 with either. On arm64 Linux with rustc 1.100 the harness reports 2760 and +/// 3064 bytes. The rest is room for a compiler that lays the frames out less tightly. const WIPED_STACK_WORDS: usize = 640; /// An SM2 private key: `dA` in `[1, n-2]` (GB/T 32918.1-2016 ยง6.1 a); the draft states no range), diff --git a/crypto/ec/src/sm2/mod.rs b/crypto/ec/src/sm2/mod.rs index b2a47d4f5..b7754c70b 100644 --- a/crypto/ec/src/sm2/mod.rs +++ b/crypto/ec/src/sm2/mod.rs @@ -262,8 +262,8 @@ //! CI runs it for x86-64 and arm64 Linux. On another target, compiler or an unoptimised //! build they may not reach everything. Loading a private key (`from_bytes`) zeroizes the //! copies it makes and has no such wipe, and neither have `encode`, `encode_out` and -//! `clone`; in the x86-64 builds the check finds nothing of the key on the stack after any -//! of the four. The key a call returns, and the bytes `encode` returns, are the caller's to +//! `clone`; in the x86-64 and arm64 builds the check finds nothing of the key on the stack +//! after any of the four. The key a call returns, and the bytes `encode` returns, are the caller's to //! look after. pub mod encryption; diff --git a/crypto/ec/src/sm2/sm2.rs b/crypto/ec/src/sm2/sm2.rs index dcdfd65e6..cde1bd1b1 100644 --- a/crypto/ec/src/sm2/sm2.rs +++ b/crypto/ec/src/sm2/sm2.rs @@ -79,8 +79,8 @@ use bouncycastle_utils::secret::Secret; /// `create_signer`, 3208 below one of `sign_out` and 2840 below the streaming final with rustc /// 1.97 (nightly), and 1384, 3008 and 2640 with rustc 1.88; with 2560 bytes wiped /// `dev_scripts/check_sm2_stack.sh` fails with rustc 1.88, and with 2816 it passes with either. -/// The rest is room for a compiler that lays the frames out less tightly; it has not been -/// measured on arm64. +/// On arm64 Linux with rustc 1.100 the harness reports 1504, 3240 and 2904 bytes. The rest is +/// room for a compiler that lays the frames out less tightly. const WIPED_STACK_WORDS: usize = 512; /// Raw `r || s` signature length: two 32-byte field-width integers. See the module docs on why diff --git a/dev_scripts/check_sm2_stack.sh b/dev_scripts/check_sm2_stack.sh index 13cd98a6b..ef9ebd3eb 100755 --- a/dev_scripts/check_sm2_stack.sh +++ b/dev_scripts/check_sm2_stack.sh @@ -25,10 +25,10 @@ # # What a pass shows: that in a release build for the host, by the installed toolchain, the # wipes reach as far as the operations write. The wipes are sized by measurement on x86-64 -# Linux (the encryption wipes also with room over arm64 Linux), and CI runs this on both -# (.github/workflows/sm2-stack.yml). A pass says nothing of another target or another compiler, -# and nothing of a debug build, whose frames are larger and are not covered. It does not look at -# registers, at the heap, or at what a caller does with a key it was returned. +# Linux (the encryption and signing wipes also with room over arm64 Linux), and CI runs this on +# both (.github/workflows/sm2-stack.yml). A pass says nothing of another target or another +# compiler, and nothing of a debug build, whose frames are larger and are not covered. It does +# not look at registers, at the heap, or at what a caller does with a key it was returned. # # ./dev_scripts/check_sm2_stack.sh set -euo pipefail From d97acac03c9afe666f86e92b20ee75ac23638f25 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:42:59 +1100 Subject: [PATCH 12/14] ci: stack harnesses share the register scrub, and their comparisons are tightened Review points on the arm64 harness fixes: - The trampoline is one file, dev_scripts/stack_scrubbed_call.rs, included by both harnesses through #[path]. Its assembly is built only for aarch64 and x86-64 Linux, so any other target reaches the compile_error! rather than an assembler error. - check_ecdsa_stack.sh and check_sm2_stack.sh say that what the caller's own callee-saved registers held is out of scope, the harness zeroing them first. check_sm2_stack.sh also says the key wipe has room over arm64. - SAVED_REGISTERS, re-measured with the registers zeroed and the allowance set to 0. ECDSA: the furthest difference is 208 bytes on arm64 with rustc 1.100 (Ed25519 sign staging the signature it returns, which is public), 136 with 1.97, and 128 on x86-64 with 1.97 and 1.88, so 512 becomes 256. SM2: nothing differs within reach on either target, so 256 becomes 64. - In the ECDSA comparison, a final piece shorter than a word must carry on from where the previous piece ended in the image. check_ecdsa_stack.sh and check_sm2_stack.sh pass on arm64 (rustc 1.100 and 1.97, under qemu-user) and x86-64 (1.97 and 1.88); check_symmetric_stack.sh and check_rsa_stack.sh pass on x86-64. Assisted-by: Claude:claude-opus-5-5 --- CLAUDE.md | 2 +- dev_scripts/check_ecdsa_stack.sh | 3 +- dev_scripts/check_sm2_stack.sh | 10 +- dev_scripts/ecdsa_stack_harness/src/main.rs | 52 +++++--- dev_scripts/sm2_stack_harness/src/main.rs | 7 +- dev_scripts/sm2_stack_harness/src/scrubbed.rs | 121 ------------------ .../scrubbed.rs => stack_scrubbed_call.rs} | 13 +- 7 files changed, 54 insertions(+), 154 deletions(-) delete mode 100644 dev_scripts/sm2_stack_harness/src/scrubbed.rs rename dev_scripts/{ecdsa_stack_harness/src/scrubbed.rs => stack_scrubbed_call.rs} (88%) diff --git a/CLAUDE.md b/CLAUDE.md index ab7dd5195..acb51eefd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -583,7 +583,7 @@ over the stack below its caller, but never clears the registers that frame saves above its array, and the size of both, like the depth of the frames it wipes, is the target's. That is why the SM2, ECDSA and symmetric stack checks run on arm64 as well, and why a target they do not run on is not covered by them. The SM2 and ECDSA harnesses run each operation with -the callee-saved registers zeroed (`src/scrubbed.rs`): arm64 has ten, and the harness's own +the callee-saved registers zeroed (`dev_scripts/stack_scrubbed_call.rs`): arm64 has ten, and the harness's own copies of a key otherwise reached the stack through a library frame's register saves. Their `STACK_DETAIL=1` prints how far below the call each finding lies. diff --git a/dev_scripts/check_ecdsa_stack.sh b/dev_scripts/check_ecdsa_stack.sh index 3750a534c..7eb315f59 100755 --- a/dev_scripts/check_ecdsa_stack.sh +++ b/dev_scripts/check_ecdsa_stack.sh @@ -34,7 +34,8 @@ # Linux, and CI runs this on x86-64 and arm64 Linux (.github/workflows/ecdsa-stack.yml). A pass # says nothing of another target or another compiler, and nothing of a debug build, whose frames # are larger and are not covered. It does not look at registers, at the heap, or at what a caller -# does with a key it was returned. +# does with a key it was returned, and what the caller's own callee-saved registers held, which a +# library frame may save, is out of its scope: the harness zeroes them before each operation. # # ./dev_scripts/check_ecdsa_stack.sh set -euo pipefail diff --git a/dev_scripts/check_sm2_stack.sh b/dev_scripts/check_sm2_stack.sh index ef9ebd3eb..475d233ba 100755 --- a/dev_scripts/check_sm2_stack.sh +++ b/dev_scripts/check_sm2_stack.sh @@ -25,10 +25,12 @@ # # What a pass shows: that in a release build for the host, by the installed toolchain, the # wipes reach as far as the operations write. The wipes are sized by measurement on x86-64 -# Linux (the encryption and signing wipes also with room over arm64 Linux), and CI runs this on -# both (.github/workflows/sm2-stack.yml). A pass says nothing of another target or another -# compiler, and nothing of a debug build, whose frames are larger and are not covered. It does -# not look at registers, at the heap, or at what a caller does with a key it was returned. +# Linux (the encryption, key and signing wipes also with room over arm64 Linux), and CI runs +# this on both (.github/workflows/sm2-stack.yml). A pass says nothing of another target or +# another compiler, and nothing of a debug build, whose frames are larger and are not covered. +# It does not look at registers, at the heap, or at what a caller does with a key it was +# returned, and what the caller's own callee-saved registers held, which a library frame may +# save, is out of its scope: the harness zeroes them before each operation. # # ./dev_scripts/check_sm2_stack.sh set -euo pipefail diff --git a/dev_scripts/ecdsa_stack_harness/src/main.rs b/dev_scripts/ecdsa_stack_harness/src/main.rs index bfcfd1eed..0670640e9 100644 --- a/dev_scripts/ecdsa_stack_harness/src/main.rs +++ b/dev_scripts/ecdsa_stack_harness/src/main.rs @@ -69,6 +69,7 @@ use std::collections::HashSet; use std::hint::black_box; mod ed; +#[path = "../../stack_scrubbed_call.rs"] mod scrubbed; /// How far below the call the stack is painted and searched. The deepest operation here uses @@ -77,11 +78,13 @@ const DEPTH: usize = 256 * 1024; /// The gap between the frame that takes the copy and the operation's first frame. const PAD: usize = 16 * 1024; const PAINT: u8 = 0xA5; -/// How far below the call a difference between two runs is put down to the registers the -/// call's first frames saved, and not counted: this program's loop index and heap addresses, -/// which the frames above the wiped ones save. The furthest seen is 408 bytes, below the -/// deterministic signer's final, whose frame holds the message hash. -const SAVED_REGISTERS: usize = 512; +/// How far below the call a difference between two runs is put down to the operation's first +/// frames, above its wiped ones, and not counted: the registers they save, which +/// [`Scan::run`] has zeroed, and values handed out on the way to the caller's slot. With this +/// at 0, the furthest seen is 208 bytes on arm64 (rustc 1.100: Ed25519's `sign`, staging the +/// signature it returns), 136 on arm64 with rustc 1.97 and 128 on x86-64 (rustc 1.97 and +/// 1.88). +const SAVED_REGISTERS: usize = 256; /// The fixed RNG's seed: one draw at its start. Every operation here draws once. const SEED_LEN: usize = 128; @@ -315,25 +318,34 @@ impl Scan { /// Whether the bytes `i..end`, in which the two runs differ, are pieces of `public_before` in /// the kept run and the same pieces of `public` in the last, one after another: two public - /// values can lie side by side, in any order. Each piece but the last is at least a word. + /// values can lie side by side, in any order. Each piece is at least a word, but for the + /// whole run when it is shorter, and for a last piece that carries on where the one before + /// it ended in the image. fn public_run(&self, i: usize, end: usize, public_before: &[u8], public: &[u8]) -> bool { + // How many bytes from `p` match the image from `at`, in both runs. + let matching = |p: usize, at: usize| { + (0..(end - p).min(public.len() - at)) + .take_while(|l| { + public_before[at + l] == self.before[p + l] && public[at + l] == self.buf[p + l] + }) + .count() + }; let mut p = i; + // Where in the image the last piece ended. + let mut after: Option = None; while p < end { - let piece = (0..public.len()) - .map(|at| { - (0..(end - p).min(public.len() - at)) - .take_while(|l| { - public_before[at + l] == self.before[p + l] - && public[at + l] == self.buf[p + l] - }) - .count() - }) - .max() - .unwrap_or(0); - if piece < 8.min(end - p) { - return false; + let (len, at) = + (0..public.len()).map(|at| (matching(p, at), at)).max().unwrap_or((0, 0)); + if len >= 8 { + p += len; + after = Some(at + len); + continue; } - p += piece; + let rest = end - p; + return match after { + None => len == rest, + Some(at) => at < public.len() && matching(p, at) == rest, + }; } true } diff --git a/dev_scripts/sm2_stack_harness/src/main.rs b/dev_scripts/sm2_stack_harness/src/main.rs index ea11fd736..3d7933a1b 100644 --- a/dev_scripts/sm2_stack_harness/src/main.rs +++ b/dev_scripts/sm2_stack_harness/src/main.rs @@ -46,6 +46,7 @@ use bouncycastle_ec::sm2::sm2::SIG_LEN; use std::collections::HashSet; use std::hint::black_box; +#[path = "../../stack_scrubbed_call.rs"] mod scrubbed; /// How far below the call the stack is painted and searched. The deepest operation here uses @@ -55,8 +56,10 @@ const DEPTH: usize = 256 * 1024; const PAD: usize = 16 * 1024; const PAINT: u8 = 0xA5; /// How far below the call a difference between two runs is put down to the registers the -/// call's first frames saved, and not counted. The furthest seen is 120 bytes. -const SAVED_REGISTERS: usize = 256; +/// call's first frames saved, and not counted. With those registers zeroed ([`Scan::run`]), +/// nothing differs there on arm64 (rustc 1.100 and 1.97) or x86-64 (rustc 1.97 and 1.88); this +/// is room for a frame record and two register pairs. +const SAVED_REGISTERS: usize = 64; /// The private key of GM/T 0003.5-2012 Annex C.2. const DB: [u8; 32] = [ diff --git a/dev_scripts/sm2_stack_harness/src/scrubbed.rs b/dev_scripts/sm2_stack_harness/src/scrubbed.rs deleted file mode 100644 index 56550d18d..000000000 --- a/dev_scripts/sm2_stack_harness/src/scrubbed.rs +++ /dev/null @@ -1,121 +0,0 @@ -//! A call made with every callee-saved register zero. This program computes with the secrets it -//! searches for (to know what to search for, and to check the operation's output), and a word -//! of one can wait in a callee-saved register of `main` across the call that runs the operation; -//! the first frame below that uses the register saves it, a copy the search then finds, which is -//! this program's and not the operation's. A Rust function cannot clear those registers, so this -//! is a few lines of assembly: it saves them in its own frame, above every frame searched, zeroes -//! them, makes the call and restores them. -//! -//! aarch64 (AAPCS64): x19-x28 and the low halves of v8-v15. x86-64 (System V): rbx, rbp and -//! r12-r15. The caller-saved registers are not touched: no callee saves those. - -#[cfg(target_arch = "aarch64")] -core::arch::global_asm!( - ".text", - ".globl stack_harness_scrubbed_call", - ".type stack_harness_scrubbed_call, %function", - ".p2align 2", - "stack_harness_scrubbed_call:", - "stp x29, x30, [sp, #-160]!", - "mov x29, sp", - "stp x19, x20, [sp, #16]", - "stp x21, x22, [sp, #32]", - "stp x23, x24, [sp, #48]", - "stp x25, x26, [sp, #64]", - "stp x27, x28, [sp, #80]", - "stp d8, d9, [sp, #96]", - "stp d10, d11, [sp, #112]", - "stp d12, d13, [sp, #128]", - "stp d14, d15, [sp, #144]", - "mov x16, x0", - "mov x0, x1", - "mov x19, xzr", - "mov x20, xzr", - "mov x21, xzr", - "mov x22, xzr", - "mov x23, xzr", - "mov x24, xzr", - "mov x25, xzr", - "mov x26, xzr", - "mov x27, xzr", - "mov x28, xzr", - "movi v8.16b, #0", - "movi v9.16b, #0", - "movi v10.16b, #0", - "movi v11.16b, #0", - "movi v12.16b, #0", - "movi v13.16b, #0", - "movi v14.16b, #0", - "movi v15.16b, #0", - "blr x16", - "ldp d14, d15, [sp, #144]", - "ldp d12, d13, [sp, #128]", - "ldp d10, d11, [sp, #112]", - "ldp d8, d9, [sp, #96]", - "ldp x27, x28, [sp, #80]", - "ldp x25, x26, [sp, #64]", - "ldp x23, x24, [sp, #48]", - "ldp x21, x22, [sp, #32]", - "ldp x19, x20, [sp, #16]", - "ldp x29, x30, [sp], #160", - "ret", - ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", -); - -#[cfg(target_arch = "x86_64")] -core::arch::global_asm!( - ".text", - ".globl stack_harness_scrubbed_call", - ".type stack_harness_scrubbed_call, @function", - ".p2align 4", - "stack_harness_scrubbed_call:", - "push rbp", - "push rbx", - "push r12", - "push r13", - "push r14", - "push r15", - // Six pushes and the return address: 8 more aligns the stack to 16 at the call. - "sub rsp, 8", - "mov rax, rdi", - "mov rdi, rsi", - "xor ebp, ebp", - "xor ebx, ebx", - "xor r12d, r12d", - "xor r13d, r13d", - "xor r14d, r14d", - "xor r15d, r15d", - "call rax", - "add rsp, 8", - "pop r15", - "pop r14", - "pop r13", - "pop r12", - "pop rbx", - "pop rbp", - "ret", - ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", -); - -#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] -compile_error!("the stack harness clears the callee-saved registers on aarch64 and x86-64 only"); - -unsafe extern "C" { - /// Calls `job(arg)` with the callee-saved registers zero, and restores them. - fn stack_harness_scrubbed_call(job: extern "C" fn(*mut u8), arg: *mut u8); -} - -/// Runs `f` with every callee-saved register zero, its frames below one of this module's that -/// holds what those registers held. -pub fn call(f: F) { - extern "C" fn job(arg: *mut u8) { - // SAFETY: `arg` is the `Option` of `call`, alive and borrowed by nothing else until - // the call returns. A panic here aborts, as a panic out of an `extern "C"` function does. - let f = unsafe { &mut *arg.cast::>() }; - (f.take().unwrap())(); - } - let mut f = Some(f); - // SAFETY: the assembly above follows the C calling convention, restores every register it - // changes that the convention asks it to keep, and passes `arg` on unchanged. - unsafe { stack_harness_scrubbed_call(job::, (&raw mut f).cast()) } -} diff --git a/dev_scripts/ecdsa_stack_harness/src/scrubbed.rs b/dev_scripts/stack_scrubbed_call.rs similarity index 88% rename from dev_scripts/ecdsa_stack_harness/src/scrubbed.rs rename to dev_scripts/stack_scrubbed_call.rs index 56550d18d..2532fcd97 100644 --- a/dev_scripts/ecdsa_stack_harness/src/scrubbed.rs +++ b/dev_scripts/stack_scrubbed_call.rs @@ -1,4 +1,5 @@ -//! A call made with every callee-saved register zero. This program computes with the secrets it +//! A call made with every callee-saved register zero, for the SM2 and ECDSA stack harnesses, each +//! of which includes this file as its `scrubbed` module. This program computes with the secrets it //! searches for (to know what to search for, and to check the operation's output), and a word //! of one can wait in a callee-saved register of `main` across the call that runs the operation; //! the first frame below that uses the register saves it, a copy the search then finds, which is @@ -9,7 +10,7 @@ //! aarch64 (AAPCS64): x19-x28 and the low halves of v8-v15. x86-64 (System V): rbx, rbp and //! r12-r15. The caller-saved registers are not touched: no callee saves those. -#[cfg(target_arch = "aarch64")] +#[cfg(all(target_os = "linux", target_arch = "aarch64"))] core::arch::global_asm!( ".text", ".globl stack_harness_scrubbed_call", @@ -62,7 +63,7 @@ core::arch::global_asm!( ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", ); -#[cfg(target_arch = "x86_64")] +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] core::arch::global_asm!( ".text", ".globl stack_harness_scrubbed_call", @@ -97,8 +98,10 @@ core::arch::global_asm!( ".size stack_harness_scrubbed_call, . - stack_harness_scrubbed_call", ); -#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))] -compile_error!("the stack harness clears the callee-saved registers on aarch64 and x86-64 only"); +#[cfg(not(all(target_os = "linux", any(target_arch = "aarch64", target_arch = "x86_64"))))] +compile_error!( + "the stack harnesses clear the callee-saved registers on aarch64 and x86-64 Linux only" +); unsafe extern "C" { /// Calls `job(arg)` with the callee-saved registers zero, and restores them. From e93a0f04eef40f7feabab9184068e8074aff5e1a Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 18:42:59 +1100 Subject: [PATCH 13/14] ec: key decoding builds the key from a reference to the wiped scalar Review of 6ae975c9: private_key_from_be_bytes passed key a clone by value. That stayed out of the frame only because key was inlined. key now takes &C::Scalar and makes the copy itself. If it is not inlined, d sits in memory as the local that is wiped on drop, and the copy is built in key's own frame, below this one, where the wipe reaches. private_scalar_from_be_bytes, now used only by curve_tests.rs, delegates to it, so the check and the load are written once. The ECDSA and ECC CDH from_bytes docs describe what runs rather than pointing at that function. The assembly of P-256's decoding (rustc 1.100) now reduces in registers and stores d only into the Result through the return pointer, on both aarch64 and x86-64; the local's only stores are the volatile zeroization. The decoding differential (3003 inputs per curve, all seven curves) is byte-identical, and the ec tests pass. Also: from_borrowed_limbs_into's implementor rationale moves to a comment, and a long line in sm2/mod.rs is rewrapped. Assisted-by: Claude:claude-opus-5-5 --- crypto/ec/src/curve.rs | 33 +++++++++++++++------------------ crypto/ec/src/eccdh/dhkem.rs | 2 +- crypto/ec/src/eccdh/keys.rs | 8 +++----- crypto/ec/src/ecdsa/keys.rs | 9 +++------ crypto/ec/src/sm2/mod.rs | 4 ++-- 5 files changed, 24 insertions(+), 32 deletions(-) diff --git a/crypto/ec/src/curve.rs b/crypto/ec/src/curve.rs index 36d4d69db..35f1a9390 100644 --- a/crypto/ec/src/curve.rs +++ b/crypto/ec/src/curve.rs @@ -122,8 +122,9 @@ pub trait SecretScalar: Clone + Debug + PartialEq + Eq + 'static { fn from_limbs(limbs: Self::Limbs) -> Self; /// From borrowed limbs, reduced mod `n`, leaving the caller's copy to the caller. fn from_borrowed_limbs(limbs: &Self::Limbs) -> Self; - /// As [`from_borrowed_limbs`](Self::from_borrowed_limbs), reduced into `out`, which is - /// wiped when it is dropped, rather than into a scalar that is returned by a move. + /// As [`from_borrowed_limbs`](Self::from_borrowed_limbs), reduced into `out`. + // For a caller that wipes what it reduced into: a scalar returned by a move leaves the + // memory it was built in behind, unwiped. fn from_borrowed_limbs_into(limbs: &Self::Limbs, out: &mut Self); /// From the big-endian encoding, reduced mod `n`. fn from_be_bytes(bytes: &Self::Bytes) -> Self; @@ -323,26 +324,19 @@ pub fn limbs_in_range(limbs: &[u64; L], n: &[u64; L]) -> Conditi /// A private scalar from its big-endian encoding, or `None` when the encoding is not in /// `[1, n-1]`: the check is on the raw value before any reduction, so that `d = n + 1` is refused /// rather than loaded as `d = 1`. The candidate is a secret from the moment it arrives, so the -/// limbs are staged in a [`Secret`] and the scalar is reduced from that borrowed copy straight into -/// its own; nothing plain is left in this frame. +/// limbs are staged in a [`Secret`], and the scalar they are reduced into is wiped once the +/// one returned has been copied from it. pub fn private_scalar_from_be_bytes(bytes: &C::ScalarBytes) -> Option { - let mut limbs = Secret::::new(); - C::limbs_from_be_bytes_into(bytes, &mut limbs); - if !C::scalar_in_range(&limbs).to_bool() { - return None; - } - Some(C::Scalar::from_borrowed_limbs(&limbs)) + private_key_from_be_bytes::(bytes, |d| Some(d.clone()), || None) } -/// [`private_scalar_from_be_bytes`] for a key's decoding in a wiped frame: `key` of the scalar, -/// or `refused()`. The scalar is reduced into a local that is wiped when it is dropped, and `key` -/// is given a copy of it. Returned by a move, as [`SecretScalar::from_borrowed_limbs`] returns -/// it, the scalar would leave the memory it was reduced into unwiped in the frame of the closure -/// that runs this, at the top, which the wipe after that frame does not reach (on aarch64 its -/// own saved registers and padding lie over those slots). +/// The check and load of [`private_scalar_from_be_bytes`], for a key's decoding: `key(&d)`, or +/// `refused()`. `d` is reduced into a local that is wiped when it is dropped, and `key` builds +/// the value returned from a reference to it, so the one copy of `d` made here is the one `key` +/// writes into that value. pub(crate) fn private_key_from_be_bytes( bytes: &C::ScalarBytes, - key: impl FnOnce(C::Scalar) -> R, + key: impl FnOnce(&C::Scalar) -> R, refused: impl FnOnce() -> R, ) -> R { let mut limbs = Secret::::new(); @@ -350,9 +344,12 @@ pub(crate) fn private_key_from_be_bytes( if !C::scalar_in_range(&limbs).to_bool() { return refused(); } + // Not `from_borrowed_limbs`: the scalar it returns is moved, and the memory it was reduced + // in stays behind unwiped, at the top of the decoding's frame, where on aarch64 the wipe + // after that frame does not reach. let mut d = C::Scalar::from_limbs(C::Limbs::ZEROED); C::Scalar::from_borrowed_limbs_into(&limbs, &mut d); - key(d.clone()) + key(&d) } /// What the stack wipe overwrites after an ECDSA or ECC CDH private key is decoded: this many of diff --git a/crypto/ec/src/eccdh/dhkem.rs b/crypto/ec/src/eccdh/dhkem.rs index cf3cafdf9..8cc46b272 100644 --- a/crypto/ec/src/eccdh/dhkem.rs +++ b/crypto/ec/src/eccdh/dhkem.rs @@ -354,7 +354,7 @@ where in_wiped_frame::(|| { private_key_from_be_bytes::( sk, - |d| Some(ECCDHPrivateKey::from_scalar(d)), + |d| Some(ECCDHPrivateKey::from_scalar(d.clone())), || None, ) }) diff --git a/crypto/ec/src/eccdh/keys.rs b/crypto/ec/src/eccdh/keys.rs index 51507cf1a..92c8112ce 100644 --- a/crypto/ec/src/eccdh/keys.rs +++ b/crypto/ec/src/eccdh/keys.rs @@ -63,10 +63,8 @@ where /// `d` must be in `[1, n-1]` (SP 800-56A Rev. 3 Section 5.6.2.1.2), checked on the raw /// big-endian value before any reduction, so that `d = n + 1` is refused rather than loaded - /// as `d = 1`; the check and the load are those of [`private_scalar_from_be_bytes`], which - /// stages the candidate in a `Secret` and reveals only whether the key loaded. - /// - /// [`private_scalar_from_be_bytes`]: crate::curve::private_scalar_from_be_bytes + /// as `d = 1`. The check and the load stage the candidate in a `Secret`, wipe the scalar it + /// is reduced into, and reveal only whether the key loaded. fn from_bytes(bytes: &[u8]) -> Result { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -76,7 +74,7 @@ where in_wiped_frame::(|| { private_key_from_be_bytes::( bytes, - |d| Ok(Self(d)), + |d| Ok(Self(d.clone())), || Err(KeyDecodingError("ECC CDH private key must be in [1, n-1]")), ) }) diff --git a/crypto/ec/src/ecdsa/keys.rs b/crypto/ec/src/ecdsa/keys.rs index 9b20a1bde..5b9db611e 100644 --- a/crypto/ec/src/ecdsa/keys.rs +++ b/crypto/ec/src/ecdsa/keys.rs @@ -76,11 +76,8 @@ where /// FIPS 186-5 Section 6.2: `d` is in `[1, n-1]`, checked on the raw big-endian value before /// any reduction, so that `d = n + 1` is refused rather than loaded as `d = 1` (one key would - /// otherwise have unboundedly many encodings); the check and the load are those of - /// [`private_scalar_from_be_bytes`], which stages the candidate in a `Secret` and reveals only - /// whether the key loaded. - /// - /// [`private_scalar_from_be_bytes`]: crate::curve::private_scalar_from_be_bytes + /// otherwise have unboundedly many encodings). The check and the load stage the candidate in + /// a `Secret`, wipe the scalar it is reduced into, and reveal only whether the key loaded. fn from_bytes(bytes: &[u8]) -> Result { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -90,7 +87,7 @@ where in_wiped_frame::(|| { private_key_from_be_bytes::( bytes, - |d| Ok(Self { d, _hash: PhantomData }), + |d| Ok(Self { d: d.clone(), _hash: PhantomData }), || Err(KeyDecodingError("ECDSA private key must be in [1, n-1]")), ) }) diff --git a/crypto/ec/src/sm2/mod.rs b/crypto/ec/src/sm2/mod.rs index b7754c70b..94a98a962 100644 --- a/crypto/ec/src/sm2/mod.rs +++ b/crypto/ec/src/sm2/mod.rs @@ -263,8 +263,8 @@ //! build they may not reach everything. Loading a private key (`from_bytes`) zeroizes the //! copies it makes and has no such wipe, and neither have `encode`, `encode_out` and //! `clone`; in the x86-64 and arm64 builds the check finds nothing of the key on the stack -//! after any of the four. The key a call returns, and the bytes `encode` returns, are the caller's to -//! look after. +//! after any of the four. The key a call returns, and the bytes `encode` returns, are the +//! caller's to look after. pub mod encryption; pub(in crate::sm2) mod encryption_core; From 9af630a43fb993080579557ad10e10514f293fd4 Mon Sep 17 00:00:00 2001 From: David Hook Date: Fri, 27 Nov 2026 19:14:55 +1100 Subject: [PATCH 14/14] ci: ECDSA harness accepts a returned value staged in chunks out of order CI's x86-64 leg (rustc 1.100) failed Ed448 sign_deterministic: 23 bytes differing 352 bytes below the call. That depth is past the new 256 SAVED_REGISTERS and was inside the old 512. Dumping the bytes shows they are the signature, which is public: bytes 23..39 then 0..7 of R || S in both runs, staged in chunks for the by-value return. The 7-byte piece does not continue where the 16-byte piece ended, so d97acac0's rule refused it. A piece now needs to be four bytes rather than eight. The chance of two runs both matching four bytes at one place by accident is 2^-64. A shorter last piece must still continue the previous one. With SAVED_REGISTERS at 0, rustc 1.100 on x86-64 also tops out at 128 bytes (brainpoolP512r1 derive_pk), so 256 stands, and its comment now lists 1.100. check_ecdsa_stack.sh passes on x86-64 (1.100, 1.97, 1.88) and arm64 (1.100, 1.97); check_sm2_stack.sh on x86-64 1.100 and 1.88. Assisted-by: Claude:claude-opus-5-5 --- dev_scripts/ecdsa_stack_harness/src/main.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/dev_scripts/ecdsa_stack_harness/src/main.rs b/dev_scripts/ecdsa_stack_harness/src/main.rs index 0670640e9..57cb227fb 100644 --- a/dev_scripts/ecdsa_stack_harness/src/main.rs +++ b/dev_scripts/ecdsa_stack_harness/src/main.rs @@ -82,8 +82,8 @@ const PAINT: u8 = 0xA5; /// frames, above its wiped ones, and not counted: the registers they save, which /// [`Scan::run`] has zeroed, and values handed out on the way to the caller's slot. With this /// at 0, the furthest seen is 208 bytes on arm64 (rustc 1.100: Ed25519's `sign`, staging the -/// signature it returns), 136 on arm64 with rustc 1.97 and 128 on x86-64 (rustc 1.97 and -/// 1.88). +/// signature it returns), 136 on arm64 with rustc 1.97 and 128 on x86-64 (rustc 1.100, 1.97 +/// and 1.88). const SAVED_REGISTERS: usize = 256; /// The fixed RNG's seed: one draw at its start. Every operation here draws once. @@ -318,9 +318,11 @@ impl Scan { /// Whether the bytes `i..end`, in which the two runs differ, are pieces of `public_before` in /// the kept run and the same pieces of `public` in the last, one after another: two public - /// values can lie side by side, in any order. Each piece is at least a word, but for the - /// whole run when it is shorter, and for a last piece that carries on where the one before - /// it ended in the image. + /// values can lie side by side, in any order, and a value returned by value can be staged in + /// chunks out of order (Ed448's signature, on x86-64 with rustc 1.100, as bytes 23..39 then + /// 0..7). Each piece is at least four bytes, which both runs match by chance at a given place + /// in the image with odds of 2^-64, but for the whole run when it is shorter, and for a last + /// piece that carries on where the one before it ended in the image. fn public_run(&self, i: usize, end: usize, public_before: &[u8], public: &[u8]) -> bool { // How many bytes from `p` match the image from `at`, in both runs. let matching = |p: usize, at: usize| { @@ -336,7 +338,7 @@ impl Scan { while p < end { let (len, at) = (0..public.len()).map(|at| (matching(p, at), at)).max().unwrap_or((0, 0)); - if len >= 8 { + if len >= 4 { p += len; after = Some(at + len); continue;