Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitea/workflows/ecdsa-stack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion .github/workflows/ecdsa-stack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
20 changes: 14 additions & 6 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -549,12 +549,17 @@ Twelve 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`.
- `symmetric-stack.yml`: `dev_scripts/check_symmetric_stack.sh`, the same shape and matrix over
`dev_scripts/symmetric_stack_harness`, which runs HMAC's key construction, one-shots and streaming
workers (SHA-256, SHA-512, SHA3-256, SM3, RIPEMD-160), HKDF's extract, expand and `KDF` derivation,
Expand All @@ -577,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 (`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.

`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.
Expand Down
2 changes: 2 additions & 0 deletions alpha_0.1.4_release_notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,5 +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; 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.
29 changes: 25 additions & 4 deletions crypto/ec/src/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ 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`.
// 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;
/// The big-endian encoding, as a plain array the caller asked for.
Expand Down Expand Up @@ -320,15 +324,32 @@ pub fn limbs_in_range<const L: usize>(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<C: Curve>(bytes: &C::ScalarBytes) -> Option<C::Scalar> {
private_key_from_be_bytes::<C, _>(bytes, |d| Some(d.clone()), || None)
}

/// 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<C: Curve, R>(
bytes: &C::ScalarBytes,
key: impl FnOnce(&C::Scalar) -> R,
refused: impl FnOnce() -> R,
) -> R {
let mut limbs = Secret::<C::Limbs>::new();
C::limbs_from_be_bytes_into(bytes, &mut limbs);
if !C::scalar_in_range(&limbs).to_bool() {
return None;
return refused();
}
Some(C::Scalar::from_borrowed_limbs(&limbs))
// 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)
}

/// What the stack wipe overwrites after an ECDSA or ECC CDH private key is decoded: this many of
Expand Down
8 changes: 6 additions & 2 deletions crypto/ec/src/eccdh/dhkem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<ECCDHPrivateKey<C>> {
in_wiped_frame::<C::Limbs, DECODE_STACK_PER_LIMB, DECODE_STACK_FIXED, _>(|| {
private_scalar_from_be_bytes::<C>(sk).map(ECCDHPrivateKey::from_scalar)
private_key_from_be_bytes::<C, _>(
sk,
|d| Some(ECCDHPrivateKey::from_scalar(d.clone())),
|| None,
)
})
}

Expand Down
15 changes: 8 additions & 7 deletions crypto/ec/src/eccdh/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -63,19 +63,20 @@ 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 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<Self, KeyDecodingError> {
let bytes: &[u8; SK_LEN] = bytes
.try_into()
.map_err(|_| KeyDecodingError("an ECC CDH private key is the curve's scalar length"))?;
// 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::<C::Limbs, DECODE_STACK_PER_LIMB, DECODE_STACK_FIXED, _>(|| {
private_scalar_from_be_bytes::<C>(bytes)
.map(Self)
.ok_or(KeyDecodingError("ECC CDH private key must be in [1, n-1]"))
private_key_from_be_bytes::<C, _>(
bytes,
|d| Ok(Self(d.clone())),
|| Err(KeyDecodingError("ECC CDH private key must be in [1, n-1]")),
)
})
}
}
Expand Down
15 changes: 8 additions & 7 deletions crypto/ec/src/ecdsa/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -76,19 +76,20 @@ 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
/// [`private_scalar_from_be_bytes`], which stages the candidate in a `Secret` and reveals only
/// whether the key loaded.
/// 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<Self, KeyDecodingError> {
let bytes: &[u8; SK_LEN] = bytes
.try_into()
.map_err(|_| KeyDecodingError("an ECDSA private key is the curve's scalar length"))?;
// 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::<C::Limbs, DECODE_STACK_PER_LIMB, DECODE_STACK_FIXED, _>(|| {
private_scalar_from_be_bytes::<C>(bytes)
.map(|d| Self { d, _hash: PhantomData })
.ok_or(KeyDecodingError("ECDSA private key must be in [1, n-1]"))
private_key_from_be_bytes::<C, _>(
bytes,
|d| Ok(Self { d: d.clone(), _hash: PhantomData }),
|| Err(KeyDecodingError("ECDSA private key must be in [1, n-1]")),
)
})
}
}
Expand Down
40 changes: 27 additions & 13 deletions crypto/ec/src/ed/ed25519/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -71,6 +72,16 @@ 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 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).
///
Expand All @@ -81,14 +92,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::<u64, 0, KEYGEN_STACK_WORDS, _>(|| {
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
Expand Down Expand Up @@ -255,19 +265,23 @@ impl PrivateKey<PRIVATE_KEY_LEN> 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<Self, KeyDecodingError> {
let mut sk = Self::zeroized();
Self::from_bytes_out(bytes, &mut sk)?;
Ok(sk)
in_wiped_frame::<u64, 0, BY_VALUE_STACK_WORDS, _>(|| {
let mut sk = Self::zeroized();
Self::from_bytes_out(bytes, &mut sk)?;
Ok(sk)
})
}
}

/// `clone` returns the copy by value, and a move wipes nothing (the module's Security
/// 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::<u64, 0, BY_VALUE_STACK_WORDS, _>(|| {
let mut sk = Self::zeroized();
sk.clone_from(self);
sk
})
}

fn clone_from(&mut self, source: &Self) {
Expand Down
Loading
Loading