From 0c3e0c2e046eb70bf44a18c24308bf785328df14 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 12:07:34 -0300 Subject: [PATCH 1/9] feat(noise_sv2): let a Responder present a pre-issued certificate Every Responder so far signed a fresh certificate at handshake time over a static key generated for that one handshake, which puts the authority private key on the internet-facing host and leaves the certificate lifetime up to that host. Responder::from_certificate takes the server's static keypair and a SIGNATURE_NOISE_MESSAGE (spec 4.5.2) issued for it elsewhere; step_1 sends those bytes verbatim, so the authority private key never has to be on the server and the validity window is the one the issuer signed. The existing constructors keep signing at handshake time. ref https://github.com/stratum-mining/stratum/issues/2437 --- Cargo.lock | 2 +- fuzz/Cargo.lock | 2 +- sv2/noise-sv2/Cargo.toml | 2 +- sv2/noise-sv2/src/responder.rs | 154 ++++++++++++++++++++++++++------- sv2/noise-sv2/src/test.rs | 54 ++++++++++++ 5 files changed, 180 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 58a34da8dd..2d567cffa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -736,7 +736,7 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.1.0" +version = "2.2.0" dependencies = [ "chacha20poly1305", "criterion", diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 79d118bb53..84ac3864c9 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -363,7 +363,7 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.1.0" +version = "2.2.0" dependencies = [ "chacha20poly1305", "rand", diff --git a/sv2/noise-sv2/Cargo.toml b/sv2/noise-sv2/Cargo.toml index 87a1d3c3f0..8ae4de627b 100644 --- a/sv2/noise-sv2/Cargo.toml +++ b/sv2/noise-sv2/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "noise_sv2" -version = "2.1.0" +version = "2.2.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index 1cab80931b..524ea0c58c 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -44,6 +44,7 @@ use crate::{ signature_message::SignatureNoiseMessage, AeadError, NoiseEngine, ELLSWIFT_ENCODING_SIZE, ENCRYPTED_ELLSWIFT_ENCODING_SIZE, ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE, + SIGNATURE_NOISE_MESSAGE_SIZE, }; use alloc::{ boxed::Box, @@ -79,16 +80,25 @@ pub struct Responder { // Ephemeral key pair generated by the responder for this session, used for generating the // shared secret with the initiator. e: Keypair, - // Static key pair of the responder, used to establish long-term identity and authenticity. - // - // Remains consistent across handshakes. + // Static key pair of the responder, the one its certificate covers: supplied by the caller + // together with that certificate, or generated for this one handshake and signed on the spot. s: Keypair, - // Authority key pair, representing the responder's authority credentials. - // - // Used to sign messages and verify the identity of the responder. - a: Keypair, - // Validity duration of the responder's certificate, in seconds. - cert_validity: u32, + // Where the `SIGNATURE_NOISE_MESSAGE` sent in the second handshake message comes from. + certificate: CertificateSource, +} + +// The `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2) a [`Responder`] sends is either signed on the spot +// or supplied by the caller, already issued. +enum CertificateSource { + // Sign a fresh certificate over the static key at handshake time, valid from the handshake's + // `now` for `cert_validity` seconds. Needs the authority private key on the host. + SignAtHandshake { + authority: Keypair, + cert_validity: u32, + }, + // Send these bytes verbatim; they were issued where the authority private key is kept. See + // [`Responder::from_certificate`]. + PreIssued([u8; SIGNATURE_NOISE_MESSAGE_SIZE]), } impl core::fmt::Debug for Responder { @@ -157,8 +167,8 @@ impl Responder { /// prepares the handshake state. The authority keypair and certificate validity period are /// also configured. #[cfg(feature = "std")] - pub fn new(a: Keypair, cert_validity: u32) -> Box { - Self::new_with_rng(a, cert_validity, &mut rand::thread_rng()) + pub fn new(authority_key: Keypair, cert_validity: u32) -> Box { + Self::new_with_rng(authority_key, cert_validity, &mut rand::thread_rng()) } /// Creates a new [`Responder`] instance with the provided authority keypair, certificate @@ -171,9 +181,65 @@ impl Responder { /// example. #[inline] pub fn new_with_rng( - a: Keypair, + authority_key: Keypair, cert_validity: u32, rng: &mut R, + ) -> Box { + let s = Self::generate_key_with_rng(rng); + let certificate = CertificateSource::SignAtHandshake { + authority: authority_key, + cert_validity, + }; + Self::build(s, certificate, rng) + } + + /// Creates a new [`Responder`] from its static keypair `s` and a certificate issued for it in + /// advance. + /// + /// `certificate` is the 74-byte `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2): the certificate + /// version, the validity window and the authority's Schnorr signature over those fields and + /// the x-only public key of `s` (spec 4.5.3). [`Self::step_1`] sends it verbatim, so the + /// validity window is the one the issuer chose and nothing on this host can extend it. + /// + /// This is the constructor for servers outside development and testing: the authority + /// private key stays wherever the certificate was signed, and the host holds only `s` and the + /// certificate. Rotating the static key means issuing a certificate for a new `s` and building + /// responders from that pair; sessions already established are unaffected. + /// + /// Nothing is checked here. A certificate issued for another static key or by another + /// authority, or one outside its validity window, is sent as is and rejected by every + /// initiator that pins the authority public key. + #[cfg(feature = "std")] + pub fn from_certificate( + s: Keypair, + certificate: [u8; SIGNATURE_NOISE_MESSAGE_SIZE], + ) -> Box { + Self::from_certificate_with_rng(s, certificate, &mut rand::thread_rng()) + } + + /// Creates a new [`Responder`] from its static keypair, a certificate issued for it in + /// advance, and a custom random number generator for the ephemeral key. + /// + /// See [`Self::from_certificate`] for more details. + /// + /// The custom random number generator should be provided in order to not implicitely rely on + /// `std` and allow `no_std` environments to provide a hardware random number generator for + /// example. + #[inline] + pub fn from_certificate_with_rng( + s: Keypair, + certificate: [u8; SIGNATURE_NOISE_MESSAGE_SIZE], + rng: &mut R, + ) -> Box { + Self::build(s, CertificateSource::PreIssued(certificate), rng) + } + + // Assembles a [`Responder`] around its static key and certificate source, generating the + // ephemeral keypair and initializing the handshake state. + fn build( + s: Keypair, + certificate: CertificateSource, + rng: &mut R, ) -> Box { let mut self_ = Self { handshake_cipher: None, @@ -182,9 +248,8 @@ impl Responder { ck: [0; 32], h: [0; 32], e: Self::generate_key_with_rng(rng), - s: Self::generate_key_with_rng(rng), - a, - cert_validity, + s, + certificate, }; Self::initialize_self(&mut self_); Box::new(self_) @@ -237,8 +302,10 @@ impl Responder { /// initial message. It processes the ephemeral public key provided by the initiator, derives /// the necessary shared secrets, and constructs the response message. The response includes /// the responder's ephemeral public key (in its ElligatorSwift-encoded form), the encrypted - /// static public key, and a signature noise message. Additionally, it establishes the session - /// ciphers for encrypting and decrypting further communication. + /// static public key, and the encrypted `SIGNATURE_NOISE_MESSAGE`: the certificate given to + /// [`Self::from_certificate`] verbatim, or one signed now by the authority keypair given to + /// [`Self::new`]. Additionally, it establishes the session ciphers for encrypting and + /// decrypting further communication. /// /// On success, it returns a tuple containing the response message to be sent back to the /// initiator and a [`NoiseEngine`] instance, which is configured with the session ciphers for @@ -247,8 +314,9 @@ impl Responder { /// On failure, the method returns an error if there is an issue during encryption, decryption, /// or any other step of the handshake process. /// - /// On success the remaining handshake secrets, including the ephemeral, static and authority - /// keypairs, are erased, so the [`Responder`] cannot be used for another handshake. + /// On success the remaining handshake secrets, including the ephemeral and static keypairs + /// and the authority keypair if there is one, are erased, so the [`Responder`] cannot be used + /// for another handshake. #[cfg(feature = "std")] pub fn step_1( &mut self, @@ -341,10 +409,19 @@ impl Responder { ecdh_static.zeroize(); // 7. appends `EncryptAndHash(SIGNATURE_NOISE_MESSAGE)` to the buffer - let valid_from = now; - let not_valid_after = now.saturating_add(self.cert_validity); - let signature_noise_message = - self.get_signature(crate::CERTIFICATE_VERSION, valid_from, not_valid_after, rng); + let signature_noise_message = match &self.certificate { + CertificateSource::SignAtHandshake { + authority, + cert_validity, + } => self.get_signature( + crate::CERTIFICATE_VERSION, + now, + now.saturating_add(*cert_validity), + authority, + rng, + ), + CertificateSource::PreIssued(certificate) => *certificate, + }; let mut signature_part = Vec::with_capacity(ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE); signature_part.extend_from_slice(&signature_noise_message[..]); Self::encrypt_and_hash(self, &mut signature_part)?; @@ -382,7 +459,7 @@ impl Responder { // // This method creates a signature noise message that includes the protocol version, // certificate validity period, and a cryptographic signature. The signature is created using - // the responder's static public key and authority keypair, ensuring that the responder's + // the responder's static public key and the `authority` keypair, ensuring that the responder's // identity and certificate validity are cryptographically verifiable. #[inline] fn get_signature( @@ -390,6 +467,7 @@ impl Responder { version: u16, valid_from: u32, not_valid_after: u32, + authority: &Keypair, rng: &mut R, ) -> [u8; 74] { let mut ret = [0; 74]; @@ -406,16 +484,22 @@ impl Responder { ret[7] = not_valid_after[1]; ret[8] = not_valid_after[2]; ret[9] = not_valid_after[3]; - SignatureNoiseMessage::sign_with_rng(&mut ret, &self.s.x_only_public_key().0, &self.a, rng); + SignatureNoiseMessage::sign_with_rng( + &mut ret, + &self.s.x_only_public_key().0, + authority, + rng, + ); ret } // Securely erases sensitive data in the responder's memory. // // Zeroizes the handshake key (`k`), the chaining key (`ck`) and the handshake - // hash (`h`), and non-securely erases the ephemeral, static and authority keypairs. This - // function is typically called when the [`Responder`] instance is no longer needed or before - // deallocation. + // hash (`h`), and non-securely erases the ephemeral and static keypairs, plus the authority + // keypair when the responder signs at handshake time. A pre-issued certificate is not secret + // and is left in place. This function is typically called when the [`Responder`] instance is + // no longer needed or before deallocation. // // It does not touch `handshake_cipher`: that key is wiped by [`ChaCha20Poly1305`]'s own // zeroize-on-drop. Nor does it reach the transport session ciphers, which by then live in the @@ -427,7 +511,9 @@ impl Responder { self.h.zeroize(); self.e.non_secure_erase(); self.s.non_secure_erase(); - self.a.non_secure_erase(); + if let CertificateSource::SignAtHandshake { authority, .. } = &mut self.certificate { + authority.non_secure_erase(); + } } } @@ -522,7 +608,13 @@ mod test { let mut rng = StdRng::seed_from_u64(3); let mut responder = make_responder(); - let authority_before = responder.a.secret_key().secret_bytes(); + let authority_secret = |responder: &Responder| match &responder.certificate { + CertificateSource::SignAtHandshake { authority, .. } => { + authority.secret_key().secret_bytes() + } + CertificateSource::PreIssued(_) => panic!("make_responder signs at handshake time"), + }; + let authority_before = authority_secret(&responder); let static_before = responder.s.secret_key().secret_bytes(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); @@ -531,7 +623,7 @@ mod test { .step_1_with_now_rng(fake_initiator_ephemeral, 100, &mut rng) .unwrap(); - assert_ne!(responder.a.secret_key().secret_bytes(), authority_before); + assert_ne!(authority_secret(&responder), authority_before); assert_ne!(responder.s.secret_key().secret_bytes(), static_before); assert_eq!(responder.ck, [0u8; 32]); assert_eq!(responder.h, [0u8; 32]); diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index 1f3dd4244f..8b562ead3a 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -47,3 +47,57 @@ fn test_1_with_rng() { assert!(message == "ciao".as_bytes().to_vec()); } + +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn pre_issued_certificate_is_sent_verbatim() { + use crate::{ + signature_message::SignatureNoiseMessage, Error, CERTIFICATE_VERSION, + SIGNATURE_NOISE_MESSAGE_SIZE, + }; + + // Issued where the authority private key lives; the responder never sees that key. + let authority = Responder::generate_key(); + let server_static = Responder::generate_key(); + let issue = |valid_from: u32, not_valid_after: u32| { + let mut certificate = [0u8; SIGNATURE_NOISE_MESSAGE_SIZE]; + certificate[0..2].copy_from_slice(&CERTIFICATE_VERSION.to_le_bytes()); + certificate[2..6].copy_from_slice(&valid_from.to_le_bytes()); + certificate[6..10].copy_from_slice(¬_valid_after.to_le_bytes()); + SignatureNoiseMessage::sign( + &mut certificate, + &server_static.x_only_public_key().0, + &authority, + ); + certificate + }; + let handshake = |certificate| { + let mut initiator = Initiator::new(Some(authority.public_key().into())); + let mut responder = Responder::from_certificate(server_static, certificate); + let first_message = initiator.step_0().unwrap(); + let (second_message, responder_engine) = responder.step_1(first_message).unwrap(); + initiator + .step_2(second_message) + .map(|initiator_engine| (initiator_engine, responder_engine)) + }; + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as u32; + + let (mut initiator_engine, mut responder_engine) = + handshake(issue(now - 60, now + 60)).unwrap(); + let mut message = "ciao".as_bytes().to_vec(); + initiator_engine.encrypt(&mut message).unwrap(); + assert!(message != "ciao".as_bytes().to_vec()); + responder_engine.decrypt(&mut message).unwrap(); + assert!(message == "ciao".as_bytes().to_vec()); + + // The validity window travels inside the certificate: an expired one is sent as is, and the + // initiator rejects it. + assert!(matches!( + handshake(issue(now - 120, now - 60)), + Err(Error::InvalidCertificate(_)) + )); +} From 4417d6dfdde3898656def185488215741e44af12 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 12:07:56 -0300 Subject: [PATCH 2/9] docs(noise_sv2): state the risks of signing certificates per handshake Responder::new and Responder::from_authority_kp need the authority private key on the internet-facing host, generate a static key that cannot be certified in advance, and let that host pick the certificate lifetime. Say so on both constructors, in the crate overview and in the README, and point servers outside development and testing at Responder::from_certificate. Closes https://github.com/stratum-mining/stratum/issues/2437 --- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/src/lib.rs | 9 +++++++++ sv2/noise-sv2/src/responder.rs | 23 ++++++++++++++++++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/sv2/noise-sv2/README.md b/sv2/noise-sv2/README.md index 6d62088783..cdd857c61e 100644 --- a/sv2/noise-sv2/README.md +++ b/sv2/noise-sv2/README.md @@ -10,7 +10,7 @@ `noise_sv2` is primarily intended to secure communication in the Stratum V2 (Sv2) protocol. It handles the necessary Noise handshakes, encrypts outgoing messages, and decrypts incoming responses, ensuring privacy and integrity across the communication link between Sv2 roles. See the [Protocol Security specification](https://github.com/stratum-mining/sv2-spec/blob/main/04-Protocol-Security.md) for more details. ## Key Capabilities -* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session. +* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. * **Cipher Support**: Uses `ChaCha20-Poly1305` for authenticated encryption. * **Handshake Roles**: Implements the `Initiator` and `Responder` roles required by the Noise handshake, allowing both sides of a connection to establish secure communication. * **Cryptographic Helpers**: Facilitates the management of cryptographic state and encryption operations. diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index 22451a4fca..c2b6c61cb5 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -39,6 +39,15 @@ //! `None`, accepts any responder and yields an encrypted but unauthenticated session that the //! crate does not distinguish from an authenticated one. Always pin the authority key for //! connections that cross a network boundary. +//! +//! ## Authority key custody +//! +//! Clients pin the authority public key, and neither the spec nor this crate defines revocation, +//! so a leaked authority private key impersonates the operator for as long as any client trusts it. +//! [`Responder::from_certificate`] lets an internet-facing server hold only its static key and a +//! certificate over it, signed where the authority private key is kept. [`Responder::new`] and +//! [`Responder::from_authority_kp`] instead sign a certificate on every handshake and need the +//! authority private key on the server; they are meant for development and testing. #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index 524ea0c58c..48afc55279 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -91,7 +91,8 @@ pub struct Responder { // or supplied by the caller, already issued. enum CertificateSource { // Sign a fresh certificate over the static key at handshake time, valid from the handshake's - // `now` for `cert_validity` seconds. Needs the authority private key on the host. + // `now` for `cert_validity` seconds. Needs the authority private key on the host; see the + // security note on [`Responder::new`]. SignAtHandshake { authority: Keypair, cert_validity: u32, @@ -166,6 +167,19 @@ impl Responder { /// protocol handshake. It generates ephemeral and static key pairs for the responder and /// prepares the handshake state. The authority keypair and certificate validity period are /// also configured. + /// + /// # Security + /// + /// A responder built here signs a fresh certificate in [`Self::step_1`], so the host running + /// it holds the authority private key in memory and, in practice, in its configuration. + /// The authority public key is what clients pin (spec 4.5.3, 4.7), and neither the spec nor + /// this crate defines revocation, so a compromise of that host leaks a key that impersonates + /// the operator to every client for as long as any of them keeps trusting it. The static key + /// is generated here and discarded with the [`Responder`], so it cannot be certified in + /// advance, and the certificate lifetime is whatever `cert_validity` says on the same host. + /// Use it for development and testing. A server outside those should hold only a static key + /// and a certificate issued where the authority private key is kept: see + /// [`Self::from_certificate`]. #[cfg(feature = "std")] pub fn new(authority_key: Keypair, cert_validity: u32) -> Box { Self::new_with_rng(authority_key, cert_validity, &mut rand::thread_rng()) @@ -261,6 +275,13 @@ impl Responder { /// the responder's authority credentials. It verifies that the provided public key matches the /// corresponding private key, ensuring the authenticity of the authority key pair. The /// certificate validity duration is also set here. Fails if the key pair is mismatched. + /// + /// # Security + /// + /// Like [`Self::new`], this signs a certificate on every handshake with the authority + /// private key on the host, over a static key that lives only as long as the [`Responder`]. + /// See the security note on [`Self::new`]; outside development and testing use + /// [`Self::from_certificate`]. #[cfg(feature = "std")] pub fn from_authority_kp( public: &[u8; 32], From 667ee22bc15e254ae696cf4dbfdaca04b22aeb05 Mon Sep 17 00:00:00 2001 From: plebhash Date: Thu, 12 Nov 2026 10:28:05 -0300 Subject: [PATCH 3/9] feat(noise_sv2): expose the certificate format to issuers `Responder::from_certificate` accepts a certificate signed elsewhere, but the type that defines its byte layout, signed digest and clock leeway was private, so an issuer had to re-implement all three and keep them in step with the initiator. Re-export `SignatureNoiseMessage` and shape it for that use: `sign` and `sign_with_rng` issue the message from a validity window, the static key and the authority keypair instead of filling in a byte buffer, `verify` borrows it, the conversion into its 74 bytes is added, and the leeway is a crate constant. `from_certificate` takes the certificate as that type rather than as raw bytes, and the responder signs through the same `sign_with_rng`. --- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/src/lib.rs | 10 + sv2/noise-sv2/src/responder.rs | 60 +----- sv2/noise-sv2/src/signature_message.rs | 255 ++++++++++++++----------- sv2/noise-sv2/src/test.rs | 15 +- 5 files changed, 164 insertions(+), 178 deletions(-) diff --git a/sv2/noise-sv2/README.md b/sv2/noise-sv2/README.md index cdd857c61e..5df1f50d0a 100644 --- a/sv2/noise-sv2/README.md +++ b/sv2/noise-sv2/README.md @@ -10,7 +10,7 @@ `noise_sv2` is primarily intended to secure communication in the Stratum V2 (Sv2) protocol. It handles the necessary Noise handshakes, encrypts outgoing messages, and decrypts incoming responses, ensuring privacy and integrity across the communication link between Sv2 roles. See the [Protocol Security specification](https://github.com/stratum-mining/sv2-spec/blob/main/04-Protocol-Security.md) for more details. ## Key Capabilities -* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. +* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it. * **Cipher Support**: Uses `ChaCha20-Poly1305` for authenticated encryption. * **Handshake Roles**: Implements the `Initiator` and `Responder` roles required by the Noise handshake, allowing both sides of a connection to establish secure communication. * **Cryptographic Helpers**: Facilitates the management of cryptographic state and encryption operations. diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index c2b6c61cb5..4cc5bc9c3d 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -48,6 +48,10 @@ //! certificate over it, signed where the authority private key is kept. [`Responder::new`] and //! [`Responder::from_authority_kp`] instead sign a certificate on every handshake and need the //! authority private key on the server; they are meant for development and testing. +//! +//! [`SignatureNoiseMessage`] is the certificate itself: the issuer signs a validity window over the +//! server's static key with [`SignatureNoiseMessage::sign_with_rng`] and hands the result to the +//! server; its `From` conversions give the 74 bytes the handshake carries and back. #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] @@ -107,6 +111,11 @@ pub const INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE: usize = ELLSWIFT_ENCODING_S /// for any other version are rejected during verification. pub const CERTIFICATE_VERSION: u16 = 0; +/// Clock drift, in seconds, tolerated on both edges of a certificate's validity window by +/// [`SignatureNoiseMessage::verify_with_now`], so that peers whose clocks disagree slightly still +/// complete the handshake. See . +pub const CERTIFICATE_TIME_LEEWAY: u32 = 10; + /// If protocolName is less than or equal to 32 bytes in length, use /// protocolName with zero bytes appended to make 32 bytes. Otherwise, apply /// HASH to it. For name = "Noise_NX_Secp256k1+EllSwift_ChaChaPoly_SHA256", we @@ -206,3 +215,4 @@ impl NoiseDecryptor { pub use error::Error; pub use initiator::Initiator; pub use responder::Responder; +pub use signature_message::SignatureNoiseMessage; diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index 48afc55279..8cf8078ee5 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -97,9 +97,9 @@ enum CertificateSource { authority: Keypair, cert_validity: u32, }, - // Send these bytes verbatim; they were issued where the authority private key is kept. See + // Send this certificate verbatim; it was issued where the authority private key is kept. See // [`Responder::from_certificate`]. - PreIssued([u8; SIGNATURE_NOISE_MESSAGE_SIZE]), + PreIssued(SignatureNoiseMessage), } impl core::fmt::Debug for Responder { @@ -210,7 +210,7 @@ impl Responder { /// Creates a new [`Responder`] from its static keypair `s` and a certificate issued for it in /// advance. /// - /// `certificate` is the 74-byte `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2): the certificate + /// `certificate` is the `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2): the certificate /// version, the validity window and the authority's Schnorr signature over those fields and /// the x-only public key of `s` (spec 4.5.3). [`Self::step_1`] sends it verbatim, so the /// validity window is the one the issuer chose and nothing on this host can extend it. @@ -224,10 +224,7 @@ impl Responder { /// authority, or one outside its validity window, is sent as is and rejected by every /// initiator that pins the authority public key. #[cfg(feature = "std")] - pub fn from_certificate( - s: Keypair, - certificate: [u8; SIGNATURE_NOISE_MESSAGE_SIZE], - ) -> Box { + pub fn from_certificate(s: Keypair, certificate: SignatureNoiseMessage) -> Box { Self::from_certificate_with_rng(s, certificate, &mut rand::thread_rng()) } @@ -242,7 +239,7 @@ impl Responder { #[inline] pub fn from_certificate_with_rng( s: Keypair, - certificate: [u8; SIGNATURE_NOISE_MESSAGE_SIZE], + certificate: SignatureNoiseMessage, rng: &mut R, ) -> Box { Self::build(s, CertificateSource::PreIssued(certificate), rng) @@ -430,19 +427,20 @@ impl Responder { ecdh_static.zeroize(); // 7. appends `EncryptAndHash(SIGNATURE_NOISE_MESSAGE)` to the buffer - let signature_noise_message = match &self.certificate { + let signature_noise_message: [u8; SIGNATURE_NOISE_MESSAGE_SIZE] = match &self.certificate { CertificateSource::SignAtHandshake { authority, cert_validity, - } => self.get_signature( - crate::CERTIFICATE_VERSION, + } => SignatureNoiseMessage::sign_with_rng( now, now.saturating_add(*cert_validity), + &self.s.x_only_public_key().0, authority, rng, ), CertificateSource::PreIssued(certificate) => *certificate, - }; + } + .into(); let mut signature_part = Vec::with_capacity(ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE); signature_part.extend_from_slice(&signature_noise_message[..]); Self::encrypt_and_hash(self, &mut signature_part)?; @@ -476,44 +474,6 @@ impl Responder { Ok((to_send, engine)) } - // Generates a signature noise message for the responder's certificate. - // - // This method creates a signature noise message that includes the protocol version, - // certificate validity period, and a cryptographic signature. The signature is created using - // the responder's static public key and the `authority` keypair, ensuring that the responder's - // identity and certificate validity are cryptographically verifiable. - #[inline] - fn get_signature( - &self, - version: u16, - valid_from: u32, - not_valid_after: u32, - authority: &Keypair, - rng: &mut R, - ) -> [u8; 74] { - let mut ret = [0; 74]; - let version = version.to_le_bytes(); - let valid_from = valid_from.to_le_bytes(); - let not_valid_after = not_valid_after.to_le_bytes(); - ret[0] = version[0]; - ret[1] = version[1]; - ret[2] = valid_from[0]; - ret[3] = valid_from[1]; - ret[4] = valid_from[2]; - ret[5] = valid_from[3]; - ret[6] = not_valid_after[0]; - ret[7] = not_valid_after[1]; - ret[8] = not_valid_after[2]; - ret[9] = not_valid_after[3]; - SignatureNoiseMessage::sign_with_rng( - &mut ret, - &self.s.x_only_public_key().0, - authority, - rng, - ); - ret - } - // Securely erases sensitive data in the responder's memory. // // Zeroizes the handshake key (`k`), the chaining key (`ck`) and the handshake diff --git a/sv2/noise-sv2/src/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index 5fe3db13f7..d37c72905f 100644 --- a/sv2/noise-sv2/src/signature_message.rs +++ b/sv2/noise-sv2/src/signature_message.rs @@ -7,25 +7,30 @@ // using Schnorr signatures over the [`secp256k1`] elliptic curve. It encapsulates signed messages // along with versioning and validity timestamps. The following capabilities are supported: // -// - Conversion of raw byte arrays into structured [`SignatureNoiseMessage`] instances. +// - Conversion between the 74-byte wire layout and structured [`SignatureNoiseMessage`] instances. // - Message signing using Schnorr signatures and the [`secp256k1`] curve. // - Verification of signed messages, ensuring they fall within valid time periods and are signed by // an authorized public key. // // ## Usage // -// The [`SignatureNoiseMessage`] is used by both the [`crate::Responder`] and [`crate::Initiator`] -// roles. The [`crate::Responder`] uses the `sign` method to generate a Schnorr signature over the -// initial message sent by the initiator. The [`crate::Initiator`] uses the `verify` method to -// check the validity of the signed message from the responder, comparing it against the provided -// public key and optional authority key, while ensuring the message falls within the specified -// validity period. +// The [`SignatureNoiseMessage`] is the certificate a [`crate::Responder`] presents. Whoever holds +// the authority key, the responder itself or a separate issuer, uses the `sign` method to produce +// the message: a Schnorr signature over the version, the validity period and the responder's +// static public key. The [`crate::Initiator`] uses the `verify` method to check the signed +// message from the responder, comparing it against the provided public key and optional authority +// key, while ensuring the message falls within the specified validity period. use core::convert::TryInto; use core::fmt; use secp256k1::{hashes::sha256, schnorr::Signature, Keypair, Message, Secp256k1, XOnlyPublicKey}; +use crate::{CERTIFICATE_TIME_LEEWAY, CERTIFICATE_VERSION, SIGNATURE_NOISE_MESSAGE_SIZE}; + +// Size in bytes of the signed header: `version`, `valid_from` and `not_valid_after`. +const HEADER_SIZE: usize = 10; + /// `SignatureNoiseMessage` represents a signed message used in the Noise NX protocol /// for authentication during the handshake process. It encapsulates the necessary /// details for signature verification, including protocol versioning, validity periods, @@ -33,15 +38,15 @@ use secp256k1::{hashes::sha256, schnorr::Signature, Keypair, Message, Secp256k1, /// /// This structure ensures that messages are authenticated and valid only within /// a specified time window, using Schnorr signatures over the `secp256k1` elliptic curve. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SignatureNoiseMessage { - // Version of the protocol being used. + /// Certificate format version; only [`crate::CERTIFICATE_VERSION`] verifies. pub version: u16, - // Start of the validity period for the message, expressed as a Unix timestamp. + /// Start of the validity period for the message, expressed as a Unix timestamp. pub valid_from: u32, - // End of the validity period for the message, expressed as a Unix timestamp. + /// End of the validity period for the message, expressed as a Unix timestamp. pub not_valid_after: u32, - // 64-byte Schnorr signature that authenticates the message. + /// 64-byte Schnorr signature that authenticates the message. pub signature: [u8; 64], } @@ -62,17 +67,26 @@ impl fmt::Display for SignatureNoiseMessage { write!(f, " }}") } } -impl From<[u8; 74]> for SignatureNoiseMessage { - // Converts a 74-byte array into a [`SignatureNoiseMessage`]. - // - // Allows a raw 74-byte array to be converted into a [`SignatureNoiseMessage`], extracting the - // version, validity periods, and signature from the provided data. Panics if the byte array - // cannot be correctly converted into the struct fields. - fn from(value: [u8; 74]) -> Self { +impl From for [u8; SIGNATURE_NOISE_MESSAGE_SIZE] { + /// Encodes a [`SignatureNoiseMessage`] in the 74-byte layout the handshake carries: the + /// little-endian `version`, `valid_from` and `not_valid_after`, then the signature. The inverse + /// of the conversion from bytes. + fn from(value: SignatureNoiseMessage) -> Self { + let mut encoded = [0; SIGNATURE_NOISE_MESSAGE_SIZE]; + encoded[..HEADER_SIZE].copy_from_slice(&value.header()); + encoded[HEADER_SIZE..].copy_from_slice(&value.signature); + encoded + } +} + +impl From<[u8; SIGNATURE_NOISE_MESSAGE_SIZE]> for SignatureNoiseMessage { + /// Decodes the 74-byte layout the handshake carries: the little-endian `version`, `valid_from` + /// and `not_valid_after`, then the signature. + fn from(value: [u8; SIGNATURE_NOISE_MESSAGE_SIZE]) -> Self { let version = u16::from_le_bytes(value[0..2].try_into().unwrap()); let valid_from = u32::from_le_bytes(value[2..6].try_into().unwrap()); - let not_valid_after = u32::from_le_bytes(value[6..10].try_into().unwrap()); - let signature = value[10..74].try_into().unwrap(); + let not_valid_after = u32::from_le_bytes(value[6..HEADER_SIZE].try_into().unwrap()); + let signature = value[HEADER_SIZE..].try_into().unwrap(); Self { version, valid_from, @@ -83,29 +97,27 @@ impl From<[u8; 74]> for SignatureNoiseMessage { } impl SignatureNoiseMessage { - // Verifies the [`SignatureNoiseMessage`] against the provided public key and an optional - // authority public key. The verification checks that the message is currently valid - // (i.e., within the `valid_from` and `not_valid_after` time window) and that the signature - // is correctly signed by the authority. - // - // If an authority public key is not provided, only the certificate version is checked; the - // signature and the validity window are ignored and the message is accepted as is. - #[allow(dead_code)] + /// Verifies the [`SignatureNoiseMessage`] against the responder's static public key and an + /// optional authority public key at the current system time. See [`Self::verify_with_now`]. #[cfg(feature = "std")] - pub fn verify(self, pk: &XOnlyPublicKey, authority_pk: &Option) -> bool { + pub fn verify( + &self, + static_pk: &XOnlyPublicKey, + authority_pk: &Option, + ) -> bool { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as u32; - self.verify_with_now(pk, authority_pk, now) + self.verify_with_now(static_pk, authority_pk, now) } /// Verifies the validity and authenticity of the `SignatureNoiseMessage` at a given timestamp - /// with 10 seconds of tolerance. + /// with [`CERTIFICATE_TIME_LEEWAY`] seconds of tolerance. /// /// With an authority public key, the message must carry the supported certificate version, /// `now` must fall inside its validity window, and its signature over the responder's static - /// key `pk` must verify against the authority key. + /// key `static_pk` must verify against the authority key. /// /// # Security /// @@ -116,56 +128,58 @@ impl SignatureNoiseMessage { /// environments to use another source of time. #[inline] pub fn verify_with_now( - self, - pk: &XOnlyPublicKey, + &self, + static_pk: &XOnlyPublicKey, authority_pk: &Option, now: u32, ) -> bool { - // Allow the local clock to drift up to 10 seconds ahead or behind. - // See https://github.com/stratum-mining/stratum/issues/2015 - const TIME_LEEWAY: u32 = 10; - - if self.version != crate::CERTIFICATE_VERSION { + if self.version != CERTIFICATE_VERSION { return false; } - if let Some(authority_pk) = authority_pk { - // Use saturating ops to cap edges (valid_from ≥ 0, not_valid_after ≤ u32::MAX), - // preventing wrap-around and subtle validation bugs with untrusted timestamps. - if self.valid_from.saturating_sub(TIME_LEEWAY) <= now - && self.not_valid_after.saturating_add(TIME_LEEWAY) >= now - { - let secp = Secp256k1::verification_only(); - let (m, s) = self.split(); - // m = SHA-256(version || valid_from || not_valid_after || server_static_key) - let m = [&m[0..10], &pk.serialize()].concat(); - let m = Message::from_hashed_data::(&m); - let s = match Signature::from_slice(&s) { - Ok(s) => s, - _ => return false, - }; - secp.verify_schnorr(&s, &m, authority_pk).is_ok() - } else { - false - } - } else { - true + let Some(authority_pk) = authority_pk else { + return true; + }; + + // Use saturating ops to cap edges (valid_from ≥ 0, not_valid_after ≤ u32::MAX), + // preventing wrap-around and subtle validation bugs with untrusted timestamps. + if self.valid_from.saturating_sub(CERTIFICATE_TIME_LEEWAY) > now + || self.not_valid_after.saturating_add(CERTIFICATE_TIME_LEEWAY) < now + { + return false; } + + let secp = Secp256k1::verification_only(); + // m = SHA-256(version || valid_from || not_valid_after || server_static_key) + let m = [&self.header()[..], &static_pk.serialize()].concat(); + let m = Message::from_hashed_data::(&m); + let s = match Signature::from_slice(&self.signature) { + Ok(s) => s, + _ => return false, + }; + secp.verify_schnorr(&s, &m, authority_pk).is_ok() } - // Signs a [`SignatureNoiseMessage`] using the provided keypair (`kp`). - // - // Creates a Schnorr signature for the message, combining the version, validity period, and - // the static public key of the server (`static_pk`). The resulting signature is then written - // into the provided message buffer (`msg`). - #[allow(dead_code)] + /// Issues a [`SignatureNoiseMessage`] of the supported certificate version for the server's + /// static public key (`static_pk`), valid between the two Unix timestamps and signed with the + /// `authority` keypair. #[cfg(feature = "std")] - pub fn sign(msg: &mut [u8; 74], static_pk: &XOnlyPublicKey, kp: &Keypair) { - Self::sign_with_rng(msg, static_pk, kp, &mut rand::thread_rng()); + pub fn sign( + valid_from: u32, + not_valid_after: u32, + static_pk: &XOnlyPublicKey, + authority: &Keypair, + ) -> Self { + Self::sign_with_rng( + valid_from, + not_valid_after, + static_pk, + authority, + &mut rand::thread_rng(), + ) } - /// Signs a [`SignatureNoiseMessage`] using the provided keypair (`kp`) and a custom random - /// number generator. + /// Issues a [`SignatureNoiseMessage`] using a custom random number generator. /// /// See [`Self::sign`] for more details. /// @@ -174,39 +188,33 @@ impl SignatureNoiseMessage { /// hardware random number generator for example. #[inline] pub fn sign_with_rng( - msg: &mut [u8; 74], + valid_from: u32, + not_valid_after: u32, static_pk: &XOnlyPublicKey, - kp: &Keypair, + authority: &Keypair, rng: &mut R, - ) { + ) -> Self { + let mut message = Self { + version: CERTIFICATE_VERSION, + valid_from, + not_valid_after, + signature: [0; 64], + }; let secp = Secp256k1::signing_only(); - let m = [&msg[0..10], &static_pk.serialize()].concat(); + // m = SHA-256(version || valid_from || not_valid_after || server_static_key) + let m = [&message.header()[..], &static_pk.serialize()].concat(); let m = Message::from_hashed_data::(&m); - let signature = secp.sign_schnorr_with_rng(&m, kp, rng); - for (i, b) in signature.as_ref().iter().enumerate() { - msg[10 + i] = *b; - } + message.signature = *secp.sign_schnorr_with_rng(&m, authority, rng).as_ref(); + message } - // Splits the [`SignatureNoiseMessage`] into its component parts: the message hash and the - // signature. - // - // Separates the message into the first 10 bytes (containing the version and validity period) - // and the 64-byte Schnorr signature, returning them in a tuple. Used internally during the - // verification process. - fn split(self) -> ([u8; 10], [u8; 64]) { - let mut m = [0; 10]; - m[0] = self.version.to_le_bytes()[0]; - m[1] = self.version.to_le_bytes()[1]; - m[2] = self.valid_from.to_le_bytes()[0]; - m[3] = self.valid_from.to_le_bytes()[1]; - m[4] = self.valid_from.to_le_bytes()[2]; - m[5] = self.valid_from.to_le_bytes()[3]; - m[6] = self.not_valid_after.to_le_bytes()[0]; - m[7] = self.not_valid_after.to_le_bytes()[1]; - m[8] = self.not_valid_after.to_le_bytes()[2]; - m[9] = self.not_valid_after.to_le_bytes()[3]; - (m, self.signature) + // The signed header: the little-endian `version`, `valid_from` and `not_valid_after`. + fn header(&self) -> [u8; HEADER_SIZE] { + let mut header = [0; HEADER_SIZE]; + header[0..2].copy_from_slice(&self.version.to_le_bytes()); + header[2..6].copy_from_slice(&self.valid_from.to_le_bytes()); + header[6..HEADER_SIZE].copy_from_slice(&self.not_valid_after.to_le_bytes()); + header } } @@ -214,6 +222,19 @@ impl SignatureNoiseMessage { mod test { use super::*; + #[test] + fn byte_encoding_round_trips() { + let mut encoded = [0u8; SIGNATURE_NOISE_MESSAGE_SIZE]; + for (i, b) in encoded.iter_mut().enumerate() { + *b = i as u8; + } + let message = SignatureNoiseMessage::from(encoded); + assert_eq!(message.version, u16::from_le_bytes([0, 1])); + assert_eq!(message.valid_from, u32::from_le_bytes([2, 3, 4, 5])); + assert_eq!(message.not_valid_after, u32::from_le_bytes([6, 7, 8, 9])); + assert_eq!(<[u8; SIGNATURE_NOISE_MESSAGE_SIZE]>::from(message), encoded); + } + #[test] #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] @@ -223,25 +244,27 @@ mod test { let secp = Secp256k1::new(); let mut rng = StdRng::seed_from_u64(42); let authority = Keypair::new(&secp, &mut rng); - let responder_static = Keypair::new(&secp, &mut rng); - - let mut encoded = [0u8; 74]; - encoded[0..2].copy_from_slice(&(crate::CERTIFICATE_VERSION + 1).to_le_bytes()); - encoded[2..6].copy_from_slice(&100u32.to_le_bytes()); - encoded[6..10].copy_from_slice(&200u32.to_le_bytes()); - SignatureNoiseMessage::sign_with_rng( - &mut encoded, - &responder_static.x_only_public_key().0, - &authority, - &mut rng, - ); - - let certificate = SignatureNoiseMessage::from(encoded); - let authority_pk = Some(authority.x_only_public_key().0); + let static_pk = Keypair::new(&secp, &mut rng).x_only_public_key().0; + + let mut certificate = + SignatureNoiseMessage::sign_with_rng(100, 200, &static_pk, &authority, &mut rng); + assert!(certificate.verify_with_now( + &static_pk, + &Some(authority.x_only_public_key().0), + 150 + )); + + // The same certificate, validly signed for a version this crate does not support. + certificate.version = CERTIFICATE_VERSION + 1; + let m = [&certificate.header()[..], &static_pk.serialize()].concat(); + let m = Message::from_hashed_data::(&m); + certificate.signature = *secp + .sign_schnorr_with_rng(&m, &authority, &mut rng) + .as_ref(); assert!(!certificate.verify_with_now( - &responder_static.x_only_public_key().0, - &authority_pk, - 150, + &static_pk, + &Some(authority.x_only_public_key().0), + 150 )); } } diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index 8b562ead3a..c13ef90f0d 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -52,25 +52,18 @@ fn test_1_with_rng() { #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] fn pre_issued_certificate_is_sent_verbatim() { - use crate::{ - signature_message::SignatureNoiseMessage, Error, CERTIFICATE_VERSION, - SIGNATURE_NOISE_MESSAGE_SIZE, - }; + use crate::{signature_message::SignatureNoiseMessage, Error}; // Issued where the authority private key lives; the responder never sees that key. let authority = Responder::generate_key(); let server_static = Responder::generate_key(); let issue = |valid_from: u32, not_valid_after: u32| { - let mut certificate = [0u8; SIGNATURE_NOISE_MESSAGE_SIZE]; - certificate[0..2].copy_from_slice(&CERTIFICATE_VERSION.to_le_bytes()); - certificate[2..6].copy_from_slice(&valid_from.to_le_bytes()); - certificate[6..10].copy_from_slice(¬_valid_after.to_le_bytes()); SignatureNoiseMessage::sign( - &mut certificate, + valid_from, + not_valid_after, &server_static.x_only_public_key().0, &authority, - ); - certificate + ) }; let handshake = |certificate| { let mut initiator = Initiator::new(Some(authority.public_key().into())); From 241ab2f1df39a1c1ce26fd3f874490642850eec1 Mon Sep 17 00:00:00 2001 From: plebhash Date: Fri, 13 Nov 2026 11:56:28 -0300 Subject: [PATCH 4/9] refactor(noise_sv2)!: verify certificates against an authority key only `SignatureNoiseMessage::verify` and `verify_with_now` took the authority public key as an `Option` and, without one, accepted any message of the supported version, so the certificate API offered unauthenticated verification as a state. Take the key outright. An `Initiator` built without a pinned key still skips the verification itself and checks only the certificate version, so its API and behaviour are unchanged; two tests now pin that down. BREAKING CHANGE: both methods lose the `Option`. `SignatureNoiseMessage` was not re-exported in 2.1.0, but a value of it is reachable through `Error::InvalidCertificate`, so the methods could already be called; `cargo semver-checks` cannot see the change because rustdoc omits unnameable items. noise_sv2 goes to 3.0.0. `codec_sv2` carries `noise_sv2::Error` in its own `Error` and `stratum-core` re-exports the crate, so they move to 9.0.0 and 0.8.0 with their requirements. --- Cargo.lock | 6 ++-- fuzz/Cargo.lock | 4 +-- stratum-core/Cargo.toml | 6 ++-- sv2/codec-sv2/Cargo.toml | 4 +-- sv2/noise-sv2/Cargo.toml | 2 +- sv2/noise-sv2/src/initiator.rs | 27 +++++++++++----- sv2/noise-sv2/src/signature_message.rs | 43 +++++++------------------- sv2/noise-sv2/src/test.rs | 41 ++++++++++++++++++++++++ 8 files changed, 82 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2d567cffa9..fc04f1f662 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -285,7 +285,7 @@ dependencies = [ [[package]] name = "codec_sv2" -version = "8.1.0" +version = "9.0.0" dependencies = [ "binary_sv2", "buffer_sv2", @@ -736,7 +736,7 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.2.0" +version = "3.0.0" dependencies = [ "chacha20poly1305", "criterion", @@ -1162,7 +1162,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" dependencies = [ "binary_sv2", "bitcoin", diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 84ac3864c9..129b60e9bf 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -162,7 +162,7 @@ dependencies = [ [[package]] name = "codec_sv2" -version = "8.0.0" +version = "9.0.0" dependencies = [ "binary_sv2", "buffer_sv2", @@ -363,7 +363,7 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.2.0" +version = "3.0.0" dependencies = [ "chacha20poly1305", "rand", diff --git a/stratum-core/Cargo.toml b/stratum-core/Cargo.toml index a04da46d3b..80cd67035c 100644 --- a/stratum-core/Cargo.toml +++ b/stratum-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "stratum-core" -version = "0.7.0" +version = "0.8.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" @@ -14,10 +14,10 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"] [dependencies] buffer_sv2 = { path = "../sv2/buffer-sv2", version = "^4.0.0" } binary_sv2 = { path = "../sv2/binary-sv2", version = "^8.0.0" } -codec_sv2 = { path = "../sv2/codec-sv2", version = "^8.0.0", features = ["noise_sv2"]} +codec_sv2 = { path = "../sv2/codec-sv2", version = "^9.0.0", features = ["noise_sv2"]} extensions_sv2 = { path = "../sv2/extensions-sv2", version = "^0.4.0" } framing_sv2 = { path = "../sv2/framing-sv2", version = "^9.0.0" } -noise_sv2 = { path = "../sv2/noise-sv2", version = "^2.1.0" } +noise_sv2 = { path = "../sv2/noise-sv2", version = "^3.0.0" } parsers_sv2 = { path = "../sv2/parsers-sv2", version = "^0.7.0" } handlers_sv2 = { path = "../sv2/handlers-sv2", version = "^0.7.0" } channels_sv2 = { path = "../sv2/channels-sv2", version = "^9.0.0" } diff --git a/sv2/codec-sv2/Cargo.toml b/sv2/codec-sv2/Cargo.toml index 872077d711..612b4353b7 100644 --- a/sv2/codec-sv2/Cargo.toml +++ b/sv2/codec-sv2/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "codec_sv2" -version = "8.1.0" +version = "9.0.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" @@ -13,7 +13,7 @@ keywords = ["stratum", "mining", "bitcoin", "protocol"] [dependencies] framing_sv2 = { path = "../framing-sv2", version = "^9.0.0" } -noise_sv2 = { path = "../noise-sv2", default-features = false, optional = true, version = "^2.1.0" } +noise_sv2 = { path = "../noise-sv2", default-features = false, optional = true, version = "^3.0.0" } binary_sv2 = { path = "../binary-sv2", version = "^8.0.0" } buffer_sv2 = { path = "../buffer-sv2", version = "^4.0.0" } rand = { workspace = true, default-features = false } diff --git a/sv2/noise-sv2/Cargo.toml b/sv2/noise-sv2/Cargo.toml index 8ae4de627b..2e21524991 100644 --- a/sv2/noise-sv2/Cargo.toml +++ b/sv2/noise-sv2/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "noise_sv2" -version = "2.2.0" +version = "3.0.0" authors = ["The Stratum V2 Developers"] edition = "2021" readme = "README.md" diff --git a/sv2/noise-sv2/src/initiator.rs b/sv2/noise-sv2/src/initiator.rs index c3e97bd3ba..c5073386e1 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -83,7 +83,8 @@ pub struct Initiator { // shared secret with the responder. e: Keypair, // Optional authority public key of the responder, used to verify the responder's certificate - // during the handshake. `None` skips that verification entirely. + // during the handshake. `None` skips that verification; only the certificate version is + // still checked. #[allow(unused)] responder_authority_pk: Option, } @@ -228,9 +229,10 @@ impl Initiator { /// /// The responder's certificate is not verified: its signature, its validity window and the /// authority that issued it are all ignored, so any peer that completes the Noise NX - /// handshake is accepted. The session is still encrypted, which protects against passive - /// eavesdropping, but an active attacker on the path can impersonate the responder or sit - /// between the two roles and read or rewrite every message. + /// handshake with a certificate of the supported version is accepted. The session is still + /// encrypted, which protects against passive eavesdropping, but an active attacker on the + /// path can impersonate the responder or sit between the two roles and read or rewrite every + /// message. /// /// Nothing in the returned [`NoiseEngine`] records that the responder was not authenticated, /// and [`Self::step_2`] returns `Ok` exactly as it does for a verified session. Callers that @@ -302,9 +304,10 @@ impl Initiator { /// /// # Security /// - /// Without a responder authority public key (see [`Self::without_pk`]) the certificate is - /// accepted unverified, and `Ok` does not mean the responder was authenticated. The returned - /// [`NoiseEngine`] carries no indication of which case applies. + /// Without a responder authority public key (see [`Self::without_pk`]) only the certificate + /// version is checked; the certificate is otherwise accepted unverified, and `Ok` does not + /// mean the responder was authenticated. The returned [`NoiseEngine`] carries no indication + /// of which case applies. /// /// On success the remaining handshake secrets, including the ephemeral keypair, are erased, /// so the [`Initiator`] cannot be used for another handshake. @@ -397,7 +400,15 @@ impl Initiator { .0 .serialize(); let rs_pk_xonly = XOnlyPublicKey::from_slice(&rs_pub_key).unwrap(); - if signature_message.verify_with_now(&rs_pk_xonly, &self.responder_authority_pk, now) { + // Without an authority key there is nothing to verify the certificate against (see + // `without_pk`), and only its format version is checked. + let accepted = match &self.responder_authority_pk { + Some(authority_pk) => { + signature_message.verify_with_now(&rs_pk_xonly, authority_pk, now) + } + None => signature_message.version == crate::CERTIFICATE_VERSION, + }; + if accepted { let (mut temp_k1, mut temp_k2) = Self::hkdf_2(self.get_ck(), &[]); let c1 = ChaCha20Poly1305::new(Key::from_slice(&temp_k1[..])); let c2 = ChaCha20Poly1305::new(Key::from_slice(&temp_k2[..])); diff --git a/sv2/noise-sv2/src/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index d37c72905f..b8968ba867 100644 --- a/sv2/noise-sv2/src/signature_message.rs +++ b/sv2/noise-sv2/src/signature_message.rs @@ -18,8 +18,8 @@ // the authority key, the responder itself or a separate issuer, uses the `sign` method to produce // the message: a Schnorr signature over the version, the validity period and the responder's // static public key. The [`crate::Initiator`] uses the `verify` method to check the signed -// message from the responder, comparing it against the provided public key and optional authority -// key, while ensuring the message falls within the specified validity period. +// message from the responder, comparing it against the provided public key and authority key, +// while ensuring the message falls within the specified validity period. use core::convert::TryInto; use core::fmt; @@ -97,14 +97,10 @@ impl From<[u8; SIGNATURE_NOISE_MESSAGE_SIZE]> for SignatureNoiseMessage { } impl SignatureNoiseMessage { - /// Verifies the [`SignatureNoiseMessage`] against the responder's static public key and an - /// optional authority public key at the current system time. See [`Self::verify_with_now`]. + /// Verifies the [`SignatureNoiseMessage`] against the responder's static public key and the + /// authority public key at the current system time. See [`Self::verify_with_now`]. #[cfg(feature = "std")] - pub fn verify( - &self, - static_pk: &XOnlyPublicKey, - authority_pk: &Option, - ) -> bool { + pub fn verify(&self, static_pk: &XOnlyPublicKey, authority_pk: &XOnlyPublicKey) -> bool { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -115,14 +111,9 @@ impl SignatureNoiseMessage { /// Verifies the validity and authenticity of the `SignatureNoiseMessage` at a given timestamp /// with [`CERTIFICATE_TIME_LEEWAY`] seconds of tolerance. /// - /// With an authority public key, the message must carry the supported certificate version, - /// `now` must fall inside its validity window, and its signature over the responder's static - /// key `static_pk` must verify against the authority key. - /// - /// # Security - /// - /// Without an authority public key, only the certificate version is checked and the message is - /// otherwise accepted unverified, so `true` does not mean the responder was authenticated. + /// The message must carry the supported certificate version, `now` must fall inside its + /// validity window, and its signature over the responder's static key `static_pk` must verify + /// against `authority_pk`. /// /// The current system time should be provided to avoid relying on `std` and allow `no_std` /// environments to use another source of time. @@ -130,17 +121,13 @@ impl SignatureNoiseMessage { pub fn verify_with_now( &self, static_pk: &XOnlyPublicKey, - authority_pk: &Option, + authority_pk: &XOnlyPublicKey, now: u32, ) -> bool { if self.version != CERTIFICATE_VERSION { return false; } - let Some(authority_pk) = authority_pk else { - return true; - }; - // Use saturating ops to cap edges (valid_from ≥ 0, not_valid_after ≤ u32::MAX), // preventing wrap-around and subtle validation bugs with untrusted timestamps. if self.valid_from.saturating_sub(CERTIFICATE_TIME_LEEWAY) > now @@ -248,11 +235,7 @@ mod test { let mut certificate = SignatureNoiseMessage::sign_with_rng(100, 200, &static_pk, &authority, &mut rng); - assert!(certificate.verify_with_now( - &static_pk, - &Some(authority.x_only_public_key().0), - 150 - )); + assert!(certificate.verify_with_now(&static_pk, &authority.x_only_public_key().0, 150)); // The same certificate, validly signed for a version this crate does not support. certificate.version = CERTIFICATE_VERSION + 1; @@ -261,10 +244,6 @@ mod test { certificate.signature = *secp .sign_schnorr_with_rng(&m, &authority, &mut rng) .as_ref(); - assert!(!certificate.verify_with_now( - &static_pk, - &Some(authority.x_only_public_key().0), - 150 - )); + assert!(!certificate.verify_with_now(&static_pk, &authority.x_only_public_key().0, 150)); } } diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index c13ef90f0d..de18cff197 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -94,3 +94,44 @@ fn pre_issued_certificate_is_sent_verbatim() { Err(Error::InvalidCertificate(_)) )); } + +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn unpinned_initiator_still_rejects_an_unsupported_certificate_version() { + use crate::{signature_message::SignatureNoiseMessage, Error, CERTIFICATE_VERSION}; + + let certificate = SignatureNoiseMessage { + version: CERTIFICATE_VERSION + 1, + valid_from: 0, + not_valid_after: u32::MAX, + signature: [0; 64], + }; + let mut initiator = Initiator::without_pk().unwrap(); + let mut responder = Responder::from_certificate(Responder::generate_key(), certificate); + let first_message = initiator.step_0().unwrap(); + let (second_message, _) = responder.step_1(first_message).unwrap(); + assert!(matches!( + initiator.step_2(second_message), + Err(Error::InvalidCertificate(_)) + )); +} + +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn unpinned_initiator_accepts_an_unverified_certificate_of_the_supported_version() { + use crate::{signature_message::SignatureNoiseMessage, CERTIFICATE_VERSION}; + + let certificate = SignatureNoiseMessage { + version: CERTIFICATE_VERSION, + valid_from: 0, + not_valid_after: u32::MAX, + signature: [0; 64], + }; + let mut initiator = Initiator::without_pk().unwrap(); + let mut responder = Responder::from_certificate(Responder::generate_key(), certificate); + let first_message = initiator.step_0().unwrap(); + let (second_message, _) = responder.step_1(first_message).unwrap(); + assert!(initiator.step_2(second_message).is_ok()); +} From e435cd97d694910f15c38473df178bd795e9a1cf Mon Sep 17 00:00:00 2001 From: plebhash Date: Fri, 13 Nov 2026 15:55:42 -0300 Subject: [PATCH 5/9] feat(noise_sv2)!: always authenticate the responder `Initiator::new` took the responder authority public key as an `Option` and `without_pk` built an initiator with none. Such an initiator completed the handshake with any responder whose certificate carried the supported version, yielding an encrypted but unauthenticated session. The Sv2 spec defines no such state: the handshake is "Noise_NX augmented by server authentication", its third step is the initiator validating the server's certificate, and the authority public key is a precondition of using the scheme (04-Protocol-Security.md 4.5, 4.5.3, 4.7). The one unauthenticated option the spec leaves is not running the handshake at all, on a local network. Make the key mandatory: `new` and `new_with_rng` take it outright, `without_pk` and `without_pk_with_rng` are gone, and `step_2` always verifies the certificate. The fuzz target drops its anonymous peer mode. BREAKING CHANGE: `Initiator::new` and `new_with_rng` take `XOnlyPublicKey` instead of `Option`; `Initiator::without_pk` and `without_pk_with_rng` are removed. Covered by the 3.0.0 bump of noise_sv2 in the previous commit. --- ...oise_handshake_and_roundtrip_encryption.rs | 25 ++--- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/benches/handshake.rs | 8 +- sv2/noise-sv2/benches/roundtrip.rs | 2 +- sv2/noise-sv2/examples/handshake.rs | 4 +- sv2/noise-sv2/src/initiator.rs | 105 ++++-------------- sv2/noise-sv2/src/lib.rs | 9 +- sv2/noise-sv2/src/test.rs | 65 ++++------- 8 files changed, 62 insertions(+), 158 deletions(-) diff --git a/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs b/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs index d50ccabadc..f75c9adcac 100644 --- a/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs +++ b/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs @@ -23,11 +23,9 @@ fn generate_key(rand_seed: u64) -> Keypair { } // Represents the relationship between the initiator and responder during the Noise handshake. -// This determines whether the initiator knows and trusts the responder's public key. +// This determines whether the key the initiator pins is the responder's. #[derive(PartialEq, Arbitrary, Debug)] enum PeerMode { - // Initiator does not know the responder's public key -> performs anonymous handshake - Unknown, // Initiator knows and expects the responder's specific public key -> authenticated handshake Known, // Initiator knows a different peer's key (not the responder's) -> handshake should fail @@ -38,7 +36,7 @@ enum PeerMode { // Generated by the arbitrary crate from raw fuzz input bytes. #[derive(Debug, Arbitrary)] struct FuzzInput { - // Controls whether initiator knows responder's public key + // Controls which authority public key the initiator pins peer_mode: PeerMode, // Certificate validity duration in seconds (passed to responder) cert_validity: u32, @@ -83,23 +81,18 @@ fuzz_target!(|input: FuzzInput| { let responder_kp = generate_key(input.rand_seed); let responder_pk: XOnlyPublicKey = responder_kp.public_key().x_only_public_key().0; - // Determine if the initiator knows the responder's key - // This affects the Noise handshake pattern (anonymous vs authenticated) + // Pick the authority public key the initiator pins let known_peer = match input.peer_mode { - // Initiator has no prior knowledge of responder -> performs anonymous handshake - PeerMode::Unknown => None, // Initiator knows responder's exact public key -> authenticated handshake - PeerMode::Known => Some(responder_pk), + PeerMode::Known => responder_pk, // Initiator knows a DIFFERENT peer's key -> handshake should fail - PeerMode::PeerDifferentFromResponder => Some( - generate_key(input.rand_seed ^ 0xcafe_babe) - .public_key() - .x_only_public_key() - .0, - ), + PeerMode::PeerDifferentFromResponder => generate_key(input.rand_seed ^ 0xcafe_babe) + .public_key() + .x_only_public_key() + .0, }; - // Create initiator (client) - optionally knows the responder + // Create initiator (client) pinning that key let mut initiator = Initiator::new(known_peer); // Create responder (server) with the generated keypair and certificate validity diff --git a/sv2/noise-sv2/README.md b/sv2/noise-sv2/README.md index 5df1f50d0a..56181bfd51 100644 --- a/sv2/noise-sv2/README.md +++ b/sv2/noise-sv2/README.md @@ -10,7 +10,7 @@ `noise_sv2` is primarily intended to secure communication in the Stratum V2 (Sv2) protocol. It handles the necessary Noise handshakes, encrypts outgoing messages, and decrypts incoming responses, ensuring privacy and integrity across the communication link between Sv2 roles. See the [Protocol Security specification](https://github.com/stratum-mining/sv2-spec/blob/main/04-Protocol-Security.md) for more details. ## Key Capabilities -* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. The responder is only authenticated when the `Initiator` is given its authority public key; an `Initiator` built without one (`Initiator::without_pk`) yields an encrypted but unauthenticated session. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it. +* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. Every `Initiator` pins the responder's authority public key and rejects a certificate that does not verify against it. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it. * **Cipher Support**: Uses `ChaCha20-Poly1305` for authenticated encryption. * **Handshake Roles**: Implements the `Initiator` and `Responder` roles required by the Noise handshake, allowing both sides of a connection to establish secure communication. * **Cryptographic Helpers**: Facilitates the management of cryptographic state and encryption operations. diff --git a/sv2/noise-sv2/benches/handshake.rs b/sv2/noise-sv2/benches/handshake.rs index 1ea4f35429..e5955331f1 100644 --- a/sv2/noise-sv2/benches/handshake.rs +++ b/sv2/noise-sv2/benches/handshake.rs @@ -9,7 +9,7 @@ fn bench_nx_handshake(c: &mut Criterion) { group.bench_function("step_0_initiator", |b| { b.iter_batched( - || Initiator::new(None), + || Initiator::new(generate_key_with_rng(&mut rng()).public_key().into()), |mut initiator| { let _msg_0 = initiator.step_0().unwrap(); }, @@ -22,7 +22,7 @@ fn bench_nx_handshake(c: &mut Criterion) { || { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); - let mut initiator = Initiator::new(None); + let mut initiator = Initiator::new(responder_key.public_key().into()); let responder = Responder::new(responder_key, 60); let msg_0 = initiator.step_0().unwrap(); @@ -40,7 +40,7 @@ fn bench_nx_handshake(c: &mut Criterion) { || { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); - let mut initiator = Initiator::new(None); + let mut initiator = Initiator::new(responder_key.public_key().into()); let mut responder = Responder::new(responder_key, 60); let msg_0 = initiator.step_0().unwrap(); @@ -60,7 +60,7 @@ fn bench_nx_handshake(c: &mut Criterion) { || { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); - let initiator = Initiator::new(None); + let initiator = Initiator::new(responder_key.public_key().into()); let responder = Responder::new(responder_key, 60); (initiator, responder, rng) }, diff --git a/sv2/noise-sv2/benches/roundtrip.rs b/sv2/noise-sv2/benches/roundtrip.rs index 33ec52e78a..ce50bc4a06 100644 --- a/sv2/noise-sv2/benches/roundtrip.rs +++ b/sv2/noise-sv2/benches/roundtrip.rs @@ -6,7 +6,7 @@ mod common; fn bench_encryption_roundtrip(c: &mut Criterion) { let responder_key = generate_key_with_rng(&mut rng()); - let mut initiator = Initiator::new(None); + let mut initiator = Initiator::new(responder_key.public_key().into()); let mut responder = Responder::new(responder_key, 10); let msg_0 = initiator.step_0().unwrap(); diff --git a/sv2/noise-sv2/examples/handshake.rs b/sv2/noise-sv2/examples/handshake.rs index 2bad0db1da..f405b33bb4 100644 --- a/sv2/noise-sv2/examples/handshake.rs +++ b/sv2/noise-sv2/examples/handshake.rs @@ -42,10 +42,10 @@ fn main() { let responder_key_pair = generate_key(); #[cfg(feature = "std")] - let mut initiator = Initiator::new(Some(responder_key_pair.public_key().into())); + let mut initiator = Initiator::new(responder_key_pair.public_key().into()); #[cfg(not(feature = "std"))] let mut initiator = Initiator::new_with_rng( - Some(responder_key_pair.public_key().into()), + responder_key_pair.public_key().into(), &mut rand::thread_rng(), ); #[cfg(feature = "std")] diff --git a/sv2/noise-sv2/src/initiator.rs b/sv2/noise-sv2/src/initiator.rs index c5073386e1..0b45f53219 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -82,11 +82,9 @@ pub struct Initiator { // Ephemeral key pair generated by the initiator for this session, used for generating the // shared secret with the responder. e: Keypair, - // Optional authority public key of the responder, used to verify the responder's certificate - // during the handshake. `None` skips that verification; only the certificate version is - // still checked. - #[allow(unused)] - responder_authority_pk: Option, + // Authority public key of the responder; the certificate received in step 2 must be signed + // by it. + responder_authority_pk: XOnlyPublicKey, } impl core::fmt::Debug for Initiator { @@ -147,28 +145,19 @@ impl HandshakeOp for Initiator { } impl Initiator { - /// Creates a new [`Initiator`] instance with an optional responder authority public key. + /// Creates a new [`Initiator`] instance pinning the responder's authority public key. /// - /// If the responder authority public key is provided, the initiator uses this key to - /// authenticate the responder during the handshake: the certificate received in - /// [`Self::step_2`] must be signed by this key and be inside its validity window, otherwise - /// the handshake fails with [`Error::InvalidCertificate`]. The initial initiator state is - /// instantiated with the ephemeral key pair and handshake hash. - /// - /// # Security - /// - /// Passing `None` disables responder authentication. The handshake then accepts any peer, - /// and the resulting session is encrypted but not authenticated. It is also indistinguishable - /// from an authenticated one, since [`Self::step_2`] returns `Ok` in both cases. Prefer - /// [`Self::without_pk`] when this is intended, so that the choice is visible at the call site, - /// and read its documentation for the consequences. + /// The initiator authenticates the responder with this key during the handshake: the + /// certificate received in [`Self::step_2`] must be signed by it and be inside its validity + /// window, otherwise the handshake fails with [`Error::InvalidCertificate`]. The initial + /// initiator state is instantiated with the ephemeral key pair and handshake hash. #[cfg(feature = "std")] - pub fn new(pk: Option) -> Box { + pub fn new(pk: XOnlyPublicKey) -> Box { Self::new_with_rng(pk, &mut rand::thread_rng()) } - /// Creates a new [`Initiator`] instance with an optional responder public key and a custom - /// random number generator. + /// Creates a new [`Initiator`] instance pinning the responder's authority public key, with a + /// custom random number generator. /// /// See [`Self::new`] for more details. /// @@ -177,7 +166,7 @@ impl Initiator { /// provide a hardware random number generator for example. #[inline] pub fn new_with_rng( - pk: Option, + pk: XOnlyPublicKey, rng: &mut R, ) -> Box { let mut self_ = Self { @@ -199,7 +188,7 @@ impl Initiator { /// [`Initiator`] with the derived public key. If the provided key cannot be converted into a /// valid [`XOnlyPublicKey`], an [`Error::InvalidRawPublicKey`] error is returned. /// - /// Typically used when the initiator is aware of the responder's public key in advance. + /// Typically used when the responder's authority public key is at hand as raw bytes. #[cfg(feature = "std")] pub fn from_raw_k(key: [u8; 32]) -> Result, Error> { Self::from_raw_k_with_rng(key, &mut rand::thread_rng()) @@ -220,46 +209,7 @@ impl Initiator { ) -> Result, Error> { let pk = secp256k1::XOnlyPublicKey::from_slice(&key).map_err(|_| Error::InvalidRawPublicKey)?; - Ok(Self::new_with_rng(Some(pk), rng)) - } - - /// Creates a new [`Initiator`] that does not authenticate the responder. - /// - /// # Security - /// - /// The responder's certificate is not verified: its signature, its validity window and the - /// authority that issued it are all ignored, so any peer that completes the Noise NX - /// handshake with a certificate of the supported version is accepted. The session is still - /// encrypted, which protects against passive eavesdropping, but an active attacker on the - /// path can impersonate the responder or sit between the two roles and read or rewrite every - /// message. - /// - /// Nothing in the returned [`NoiseEngine`] records that the responder was not authenticated, - /// and [`Self::step_2`] returns `Ok` exactly as it does for a verified session. Callers that - /// need to tell the two apart must track which constructor they used. - /// - /// Only use this constructor when the initiator and responder are on the same trusted network - /// and the responder has no authority key to pin. Whenever the responder's authority public - /// key is available, use [`Self::new`] with `Some(key)` or [`Self::from_raw_k`] instead. - #[cfg(feature = "std")] - pub fn without_pk() -> Result, Error> { - Self::without_pk_with_rng(&mut rand::thread_rng()) - } - - /// Creates a new [`Initiator`] that does not authenticate the responder, using a custom - /// random number generator. - /// - /// See [`Self::without_pk`] for more details, including the security consequences of - /// skipping responder authentication. - /// - /// The custom random number generator should be provided in order to not implicitely rely on - /// `std` and allow `no_std` environments to provide a hardware random number generator for - /// example. - #[inline] - pub fn without_pk_with_rng( - rng: &mut R, - ) -> Result, Error> { - Ok(Self::new_with_rng(None, rng)) + Ok(Self::new_with_rng(pk, rng)) } /// Executes the initial step of the Noise NX protocol handshake. @@ -294,8 +244,8 @@ impl Initiator { /// The next 80 bytes of the message contain the responder's static public key, encrypted and /// authenticated. The method decrypts this segment and derives another shared secret using the /// responder's static public key, further securing the handshake state. Finally, the method - /// decrypts the certificate included in the message and, if this [`Initiator`] was built with - /// a responder authority public key, verifies it to ensure the responder's authenticity. + /// decrypts the certificate included in the message and verifies it against the responder's + /// authority public key to ensure the responder's authenticity. /// /// On success, this method returns a [`NoiseEngine`] instance initialized with session ciphers /// for secure communication. If the provided `message` has an incorrect length, it returns an @@ -304,11 +254,6 @@ impl Initiator { /// /// # Security /// - /// Without a responder authority public key (see [`Self::without_pk`]) only the certificate - /// version is checked; the certificate is otherwise accepted unverified, and `Ok` does not - /// mean the responder was authenticated. The returned [`NoiseEngine`] carries no indication - /// of which case applies. - /// /// On success the remaining handshake secrets, including the ephemeral keypair, are erased, /// so the [`Initiator`] cannot be used for another handshake. #[cfg(feature = "std")] @@ -400,15 +345,7 @@ impl Initiator { .0 .serialize(); let rs_pk_xonly = XOnlyPublicKey::from_slice(&rs_pub_key).unwrap(); - // Without an authority key there is nothing to verify the certificate against (see - // `without_pk`), and only its format version is checked. - let accepted = match &self.responder_authority_pk { - Some(authority_pk) => { - signature_message.verify_with_now(&rs_pk_xonly, authority_pk, now) - } - None => signature_message.version == crate::CERTIFICATE_VERSION, - }; - if accepted { + if signature_message.verify_with_now(&rs_pk_xonly, &self.responder_authority_pk, now) { let (mut temp_k1, mut temp_k2) = Self::hkdf_2(self.get_ck(), &[]); let c1 = ChaCha20Poly1305::new(Key::from_slice(&temp_k1[..])); let c2 = ChaCha20Poly1305::new(Key::from_slice(&temp_k2[..])); @@ -464,7 +401,7 @@ mod test { #[test] #[cfg_attr(miri, ignore)] fn initiator_step0_produces_elligator_message() { - let mut initiator = Initiator::without_pk().unwrap(); + let mut initiator = Initiator::new(crate::Responder::generate_key().public_key().into()); let msg = initiator.step_0().expect("step_0 must succeed"); @@ -476,7 +413,7 @@ mod test { #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] fn initiator_erase_zeroes_ck_and_h() { - let mut initiator = Initiator::without_pk().unwrap(); + let mut initiator = Initiator::new(crate::Responder::generate_key().public_key().into()); assert!(initiator.ck.iter().any(|b| *b != 0)); assert!(initiator.h.iter().any(|b| *b != 0)); @@ -494,7 +431,7 @@ mod test { let authority_kp = Responder::generate_key(); let mut responder = Responder::new(authority_kp, 60); - let mut initiator = Initiator::without_pk().unwrap(); + let mut initiator = Initiator::new(authority_kp.public_key().into()); let msg0 = initiator.step_0().unwrap(); let (mut msg1, _) = responder.step_1(msg0).unwrap(); @@ -514,7 +451,7 @@ mod test { let authority_kp = Responder::generate_key(); let mut responder = Responder::new(authority_kp, 60); - let mut initiator = Initiator::without_pk().unwrap(); + let mut initiator = Initiator::new(authority_kp.public_key().into()); let ephemeral_before = initiator.e.secret_key().secret_bytes(); let msg0 = initiator.step_0().unwrap(); diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index 4cc5bc9c3d..9549235ed9 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -33,12 +33,9 @@ //! //! ## Responder authentication //! -//! The responder is only authenticated when the [`Initiator`] is given the responder's authority -//! public key, which it uses to verify the certificate received during the handshake. An -//! [`Initiator`] built without one, through `Initiator::without_pk` or `Initiator::new` with -//! `None`, accepts any responder and yields an encrypted but unauthenticated session that the -//! crate does not distinguish from an authenticated one. Always pin the authority key for -//! connections that cross a network boundary. +//! Every [`Initiator`] pins the responder's authority public key and verifies the certificate +//! received during the handshake against it, as the Sv2 spec requires (section 4.5.3). The crate +//! offers no handshake that skips that step: a session is authenticated or not established. //! //! ## Authority key custody //! diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index de18cff197..21e57d895a 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -6,7 +6,7 @@ use crate::{handshake::HandshakeOp, initiator::Initiator, responder::Responder}; fn test_1() { let key_pair = Responder::generate_key(); - let mut initiator = Initiator::new(Some(key_pair.public_key().into())); + let mut initiator = Initiator::new(key_pair.public_key().into()); let mut responder = Responder::new(key_pair, 31449600); let first_message = initiator.step_0().unwrap(); let (second_message, mut responder_engine) = responder.step_1(first_message).unwrap(); @@ -25,7 +25,7 @@ fn test_1_with_rng() { let key_pair = Responder::generate_key_with_rng(&mut rand::thread_rng()); let mut initiator: Box = - Initiator::new_with_rng(Some(key_pair.public_key().into()), &mut rand::thread_rng()); + Initiator::new_with_rng(key_pair.public_key().into(), &mut rand::thread_rng()); let mut responder = Responder::new_with_rng(key_pair, 31449600, &mut rand::thread_rng()); let first_message = initiator.step_0().unwrap(); let now = std::time::SystemTime::now() @@ -48,6 +48,24 @@ fn test_1_with_rng() { assert!(message == "ciao".as_bytes().to_vec()); } +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn initiator_rejects_a_certificate_from_another_authority() { + use crate::Error; + + let authority = Responder::generate_key(); + let other_authority = Responder::generate_key(); + let mut initiator = Initiator::new(other_authority.public_key().into()); + let mut responder = Responder::new(authority, 60); + let first_message = initiator.step_0().unwrap(); + let (second_message, _) = responder.step_1(first_message).unwrap(); + assert!(matches!( + initiator.step_2(second_message), + Err(Error::InvalidCertificate(_)) + )); +} + #[test] #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] @@ -66,7 +84,7 @@ fn pre_issued_certificate_is_sent_verbatim() { ) }; let handshake = |certificate| { - let mut initiator = Initiator::new(Some(authority.public_key().into())); + let mut initiator = Initiator::new(authority.public_key().into()); let mut responder = Responder::from_certificate(server_static, certificate); let first_message = initiator.step_0().unwrap(); let (second_message, responder_engine) = responder.step_1(first_message).unwrap(); @@ -94,44 +112,3 @@ fn pre_issued_certificate_is_sent_verbatim() { Err(Error::InvalidCertificate(_)) )); } - -#[test] -#[cfg(feature = "std")] -#[cfg_attr(miri, ignore)] -fn unpinned_initiator_still_rejects_an_unsupported_certificate_version() { - use crate::{signature_message::SignatureNoiseMessage, Error, CERTIFICATE_VERSION}; - - let certificate = SignatureNoiseMessage { - version: CERTIFICATE_VERSION + 1, - valid_from: 0, - not_valid_after: u32::MAX, - signature: [0; 64], - }; - let mut initiator = Initiator::without_pk().unwrap(); - let mut responder = Responder::from_certificate(Responder::generate_key(), certificate); - let first_message = initiator.step_0().unwrap(); - let (second_message, _) = responder.step_1(first_message).unwrap(); - assert!(matches!( - initiator.step_2(second_message), - Err(Error::InvalidCertificate(_)) - )); -} - -#[test] -#[cfg(feature = "std")] -#[cfg_attr(miri, ignore)] -fn unpinned_initiator_accepts_an_unverified_certificate_of_the_supported_version() { - use crate::{signature_message::SignatureNoiseMessage, CERTIFICATE_VERSION}; - - let certificate = SignatureNoiseMessage { - version: CERTIFICATE_VERSION, - valid_from: 0, - not_valid_after: u32::MAX, - signature: [0; 64], - }; - let mut initiator = Initiator::without_pk().unwrap(); - let mut responder = Responder::from_certificate(Responder::generate_key(), certificate); - let first_message = initiator.step_0().unwrap(); - let (second_message, _) = responder.step_1(first_message).unwrap(); - assert!(initiator.step_2(second_message).is_ok()); -} From 9f8eddf994a337e764ff732c18755df8b69c7fd1 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 16 Nov 2026 10:40:07 -0300 Subject: [PATCH 6/9] refactor(noise_sv2)!: remove Responder::from_authority_kp `from_authority_kp` and `from_authority_kp_with_rng` built a keypair from raw bytes and called `new`. A caller holding raw bytes can build the `Keypair` itself, and a public key passed only to be compared with the one derived from the private key is not worth a constructor. The callers were tests, a bench and an example in codec_sv2, which now build the keypair and call `Responder::new`. That needs secp256k1 as a dev-dependency there. `Error::InvalidRawPrivateKey` is no longer returned by anything and is kept so the error enum does not change. BREAKING CHANGE: `Responder::from_authority_kp` and `Responder::from_authority_kp_with_rng` are removed. Use `Responder::new` or `Responder::new_with_rng` with a `secp256k1::Keypair`. --- Cargo.lock | 1 + sv2/codec-sv2/Cargo.toml | 1 + sv2/codec-sv2/benches/common.rs | 10 ++---- sv2/codec-sv2/examples/encrypted.rs | 20 ++++------- sv2/codec-sv2/src/test_utils.rs | 9 ++--- sv2/noise-sv2/src/lib.rs | 6 ++-- sv2/noise-sv2/src/responder.rs | 53 ++--------------------------- 7 files changed, 19 insertions(+), 81 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fc04f1f662..58b303b440 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -297,6 +297,7 @@ dependencies = [ "quickcheck_macros", "rand", "rayon-core", + "secp256k1 0.28.2", ] [[package]] diff --git a/sv2/codec-sv2/Cargo.toml b/sv2/codec-sv2/Cargo.toml index 612b4353b7..e36f1b576d 100644 --- a/sv2/codec-sv2/Cargo.toml +++ b/sv2/codec-sv2/Cargo.toml @@ -20,6 +20,7 @@ rand = { workspace = true, default-features = false } [dev-dependencies] key-utils = { workspace = true } +secp256k1 = { workspace = true } criterion = { workspace = true } rayon-core = { workspace = true } quickcheck = { workspace = true } diff --git a/sv2/codec-sv2/benches/common.rs b/sv2/codec-sv2/benches/common.rs index 8c0baa2d36..283588906d 100644 --- a/sv2/codec-sv2/benches/common.rs +++ b/sv2/codec-sv2/benches/common.rs @@ -57,19 +57,15 @@ mod noise { const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; - const CERT_VALIDITY: core::time::Duration = core::time::Duration::from_secs(3600); + const CERT_VALIDITY: u32 = 3600; pub fn make_handshake_pair() -> (Handshake, Handshake) { let public_k: Secp256k1PublicKey = AUTHORITY_PUBLIC_K.to_string().try_into().unwrap(); let private_k: Secp256k1SecretKey = AUTHORITY_PRIVATE_K.to_string().try_into().unwrap(); let initiator = Initiator::from_raw_k(public_k.into_bytes()).unwrap(); - let responder = Responder::from_authority_kp( - &public_k.into_bytes(), - &private_k.into_bytes(), - CERT_VALIDITY, - ) - .unwrap(); + let authority = private_k.0.keypair(&secp256k1::Secp256k1::signing_only()); + let responder = Responder::new(authority, CERT_VALIDITY); ( Handshake::initiator(initiator), diff --git a/sv2/codec-sv2/examples/encrypted.rs b/sv2/codec-sv2/examples/encrypted.rs index 5dc1064b6a..c93365da61 100644 --- a/sv2/codec-sv2/examples/encrypted.rs +++ b/sv2/codec-sv2/examples/encrypted.rs @@ -49,7 +49,7 @@ const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu #[cfg(feature = "noise_sv2")] const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; #[cfg(feature = "noise_sv2")] -const CERT_VALIDITY: std::time::Duration = std::time::Duration::from_secs(3600); +const CERT_VALIDITY: u32 = 3600; // Example message type. // In practice, all Sv2 messages are defined in the following crates: @@ -97,21 +97,13 @@ fn main() { Initiator::from_raw_k_with_rng(authority_public_k.into_bytes(), &mut rand::thread_rng()) .expect("Failed to create initiator role from raw pub key"); + let authority = authority_private_k + .0 + .keypair(&secp256k1::Secp256k1::signing_only()); #[cfg(feature = "std")] - let responder = Responder::from_authority_kp( - &authority_public_k.into_bytes(), - &authority_private_k.into_bytes(), - CERT_VALIDITY, - ) - .expect("Failed to initialize responder from pub/key pair and/or cert"); + let responder = Responder::new(authority, CERT_VALIDITY); #[cfg(not(feature = "std"))] - let responder = Responder::from_authority_kp_with_rng( - &authority_public_k.into_bytes(), - &authority_private_k.into_bytes(), - CERT_VALIDITY, - &mut rand::thread_rng(), - ) - .expect("Failed to initialize responder from pub/key pair and/or cert"); + let responder = Responder::new_with_rng(authority, CERT_VALIDITY, &mut rand::thread_rng()); let sender = Handshake::initiator(initiator); let receiver = Handshake::responder(responder); diff --git a/sv2/codec-sv2/src/test_utils.rs b/sv2/codec-sv2/src/test_utils.rs index ff34d85bb8..58137484ae 100644 --- a/sv2/codec-sv2/src/test_utils.rs +++ b/sv2/codec-sv2/src/test_utils.rs @@ -9,7 +9,6 @@ use crate::{ Buffer, SerializedFrame, TransportDecryptState, TransportEncryptState, }; use buffer_sv2::Buffer as IsBuffer; -use core::time::Duration; use key_utils::{Secp256k1PublicKey, Secp256k1SecretKey}; use noise_sv2::{ Initiator, Responder, ELLSWIFT_ENCODING_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE, @@ -17,7 +16,7 @@ use noise_sv2::{ pub(crate) const AUTHORITY_PUBLIC_K: &str = "9auqWEzQDVyd2oe1JVGFLMLHZtCo2FFqZwtKA5gd9xbuEu7PH72"; pub(crate) const AUTHORITY_PRIVATE_K: &str = "mkDLTBBRxdBv998612qipDYoTK3YUrqLe8uWw7gu3iXbSrn2n"; -pub(crate) const CERT_VALIDITY: Duration = Duration::from_secs(3600); +pub(crate) const CERT_VALIDITY: u32 = 3600; pub(crate) type Slice = ::Slice; @@ -26,13 +25,11 @@ pub(crate) fn make_handshake_pair() -> (Handshake, Handshake Result, Error> { - Self::from_authority_kp_with_rng(public, private, cert_validity, &mut rand::thread_rng()) - } - - /// Creates a new [`Responder`] instance with the provided 32-byte authority key pair and a - /// custom random number generator. - /// - /// See [`Self::from_authority_kp`] for more details. - /// - /// The custom random number generator should be provided in order to not implicitely rely on - /// `std` and allow `no_std` environments to provide a hardware random number generator for - /// example. - #[inline] - pub fn from_authority_kp_with_rng( - public: &[u8; 32], - private: &[u8; 32], - cert_validity: Duration, - rng: &mut R, - ) -> Result, Error> { - let secp = Secp256k1::new(); - let secret = SecretKey::from_slice(private).map_err(|_| Error::InvalidRawPrivateKey)?; - let kp = Keypair::from_secret_key(&secp, &secret); - let pub_ = kp.x_only_public_key().0.serialize(); - if public == &pub_[..] { - Ok(Self::new_with_rng(kp, cert_validity.as_secs() as u32, rng)) - } else { - Err(Error::InvalidRawPublicKey) - } - } - /// Processes the first step of the Noise NX protocol handshake for the responder. /// /// This function manages the responder's side of the handshake after receiving the initiator's @@ -513,6 +463,7 @@ mod test { fn make_responder() -> Responder { use rand::{rngs::StdRng, SeedableRng}; + use secp256k1::Secp256k1; let secp = Secp256k1::new(); let mut rng = StdRng::seed_from_u64(42); From 25331814a178c50403763ef6c0c9d13e76fc45e0 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 16 Nov 2026 10:41:33 -0300 Subject: [PATCH 7/9] refactor(noise_sv2,codec_sv2)!: sign the Responder's certificate at construction Both ways of building a `Responder` end with the same two things: a static key and a certificate over it. `Responder::new` now signs that certificate right away and stores it, the same as `from_certificate` does with one issued in advance, so the `Responder` no longer carries the authority keypair until `step_1` and the private `CertificateSource` enum is gone. `step_1` needed the current time and a random number generator only for that signature, so `step_1_with_now_rng` is removed, here and on `codec_sv2::Handshake`, and `step_1` is available without `std`. The time moves to the constructor: `new_with_rng` becomes `new_with_now_rng`. A `Responder` serves one handshake, so the certificate still covers one connection. Its validity window now starts when the `Responder` is built instead of when the initiator's first message arrives, and the signature is computed whether or not that message ever comes. In the noise_sv2 benches, `step_1_responder` no longer includes the signature, and `handshake` builds the `Responder` inside the measured closure so that it still does. BREAKING CHANGE: `Responder::step_1_with_now_rng` and `Handshake::::step_1_with_now_rng` are removed; call `step_1`. `Responder::new_with_rng` is replaced by `Responder::new_with_now_rng`, which takes the current time. --- sv2/codec-sv2/examples/encrypted.rs | 18 +-- sv2/codec-sv2/src/state.rs | 24 +--- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/benches/handshake.rs | 20 +-- sv2/noise-sv2/examples/handshake.rs | 18 +-- sv2/noise-sv2/src/lib.rs | 4 +- sv2/noise-sv2/src/responder.rs | 204 ++++++++++------------------ sv2/noise-sv2/src/test.rs | 9 +- 8 files changed, 102 insertions(+), 197 deletions(-) diff --git a/sv2/codec-sv2/examples/encrypted.rs b/sv2/codec-sv2/examples/encrypted.rs index c93365da61..f3b6c138df 100644 --- a/sv2/codec-sv2/examples/encrypted.rs +++ b/sv2/codec-sv2/examples/encrypted.rs @@ -103,7 +103,13 @@ fn main() { #[cfg(feature = "std")] let responder = Responder::new(authority, CERT_VALIDITY); #[cfg(not(feature = "std"))] - let responder = Responder::new_with_rng(authority, CERT_VALIDITY, &mut rand::thread_rng()); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as u32; + #[cfg(not(feature = "std"))] + let responder = + Responder::new_with_now_rng(authority, CERT_VALIDITY, now, &mut rand::thread_rng()); let sender = Handshake::initiator(initiator); let receiver = Handshake::responder(responder); @@ -116,19 +122,9 @@ fn main() { .try_into() .expect("Handshake remote invlaid message"); - #[cfg(feature = "std")] let (second_message, receiver_transport) = receiver .step_1(first_message) .expect("Responder failed second step of handshake"); - #[cfg(not(feature = "std"))] - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs() as u32; - #[cfg(not(feature = "std"))] - let (second_message, receiver_transport) = receiver - .step_1_with_now_rng(first_message, now, &mut rand::thread_rng()) - .expect("Responder failed second step of handshake"); let second_message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE] = second_message .payload() .try_into() diff --git a/sv2/codec-sv2/src/state.rs b/sv2/codec-sv2/src/state.rs index 28df19eb8e..c8e6cedf65 100644 --- a/sv2/codec-sv2/src/state.rs +++ b/sv2/codec-sv2/src/state.rs @@ -74,13 +74,10 @@ pub struct InitiatorSent(Initiator); /// use noise_sv2::{Responder, ELLSWIFT_ENCODING_SIZE}; /// /// fn responder() -> Handshake { unimplemented!() } -/// fn rng() -> rand::rngs::ThreadRng { unimplemented!() } /// /// let responder = responder(); -/// let (_first, _transport) = responder -/// .step_1_with_now_rng([0; ELLSWIFT_ENCODING_SIZE], 0, &mut rng()) -/// .unwrap(); -/// let _second = responder.step_1_with_now_rng([0; ELLSWIFT_ENCODING_SIZE], 0, &mut rng()); +/// let (_first, _transport) = responder.step_1([0; ELLSWIFT_ENCODING_SIZE]).unwrap(); +/// let _second = responder.step_1([0; ELLSWIFT_ENCODING_SIZE]); /// ``` /// /// Nor does sending the first message twice, which would mix it into the transcript twice and @@ -174,7 +171,6 @@ impl Handshake { /// Answers the initiator's public key, completing the handshake on this side and consuming /// the state. The returned frame is what the initiator needs for its [`Handshake::step_2`]. - #[cfg(feature = "std")] pub fn step_1( mut self, re_pub: [u8; ELLSWIFT_ENCODING_SIZE], @@ -185,22 +181,6 @@ impl Handshake { Transport::new(engine), )) } - - /// [`Self::step_1`] given the current time and a random number generator, for `no_std` - /// environments that have their own of each. - #[inline] - pub fn step_1_with_now_rng( - mut self, - re_pub: [u8; ELLSWIFT_ENCODING_SIZE], - now: u32, - rng: &mut G, - ) -> Result<(HandshakeMessage, Transport)> { - let (message, engine) = self.role.step_1_with_now_rng(re_pub, now, rng)?; - Ok(( - HandshakeMessage::from_message(message), - Transport::new(engine), - )) - } } /// The codec state once the handshake is complete, where AEAD encryption and decryption are diff --git a/sv2/noise-sv2/README.md b/sv2/noise-sv2/README.md index 56181bfd51..5089ec6745 100644 --- a/sv2/noise-sv2/README.md +++ b/sv2/noise-sv2/README.md @@ -10,7 +10,7 @@ `noise_sv2` is primarily intended to secure communication in the Stratum V2 (Sv2) protocol. It handles the necessary Noise handshakes, encrypts outgoing messages, and decrypts incoming responses, ensuring privacy and integrity across the communication link between Sv2 roles. See the [Protocol Security specification](https://github.com/stratum-mining/sv2-spec/blob/main/04-Protocol-Security.md) for more details. ## Key Capabilities -* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. Every `Initiator` pins the responder's authority public key and rejects a certificate that does not verify against it. A server built with `Responder::new` signs its certificate on every handshake, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it. +* **Secure Communication**: Provides encryption and authentication for messages exchanged between different Sv2 roles. Every `Initiator` pins the responder's authority public key and rejects a certificate that does not verify against it. A server that uses `Responder::new` signs a certificate for every connection it accepts, so the authority private key has to be on that server; this is for development and testing. In production, sign the certificate on a machine that holds the authority private key, and give the server only its static key and that certificate through `Responder::from_certificate`. `SignatureNoiseMessage` is that certificate's format, for whatever issues it. * **Cipher Support**: Uses `ChaCha20-Poly1305` for authenticated encryption. * **Handshake Roles**: Implements the `Initiator` and `Responder` roles required by the Noise handshake, allowing both sides of a connection to establish secure communication. * **Cryptographic Helpers**: Facilitates the management of cryptographic state and encryption operations. diff --git a/sv2/noise-sv2/benches/handshake.rs b/sv2/noise-sv2/benches/handshake.rs index e5955331f1..6fde307cc0 100644 --- a/sv2/noise-sv2/benches/handshake.rs +++ b/sv2/noise-sv2/benches/handshake.rs @@ -23,13 +23,13 @@ fn bench_nx_handshake(c: &mut Criterion) { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); let mut initiator = Initiator::new(responder_key.public_key().into()); - let responder = Responder::new(responder_key, 60); + let responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); let msg_0 = initiator.step_0().unwrap(); - (responder, msg_0, rng) + (responder, msg_0) }, - |(mut responder, msg_0, mut rng)| { - let _ = responder.step_1_with_now_rng(msg_0, 10, &mut rng).unwrap(); + |(mut responder, msg_0)| { + let _ = responder.step_1(msg_0).unwrap(); }, BatchSize::SmallInput, ); @@ -41,10 +41,10 @@ fn bench_nx_handshake(c: &mut Criterion) { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); let mut initiator = Initiator::new(responder_key.public_key().into()); - let mut responder = Responder::new(responder_key, 60); + let mut responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); let msg_0 = initiator.step_0().unwrap(); - let (msg_2, _) = responder.step_1_with_now_rng(msg_0, 10, &mut rng).unwrap(); + let (msg_2, _) = responder.step_1(msg_0).unwrap(); (initiator, msg_2) }, @@ -61,12 +61,12 @@ fn bench_nx_handshake(c: &mut Criterion) { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); let initiator = Initiator::new(responder_key.public_key().into()); - let responder = Responder::new(responder_key, 60); - (initiator, responder, rng) + (initiator, responder_key, rng) }, - |(mut initiator, mut responder, mut rng)| { + |(mut initiator, responder_key, mut rng)| { + let mut responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); let msg_0 = initiator.step_0().unwrap(); - let (msg_2, _) = responder.step_1_with_now_rng(msg_0, 10, &mut rng).unwrap(); + let (msg_2, _) = responder.step_1(msg_0).unwrap(); let _ = initiator.step_2_with_now(msg_2, 10).unwrap(); }, BatchSize::SmallInput, diff --git a/sv2/noise-sv2/examples/handshake.rs b/sv2/noise-sv2/examples/handshake.rs index f405b33bb4..de97fb21f9 100644 --- a/sv2/noise-sv2/examples/handshake.rs +++ b/sv2/noise-sv2/examples/handshake.rs @@ -51,9 +51,15 @@ fn main() { #[cfg(feature = "std")] let mut responder = Responder::new(responder_key_pair, RESPONDER_CERT_VALIDITY); #[cfg(not(feature = "std"))] - let mut responder = Responder::new_with_rng( + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as u32; + #[cfg(not(feature = "std"))] + let mut responder = Responder::new_with_now_rng( responder_key_pair, RESPONDER_CERT_VALIDITY, + now, &mut rand::thread_rng(), ); @@ -61,19 +67,9 @@ fn main() { .step_0() .expect("Initiator failed first step of handshake"); - #[cfg(feature = "std")] let (second_message, mut responder_state) = responder .step_1(first_message) .expect("Responder failed second step of handshake"); - #[cfg(not(feature = "std"))] - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs() as u32; - #[cfg(not(feature = "std"))] - let (second_message, mut responder_state) = responder - .step_1_with_now_rng(first_message, now, &mut rand::thread_rng()) - .expect("Responder failed second step of handshake"); #[cfg(feature = "std")] let mut initiator_state = initiator diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index 0ccbb20fc2..c9afa6cb05 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -43,8 +43,8 @@ //! so a leaked authority private key impersonates the operator for as long as any client trusts it. //! [`Responder::from_certificate`] lets an internet-facing server hold only its static key and a //! certificate over it, signed where the authority private key is kept. [`Responder::new`] -//! instead signs a certificate on every handshake and needs the authority private key on the -//! server; it is meant for development and testing. +//! instead signs a certificate for every [`Responder`] it builds and needs the authority private +//! key on the server; it is meant for development and testing. //! //! [`SignatureNoiseMessage`] is the certificate itself: the issuer signs a validity window over the //! server's static key with [`SignatureNoiseMessage::sign_with_rng`] and hands the result to the diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index 81a500bbab..fe1b8b1e3c 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -79,25 +79,11 @@ pub struct Responder { // shared secret with the initiator. e: Keypair, // Static key pair of the responder, the one its certificate covers: supplied by the caller - // together with that certificate, or generated for this one handshake and signed on the spot. + // together with that certificate, or generated for this one handshake and certified at + // construction. s: Keypair, - // Where the `SIGNATURE_NOISE_MESSAGE` sent in the second handshake message comes from. - certificate: CertificateSource, -} - -// The `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2) a [`Responder`] sends is either signed on the spot -// or supplied by the caller, already issued. -enum CertificateSource { - // Sign a fresh certificate over the static key at handshake time, valid from the handshake's - // `now` for `cert_validity` seconds. Needs the authority private key on the host; see the - // security note on [`Responder::new`]. - SignAtHandshake { - authority: Keypair, - cert_validity: u32, - }, - // Send this certificate verbatim; it was issued where the authority private key is kept. See - // [`Responder::from_certificate`]. - PreIssued(SignatureNoiseMessage), + // The `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2) sent in the second handshake message. + certificate: SignatureNoiseMessage, } impl core::fmt::Debug for Responder { @@ -163,46 +149,56 @@ impl Responder { /// /// Constructs a new [`Responder`] with the necessary cryptographic state for the Noise NX /// protocol handshake. It generates ephemeral and static key pairs for the responder and - /// prepares the handshake state. The authority keypair and certificate validity period are - /// also configured. + /// prepares the handshake state. The certificate over the static key is signed here with the + /// authority keypair, valid from now for `cert_validity` seconds, and sent in + /// [`Self::step_1`]. The [`Responder`] does not keep the authority keypair; the caller's + /// copy is the caller's to erase. /// /// # Security /// - /// A responder built here signs a fresh certificate in [`Self::step_1`], so the host running - /// it holds the authority private key in memory and, in practice, in its configuration. - /// The authority public key is what clients pin (spec 4.5.3, 4.7), and neither the spec nor - /// this crate defines revocation, so a compromise of that host leaks a key that impersonates - /// the operator to every client for as long as any of them keeps trusting it. The static key - /// is generated here and discarded with the [`Responder`], so it cannot be certified in - /// advance, and the certificate lifetime is whatever `cert_validity` says on the same host. - /// Use it for development and testing. A server outside those should hold only a static key - /// and a certificate issued where the authority private key is kept: see - /// [`Self::from_certificate`]. + /// A host that calls this for every connection holds the authority private key in memory + /// and, in practice, in its configuration. The authority public key is what clients pin (spec + /// 4.5.3, 4.7), and neither the spec nor this crate defines revocation, so a compromise of + /// that host leaks a key that impersonates the operator to every client for as long as any of + /// them keeps trusting it. The static key is generated here and discarded with the + /// [`Responder`], so it cannot be certified in advance, and the certificate lifetime is + /// whatever `cert_validity` says on the same host. Use it for development and testing. A + /// server outside those should hold only a static key and a certificate issued where the + /// authority private key is kept: see [`Self::from_certificate`]. #[cfg(feature = "std")] pub fn new(authority_key: Keypair, cert_validity: u32) -> Box { - Self::new_with_rng(authority_key, cert_validity, &mut rand::thread_rng()) + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() as u32; + Self::new_with_now_rng(authority_key, cert_validity, now, &mut rand::thread_rng()) } /// Creates a new [`Responder`] instance with the provided authority keypair, certificate - /// validity, and a custom random number generator. + /// validity, the current time and a custom random number generator. /// /// See [`Self::new`] for more details. /// - /// The custom random number generator should be provided in order to not implicitely rely on - /// `std` and allow `no_std` environments to provide a hardware random number generator for - /// example. + /// The current time and the custom random number generator should be provided in order to not + /// implicitely rely on `std` and allow `no_std` environments to provide a hardware random + /// number generator for example. #[inline] - pub fn new_with_rng( - authority_key: Keypair, + pub fn new_with_now_rng( + mut authority_key: Keypair, cert_validity: u32, + now: u32, rng: &mut R, ) -> Box { let s = Self::generate_key_with_rng(rng); - let certificate = CertificateSource::SignAtHandshake { - authority: authority_key, - cert_validity, - }; - Self::build(s, certificate, rng) + let certificate = SignatureNoiseMessage::sign_with_rng( + now, + now.saturating_add(cert_validity), + &s.x_only_public_key().0, + &authority_key, + &mut &mut *rng, + ); + authority_key.non_secure_erase(); + Self::from_certificate_with_rng(s, certificate, rng) } /// Creates a new [`Responder`] from its static keypair `s` and a certificate issued for it in @@ -239,16 +235,6 @@ impl Responder { s: Keypair, certificate: SignatureNoiseMessage, rng: &mut R, - ) -> Box { - Self::build(s, CertificateSource::PreIssued(certificate), rng) - } - - // Assembles a [`Responder`] around its static key and certificate source, generating the - // ephemeral keypair and initializing the handshake state. - fn build( - s: Keypair, - certificate: CertificateSource, - rng: &mut R, ) -> Box { let mut self_ = Self { handshake_cipher: None, @@ -271,9 +257,8 @@ impl Responder { /// the necessary shared secrets, and constructs the response message. The response includes /// the responder's ephemeral public key (in its ElligatorSwift-encoded form), the encrypted /// static public key, and the encrypted `SIGNATURE_NOISE_MESSAGE`: the certificate given to - /// [`Self::from_certificate`] verbatim, or one signed now by the authority keypair given to - /// [`Self::new`]. Additionally, it establishes the session ciphers for encrypting and - /// decrypting further communication. + /// [`Self::from_certificate`], or the one [`Self::new`] signed. Additionally, it establishes + /// the session ciphers for encrypting and decrypting further communication. /// /// On success, it returns a tuple containing the response message to be sent back to the /// initiator and a [`NoiseEngine`] instance, which is configured with the session ciphers for @@ -282,40 +267,11 @@ impl Responder { /// On failure, the method returns an error if there is an issue during encryption, decryption, /// or any other step of the handshake process. /// - /// On success the remaining handshake secrets, including the ephemeral and static keypairs - /// and the authority keypair if there is one, are erased, so the [`Responder`] cannot be used - /// for another handshake. - #[cfg(feature = "std")] + /// On success the remaining handshake secrets, including the ephemeral and static keypairs, + /// are erased, so the [`Responder`] cannot be used for another handshake. pub fn step_1( &mut self, elligatorswift_theirs_ephemeral_serialized: [u8; ELLSWIFT_ENCODING_SIZE], - ) -> Result<([u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], NoiseEngine), AeadError> { - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_secs() as u32; - - self.step_1_with_now_rng( - elligatorswift_theirs_ephemeral_serialized, - now, - &mut rand::thread_rng(), - ) - } - - /// Executes the first step of the Noise NX protocol handshake for the responder given - /// the current time and a custom random number generator. - /// - /// See [`Self::step_1`] for more details. - /// - /// The current time and the custom random number generatorshould be provided in order to not - /// implicitely rely on `std` and allow `no_std` environments to provide a hardware random - /// number generator for example. - #[inline] - pub fn step_1_with_now_rng( - &mut self, - elligatorswift_theirs_ephemeral_serialized: [u8; ELLSWIFT_ENCODING_SIZE], - now: u32, - rng: &mut R, ) -> Result<([u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], NoiseEngine), AeadError> { // 4.5.1.2 Responder Self::mix_hash(self, &elligatorswift_theirs_ephemeral_serialized[..]); @@ -377,20 +333,7 @@ impl Responder { ecdh_static.zeroize(); // 7. appends `EncryptAndHash(SIGNATURE_NOISE_MESSAGE)` to the buffer - let signature_noise_message: [u8; SIGNATURE_NOISE_MESSAGE_SIZE] = match &self.certificate { - CertificateSource::SignAtHandshake { - authority, - cert_validity, - } => SignatureNoiseMessage::sign_with_rng( - now, - now.saturating_add(*cert_validity), - &self.s.x_only_public_key().0, - authority, - rng, - ), - CertificateSource::PreIssued(certificate) => *certificate, - } - .into(); + let signature_noise_message: [u8; SIGNATURE_NOISE_MESSAGE_SIZE] = self.certificate.into(); let mut signature_part = Vec::with_capacity(ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE); signature_part.extend_from_slice(&signature_noise_message[..]); Self::encrypt_and_hash(self, &mut signature_part)?; @@ -427,10 +370,9 @@ impl Responder { // Securely erases sensitive data in the responder's memory. // // Zeroizes the handshake key (`k`), the chaining key (`ck`) and the handshake - // hash (`h`), and non-securely erases the ephemeral and static keypairs, plus the authority - // keypair when the responder signs at handshake time. A pre-issued certificate is not secret - // and is left in place. This function is typically called when the [`Responder`] instance is - // no longer needed or before deallocation. + // hash (`h`), and non-securely erases the ephemeral and static keypairs. The certificate is + // not secret and is left in place. This function is typically called when the [`Responder`] + // instance is no longer needed or before deallocation. // // It does not touch `handshake_cipher`: that key is wiped by [`ChaCha20Poly1305`]'s own // zeroize-on-drop. Nor does it reach the transport session ciphers, which by then live in the @@ -442,9 +384,6 @@ impl Responder { self.h.zeroize(); self.e.non_secure_erase(); self.s.non_secure_erase(); - if let CertificateSource::SignAtHandshake { authority, .. } = &mut self.certificate { - authority.non_secure_erase(); - } } } @@ -469,31 +408,44 @@ mod test { let mut rng = StdRng::seed_from_u64(42); let authority = Keypair::new(&secp, &mut rng); - *Responder::new_with_rng(authority, 60, &mut rng) + *Responder::new_with_now_rng(authority, 60, 100, &mut rng) } #[test] - #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] - fn responder_step_1_returns_valid_message_and_engine() { + fn new_certifies_the_static_key_from_the_given_time() { use rand::{rngs::StdRng, SeedableRng}; + use secp256k1::Secp256k1; + + let mut rng = StdRng::seed_from_u64(7); + let authority = Keypair::new(&Secp256k1::new(), &mut rng); + let responder = Responder::new_with_now_rng(authority, 60, 100, &mut rng); + + assert_eq!(responder.certificate.valid_from, 100); + assert_eq!(responder.certificate.not_valid_after, 160); + assert!(responder.certificate.verify_with_now( + &responder.s.x_only_public_key().0, + &authority.x_only_public_key().0, + 100, + )); + } + + #[test] + #[cfg_attr(miri, ignore)] + fn responder_step_1_returns_valid_message_and_engine() { use secp256k1::ellswift::ElligatorSwift; - let mut rng = StdRng::seed_from_u64(1); let mut responder = make_responder(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); - let (msg, _) = responder - .step_1_with_now_rng(fake_initiator_ephemeral, 100, &mut rng) - .unwrap(); + let (msg, _) = responder.step_1(fake_initiator_ephemeral).unwrap(); assert_eq!(msg.len(), INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE); } #[test] - #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] fn responder_erase_zeroes_ck_and_h() { let mut responder = make_responder(); @@ -507,21 +459,16 @@ mod test { } #[test] - #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] fn responder_cipher_detects_tampering() { - use rand::{rngs::StdRng, SeedableRng}; use secp256k1::ellswift::ElligatorSwift; - let mut rng = StdRng::seed_from_u64(2); let mut responder = make_responder(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); - let (_msg, mut engine) = responder - .step_1_with_now_rng(fake_initiator_ephemeral, 100, &mut rng) - .unwrap(); + let (_msg, mut engine) = responder.step_1(fake_initiator_ephemeral).unwrap(); let mut data = vec![10, 20, 30]; engine.encrypt(&mut data).unwrap(); @@ -532,30 +479,17 @@ mod test { } #[test] - #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] fn responder_step_1_erases_handshake_secrets() { - use rand::{rngs::StdRng, SeedableRng}; use secp256k1::ellswift::ElligatorSwift; - let mut rng = StdRng::seed_from_u64(3); let mut responder = make_responder(); - let authority_secret = |responder: &Responder| match &responder.certificate { - CertificateSource::SignAtHandshake { authority, .. } => { - authority.secret_key().secret_bytes() - } - CertificateSource::PreIssued(_) => panic!("make_responder signs at handshake time"), - }; - let authority_before = authority_secret(&responder); let static_before = responder.s.secret_key().secret_bytes(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); - let _ = responder - .step_1_with_now_rng(fake_initiator_ephemeral, 100, &mut rng) - .unwrap(); + let _ = responder.step_1(fake_initiator_ephemeral).unwrap(); - assert_ne!(authority_secret(&responder), authority_before); assert_ne!(responder.s.secret_key().secret_bytes(), static_before); assert_eq!(responder.ck, [0u8; 32]); assert_eq!(responder.h, [0u8; 32]); diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index 21e57d895a..643b1f102a 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -26,15 +26,14 @@ fn test_1_with_rng() { let mut initiator: Box = Initiator::new_with_rng(key_pair.public_key().into(), &mut rand::thread_rng()); - let mut responder = Responder::new_with_rng(key_pair, 31449600, &mut rand::thread_rng()); - let first_message = initiator.step_0().unwrap(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as u32; - let (second_message, mut responder_engine) = responder - .step_1_with_now_rng(first_message, now, &mut rand::thread_rng()) - .unwrap(); + let mut responder = + Responder::new_with_now_rng(key_pair, 31449600, now, &mut rand::thread_rng()); + let first_message = initiator.step_0().unwrap(); + let (second_message, mut responder_engine) = responder.step_1(first_message).unwrap(); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() From 477fd7eeba75de104ffb5042dcf9822e18bce5d1 Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 16 Nov 2026 12:41:52 -0300 Subject: [PATCH 8/9] refactor(noise_sv2)!: consume the Responder in step_1 step_1 took `&mut self` and erased the handshake secrets only on success, leaving a Responder that could be passed around but not used. It now takes `self: Box`, so a second call does not compile and the secrets are erased by `Drop` on every path, including a failed step. The receiver is the `Box` the constructors return rather than a plain `self`: moving the struct out of the box would copy the secrets to the stack and free the heap allocation without wiping it. The test that inspected the Responder after step_1 is replaced by one that drops a Responder in place and checks the secrets are gone. BREAKING CHANGE: `Responder::step_1` takes `self: Box` instead of `&mut self`. --- ...oise_handshake_and_roundtrip_encryption.rs | 2 +- sv2/codec-sv2/src/state.rs | 2 +- sv2/noise-sv2/benches/handshake.rs | 6 +-- sv2/noise-sv2/benches/roundtrip.rs | 2 +- sv2/noise-sv2/examples/handshake.rs | 2 +- sv2/noise-sv2/src/initiator.rs | 4 +- sv2/noise-sv2/src/responder.rs | 46 +++++++++---------- sv2/noise-sv2/src/test.rs | 9 ++-- 8 files changed, 35 insertions(+), 38 deletions(-) diff --git a/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs b/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs index f75c9adcac..fa9466dcbf 100644 --- a/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs +++ b/fuzz/fuzz_targets/fuzz_noise_handshake_and_roundtrip_encryption.rs @@ -96,7 +96,7 @@ fuzz_target!(|input: FuzzInput| { let mut initiator = Initiator::new(known_peer); // Create responder (server) with the generated keypair and certificate validity - let mut responder = Responder::new(responder_kp, input.cert_validity); + let responder = Responder::new(responder_kp, input.cert_validity); // ========== Handshake Phase ========== diff --git a/sv2/codec-sv2/src/state.rs b/sv2/codec-sv2/src/state.rs index c8e6cedf65..f77abca087 100644 --- a/sv2/codec-sv2/src/state.rs +++ b/sv2/codec-sv2/src/state.rs @@ -172,7 +172,7 @@ impl Handshake { /// Answers the initiator's public key, completing the handshake on this side and consuming /// the state. The returned frame is what the initiator needs for its [`Handshake::step_2`]. pub fn step_1( - mut self, + self, re_pub: [u8; ELLSWIFT_ENCODING_SIZE], ) -> Result<(HandshakeMessage, Transport)> { let (message, engine) = self.role.step_1(re_pub)?; diff --git a/sv2/noise-sv2/benches/handshake.rs b/sv2/noise-sv2/benches/handshake.rs index 6fde307cc0..e96f8a3e9d 100644 --- a/sv2/noise-sv2/benches/handshake.rs +++ b/sv2/noise-sv2/benches/handshake.rs @@ -28,7 +28,7 @@ fn bench_nx_handshake(c: &mut Criterion) { let msg_0 = initiator.step_0().unwrap(); (responder, msg_0) }, - |(mut responder, msg_0)| { + |(responder, msg_0)| { let _ = responder.step_1(msg_0).unwrap(); }, BatchSize::SmallInput, @@ -41,7 +41,7 @@ fn bench_nx_handshake(c: &mut Criterion) { let mut rng = rng(); let responder_key = generate_key_with_rng(&mut rng); let mut initiator = Initiator::new(responder_key.public_key().into()); - let mut responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); + let responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); let msg_0 = initiator.step_0().unwrap(); let (msg_2, _) = responder.step_1(msg_0).unwrap(); @@ -64,7 +64,7 @@ fn bench_nx_handshake(c: &mut Criterion) { (initiator, responder_key, rng) }, |(mut initiator, responder_key, mut rng)| { - let mut responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); + let responder = Responder::new_with_now_rng(responder_key, 60, 10, &mut rng); let msg_0 = initiator.step_0().unwrap(); let (msg_2, _) = responder.step_1(msg_0).unwrap(); let _ = initiator.step_2_with_now(msg_2, 10).unwrap(); diff --git a/sv2/noise-sv2/benches/roundtrip.rs b/sv2/noise-sv2/benches/roundtrip.rs index ce50bc4a06..8961d63fff 100644 --- a/sv2/noise-sv2/benches/roundtrip.rs +++ b/sv2/noise-sv2/benches/roundtrip.rs @@ -7,7 +7,7 @@ mod common; fn bench_encryption_roundtrip(c: &mut Criterion) { let responder_key = generate_key_with_rng(&mut rng()); let mut initiator = Initiator::new(responder_key.public_key().into()); - let mut responder = Responder::new(responder_key, 10); + let responder = Responder::new(responder_key, 10); let msg_0 = initiator.step_0().unwrap(); let (msg_2, mut responder_transport) = responder.step_1(msg_0).unwrap(); diff --git a/sv2/noise-sv2/examples/handshake.rs b/sv2/noise-sv2/examples/handshake.rs index de97fb21f9..cf73c65cfc 100644 --- a/sv2/noise-sv2/examples/handshake.rs +++ b/sv2/noise-sv2/examples/handshake.rs @@ -49,7 +49,7 @@ fn main() { &mut rand::thread_rng(), ); #[cfg(feature = "std")] - let mut responder = Responder::new(responder_key_pair, RESPONDER_CERT_VALIDITY); + let responder = Responder::new(responder_key_pair, RESPONDER_CERT_VALIDITY); #[cfg(not(feature = "std"))] let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) diff --git a/sv2/noise-sv2/src/initiator.rs b/sv2/noise-sv2/src/initiator.rs index 0b45f53219..099f2baf13 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -430,7 +430,7 @@ mod test { use crate::Responder; let authority_kp = Responder::generate_key(); - let mut responder = Responder::new(authority_kp, 60); + let responder = Responder::new(authority_kp, 60); let mut initiator = Initiator::new(authority_kp.public_key().into()); let msg0 = initiator.step_0().unwrap(); @@ -450,7 +450,7 @@ mod test { use crate::Responder; let authority_kp = Responder::generate_key(); - let mut responder = Responder::new(authority_kp, 60); + let responder = Responder::new(authority_kp, 60); let mut initiator = Initiator::new(authority_kp.public_key().into()); let ephemeral_before = initiator.e.secret_key().secret_bytes(); diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index fe1b8b1e3c..920fe24027 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -267,15 +267,17 @@ impl Responder { /// On failure, the method returns an error if there is an issue during encryption, decryption, /// or any other step of the handshake process. /// - /// On success the remaining handshake secrets, including the ephemeral and static keypairs, - /// are erased, so the [`Responder`] cannot be used for another handshake. + /// The [`Responder`] is consumed: each step mixes into the handshake transcript, so it cannot + /// be taken twice. Whether the step succeeds or fails, the remaining handshake secrets, + /// including the ephemeral and static keypairs, are erased in place before the allocation is + /// freed. pub fn step_1( - &mut self, + mut self: Box, elligatorswift_theirs_ephemeral_serialized: [u8; ELLSWIFT_ENCODING_SIZE], ) -> Result<([u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], NoiseEngine), AeadError> { // 4.5.1.2 Responder - Self::mix_hash(self, &elligatorswift_theirs_ephemeral_serialized[..]); - Self::decrypt_and_hash(self, &mut vec![])?; + self.mix_hash(&elligatorswift_theirs_ephemeral_serialized[..]); + self.decrypt_and_hash(&mut vec![])?; // 4.5.2.1 Responder let mut out = [0; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE]; @@ -289,7 +291,7 @@ impl Responder { // what is here is not the public key encoded with ElligatorSwift, but the x-coordinate of // the public key (which is a point in the EC). - Self::mix_hash(self, &elligatorswift_ours_ephemeral_serialized); + self.mix_hash(&elligatorswift_ours_ephemeral_serialized); // 4. calls `MixKey(ECDH(e.private_key, re.public_key))` let e_private_key = keypair.secret_key(); @@ -303,7 +305,7 @@ impl Responder { None, ) .to_secret_bytes(); - Self::mix_key(self, &ecdh_ephemeral); + self.mix_key(&ecdh_ephemeral); ecdh_ephemeral.zeroize(); // 5. appends `EncryptAndHash(s.public_key)` (64 bytes encrypted elligatorswift public key, @@ -329,14 +331,14 @@ impl Responder { None, ) .to_secret_bytes(); - Self::mix_key(self, &ecdh_static[..]); + self.mix_key(&ecdh_static[..]); ecdh_static.zeroize(); // 7. appends `EncryptAndHash(SIGNATURE_NOISE_MESSAGE)` to the buffer let signature_noise_message: [u8; SIGNATURE_NOISE_MESSAGE_SIZE] = self.certificate.into(); let mut signature_part = Vec::with_capacity(ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE); signature_part.extend_from_slice(&signature_noise_message[..]); - Self::encrypt_and_hash(self, &mut signature_part)?; + self.encrypt_and_hash(&mut signature_part)?; let ephemeral_plus_static_encrypted_length = ELLSWIFT_ENCODING_SIZE + ENCRYPTED_ELLSWIFT_ENCODING_SIZE; out[ephemeral_plus_static_encrypted_length..(INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE)] @@ -344,7 +346,7 @@ impl Responder { // 9. return pair of CipherState objects, the first for encrypting transport messages from // initiator to responder, and the second for messages in the other direction: - let ck = Self::get_ck(self); + let ck = self.get_ck(); let (mut temp_k1, mut temp_k2) = Self::hkdf_2(ck, &[]); let c1 = ChaCha20Poly1305::new(Key::from_slice(&temp_k1[..])); let c2 = ChaCha20Poly1305::new(Key::from_slice(&temp_k2[..])); @@ -363,7 +365,6 @@ impl Responder { encryptor, decryptor, }; - self.erase(); Ok((to_send, engine)) } @@ -400,7 +401,7 @@ mod test { use super::*; - fn make_responder() -> Responder { + fn make_responder() -> Box { use rand::{rngs::StdRng, SeedableRng}; use secp256k1::Secp256k1; @@ -408,7 +409,7 @@ mod test { let mut rng = StdRng::seed_from_u64(42); let authority = Keypair::new(&secp, &mut rng); - *Responder::new_with_now_rng(authority, 60, 100, &mut rng) + Responder::new_with_now_rng(authority, 60, 100, &mut rng) } #[test] @@ -435,7 +436,7 @@ mod test { fn responder_step_1_returns_valid_message_and_engine() { use secp256k1::ellswift::ElligatorSwift; - let mut responder = make_responder(); + let responder = make_responder(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); @@ -463,7 +464,7 @@ mod test { fn responder_cipher_detects_tampering() { use secp256k1::ellswift::ElligatorSwift; - let mut responder = make_responder(); + let responder = make_responder(); let fake_initiator_ephemeral = ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); @@ -480,17 +481,14 @@ mod test { #[test] #[cfg_attr(miri, ignore)] - fn responder_step_1_erases_handshake_secrets() { - use secp256k1::ellswift::ElligatorSwift; - - let mut responder = make_responder(); - let static_before = responder.s.secret_key().secret_bytes(); - let fake_initiator_ephemeral = - ElligatorSwift::from_pubkey(responder.e.public_key()).to_array(); + fn responder_drop_erases_handshake_secrets() { + // Leaked on purpose: the allocation has to outlive the drop to be inspected. + let mut responder = core::mem::ManuallyDrop::new(make_responder()); + assert!(responder.ck.iter().any(|b| *b != 0)); - let _ = responder.step_1(fake_initiator_ephemeral).unwrap(); + // SAFETY: dropped once, and the fields read below are plain arrays in live memory. + unsafe { core::ptr::drop_in_place(&mut **responder) }; - assert_ne!(responder.s.secret_key().secret_bytes(), static_before); assert_eq!(responder.ck, [0u8; 32]); assert_eq!(responder.h, [0u8; 32]); } diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index 643b1f102a..b4d4891bbe 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -7,7 +7,7 @@ fn test_1() { let key_pair = Responder::generate_key(); let mut initiator = Initiator::new(key_pair.public_key().into()); - let mut responder = Responder::new(key_pair, 31449600); + let responder = Responder::new(key_pair, 31449600); let first_message = initiator.step_0().unwrap(); let (second_message, mut responder_engine) = responder.step_1(first_message).unwrap(); let mut initiator_engine = initiator.step_2(second_message).unwrap(); @@ -30,8 +30,7 @@ fn test_1_with_rng() { .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as u32; - let mut responder = - Responder::new_with_now_rng(key_pair, 31449600, now, &mut rand::thread_rng()); + let responder = Responder::new_with_now_rng(key_pair, 31449600, now, &mut rand::thread_rng()); let first_message = initiator.step_0().unwrap(); let (second_message, mut responder_engine) = responder.step_1(first_message).unwrap(); let now = std::time::SystemTime::now() @@ -56,7 +55,7 @@ fn initiator_rejects_a_certificate_from_another_authority() { let authority = Responder::generate_key(); let other_authority = Responder::generate_key(); let mut initiator = Initiator::new(other_authority.public_key().into()); - let mut responder = Responder::new(authority, 60); + let responder = Responder::new(authority, 60); let first_message = initiator.step_0().unwrap(); let (second_message, _) = responder.step_1(first_message).unwrap(); assert!(matches!( @@ -84,7 +83,7 @@ fn pre_issued_certificate_is_sent_verbatim() { }; let handshake = |certificate| { let mut initiator = Initiator::new(authority.public_key().into()); - let mut responder = Responder::from_certificate(server_static, certificate); + let responder = Responder::from_certificate(server_static, certificate); let first_message = initiator.step_0().unwrap(); let (second_message, responder_engine) = responder.step_1(first_message).unwrap(); initiator From 1581d171f8a2486fd4ba5692cb7006793219e8db Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 16 Nov 2026 12:42:25 -0300 Subject: [PATCH 9/9] refactor(noise_sv2,codec_sv2)!: consume the Initiator in step_2 The same change as for `Responder::step_1`: `step_2` and `step_2_with_now` take `self: Box` instead of `&mut self`, so the step cannot be taken twice and `Drop` erases the handshake secrets on every path, including a rejected certificate. codec_sv2's `InitiatorSent` now holds the `Box` it is given instead of moving the `Initiator` out of it, which also stops `Handshake::step_0` from copying the ephemeral key out of an allocation that is then freed without being wiped. The test that inspected the Initiator after step_2 is replaced by one that drops an Initiator in place and checks the secrets are gone. BREAKING CHANGE: `Initiator::step_2` and `Initiator::step_2_with_now` take `self: Box` instead of `&mut self`. --- sv2/codec-sv2/src/state.rs | 8 ++++---- sv2/noise-sv2/benches/handshake.rs | 2 +- sv2/noise-sv2/src/initiator.rs | 30 +++++++++++++----------------- 3 files changed, 18 insertions(+), 22 deletions(-) diff --git a/sv2/codec-sv2/src/state.rs b/sv2/codec-sv2/src/state.rs index f77abca087..db67e41375 100644 --- a/sv2/codec-sv2/src/state.rs +++ b/sv2/codec-sv2/src/state.rs @@ -50,7 +50,7 @@ impl ExpectsHandshakeMessage for Responder { /// [`Handshake::step_0`] is the only thing that builds one, which is what stops a caller from /// sending that first message twice. #[derive(Debug)] -pub struct InitiatorSent(Initiator); +pub struct InitiatorSent(Box); /// The codec state while the handshake runs, in the role `R`: [`Initiator`] before it has sent /// its first message, [`InitiatorSent`] after, or [`Responder`]. Frames exchanged in this state @@ -127,7 +127,7 @@ impl Handshake { Ok(( HandshakeMessage::from_message(message), Handshake { - role: Box::new(InitiatorSent(*self.role)), + role: Box::new(InitiatorSent(self.role)), }, )) } @@ -137,7 +137,7 @@ impl Handshake { /// Completes the handshake with the responder's reply, consuming the state. #[cfg(feature = "std")] pub fn step_2( - mut self, + self, message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], ) -> Result { self.role @@ -151,7 +151,7 @@ impl Handshake { /// another source of time. #[inline] pub fn step_2_with_now( - mut self, + self, message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], now: u32, ) -> Result { diff --git a/sv2/noise-sv2/benches/handshake.rs b/sv2/noise-sv2/benches/handshake.rs index e96f8a3e9d..a421acdfc2 100644 --- a/sv2/noise-sv2/benches/handshake.rs +++ b/sv2/noise-sv2/benches/handshake.rs @@ -48,7 +48,7 @@ fn bench_nx_handshake(c: &mut Criterion) { (initiator, msg_2) }, - |(mut initiator, msg_2)| { + |(initiator, msg_2)| { let _ = initiator.step_2_with_now(msg_2, 10).unwrap(); }, BatchSize::SmallInput, diff --git a/sv2/noise-sv2/src/initiator.rs b/sv2/noise-sv2/src/initiator.rs index 099f2baf13..bea2b33c4c 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -254,11 +254,12 @@ impl Initiator { /// /// # Security /// - /// On success the remaining handshake secrets, including the ephemeral keypair, are erased, - /// so the [`Initiator`] cannot be used for another handshake. + /// The [`Initiator`] is consumed: each step mixes into the handshake transcript, so it cannot + /// be taken twice. Whether the step succeeds or fails, the remaining handshake secrets, + /// including the ephemeral keypair, are erased in place before the allocation is freed. #[cfg(feature = "std")] pub fn step_2( - &mut self, + self: Box, message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], ) -> Result { let now = std::time::SystemTime::now() @@ -276,7 +277,7 @@ impl Initiator { /// The current system time should be provided to avoid relying on `std` and allow `no_std` /// environments to use another source of time. pub fn step_2_with_now( - &mut self, + mut self: Box, message: [u8; INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE], now: u32, ) -> Result { @@ -363,7 +364,6 @@ impl Initiator { encryptor, decryptor, }; - self.erase(); Ok(engine) } else { Err(Error::InvalidCertificate(plaintext.into())) @@ -444,21 +444,17 @@ mod test { } #[test] - #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] - fn initiator_step_2_erases_handshake_secrets() { - use crate::Responder; - - let authority_kp = Responder::generate_key(); - let responder = Responder::new(authority_kp, 60); - let mut initiator = Initiator::new(authority_kp.public_key().into()); - let ephemeral_before = initiator.e.secret_key().secret_bytes(); + fn initiator_drop_erases_handshake_secrets() { + // Leaked on purpose: the allocation has to outlive the drop to be inspected. + let mut initiator = core::mem::ManuallyDrop::new(Initiator::new( + crate::Responder::generate_key().public_key().into(), + )); + assert!(initiator.ck.iter().any(|b| *b != 0)); - let msg0 = initiator.step_0().unwrap(); - let (msg1, _) = responder.step_1(msg0).unwrap(); - let _engine = initiator.step_2(msg1).unwrap(); + // SAFETY: dropped once, and the fields read below are plain arrays in live memory. + unsafe { core::ptr::drop_in_place(&mut **initiator) }; - assert_ne!(initiator.e.secret_key().secret_bytes(), ephemeral_before); assert_eq!(initiator.ck, [0u8; 32]); assert_eq!(initiator.h, [0u8; 32]); }