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 e54bf6aa7..acb51eefd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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, @@ -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. diff --git a/alpha_0.1.4_release_notes.md b/alpha_0.1.4_release_notes.md index 29f4f6856..b9234cca7 100644 --- a/alpha_0.1.4_release_notes.md +++ b/alpha_0.1.4_release_notes.md @@ -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. diff --git a/crypto/ec/src/curve.rs b/crypto/ec/src/curve.rs index 4765de13b..35f1a9390 100644 --- a/crypto/ec/src/curve.rs +++ b/crypto/ec/src/curve.rs @@ -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. @@ -320,15 +324,32 @@ 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 { + private_key_from_be_bytes::(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( + 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 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 diff --git a/crypto/ec/src/eccdh/dhkem.rs b/crypto/ec/src/eccdh/dhkem.rs index 629cf91ee..8cc46b272 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.clone())), + || None, + ) }) } diff --git a/crypto/ec/src/eccdh/keys.rs b/crypto/ec/src/eccdh/keys.rs index 177457901..92c8112ce 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,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 - /// [`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 { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -73,9 +72,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.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 0ee800ba7..5b9db611e 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,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 - /// [`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 { let bytes: &[u8; SK_LEN] = bytes .try_into() @@ -86,9 +85,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: d.clone(), _hash: PhantomData }), + || Err(KeyDecodingError("ECDSA private key must be in [1, n-1]")), + ) }) } } diff --git a/crypto/ec/src/ed/ed25519/keys.rs b/crypto/ec/src/ed/ed25519/keys.rs index 39e1ce0e8..79e87e9c8 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,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). /// @@ -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::(|| { + 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 +265,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 +277,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 ca5f874ec..22246e4cd 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 ๐Ÿšจ //! @@ -163,11 +165,15 @@ //! 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 -//! 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 -//! leave words of it on the stack, seen as one word after `from_bytes_out` in the arm64 build. +//! 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. +//! `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) 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/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/keys.rs b/crypto/ec/src/ed/ed448/keys.rs index f177f0f9b..5e73d1cc2 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,16 @@ 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 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). /// @@ -86,14 +97,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 +282,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 +294,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 b7dea66e8..f00c70bd9 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 ๐Ÿšจ //! @@ -173,11 +174,15 @@ //! 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. -//! -//! 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 +//! 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 +//! 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, @@ -185,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/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); diff --git a/crypto/ec/src/ed/x25519.rs b/crypto/ec/src/ed/x25519.rs index d61de9ce3..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 @@ -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..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 @@ -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) { 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) } 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..94a98a962 100644 --- a/crypto/ec/src/sm2/mod.rs +++ b/crypto/ec/src/sm2/mod.rs @@ -262,9 +262,9 @@ //! 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 -//! look after. +//! `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; pub(in crate::sm2) mod encryption_core; 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_ecdsa_stack.sh b/dev_scripts/check_ecdsa_stack.sh index f00099439..7eb315f59 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 @@ -28,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 13cd98a6b..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 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/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..1002420d1 --- /dev/null +++ b/dev_scripts/ecdsa_stack_harness/src/ed.rs @@ -0,0 +1,949 @@ +//! 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::()); + } + // `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); + 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]; + /// 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>; + 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 LIMB_BITS: usize = 51; + const LIMBS: usize = 5; + 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 LIMB_BITS: usize = 56; + const LIMBS: usize = 8; + 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 + }; + // 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. + 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())); + values.push(("K (limbs)".to_string(), limbs(z.ref_to_bytes()))); + 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..57cb227fb 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: @@ -14,12 +15,18 @@ //! 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. //! -//! 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,22 +62,29 @@ 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; +#[path = "../../stack_scrubbed_call.rs"] +mod scrubbed; + /// How far below the call the stack is painted and searched. The deepest operation here uses /// under 16 KiB. 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.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. const SEED_LEN: usize = 128; @@ -160,9 +174,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 @@ -198,6 +221,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 { @@ -210,6 +236,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); @@ -256,16 +295,19 @@ 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. 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)); } @@ -274,6 +316,42 @@ 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, 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| { + (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 (len, at) = + (0..public.len()).map(|at| (matching(p, at), at)).max().unwrap_or((0, 0)); + if len >= 4 { + p += len; + after = Some(at + len); + continue; + } + let rest = end - p; + return match after { + None => len == rest, + Some(at) => at < public.len() && matching(p, at) == rest, + }; + } + 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 @@ -307,6 +385,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 { @@ -457,6 +540,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 }); } diff --git a/dev_scripts/sm2_stack_harness/src/main.rs b/dev_scripts/sm2_stack_harness/src/main.rs index bff347337..3d7933a1b 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,9 @@ 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 /// under 8 KiB. const DEPTH: usize = 256 * 1024; @@ -47,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] = [ @@ -256,9 +267,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 +314,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 +328,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 +385,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 +431,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/stack_scrubbed_call.rs b/dev_scripts/stack_scrubbed_call.rs new file mode 100644 index 000000000..2532fcd97 --- /dev/null +++ b/dev_scripts/stack_scrubbed_call.rs @@ -0,0 +1,124 @@ +//! 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 +//! 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(all(target_os = "linux", 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(all(target_os = "linux", 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(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. + 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()) } +}