Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions fuzz/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions stratum-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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" }
Expand Down
4 changes: 2 additions & 2 deletions sv2/codec-sv2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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 }
Expand Down
10 changes: 8 additions & 2 deletions sv2/codec-sv2/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 8 additions & 2 deletions sv2/codec-sv2/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion sv2/noise-sv2/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "noise_sv2"
version = "2.1.0"
version = "3.0.0"
authors = ["The Stratum V2 Developers"]
edition = "2021"
readme = "README.md"
Expand Down
2 changes: 1 addition & 1 deletion sv2/noise-sv2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. `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.
Expand Down
12 changes: 9 additions & 3 deletions sv2/noise-sv2/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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,
Expand Down
90 changes: 52 additions & 38 deletions sv2/noise-sv2/src/initiator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -149,16 +149,17 @@ 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
///
/// 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")]
Expand Down Expand Up @@ -232,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
Expand Down Expand Up @@ -292,19 +292,21 @@ 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. 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.
Expand Down Expand Up @@ -381,7 +383,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();
Expand All @@ -397,29 +400,40 @@ 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<ChaCha20Poly1305> = Cipher::from_key_and_cipher(temp_k1, c1);
let c2: Cipher<ChaCha20Poly1305> = 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<ChaCha20Poly1305> = Cipher::from_key_and_cipher(temp_k1, c1);
let c2: Cipher<ChaCha20Poly1305> = 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,
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)
}

// Securely erases sensitive data from the [`Initiator`] memory.
Expand Down
41 changes: 37 additions & 4 deletions sv2/noise-sv2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,25 @@
//! ## 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
//! 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
//!
//! 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.
//!
//! 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.

#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]

Expand Down Expand Up @@ -98,6 +112,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 <https://github.com/stratum-mining/stratum/issues/2015>.
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
Expand Down Expand Up @@ -126,6 +145,9 @@ pub struct NoiseEngine {

// Cipher to decrypt incoming messages.
decryptor: Cipher<ChaCha20Poly1305>,

// The responder's certificate, kept only when it was verified against an authority key.
certificate: Option<Certificate>,
}

impl core::fmt::Debug for NoiseEngine {
Expand All @@ -135,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<T: Buffer>(&mut self, msg: &mut T) -> Result<(), AeadError> {
self.encryptor.encrypt(msg)
Expand Down Expand Up @@ -197,3 +229,4 @@ impl NoiseDecryptor {
pub use error::Error;
pub use initiator::Initiator;
pub use responder::Responder;
pub use signature_message::{Certificate, CertificateError, SignatureNoiseMessage};
Loading
Loading