diff --git a/Cargo.lock b/Cargo.lock index 58a34da8dd..58b303b440 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", @@ -297,6 +297,7 @@ dependencies = [ "quickcheck_macros", "rand", "rayon-core", + "secp256k1 0.28.2", ] [[package]] @@ -736,7 +737,7 @@ dependencies = [ [[package]] name = "noise_sv2" -version = "2.1.0" +version = "3.0.0" dependencies = [ "chacha20poly1305", "criterion", @@ -1162,7 +1163,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 79d118bb53..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.1.0" +version = "3.0.0" dependencies = [ "chacha20poly1305", "rand", 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..fa9466dcbf 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,27 +81,22 @@ 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 - let mut responder = Responder::new(responder_kp, input.cert_validity); + let responder = Responder::new(responder_kp, input.cert_validity); // ========== Handshake Phase ========== 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..e36f1b576d 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,13 +13,14 @@ 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 } [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..f3b6c138df 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,19 @@ 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 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); @@ -124,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..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 @@ -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 @@ -130,7 +127,7 @@ impl Handshake { Ok(( HandshakeMessage::from_message(message), Handshake { - role: Box::new(InitiatorSent(*self.role)), + role: Box::new(InitiatorSent(self.role)), }, )) } @@ -140,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 @@ -154,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 { @@ -174,9 +171,8 @@ 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, + self, re_pub: [u8; ELLSWIFT_ENCODING_SIZE], ) -> Result<(HandshakeMessage, Transport)> { let (message, engine) = self.role.step_1(re_pub)?; @@ -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/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, + // 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 { @@ -146,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. /// @@ -176,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 { @@ -198,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()) @@ -219,45 +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 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. @@ -292,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 @@ -302,15 +254,12 @@ 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. - /// - /// 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() @@ -328,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 { @@ -415,7 +364,6 @@ impl Initiator { encryptor, decryptor, }; - self.erase(); Ok(engine) } else { Err(Error::InvalidCertificate(plaintext.into())) @@ -453,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"); @@ -465,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)); @@ -482,8 +430,8 @@ mod test { use crate::Responder; let authority_kp = Responder::generate_key(); - let mut responder = Responder::new(authority_kp, 60); - let mut initiator = Initiator::without_pk().unwrap(); + let responder = Responder::new(authority_kp, 60); + let mut initiator = Initiator::new(authority_kp.public_key().into()); let msg0 = initiator.step_0().unwrap(); let (mut msg1, _) = responder.step_1(msg0).unwrap(); @@ -496,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 mut responder = Responder::new(authority_kp, 60); - let mut initiator = Initiator::without_pk().unwrap(); - 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]); } diff --git a/sv2/noise-sv2/src/lib.rs b/sv2/noise-sv2/src/lib.rs index 22451a4fca..c9afa6cb05 100644 --- a/sv2/noise-sv2/src/lib.rs +++ b/sv2/noise-sv2/src/lib.rs @@ -33,12 +33,22 @@ //! //! ## 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 +//! +//! 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`] +//! 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 +//! server; its `From` conversions give the 74 bytes the handshake carries and back. #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] @@ -98,6 +108,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 @@ -197,3 +212,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 1cab80931b..920fe24027 100644 --- a/sv2/noise-sv2/src/responder.rs +++ b/sv2/noise-sv2/src/responder.rs @@ -34,16 +34,15 @@ // The [`Drop`] trait is implemented to automatically trigger secure erasure when the [`Responder`] // instance goes out of scope, preventing potential misuse or leakage of cryptographic material. -use core::time::Duration; use zeroize::Zeroize; use crate::{ cipher_state::{Cipher, CipherState}, - error::Error, handshake::HandshakeOp, 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, @@ -51,7 +50,7 @@ use alloc::{ vec::Vec, }; use chacha20poly1305::{ChaCha20Poly1305, Key, KeyInit}; -use secp256k1::{ellswift::ElligatorSwift, Keypair, Secp256k1, SecretKey}; +use secp256k1::{ellswift::ElligatorSwift, Keypair}; /// Represents the state and operations of the responder in the Noise NX protocol handshake. /// It handles cryptographic key exchanges, manages handshake state, and securely establishes @@ -79,16 +78,12 @@ 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 certified at + // construction. 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, + // The `SIGNATURE_NOISE_MESSAGE` (spec 4.5.2) sent in the second handshake message. + certificate: SignatureNoiseMessage, } impl core::fmt::Debug for Responder { @@ -154,81 +149,105 @@ 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 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(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 { + 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( - a: Keypair, + pub fn new_with_now_rng( + mut authority_key: Keypair, cert_validity: u32, + now: u32, rng: &mut R, ) -> Box { - let mut self_ = Self { - handshake_cipher: None, - k: None, - n: 0, - ck: [0; 32], - h: [0; 32], - e: Self::generate_key_with_rng(rng), - s: Self::generate_key_with_rng(rng), - a, - cert_validity, - }; - Self::initialize_self(&mut self_); - Box::new(self_) + let s = Self::generate_key_with_rng(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`] instance with the provided 32-byte authority key pair. + /// Creates a new [`Responder`] from its static keypair `s` and a certificate issued for it in + /// advance. + /// + /// `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. + /// + /// 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. /// - /// Constructs a new [`Responder`] with a given public and private key pair, which represents - /// 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. + /// 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_authority_kp( - public: &[u8; 32], - private: &[u8; 32], - cert_validity: Duration, - ) -> Result, Error> { - Self::from_authority_kp_with_rng(public, private, cert_validity, &mut rand::thread_rng()) + pub fn from_certificate(s: Keypair, certificate: SignatureNoiseMessage) -> Box { + Self::from_certificate_with_rng(s, certificate, &mut rand::thread_rng()) } - /// Creates a new [`Responder`] instance with the provided 32-byte authority key pair and a - /// custom random number generator. + /// 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_authority_kp`] for more details. + /// 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_authority_kp_with_rng( - public: &[u8; 32], - private: &[u8; 32], - cert_validity: Duration, + pub fn from_certificate_with_rng( + s: Keypair, + certificate: SignatureNoiseMessage, 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) - } + ) -> Box { + let mut self_ = Self { + handshake_cipher: None, + k: None, + n: 0, + ck: [0; 32], + h: [0; 32], + e: Self::generate_key_with_rng(rng), + s, + certificate, + }; + Self::initialize_self(&mut self_); + Box::new(self_) } /// Processes the first step of the Noise NX protocol handshake for the responder. @@ -237,8 +256,9 @@ 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`], 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 @@ -247,43 +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, static and authority - /// keypairs, are erased, so the [`Responder`] cannot be used for another handshake. - #[cfg(feature = "std")] + /// 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, - 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, + mut self: Box, 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[..]); - 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]; @@ -297,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(); @@ -311,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, @@ -337,17 +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 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: [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)] @@ -355,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[..])); @@ -374,48 +365,15 @@ impl Responder { encryptor, decryptor, }; - self.erase(); 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 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, - 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, &self.a, 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. 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 @@ -427,7 +385,6 @@ impl Responder { self.h.zeroize(); self.e.non_secure_erase(); self.s.non_secure_erase(); - self.a.non_secure_erase(); } } @@ -444,38 +401,52 @@ mod test { use super::*; - fn make_responder() -> Responder { + fn make_responder() -> Box { use rand::{rngs::StdRng, SeedableRng}; + use secp256k1::Secp256k1; let secp = Secp256k1::new(); 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 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(); @@ -489,21 +460,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 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(); @@ -514,25 +480,15 @@ 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_before = responder.a.secret_key().secret_bytes(); - 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_with_now_rng(fake_initiator_ephemeral, 100, &mut rng) - .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.a.secret_key().secret_bytes(), 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/signature_message.rs b/sv2/noise-sv2/src/signature_message.rs index 5fe3db13f7..b8968ba867 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 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,89 +97,76 @@ 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 the + /// 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: &XOnlyPublicKey) -> 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 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. - /// - /// # Security + /// with [`CERTIFICATE_TIME_LEEWAY`] seconds of tolerance. /// - /// 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. #[inline] pub fn verify_with_now( - self, - pk: &XOnlyPublicKey, - authority_pk: &Option, + &self, + static_pk: &XOnlyPublicKey, + authority_pk: &XOnlyPublicKey, 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 + // 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 +175,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 +209,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 +231,19 @@ 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); - assert!(!certificate.verify_with_now( - &responder_static.x_only_public_key().0, - &authority_pk, - 150, - )); + 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, &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(&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 1f3dd4244f..b4d4891bbe 100644 --- a/sv2/noise-sv2/src/test.rs +++ b/sv2/noise-sv2/src/test.rs @@ -6,8 +6,8 @@ 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 responder = Responder::new(key_pair, 31449600); + let mut initiator = Initiator::new(key_pair.public_key().into()); + 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(); @@ -25,16 +25,14 @@ 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()); - let mut responder = Responder::new_with_rng(key_pair, 31449600, &mut rand::thread_rng()); - let first_message = initiator.step_0().unwrap(); + Initiator::new_with_rng(key_pair.public_key().into(), &mut rand::thread_rng()); 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 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() @@ -47,3 +45,68 @@ 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 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)] +fn pre_issued_certificate_is_sent_verbatim() { + 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| { + SignatureNoiseMessage::sign( + valid_from, + not_valid_after, + &server_static.x_only_public_key().0, + &authority, + ) + }; + let handshake = |certificate| { + let mut initiator = Initiator::new(authority.public_key().into()); + 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 + .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(_)) + )); +}