From 588f270e531f6044e32ad8dd6a8ac10f8539bd1c Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 12:07:34 -0300 Subject: [PATCH 1/5] 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 | 148 ++++++++++++++++++++++++++------- sv2/noise-sv2/src/test.rs | 54 ++++++++++++ 5 files changed, 177 insertions(+), 31 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..2b934660bc 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 { @@ -174,6 +184,62 @@ impl Responder { a: Keypair, cert_validity: u32, rng: &mut R, + ) -> Box { + let s = Self::generate_key_with_rng(rng); + let certificate = CertificateSource::SignAtHandshake { + authority: a, + 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 a9d73acb0bd160cf6c165860a2a98e7498c8892c Mon Sep 17 00:00:00 2001 From: plebhash Date: Mon, 9 Nov 2026 12:07:56 -0300 Subject: [PATCH 2/5] 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 2b934660bc..a37e819279 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 `a` 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(a: Keypair, cert_validity: u32) -> Box { Self::new_with_rng(a, 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 493a191aabb8673fcf3ed4de5f78b14b60399e64 Mon Sep 17 00:00:00 2001 From: plebhash Date: Thu, 12 Nov 2026 10:28:05 -0300 Subject: [PATCH 3/5] 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`, add the conversion into its 74 bytes so an issuer can encode the header it signs, and make the leeway a crate constant. --- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/src/lib.rs | 10 ++++ sv2/noise-sv2/src/signature_message.rs | 82 +++++++++++++++----------- 3 files changed, 59 insertions(+), 35 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..eb37405c22 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 encodes the version and the +//! validity window with its `From` conversion into bytes, signs them over the server's static key +//! with [`SignatureNoiseMessage::sign_with_rng`], and hands the 74 bytes to the server. #![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/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index 5fe3db13f7..053912b649 100644 --- a/sv2/noise-sv2/src/signature_message.rs +++ b/sv2/noise-sv2/src/signature_message.rs @@ -7,19 +7,19 @@ // 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 +// 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 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. use core::convert::TryInto; use core::fmt; @@ -35,13 +35,13 @@ use secp256k1::{hashes::sha256, schnorr::Signature, Keypair, Message, Secp256k1, /// a specified time window, using Schnorr signatures over the `secp256k1` elliptic curve. #[derive(Debug, 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,12 +62,22 @@ impl fmt::Display for SignatureNoiseMessage { write!(f, " }}") } } +impl From for [u8; 74] { + /// 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 (header, signature) = value.split(); + let mut encoded = [0; 74]; + encoded[0..10].copy_from_slice(&header); + encoded[10..74].copy_from_slice(&signature); + encoded + } +} + 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. + /// 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; 74]) -> 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()); @@ -83,14 +93,8 @@ 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 provided 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 { let now = std::time::SystemTime::now() @@ -101,7 +105,7 @@ impl SignatureNoiseMessage { } /// Verifies the validity and authenticity of the `SignatureNoiseMessage` at a given timestamp - /// with 10 seconds of tolerance. + /// with [`crate::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 @@ -121,9 +125,7 @@ impl SignatureNoiseMessage { 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; + use crate::CERTIFICATE_TIME_LEEWAY as TIME_LEEWAY; if self.version != crate::CERTIFICATE_VERSION { return false; @@ -153,12 +155,11 @@ impl SignatureNoiseMessage { } } - // 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)] + /// Signs a [`SignatureNoiseMessage`] using the provided keypair (`kp`). + /// + /// `msg` holds the encoded message, as produced by the conversion into `[u8; 74]`; its first 10 + /// bytes (version and validity period) are signed together with the static public key of the + /// server (`static_pk`), and the resulting signature is written into its remaining 64 bytes. #[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()); @@ -214,6 +215,19 @@ impl SignatureNoiseMessage { mod test { use super::*; + #[test] + fn byte_encoding_round_trips() { + let mut encoded = [0u8; 74]; + 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; 74]>::from(message), encoded); + } + #[test] #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] From 997efc04b9756b9b6b9329297750476aa43db52a Mon Sep 17 00:00:00 2001 From: plebhash Date: Thu, 12 Nov 2026 11:21:11 -0300 Subject: [PATCH 4/5] feat(noise_sv2)!: report why a responder certificate was rejected A failed handshake used to return the `SignatureNoiseMessage` alone, leaving the operator to compare raw unix timestamps against the clock to guess what went wrong, and an application nothing to act on short of parsing a log line. Verification now returns a `CertificateError` naming the failed check (unsupported version, bad signature, not yet valid, expired), with the clock reading the time checks were made against, and `Error::InvalidCertificate` carries it next to the `SignatureNoiseMessage`. The signature is checked before the validity window, so a reported `NotYetValid` or `Expired` always refers to timestamps the authority signed: a forged certificate, or one that does not verify for this server static pubkey and authority pubkey, is reported as `InvalidSignature` whatever timestamps it carries. `SignatureNoiseMessage::verify` and `verify_with_now` return the same `Result<(), CertificateError>` in place of a bool, so whoever loads a pre-issued certificate for `Responder::from_certificate` can run the initiator's checks ahead of any handshake and learn which one failed, instead of re-implementing them. The `SignatureNoiseMessage` `Display` drops the hex signature, which means nothing in a log line (`Debug` still has it), and codec_sv2 prints the reason ahead of it. `CertificateError` is re-exported next to `SignatureNoiseMessage`. The docs around them now tell the `SIGNATURE_NOISE_MESSAGE` apart from the certificate it forms with the responder's static key, as the spec does. noise_sv2 3.0.0, codec_sv2 9.0.0 and stratum-core 0.8.0, since each exposes the one below in its public API. https://github.com/stratum-mining/stratum/issues/2425 --- Cargo.lock | 6 +- fuzz/Cargo.lock | 4 +- stratum-core/Cargo.toml | 6 +- sv2/codec-sv2/Cargo.toml | 4 +- sv2/codec-sv2/src/error.rs | 10 +- sv2/noise-sv2/Cargo.toml | 2 +- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/src/error.rs | 12 +- sv2/noise-sv2/src/initiator.rs | 70 ++++---- sv2/noise-sv2/src/lib.rs | 6 +- sv2/noise-sv2/src/signature_message.rs | 221 ++++++++++++++++--------- sv2/noise-sv2/src/test.rs | 23 ++- 12 files changed, 232 insertions(+), 134 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/codec-sv2/src/error.rs b/sv2/codec-sv2/src/error.rs index 7eb6c047d6..d8011b53ec 100644 --- a/sv2/codec-sv2/src/error.rs +++ b/sv2/codec-sv2/src/error.rs @@ -57,8 +57,14 @@ impl fmt::Display for Error { FramingSv2Error(e) => write!(f, "Framing Sv2 Error: `{e}`"), #[cfg(feature = "noise_sv2")] NoiseSv2Error(e) => match e { - NoiseError::InvalidCertificate(msg) => { - write!(f, "Invalid Certificate: {}", msg) + NoiseError::InvalidCertificate { + signature_noise_message, + reason, + } => { + write!( + f, + "Invalid Certificate ({reason}): {signature_noise_message}" + ) } other => { write!(f, "Noise SV2 Error: {:?}", other) 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/README.md b/sv2/noise-sv2/README.md index 5df1f50d0a..ba28c557a8 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. 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 the signed part of that certificate, the 74 bytes an issuer produces and the server sends. * **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/error.rs b/sv2/noise-sv2/src/error.rs index 312879e742..f4d6eb51ca 100644 --- a/sv2/noise-sv2/src/error.rs +++ b/sv2/noise-sv2/src/error.rs @@ -6,7 +6,7 @@ use alloc::vec::Vec; use chacha20poly1305::aead::Error as AeadError; -use crate::signature_message::SignatureNoiseMessage; +use crate::signature_message::{CertificateError, SignatureNoiseMessage}; /// Noise protocol error handling. #[derive(Debug, PartialEq, Eq)] @@ -32,8 +32,14 @@ pub enum Error { /// Cipher is in an invalid state during encryption/decryption operations. InvalidCipherState, - /// Provided certificate is invalid or cannot be verified. - InvalidCertificate(SignatureNoiseMessage), + /// The certificate formed by the responder's [`SignatureNoiseMessage`] and static key failed + /// verification for the given `reason`. + InvalidCertificate { + /// The `SIGNATURE_NOISE_MESSAGE` the responder sent. + signature_noise_message: SignatureNoiseMessage, + /// The check the certificate failed. + reason: CertificateError, + }, /// A raw public key is invalid or cannot be parsed. InvalidRawPublicKey, diff --git a/sv2/noise-sv2/src/initiator.rs b/sv2/noise-sv2/src/initiator.rs index c3e97bd3ba..0622f43913 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -149,10 +149,11 @@ impl Initiator { /// Creates a new [`Initiator`] instance with an optional responder 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. + /// authenticate the responder during the handshake: the certificate formed by the + /// [`SignatureNoiseMessage`] received in [`Self::step_2`] and the responder's static key must + /// carry a supported version, 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 /// @@ -292,13 +293,15 @@ 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 [`SignatureNoiseMessage`] included in the message and, if this [`Initiator`] + /// was built with a responder authority public key, verifies the certificate it forms with the + /// responder's static 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 - /// [`Error::InvalidMessageLength`]. If decryption or signature verification fails, it returns - /// an [`Error::InvalidCertificate`]. + /// [`Error::InvalidMessageLength`]. If the certificate fails verification, it returns an + /// [`Error::InvalidCertificate`] carrying the [`SignatureNoiseMessage`] and the check it + /// failed. /// /// # Security /// @@ -381,7 +384,8 @@ impl Initiator { self.mix_key(&ecdh_static); ecdh_static.zeroize(); - // Decrypt and verify the SignatureNoiseMessage + // Decrypt the SignatureNoiseMessage and verify the certificate it forms with the + // responder's static key let mut to_decrypt = message[ELLSWIFT_ENCODING_SIZE + ENCRYPTED_ELLSWIFT_ENCODING_SIZE ..INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE] .to_vec(); @@ -397,29 +401,33 @@ 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) { - 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[..])); - let c1: Cipher = Cipher::from_key_and_cipher(temp_k1, c1); - let c2: Cipher = Cipher::from_key_and_cipher(temp_k2, c2); - let mut encryptor = c1; - let mut decryptor = c2; - encryptor.erase_k(); - decryptor.erase_k(); - // The ciphers keep the only copies of the session keys from here on; `erase_k` above - // wiped the copies the `Cipher`s carried, and these are the ones the handshake used. - temp_k1.zeroize(); - temp_k2.zeroize(); - let engine = crate::NoiseEngine { - encryptor, - decryptor, - }; - self.erase(); - Ok(engine) - } else { - Err(Error::InvalidCertificate(plaintext.into())) + if let Err(reason) = + signature_message.verify_with_now(&rs_pk_xonly, &self.responder_authority_pk, now) + { + return Err(Error::InvalidCertificate { + signature_noise_message: signature_message, + reason, + }); } + 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[..])); + let c1: Cipher = Cipher::from_key_and_cipher(temp_k1, c1); + let c2: Cipher = Cipher::from_key_and_cipher(temp_k2, c2); + let mut encryptor = c1; + let mut decryptor = c2; + encryptor.erase_k(); + decryptor.erase_k(); + // The ciphers keep the only copies of the session keys from here on; `erase_k` above + // wiped the copies the `Cipher`s carried, and these are the ones the handshake used. + temp_k1.zeroize(); + temp_k2.zeroize(); + let engine = crate::NoiseEngine { + encryptor, + decryptor, + }; + self.erase(); + Ok(engine) } // Securely erases sensitive data from the [`Initiator`] memory. diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index eb37405c22..4989158bc9 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -34,7 +34,7 @@ //! ## 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 +//! public key, which it uses to verify the certificate formed 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 @@ -49,7 +49,7 @@ //! [`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 encodes the version and the +//! The certificate travels as a [`SignatureNoiseMessage`]: the issuer encodes the version and the //! validity window with its `From` conversion into bytes, signs them over the server's static key //! with [`SignatureNoiseMessage::sign_with_rng`], and hands the 74 bytes to the server. @@ -215,4 +215,4 @@ impl NoiseDecryptor { pub use error::Error; pub use initiator::Initiator; pub use responder::Responder; -pub use signature_message::SignatureNoiseMessage; +pub use signature_message::{CertificateError, SignatureNoiseMessage}; diff --git a/sv2/noise-sv2/src/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index 053912b649..e39a343c3d 100644 --- a/sv2/noise-sv2/src/signature_message.rs +++ b/sv2/noise-sv2/src/signature_message.rs @@ -1,39 +1,30 @@ -// # Signature-Based Message Handling +// # Signature Noise Message and Certificate // -// Defines the [`SignatureNoiseMessage`] struct, which represents a signed message used in the -// Noise protocol to authenticate and verify the identity of a party during the handshake. -// -// This module provides utilities for creating, signing, and verifying Noise protocol messages -// using Schnorr signatures over the [`secp256k1`] elliptic curve. It encapsulates signed messages -// along with versioning and validity timestamps. The following capabilities are supported: -// -// - 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. +// Defines the [`SignatureNoiseMessage`] (spec 4.5.2 `SIGNATURE_NOISE_MESSAGE`), which the +// responder sends as the payload of the second handshake message, and verification of the +// certificate (spec 4.5.3 `CERTIFICATE`) it forms together with the responder's static public key. // // ## Usage // -// 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 -// 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 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. +// Whoever holds the authority key, a [`crate::Responder`] signing at handshake time or a separate +// issuer, uses `sign` or `sign_with_rng` to produce the signature over the version, the validity +// window and the responder's static public key. The [`crate::Initiator`] uses `verify_with_now` +// to check that certificate against the authority public key it was given, if any, and the +// current time; whoever loads a pre-issued certificate can run the same check ahead of any +// handshake and learn which part of it failed. use core::convert::TryInto; use core::fmt; use secp256k1::{hashes::sha256, schnorr::Signature, Keypair, Message, Secp256k1, XOnlyPublicKey}; -/// `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, -/// and a Schnorr signature over the message. +/// The 74-byte `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2) the responder sends during the handshake. /// -/// 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)] +/// It carries the certificate's version and validity window and the authority's Schnorr +/// signature over the certificate (spec 4.5.3), which also covers the responder's static public +/// key. The message alone authenticates nothing: only the certificate it forms with that key can +/// be verified against the authority key. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SignatureNoiseMessage { /// Certificate format version; only [`crate::CERTIFICATE_VERSION`] verifies. pub version: u16, @@ -45,21 +36,53 @@ pub struct SignatureNoiseMessage { pub signature: [u8; 64], } +// The signature is left out: it means nothing to a human reading logs, and `Debug` still has it. impl fmt::Display for SignatureNoiseMessage { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - // write header write!( f, - "SignatureNoiseMessage {{ version: {}, valid_from: {}, not_valid_after: {}, signature: ", + "signature noise message version {}, valid from {} until {} (unix time)", self.version, self.valid_from, self.not_valid_after - )?; + ) + } +} - // write signature as hex manually - for byte in &self.signature { - write!(f, "{:02x}", byte)?; - } +/// The check the responder's certificate failed during verification. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CertificateError { + /// The certificate version is not [`crate::CERTIFICATE_VERSION`]. + UnsupportedVersion, + /// `now` (unix time) falls before the certificate's `valid_from`, beyond the clock leeway. + NotYetValid { + /// The clock reading the window was checked against (unix time). + now: u32, + }, + /// `now` (unix time) falls after the certificate's `not_valid_after`, beyond the clock leeway. + Expired { + /// The clock reading the window was checked against (unix time). + now: u32, + }, + /// The certificate signature, over the version, the validity window and the responder's static + /// public key, does not verify against the authority public key. Either key can be the cause, + /// as can malformed signature bytes; the signature cannot tell them apart. + InvalidSignature, +} - write!(f, " }}") +impl fmt::Display for CertificateError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnsupportedVersion => write!( + f, + "unsupported version, expected {}", + crate::CERTIFICATE_VERSION + ), + Self::NotYetValid { now } => write!(f, "not yet valid, local clock reads {now}"), + Self::Expired { now } => write!(f, "expired, local clock reads {now}"), + Self::InvalidSignature => write!( + f, + "signature does not verify for this server static pubkey and authority pubkey" + ), + } } } impl From for [u8; 74] { @@ -93,10 +116,14 @@ impl From<[u8; 74]> for SignatureNoiseMessage { } impl SignatureNoiseMessage { - /// Verifies the [`SignatureNoiseMessage`] against the provided public key and an optional - /// authority public key at the current system time. See [`Self::verify_with_now`]. + /// Verifies the certificate this `SignatureNoiseMessage` forms with the responder's static key + /// `pk` 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, + pk: &XOnlyPublicKey, + authority_pk: &Option, + ) -> Result<(), CertificateError> { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -104,17 +131,19 @@ impl SignatureNoiseMessage { self.verify_with_now(pk, authority_pk, now) } - /// Verifies the validity and authenticity of the `SignatureNoiseMessage` at a given timestamp - /// with [`crate::CERTIFICATE_TIME_LEEWAY`] seconds of tolerance. + /// Verifies the certificate this `SignatureNoiseMessage` forms with the responder's static key + /// `pk`, at a given timestamp with [`crate::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. + /// its signature over the responder's static key `pk` must verify against the authority key, + /// and `now` must fall inside its validity window. The checks run in that order, so + /// [`CertificateError::NotYetValid`] and [`CertificateError::Expired`] are only reported for + /// timestamps the authority actually signed. /// /// # 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. + /// otherwise accepted unverified, so `Ok` does not mean the responder was authenticated. /// /// The current system time should be provided to avoid relying on `std` and allow `no_std` /// environments to use another source of time. @@ -124,35 +153,35 @@ impl SignatureNoiseMessage { pk: &XOnlyPublicKey, authority_pk: &Option, now: u32, - ) -> bool { + ) -> Result<(), CertificateError> { use crate::CERTIFICATE_TIME_LEEWAY as TIME_LEEWAY; if self.version != crate::CERTIFICATE_VERSION { - return false; + return Err(CertificateError::UnsupportedVersion); } - 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 Ok(()); + }; + + 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); + Signature::from_slice(&s) + .and_then(|s| secp.verify_schnorr(&s, &m, authority_pk)) + .map_err(|_| CertificateError::InvalidSignature)?; + + // 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 { + return Err(CertificateError::NotYetValid { now }); } + if self.not_valid_after.saturating_add(TIME_LEEWAY) < now { + return Err(CertificateError::Expired { now }); + } + Ok(()) } /// Signs a [`SignatureNoiseMessage`] using the provided keypair (`kp`). @@ -231,31 +260,59 @@ mod test { #[test] #[cfg(feature = "std")] #[cfg_attr(miri, ignore)] - fn verify_rejects_unsupported_certificate_version() { + fn verify_reports_why_a_certificate_is_rejected() { use rand::{rngs::StdRng, SeedableRng}; 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 pk = responder_static.x_only_public_key().0; + let authority_pk = Some(authority.x_only_public_key().0); - 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 mut signature_noise_message = |version: u16| { + let mut encoded = [0u8; 74]; + encoded[0..2].copy_from_slice(&version.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, &pk, &authority, &mut rng); + SignatureNoiseMessage::from(encoded) + }; + let valid = signature_noise_message(crate::CERTIFICATE_VERSION); + let mut forged = valid; + forged.signature[0] ^= 1; - let certificate = SignatureNoiseMessage::from(encoded); - let authority_pk = Some(authority.x_only_public_key().0); - assert!(!certificate.verify_with_now( - &responder_static.x_only_public_key().0, - &authority_pk, - 150, - )); + assert_eq!(valid.verify_with_now(&pk, &authority_pk, 150), Ok(())); + assert_eq!( + signature_noise_message(crate::CERTIFICATE_VERSION + 1).verify_with_now( + &pk, + &authority_pk, + 150 + ), + Err(CertificateError::UnsupportedVersion) + ); + assert_eq!( + valid.verify_with_now(&pk, &authority_pk, 89), + Err(CertificateError::NotYetValid { now: 89 }) + ); + assert_eq!( + valid.verify_with_now(&pk, &authority_pk, 211), + Err(CertificateError::Expired { now: 211 }) + ); + assert_eq!( + forged.verify_with_now(&pk, &authority_pk, 150), + Err(CertificateError::InvalidSignature) + ); + // A certificate issued for another server static pubkey does not verify either. + let other_pk = Keypair::new(&secp, &mut rng).x_only_public_key().0; + assert_eq!( + valid.verify_with_now(&other_pk, &authority_pk, 150), + Err(CertificateError::InvalidSignature) + ); + // A forged certificate outside its window is reported as forged, not as expired. + assert_eq!( + forged.verify_with_now(&pk, &authority_pk, 211), + Err(CertificateError::InvalidSignature) + ); } } diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index 8b562ead3a..e2348f2df6 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -19,6 +19,24 @@ fn test_1() { assert!(message == "ciao".as_bytes().to_vec()); } +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn handshake_reports_why_the_certificate_was_rejected() { + let wrong_authority = Responder::generate_key(); + let mut initiator = Initiator::new(Some(wrong_authority.public_key().into())); + let mut responder = Responder::new(Responder::generate_key(), 31449600); + let first_message = initiator.step_0().unwrap(); + let (second_message, _) = responder.step_1(first_message).unwrap(); + assert!(matches!( + initiator.step_2(second_message), + Err(crate::Error::InvalidCertificate { + reason: crate::CertificateError::InvalidSignature, + .. + }) + )); +} + #[test] #[cfg_attr(miri, ignore)] fn test_1_with_rng() { @@ -98,6 +116,9 @@ fn pre_issued_certificate_is_sent_verbatim() { // initiator rejects it. assert!(matches!( handshake(issue(now - 120, now - 60)), - Err(Error::InvalidCertificate(_)) + Err(Error::InvalidCertificate { + reason: crate::CertificateError::Expired { .. }, + .. + }) )); } From 735556de24c5a55fea659930691168e73ff90d50 Mon Sep 17 00:00:00 2001 From: plebhash Date: Fri, 16 Oct 2026 20:38:00 -0300 Subject: [PATCH 5/5] feat(noise_sv2): expose the verified certificate A successful handshake discarded the certificate, so an initiator could not log which certificate it accepted or when it expires. `NoiseEngine::certificate` and codec_sv2's `Transport::certificate` now return it as a `Certificate`: the spec's CERTIFICATE, formed by the `SignatureNoiseMessage` and the server's static public key its signature covers, together with the authority public key that signature was verified against. A certificate needs an authority key, so an initiator built with `Initiator::without_pk` gets `None`, as does the responder. That also lets callers tell an authenticated session from an unauthenticated one without tracking which constructor they used (https://github.com/stratum-mining/stratum/issues/2391). https://github.com/stratum-mining/stratum/issues/2425 --- sv2/codec-sv2/src/state.rs | 10 ++++++++-- sv2/noise-sv2/README.md | 2 +- sv2/noise-sv2/src/initiator.rs | 22 ++++++++++++++-------- sv2/noise-sv2/src/lib.rs | 22 ++++++++++++++++++---- sv2/noise-sv2/src/responder.rs | 1 + sv2/noise-sv2/src/signature_message.rs | 20 +++++++++++++++++++- sv2/noise-sv2/src/test.rs | 24 ++++++++++++++++++++++++ 7 files changed, 85 insertions(+), 16 deletions(-) diff --git a/sv2/codec-sv2/src/state.rs b/sv2/codec-sv2/src/state.rs index 28df19eb8e..e149db5cb0 100644 --- a/sv2/codec-sv2/src/state.rs +++ b/sv2/codec-sv2/src/state.rs @@ -24,8 +24,8 @@ use alloc::boxed::Box; use buffer_sv2::Buffer as IsBuffer; use framing_sv2::framing::HandshakeMessage; use noise_sv2::{ - AeadBuffer, AeadError, Initiator, NoiseDecryptor, NoiseEncryptor, NoiseEngine, Responder, - ELLSWIFT_ENCODING_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE, + AeadBuffer, AeadError, Certificate, Initiator, NoiseDecryptor, NoiseEncryptor, NoiseEngine, + Responder, ELLSWIFT_ENCODING_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE, }; /// A handshake role that is waiting on a message from its counterpart. @@ -227,6 +227,12 @@ impl Transport { Self { engine } } + /// The responder's verified certificate, see [`NoiseEngine::certificate`]. Read it before + /// [`Self::split`], which drops it. + pub fn certificate(&self) -> Option<&Certificate> { + self.engine.certificate() + } + /// Splits into the half the encoder uses and the half the decoder uses, consuming it. pub fn split(self) -> (TransportEncryptState, TransportDecryptState) { let (encryption, decryption) = self.engine.into_split(); diff --git a/sv2/noise-sv2/README.md b/sv2/noise-sv2/README.md index ba28c557a8..95c14117cc 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 the signed part of that certificate, the 74 bytes an issuer produces and the server sends. +* **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 the signed part of that certificate, the 74 bytes an issuer produces and the server sends. An `Initiator` that verified the certificate exposes it through `NoiseEngine::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/initiator.rs b/sv2/noise-sv2/src/initiator.rs index 0622f43913..fdbd24f4b4 100644 --- a/sv2/noise-sv2/src/initiator.rs +++ b/sv2/noise-sv2/src/initiator.rs @@ -45,7 +45,7 @@ use crate::{ cipher_state::{Cipher, CipherState}, error::Error, handshake::HandshakeOp, - signature_message::SignatureNoiseMessage, + signature_message::{Certificate, SignatureNoiseMessage}, AeadError, NoiseEngine, ELLSWIFT_ENCODING_SIZE, ENCRYPTED_ELLSWIFT_ENCODING_SIZE, ENCRYPTED_SIGNATURE_NOISE_MESSAGE_SIZE, INITIATOR_EXPECTED_HANDSHAKE_MESSAGE_SIZE, SIGNATURE_NOISE_MESSAGE_SIZE, @@ -158,8 +158,8 @@ impl Initiator { /// # 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 + /// and the resulting session is encrypted but not authenticated: [`Self::step_2`] still + /// returns `Ok`, and only the missing [`NoiseEngine::certificate`] tells it apart. 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. #[cfg(feature = "std")] @@ -233,9 +233,8 @@ impl Initiator { /// 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. + /// [`Self::step_2`] returns `Ok` as it does for a verified session; the only difference is + /// that the returned [`NoiseEngine`] has no [`NoiseEngine::certificate`]. /// /// 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 @@ -301,13 +300,13 @@ impl Initiator { /// for secure communication. If the provided `message` has an incorrect length, it returns an /// [`Error::InvalidMessageLength`]. If the certificate fails verification, it returns an /// [`Error::InvalidCertificate`] carrying the [`SignatureNoiseMessage`] and the check it - /// failed. + /// failed. The verified certificate is available from [`NoiseEngine::certificate`]. /// /// # 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. + /// [`NoiseEngine`] then has no [`NoiseEngine::certificate`]. /// /// On success the remaining handshake secrets, including the ephemeral keypair, are erased, /// so the [`Initiator`] cannot be used for another handshake. @@ -425,6 +424,13 @@ impl Initiator { let engine = crate::NoiseEngine { encryptor, decryptor, + certificate: self + .responder_authority_pk + .map(|authority_pubkey| Certificate { + signature_noise_message: signature_message, + server_static_pubkey: rs_pk_xonly, + authority_pubkey, + }), }; self.erase(); Ok(engine) diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index 4989158bc9..1cda82ff60 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -36,9 +36,10 @@ //! The responder is only authenticated when the [`Initiator`] is given the responder's authority //! public key, which it uses to verify the certificate formed 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. +//! `None`, accepts any responder and yields an encrypted but unauthenticated session: the +//! handshake still succeeds, and only the missing [`NoiseEngine::certificate`] tells it apart +//! from an authenticated one. Always pin the authority key for connections that cross a network +//! boundary. //! //! ## Authority key custody //! @@ -144,6 +145,9 @@ pub struct NoiseEngine { // Cipher to decrypt incoming messages. decryptor: Cipher, + + // The responder's certificate, kept only when it was verified against an authority key. + certificate: Option, } impl core::fmt::Debug for NoiseEngine { @@ -153,6 +157,16 @@ impl core::fmt::Debug for NoiseEngine { } impl NoiseEngine { + /// The responder's certificate, verified against the authority public key the [`Initiator`] + /// was built with. + /// + /// `None` on the [`Responder`] side, and on an [`Initiator`] built without an authority key + /// (see `Initiator::without_pk`), whose session is not authenticated. Read it before + /// [`Self::into_split`], which drops it. + pub fn certificate(&self) -> Option<&Certificate> { + self.certificate.as_ref() + } + /// Encrypts a message (`msg`) in place using the stored cipher. pub fn encrypt(&mut self, msg: &mut T) -> Result<(), AeadError> { self.encryptor.encrypt(msg) @@ -215,4 +229,4 @@ impl NoiseDecryptor { pub use error::Error; pub use initiator::Initiator; pub use responder::Responder; -pub use signature_message::{CertificateError, SignatureNoiseMessage}; +pub use signature_message::{Certificate, CertificateError, SignatureNoiseMessage}; diff --git a/sv2/noise-sv2/src/responder.rs b/sv2/noise-sv2/src/responder.rs index a37e819279..4c3e188a42 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -471,6 +471,7 @@ impl Responder { let engine = crate::NoiseEngine { encryptor, decryptor, + certificate: None, }; self.erase(); Ok((to_send, engine)) diff --git a/sv2/noise-sv2/src/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index e39a343c3d..a5540aece0 100644 --- a/sv2/noise-sv2/src/signature_message.rs +++ b/sv2/noise-sv2/src/signature_message.rs @@ -2,7 +2,8 @@ // // Defines the [`SignatureNoiseMessage`] (spec 4.5.2 `SIGNATURE_NOISE_MESSAGE`), which the // responder sends as the payload of the second handshake message, and verification of the -// certificate (spec 4.5.3 `CERTIFICATE`) it forms together with the responder's static public key. +// certificate (spec 4.5.3 `CERTIFICATE`) it forms together with the responder's static public key, +// kept as a [`Certificate`] once that verification succeeds. // // ## Usage // @@ -47,6 +48,23 @@ impl fmt::Display for SignatureNoiseMessage { } } +/// The responder's certificate (spec 4.5.3 `CERTIFICATE`), which the handshake never sends as +/// such: it is formed by the [`SignatureNoiseMessage`] received during the handshake and the +/// server's static public key its signature covers, together with the authority public key that +/// signature was verified against. +/// +/// Only a `Certificate` returned by [`crate::NoiseEngine::certificate`] is known to have been +/// verified; one built from its public fields carries no such guarantee. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Certificate { + /// The `SIGNATURE_NOISE_MESSAGE` the responder sent. + pub signature_noise_message: SignatureNoiseMessage, + /// The responder's static public key used in the NX handshake, which the signature covers. + pub server_static_pubkey: XOnlyPublicKey, + /// The authority public key the signature was verified against; not covered by the signature. + pub authority_pubkey: XOnlyPublicKey, +} + /// The check the responder's certificate failed during verification. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CertificateError { diff --git a/sv2/noise-sv2/src/test.rs b/sv2/noise-sv2/src/test.rs index e2348f2df6..a18d7cf9e3 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -11,6 +11,18 @@ fn test_1() { 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(); + let certificate = initiator_engine.certificate().unwrap(); + assert_eq!(certificate.authority_pubkey, key_pair.x_only_public_key().0); + // The server static pubkey is the one the authority signed. + assert_eq!( + certificate.signature_noise_message.verify_with_now( + &certificate.server_static_pubkey, + &Some(certificate.authority_pubkey), + certificate.signature_noise_message.valid_from, + ), + Ok(()) + ); + assert!(responder_engine.certificate().is_none()); let mut message = "ciao".as_bytes().to_vec(); initiator_engine.encrypt(&mut message).unwrap(); assert!(message != "ciao".as_bytes().to_vec()); @@ -37,6 +49,18 @@ fn handshake_reports_why_the_certificate_was_rejected() { )); } +#[test] +#[cfg(feature = "std")] +#[cfg_attr(miri, ignore)] +fn unverified_session_exposes_no_certificate() { + let mut initiator = Initiator::without_pk().unwrap(); + let mut responder = Responder::new(Responder::generate_key(), 31449600); + let first_message = initiator.step_0().unwrap(); + let (second_message, _) = responder.step_1(first_message).unwrap(); + let initiator_engine = initiator.step_2(second_message).unwrap(); + assert!(initiator_engine.certificate().is_none()); +} + #[test] #[cfg_attr(miri, ignore)] fn test_1_with_rng() {