feat: M1 — Noise transport, Cap'n Proto framing, Ping/Pong
Establishes the foundational transport layer for noiseml: - Noise_XX_25519_ChaChaPoly_BLAKE2s handshake (initiator + responder) via `snow`; mutual authentication of static X25519 keys guaranteed before any application data flows. - Length-prefixed frame codec (4-byte LE u32, max 65 535 B per Noise spec) implemented as a Tokio Encoder/Decoder pair. - Cap'n Proto Envelope schema with MsgType enum (Ping, Pong, and future MLS message types defined but not yet dispatched). - Server: TCP listener, one Tokio task per connection, Ping→Pong handler, fresh X25519 keypair logged at startup. - Client: `ping` subcommand — handshake, send Ping, receive Pong, print RTT, exit 0. - Integration tests: bidirectional Ping/Pong with mutual-auth verification; server keypair reuse across sequential connections. - Docker multi-stage build (rust:bookworm → debian:bookworm-slim, non-root) and docker-compose with TCP healthcheck. No MLS group state, no AS/DS, no persistence — out of scope for M1.
This commit is contained in:
32
crates/noiseml-core/Cargo.toml
Normal file
32
crates/noiseml-core/Cargo.toml
Normal file
@@ -0,0 +1,32 @@
|
||||
[package]
|
||||
name = "noiseml-core"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Crypto primitives, Noise_XX transport, MLS state machine, and Cap'n Proto frame codec for noiseml."
|
||||
license = "MIT"
|
||||
|
||||
[dependencies]
|
||||
# Crypto
|
||||
# openmls / openmls_rust_crypto / openmls_basic_credential — added in M2
|
||||
# ml-kem — added in M5 (hybrid PQ ciphersuite)
|
||||
x25519-dalek = { workspace = true }
|
||||
ed25519-dalek = { workspace = true }
|
||||
snow = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
hkdf = { workspace = true }
|
||||
zeroize = { workspace = true }
|
||||
rand = { workspace = true }
|
||||
|
||||
# Serialisation
|
||||
capnp = { workspace = true }
|
||||
noiseml-proto = { path = "../noiseml-proto" }
|
||||
|
||||
# Async codec
|
||||
tokio-util = { workspace = true }
|
||||
bytes = { version = "1" }
|
||||
|
||||
# Error handling
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
204
crates/noiseml-core/src/codec.rs
Normal file
204
crates/noiseml-core/src/codec.rs
Normal file
@@ -0,0 +1,204 @@
|
||||
//! Length-prefixed byte frame codec for Tokio's `Framed` adapter.
|
||||
//!
|
||||
//! # Wire format
|
||||
//!
|
||||
//! ```text
|
||||
//! ┌──────────────────────────┬──────────────────────────────────────┐
|
||||
//! │ length (4 bytes, LE u32)│ payload (length bytes) │
|
||||
//! └──────────────────────────┴──────────────────────────────────────┘
|
||||
//! ```
|
||||
//!
|
||||
//! Little-endian was chosen over big-endian for consistency with Cap'n Proto's
|
||||
//! own segment table encoding. Both sides of the connection use the same codec.
|
||||
//!
|
||||
//! # Usage
|
||||
//!
|
||||
//! This codec is transport-agnostic: during the Noise handshake it frames raw
|
||||
//! Noise handshake messages; after the handshake it frames Noise-encrypted
|
||||
//! application data. In both cases the payload is opaque bytes from the
|
||||
//! codec's perspective.
|
||||
//!
|
||||
//! # Frame size limit
|
||||
//!
|
||||
//! The Noise protocol specifies a maximum message size of 65 535 bytes.
|
||||
//! Frames larger than [`NOISE_MAX_MSG`] are rejected as protocol violations.
|
||||
|
||||
use bytes::{Buf, BufMut, Bytes, BytesMut};
|
||||
use tokio_util::codec::{Decoder, Encoder};
|
||||
|
||||
use crate::error::CodecError;
|
||||
|
||||
/// Maximum Noise protocol message size in bytes (per RFC / Noise spec §3).
|
||||
pub const NOISE_MAX_MSG: usize = 65_535;
|
||||
|
||||
/// A stateless codec that prepends / reads a 4-byte little-endian length field.
|
||||
///
|
||||
/// Implements both [`Encoder<Bytes>`] and [`Decoder`] so it can be used with
|
||||
/// `tokio_util::codec::Framed`.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct LengthPrefixedCodec;
|
||||
|
||||
impl LengthPrefixedCodec {
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
}
|
||||
|
||||
impl Encoder<Bytes> for LengthPrefixedCodec {
|
||||
type Error = CodecError;
|
||||
|
||||
/// Prepend a 4-byte LE length field and append the payload to `dst`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`CodecError::FrameTooLarge`] if `item.len() > NOISE_MAX_MSG`.
|
||||
/// Returns [`CodecError::Io`] if the underlying write fails (propagated
|
||||
/// by `tokio-util` from the TCP stream).
|
||||
fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
|
||||
let len = item.len();
|
||||
if len > NOISE_MAX_MSG {
|
||||
return Err(CodecError::FrameTooLarge {
|
||||
len,
|
||||
max: NOISE_MAX_MSG,
|
||||
});
|
||||
}
|
||||
// Reserve exactly the space needed: 4 bytes header + payload.
|
||||
dst.reserve(4 + len);
|
||||
dst.put_u32_le(len as u32);
|
||||
dst.extend_from_slice(&item);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Decoder for LengthPrefixedCodec {
|
||||
type Item = BytesMut;
|
||||
type Error = CodecError;
|
||||
|
||||
/// Read a length-prefixed frame from `src`.
|
||||
///
|
||||
/// Returns `Ok(None)` when more bytes are needed (standard Decoder contract).
|
||||
/// Returns `Ok(Some(frame))` when a complete frame is available.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`CodecError::FrameTooLarge`] if the length field exceeds
|
||||
/// [`NOISE_MAX_MSG`]. This is treated as an unrecoverable protocol
|
||||
/// violation — callers should close the connection.
|
||||
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
|
||||
// Need at least the 4-byte length header.
|
||||
if src.len() < 4 {
|
||||
src.reserve(4_usize.saturating_sub(src.len()));
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Peek at the length without advancing — avoid mutating state on None.
|
||||
let frame_len =
|
||||
u32::from_le_bytes([src[0], src[1], src[2], src[3]]) as usize;
|
||||
|
||||
if frame_len > NOISE_MAX_MSG {
|
||||
return Err(CodecError::FrameTooLarge {
|
||||
len: frame_len,
|
||||
max: NOISE_MAX_MSG,
|
||||
});
|
||||
}
|
||||
|
||||
let total = 4 + frame_len;
|
||||
if src.len() < total {
|
||||
// Tell Tokio how many additional bytes we need to avoid O(n) polling.
|
||||
src.reserve(total - src.len());
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Consume the 4-byte length header, then split the payload.
|
||||
src.advance(4);
|
||||
Ok(Some(src.split_to(frame_len)))
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn encode_then_decode(payload: &[u8]) -> BytesMut {
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
codec
|
||||
.encode(Bytes::copy_from_slice(payload), &mut buf)
|
||||
.expect("encode failed");
|
||||
let decoded = codec.decode(&mut buf).expect("decode error");
|
||||
decoded.expect("expected a complete frame")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_empty_payload() {
|
||||
let result = encode_then_decode(&[]);
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_small_payload() {
|
||||
let payload = b"hello noiseml";
|
||||
let result = encode_then_decode(payload);
|
||||
assert_eq!(&result[..], payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_max_size_payload() {
|
||||
let payload = vec![0xAB_u8; NOISE_MAX_MSG];
|
||||
let result = encode_then_decode(&payload);
|
||||
assert_eq!(&result[..], &payload[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_encode_returns_error() {
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
let oversized = Bytes::from(vec![0u8; NOISE_MAX_MSG + 1]);
|
||||
let err = codec.encode(oversized, &mut buf).unwrap_err();
|
||||
assert!(matches!(err, CodecError::FrameTooLarge { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_length_field_decode_returns_error() {
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
// Encode a fake length field that exceeds NOISE_MAX_MSG.
|
||||
buf.put_u32_le((NOISE_MAX_MSG + 1) as u32);
|
||||
let err = codec.decode(&mut buf).unwrap_err();
|
||||
assert!(matches!(err, CodecError::FrameTooLarge { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_payload_returns_none() {
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
// Length header says 10 bytes but we only provide 5.
|
||||
buf.put_u32_le(10);
|
||||
buf.extend_from_slice(&[0u8; 5]);
|
||||
let result = codec.decode(&mut buf).expect("decode error");
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_header_returns_none() {
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
// Only 2 bytes of the 4-byte header are available.
|
||||
let mut buf = BytesMut::from(&[0x00_u8, 0x01][..]);
|
||||
let result = codec.decode(&mut buf).expect("decode error");
|
||||
assert!(result.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_field_is_little_endian() {
|
||||
let payload = b"le-check";
|
||||
let mut codec = LengthPrefixedCodec::new();
|
||||
let mut buf = BytesMut::new();
|
||||
codec
|
||||
.encode(Bytes::from_static(payload), &mut buf)
|
||||
.expect("encode failed");
|
||||
// First 4 bytes are the LE length: 8 in LE is [0x08, 0x00, 0x00, 0x00].
|
||||
assert_eq!(&buf[..4], &[8, 0, 0, 0]);
|
||||
}
|
||||
}
|
||||
71
crates/noiseml-core/src/error.rs
Normal file
71
crates/noiseml-core/src/error.rs
Normal file
@@ -0,0 +1,71 @@
|
||||
//! Error types for `noiseml-core`.
|
||||
//!
|
||||
//! Two separate error types are used to preserve type-level separation of concerns:
|
||||
//!
|
||||
//! - [`CodecError`] — errors from the length-prefixed frame codec (I/O and framing only).
|
||||
//! `tokio-util` requires the codec error implement `From<io::Error>`.
|
||||
//!
|
||||
//! - [`CoreError`] — errors from the Noise handshake and transport layer.
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// Maximum plaintext bytes per Noise transport frame.
|
||||
///
|
||||
/// Noise limits each message to 65 535 bytes. ChaCha20-Poly1305 consumes
|
||||
/// 16 bytes for the authentication tag, leaving 65 519 bytes for plaintext.
|
||||
pub const MAX_PLAINTEXT_LEN: usize = 65_519;
|
||||
|
||||
// ── Codec errors ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// Errors produced by [`LengthPrefixedCodec`](crate::LengthPrefixedCodec).
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CodecError {
|
||||
/// The underlying TCP stream returned an I/O error.
|
||||
///
|
||||
/// This variant satisfies the `tokio-util` requirement that codec error
|
||||
/// types implement `From<std::io::Error>`.
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
|
||||
/// A frame length field exceeded the Noise protocol maximum (65 535 bytes).
|
||||
///
|
||||
/// This is treated as a protocol violation and the connection should be
|
||||
/// closed rather than retried.
|
||||
#[error("frame length {len} exceeds maximum {max} bytes")]
|
||||
FrameTooLarge { len: usize, max: usize },
|
||||
}
|
||||
|
||||
// ── Core errors ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Errors produced by the Noise handshake and [`NoiseTransport`](crate::NoiseTransport).
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CoreError {
|
||||
/// The `snow` Noise protocol engine returned an error.
|
||||
///
|
||||
/// This covers DH failures, decryption failures, state machine violations,
|
||||
/// and pattern parse errors.
|
||||
#[error("Noise protocol error: {0}")]
|
||||
Noise(#[from] snow::Error),
|
||||
|
||||
/// The frame codec reported an I/O or framing error.
|
||||
#[error("frame codec error: {0}")]
|
||||
Codec(#[from] CodecError),
|
||||
|
||||
/// Cap'n Proto serialisation or deserialisation failed.
|
||||
#[error("Cap'n Proto error: {0}")]
|
||||
Capnp(#[from] capnp::Error),
|
||||
|
||||
/// The remote peer closed the connection before the handshake completed.
|
||||
#[error("peer closed connection during Noise handshake")]
|
||||
HandshakeIncomplete,
|
||||
|
||||
/// The remote peer closed the connection during normal operation.
|
||||
#[error("peer closed connection")]
|
||||
ConnectionClosed,
|
||||
|
||||
/// The caller attempted to send a plaintext larger than the Noise maximum.
|
||||
///
|
||||
/// The limit is [`MAX_PLAINTEXT_LEN`] bytes per frame.
|
||||
#[error("plaintext {size} B exceeds Noise frame limit of {MAX_PLAINTEXT_LEN} B")]
|
||||
MessageTooLarge { size: usize },
|
||||
}
|
||||
119
crates/noiseml-core/src/keypair.rs
Normal file
119
crates/noiseml-core/src/keypair.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Static X25519 keypair for the Noise_XX handshake.
|
||||
//!
|
||||
//! # Security properties
|
||||
//!
|
||||
//! - The private key is stored as [`x25519_dalek::StaticSecret`], which
|
||||
//! implements [`ZeroizeOnDrop`](zeroize::ZeroizeOnDrop) — the key material
|
||||
//! is overwritten with zeros when the `StaticSecret` is dropped.
|
||||
//!
|
||||
//! - [`NoiseKeypair::private_bytes`] returns a [`Zeroizing`](zeroize::Zeroizing)
|
||||
//! wrapper so the caller's copy of the raw bytes is also cleared on drop.
|
||||
//! Pass it directly to `snow::Builder::local_private_key` and let it fall
|
||||
//! out of scope immediately after.
|
||||
//!
|
||||
//! - The public key is not secret and may be freely cloned or logged.
|
||||
//!
|
||||
//! # Persistence
|
||||
//!
|
||||
//! `NoiseKeypair` does not implement `Serialize` intentionally. Key persistence
|
||||
//! to disk is handled at the application layer (M6) with appropriate file
|
||||
//! permission checks and, optionally, passphrase-based encryption.
|
||||
|
||||
use rand::rngs::OsRng;
|
||||
use x25519_dalek::{PublicKey, StaticSecret};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// A static X25519 keypair used for Noise_XX mutual authentication.
|
||||
///
|
||||
/// Generate once per node identity and reuse across connections.
|
||||
/// The private scalar is zeroized when this value is dropped.
|
||||
pub struct NoiseKeypair {
|
||||
/// Private scalar — zeroized on drop via `x25519_dalek`'s `ZeroizeOnDrop` impl.
|
||||
private: StaticSecret,
|
||||
/// Corresponding public key — derived from `private` at construction time.
|
||||
public: PublicKey,
|
||||
}
|
||||
|
||||
impl NoiseKeypair {
|
||||
/// Generate a fresh keypair from the OS CSPRNG.
|
||||
///
|
||||
/// This calls `getrandom` on Linux (via `OsRng`) and is suitable for
|
||||
/// generating long-lived static identity keys.
|
||||
pub fn generate() -> Self {
|
||||
let private = StaticSecret::random_from_rng(OsRng);
|
||||
let public = PublicKey::from(&private);
|
||||
Self { private, public }
|
||||
}
|
||||
|
||||
/// Return the raw private key bytes in a [`Zeroizing`] wrapper.
|
||||
///
|
||||
/// The returned wrapper clears the 32-byte copy when dropped.
|
||||
/// Use it immediately to initialise a `snow::Builder` and let it drop:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// let private = keypair.private_bytes();
|
||||
/// let session = snow::Builder::new(params)
|
||||
/// .local_private_key(&private[..])
|
||||
/// .build_initiator()?;
|
||||
/// // `private` is zeroized here.
|
||||
/// ```
|
||||
pub fn private_bytes(&self) -> Zeroizing<[u8; 32]> {
|
||||
Zeroizing::new(self.private.to_bytes())
|
||||
}
|
||||
|
||||
/// Return the public key bytes.
|
||||
///
|
||||
/// Safe to log or transmit — this is not secret material.
|
||||
pub fn public_bytes(&self) -> [u8; 32] {
|
||||
self.public.to_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent accidental `{:?}` printing of the private key.
|
||||
impl std::fmt::Debug for NoiseKeypair {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Show only the first 4 bytes of the public key as a sanity identifier.
|
||||
// No external crate needed; the private key is never printed.
|
||||
let pub_bytes = self.public_bytes();
|
||||
write!(
|
||||
f,
|
||||
"NoiseKeypair {{ public: {:02x}{:02x}{:02x}{:02x}…, private: [redacted] }}",
|
||||
pub_bytes[0], pub_bytes[1], pub_bytes[2], pub_bytes[3],
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generated_public_key_matches_private() {
|
||||
let kp = NoiseKeypair::generate();
|
||||
// Re-derive the public key from the private bytes and confirm they match.
|
||||
let private_bytes = kp.private_bytes();
|
||||
let secret = StaticSecret::from(*private_bytes);
|
||||
let rederived = PublicKey::from(&secret);
|
||||
assert_eq!(rederived.to_bytes(), kp.public_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_keypairs_differ() {
|
||||
let a = NoiseKeypair::generate();
|
||||
let b = NoiseKeypair::generate();
|
||||
assert_ne!(a.public_bytes(), b.public_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn private_bytes_is_zeroizing() {
|
||||
// Verify that Zeroizing<[u8;32]> does not expose the key via Debug.
|
||||
let kp = NoiseKeypair::generate();
|
||||
let private = kp.private_bytes();
|
||||
// We cannot observe zeroization after drop in a test without unsafe,
|
||||
// but we can confirm the wrapper type is returned and is non-zero.
|
||||
assert!(private.iter().any(|&b| b != 0),
|
||||
"freshly generated private key should not be all zeros");
|
||||
}
|
||||
}
|
||||
28
crates/noiseml-core/src/lib.rs
Normal file
28
crates/noiseml-core/src/lib.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Core cryptographic primitives, Noise_XX transport, and frame codec for noiseml.
|
||||
//!
|
||||
//! # Module layout
|
||||
//!
|
||||
//! | Module | Responsibility |
|
||||
//! |------------|----------------------------------------------------------|
|
||||
//! | `error` | [`CoreError`] and [`CodecError`] types |
|
||||
//! | `keypair` | [`NoiseKeypair`] — static X25519 key, zeroize-on-drop |
|
||||
//! | `codec` | [`LengthPrefixedCodec`] — Tokio Encoder + Decoder |
|
||||
//! | `noise` | [`handshake_initiator`], [`handshake_responder`], [`NoiseTransport`] |
|
||||
//!
|
||||
//! # What is NOT in this crate (M1)
|
||||
//!
|
||||
//! - MLS group state machine — added in M2/M3 (`openmls` integration)
|
||||
//! - Hybrid PQ KEM — added in M5
|
||||
//! - Ed25519 identity keypair — added in M2 (needed for MLS credentials)
|
||||
|
||||
mod codec;
|
||||
mod error;
|
||||
mod keypair;
|
||||
mod noise;
|
||||
|
||||
// ── Public API ────────────────────────────────────────────────────────────────
|
||||
|
||||
pub use codec::{LengthPrefixedCodec, NOISE_MAX_MSG};
|
||||
pub use error::{CodecError, CoreError, MAX_PLAINTEXT_LEN};
|
||||
pub use keypair::NoiseKeypair;
|
||||
pub use noise::{handshake_initiator, handshake_responder, NoiseTransport};
|
||||
325
crates/noiseml-core/src/noise.rs
Normal file
325
crates/noiseml-core/src/noise.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
//! Noise_XX handshake and encrypted transport.
|
||||
//!
|
||||
//! # Protocol
|
||||
//!
|
||||
//! Pattern: `Noise_XX_25519_ChaChaPoly_BLAKE2s`
|
||||
//!
|
||||
//! ```text
|
||||
//! XX handshake (3 messages):
|
||||
//! -> e (initiator sends ephemeral public key)
|
||||
//! <- e, ee, s, es (responder replies; mutual DH + responder static)
|
||||
//! -> s, se (initiator sends static key; final DH)
|
||||
//! ```
|
||||
//!
|
||||
//! After the handshake both peers have authenticated each other's static X25519
|
||||
//! keys and negotiated a symmetric session with ChaCha20-Poly1305.
|
||||
//!
|
||||
//! # Framing
|
||||
//!
|
||||
//! All messages — handshake and application — are carried in length-prefixed
|
||||
//! frames (see [`LengthPrefixedCodec`](crate::LengthPrefixedCodec)).
|
||||
//!
|
||||
//! In the handshake phase the frame payload is the raw Noise handshake bytes
|
||||
//! produced by `snow`. In the transport phase the frame payload is a
|
||||
//! Noise-encrypted Cap'n Proto message.
|
||||
//!
|
||||
//! # Post-quantum gap (ADR-006)
|
||||
//!
|
||||
//! The Noise transport uses classical X25519. PQ-Noise is not yet standardised
|
||||
//! in `snow`. MLS application data is PQ-protected from M5 onward. The residual
|
||||
//! risk (metadata exposure via handshake harvest) is accepted for M1–M5.
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_util::codec::Framed;
|
||||
|
||||
use crate::{
|
||||
codec::{LengthPrefixedCodec, NOISE_MAX_MSG},
|
||||
error::{CoreError, MAX_PLAINTEXT_LEN},
|
||||
keypair::NoiseKeypair,
|
||||
};
|
||||
use noiseml_proto::{parse_envelope, build_envelope, ParsedEnvelope};
|
||||
|
||||
/// Noise parameters used throughout noiseml.
|
||||
///
|
||||
/// `Noise_XX_25519_ChaChaPoly_BLAKE2s` — both parties authenticate each
|
||||
/// other's static X25519 keys; ChaCha20-Poly1305 for AEAD; BLAKE2s as PRF.
|
||||
const NOISE_PARAMS: &str = "Noise_XX_25519_ChaChaPoly_BLAKE2s";
|
||||
|
||||
/// ChaCha20-Poly1305 authentication tag overhead per Noise message.
|
||||
const NOISE_TAG_LEN: usize = 16;
|
||||
|
||||
// ── Public type ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// An authenticated, encrypted Noise transport session.
|
||||
///
|
||||
/// Obtained by completing a [`handshake_initiator`] or [`handshake_responder`]
|
||||
/// call. All subsequent I/O is through [`send_frame`](Self::send_frame) and
|
||||
/// [`recv_frame`](Self::recv_frame), or the higher-level envelope helpers.
|
||||
///
|
||||
/// # Thread safety
|
||||
///
|
||||
/// `NoiseTransport` is `Send` but not `Clone` or `Sync`. Use one instance per
|
||||
/// Tokio task; use message passing to share data across tasks.
|
||||
pub struct NoiseTransport {
|
||||
/// The TCP stream wrapped in the length-prefix codec.
|
||||
framed: Framed<TcpStream, LengthPrefixedCodec>,
|
||||
/// The Noise session in transport mode — encrypts and decrypts frames.
|
||||
session: snow::TransportState,
|
||||
/// Remote peer's static X25519 public key, captured from the HandshakeState
|
||||
/// before `into_transport_mode()` consumes it.
|
||||
///
|
||||
/// Stored here explicitly rather than via `TransportState::get_remote_static()`
|
||||
/// because snow does not guarantee the method survives the mode transition.
|
||||
remote_static: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl NoiseTransport {
|
||||
// ── Transport-layer I/O ───────────────────────────────────────────────────
|
||||
|
||||
/// Encrypt `plaintext` and send it as a single length-prefixed frame.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`CoreError::MessageTooLarge`] if `plaintext` exceeds
|
||||
/// [`MAX_PLAINTEXT_LEN`] bytes.
|
||||
/// - [`CoreError::Noise`] if the Noise session fails to encrypt.
|
||||
/// - [`CoreError::Codec`] if the underlying TCP write fails.
|
||||
pub async fn send_frame(&mut self, plaintext: &[u8]) -> Result<(), CoreError> {
|
||||
if plaintext.len() > MAX_PLAINTEXT_LEN {
|
||||
return Err(CoreError::MessageTooLarge {
|
||||
size: plaintext.len(),
|
||||
});
|
||||
}
|
||||
|
||||
// Allocate exactly the right amount: plaintext + AEAD tag.
|
||||
let mut ciphertext = vec![0u8; plaintext.len() + NOISE_TAG_LEN];
|
||||
let len = self
|
||||
.session
|
||||
.write_message(plaintext, &mut ciphertext)
|
||||
.map_err(CoreError::Noise)?;
|
||||
|
||||
self.framed
|
||||
.send(Bytes::copy_from_slice(&ciphertext[..len]))
|
||||
.await
|
||||
.map_err(CoreError::Codec)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Receive the next length-prefixed frame and decrypt it.
|
||||
///
|
||||
/// Awaits until a complete frame arrives on the TCP stream.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`CoreError::ConnectionClosed`] if the peer closed the connection.
|
||||
/// - [`CoreError::Noise`] if decryption or authentication fails.
|
||||
/// - [`CoreError::Codec`] if the underlying TCP read or framing fails.
|
||||
pub async fn recv_frame(&mut self) -> Result<Vec<u8>, CoreError> {
|
||||
let ciphertext = self
|
||||
.framed
|
||||
.next()
|
||||
.await
|
||||
.ok_or(CoreError::ConnectionClosed)?
|
||||
.map_err(CoreError::Codec)?;
|
||||
|
||||
// Plaintext is always shorter than ciphertext (AEAD tag is stripped).
|
||||
let mut plaintext = vec![0u8; ciphertext.len()];
|
||||
let len = self
|
||||
.session
|
||||
.read_message(&ciphertext, &mut plaintext)
|
||||
.map_err(CoreError::Noise)?;
|
||||
|
||||
plaintext.truncate(len);
|
||||
Ok(plaintext)
|
||||
}
|
||||
|
||||
// ── Envelope-level I/O ────────────────────────────────────────────────────
|
||||
|
||||
/// Serialise and encrypt a [`ParsedEnvelope`], then send it.
|
||||
///
|
||||
/// This is the primary application-level send method. The Cap'n Proto
|
||||
/// encoding is done by [`noiseml_proto::build_envelope`] before encryption.
|
||||
pub async fn send_envelope(&mut self, env: &ParsedEnvelope) -> Result<(), CoreError> {
|
||||
let bytes = build_envelope(env).map_err(CoreError::Capnp)?;
|
||||
self.send_frame(&bytes).await
|
||||
}
|
||||
|
||||
/// Receive a frame, decrypt it, and deserialise it as a [`ParsedEnvelope`].
|
||||
///
|
||||
/// This is the primary application-level receive method.
|
||||
pub async fn recv_envelope(&mut self) -> Result<ParsedEnvelope, CoreError> {
|
||||
let bytes = self.recv_frame().await?;
|
||||
parse_envelope(&bytes).map_err(CoreError::Capnp)
|
||||
}
|
||||
|
||||
// ── Session metadata ──────────────────────────────────────────────────────
|
||||
|
||||
/// Return the remote peer's static X25519 public key (32 bytes), as
|
||||
/// authenticated during the Noise_XX handshake.
|
||||
///
|
||||
/// Returns `None` only in the impossible case where the XX handshake
|
||||
/// completed without exchanging static keys (a snow implementation bug).
|
||||
/// In practice this is always `Some` after a successful handshake.
|
||||
pub fn remote_static_public_key(&self) -> Option<&[u8]> {
|
||||
self.remote_static.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NoiseTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let remote = self.remote_static.as_deref().map(|k| {
|
||||
format!("{:02x}{:02x}{:02x}{:02x}…", k[0], k[1], k[2], k[3])
|
||||
});
|
||||
f.debug_struct("NoiseTransport")
|
||||
.field("remote_static", &remote)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// ── Handshake functions ───────────────────────────────────────────────────────
|
||||
|
||||
/// Complete a Noise_XX handshake as the **initiator** over `stream`.
|
||||
///
|
||||
/// The initiator sends the first handshake message. After the three-message
|
||||
/// exchange completes, the function returns an authenticated [`NoiseTransport`]
|
||||
/// ready for application data.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// - [`CoreError::HandshakeIncomplete`] if the peer closes the connection mid-handshake.
|
||||
/// - [`CoreError::Noise`] if any Noise operation fails (pattern mismatch, bad DH, etc.).
|
||||
/// - [`CoreError::Codec`] if any TCP I/O fails during the handshake.
|
||||
pub async fn handshake_initiator(
|
||||
stream: TcpStream,
|
||||
keypair: &NoiseKeypair,
|
||||
) -> Result<NoiseTransport, CoreError> {
|
||||
let params: snow::params::NoiseParams = NOISE_PARAMS.parse().expect(
|
||||
"NOISE_PARAMS is a compile-time constant and must parse successfully",
|
||||
);
|
||||
|
||||
// The private key bytes are held in a Zeroizing wrapper and cleared after
|
||||
// snow clones them internally during build_initiator().
|
||||
let private = keypair.private_bytes();
|
||||
let mut session = snow::Builder::new(params)
|
||||
.local_private_key(&private[..])
|
||||
.build_initiator()
|
||||
.map_err(CoreError::Noise)?;
|
||||
drop(private); // zeroize our copy; snow holds its own internal copy
|
||||
|
||||
let mut framed = Framed::new(stream, LengthPrefixedCodec::new());
|
||||
let mut buf = vec![0u8; NOISE_MAX_MSG];
|
||||
|
||||
// ── Message 1: -> e ──────────────────────────────────────────────────────
|
||||
let len = session
|
||||
.write_message(&[], &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
framed
|
||||
.send(Bytes::copy_from_slice(&buf[..len]))
|
||||
.await
|
||||
.map_err(CoreError::Codec)?;
|
||||
|
||||
// ── Message 2: <- e, ee, s, es ───────────────────────────────────────────
|
||||
let msg2 = recv_handshake_frame(&mut framed).await?;
|
||||
session
|
||||
.read_message(&msg2, &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
|
||||
// ── Message 3: -> s, se ──────────────────────────────────────────────────
|
||||
let len = session
|
||||
.write_message(&[], &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
framed
|
||||
.send(Bytes::copy_from_slice(&buf[..len]))
|
||||
.await
|
||||
.map_err(CoreError::Codec)?;
|
||||
|
||||
// Zeroize the scratch buffer — it contained plaintext key material during
|
||||
// the handshake (ephemeral key bytes in message 2 payload).
|
||||
zeroize::Zeroize::zeroize(&mut buf);
|
||||
|
||||
// Capture the remote static key from HandshakeState before consuming it.
|
||||
let remote_static = session.get_remote_static().map(|k| k.to_vec());
|
||||
let transport_session = session.into_transport_mode().map_err(CoreError::Noise)?;
|
||||
Ok(NoiseTransport {
|
||||
framed,
|
||||
session: transport_session,
|
||||
remote_static,
|
||||
})
|
||||
}
|
||||
|
||||
/// Complete a Noise_XX handshake as the **responder** over `stream`.
|
||||
///
|
||||
/// The responder waits for the initiator's first message. After the
|
||||
/// three-message exchange completes, the function returns an authenticated
|
||||
/// [`NoiseTransport`] ready for application data.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Same as [`handshake_initiator`].
|
||||
pub async fn handshake_responder(
|
||||
stream: TcpStream,
|
||||
keypair: &NoiseKeypair,
|
||||
) -> Result<NoiseTransport, CoreError> {
|
||||
let params: snow::params::NoiseParams = NOISE_PARAMS.parse().expect(
|
||||
"NOISE_PARAMS is a compile-time constant and must parse successfully",
|
||||
);
|
||||
|
||||
let private = keypair.private_bytes();
|
||||
let mut session = snow::Builder::new(params)
|
||||
.local_private_key(&private[..])
|
||||
.build_responder()
|
||||
.map_err(CoreError::Noise)?;
|
||||
drop(private);
|
||||
|
||||
let mut framed = Framed::new(stream, LengthPrefixedCodec::new());
|
||||
let mut buf = vec![0u8; NOISE_MAX_MSG];
|
||||
|
||||
// ── Message 1: <- e ──────────────────────────────────────────────────────
|
||||
let msg1 = recv_handshake_frame(&mut framed).await?;
|
||||
session
|
||||
.read_message(&msg1, &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
|
||||
// ── Message 2: -> e, ee, s, es ───────────────────────────────────────────
|
||||
let len = session
|
||||
.write_message(&[], &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
framed
|
||||
.send(Bytes::copy_from_slice(&buf[..len]))
|
||||
.await
|
||||
.map_err(CoreError::Codec)?;
|
||||
|
||||
// ── Message 3: <- s, se ──────────────────────────────────────────────────
|
||||
let msg3 = recv_handshake_frame(&mut framed).await?;
|
||||
session
|
||||
.read_message(&msg3, &mut buf)
|
||||
.map_err(CoreError::Noise)?;
|
||||
|
||||
zeroize::Zeroize::zeroize(&mut buf);
|
||||
|
||||
// Capture the remote static key from HandshakeState before consuming it.
|
||||
let remote_static = session.get_remote_static().map(|k| k.to_vec());
|
||||
let transport_session = session.into_transport_mode().map_err(CoreError::Noise)?;
|
||||
Ok(NoiseTransport {
|
||||
framed,
|
||||
session: transport_session,
|
||||
remote_static,
|
||||
})
|
||||
}
|
||||
|
||||
// ── Private helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/// Read one handshake frame from `framed`, mapping stream closure to
|
||||
/// [`CoreError::HandshakeIncomplete`].
|
||||
async fn recv_handshake_frame(
|
||||
framed: &mut Framed<TcpStream, LengthPrefixedCodec>,
|
||||
) -> Result<bytes::BytesMut, CoreError> {
|
||||
framed
|
||||
.next()
|
||||
.await
|
||||
.ok_or(CoreError::HandshakeIncomplete)?
|
||||
.map_err(CoreError::Codec)
|
||||
}
|
||||
Reference in New Issue
Block a user