syncspin_core/noise.rs
1//! Sendspin's Noise layer: `Noise_KKpsk2_25519_<cipher>_SHA256`.
2//!
3//! Every Sendspin connection is wrapped in Noise. The handshake follows the cleartext init
4//! exchange and precedes all application traffic:
5//!
6//! ```text
7//! client -> server client/init cleartext JSON, carries the client_id and the suite
8//! server -> client server/init cleartext JSON, carries the server_id
9//! server -> client noise/handshake Noise message 1, payload {"psk_id": .., "psk_category": ..}
10//! client -> server noise/handshake Noise message 2, payload {}
11//! ```
12//!
13//! The server is always the Noise initiator and the client the responder, whichever side opened
14//! the WebSocket. Both static public keys are known before the handshake (`KK`), and the
15//! pre-shared key is mixed in at the end of the second message (`psk2`). The Noise prologue is
16//! the exact concatenation of the `client/init` and `server/init` bytes as sent on the wire, so
17//! tampering with the cleartext exchange fails the handshake.
18//!
19//! This module carries both halves of the handshake - [`Responder`] for the client, [`Initiator`]
20//! for the server - plus the transport that follows it. It does not interpret handshake payloads;
21//! the session layer validates the `psk_id`/`psk_category` metadata. This milestone uses the
22//! published Sentinel PSK, which is what an unpaired client uses and which provides no
23//! authentication on its own; selecting a different PSK from message 1 arrives with the session
24//! layer.
25//!
26//! # Cipher suites
27//!
28//! The specification defines two suites and requires a server to support both. [`Suite`] is the
29//! set this build has; a name outside it is refused. The client picks the suite and announces it
30//! in `client/init`, so there is no negotiation to fall back from: a responder built for another
31//! suite than the one announced is an error, not a downgrade.
32
33use std::fmt;
34
35use anyhow::{anyhow, bail, Context, Result};
36use base64::engine::general_purpose::URL_SAFE_NO_PAD;
37use base64::Engine as _;
38use sha2::{Digest, Sha256};
39use x25519_dalek::{PublicKey, StaticSecret};
40
41/// A Sendspin cipher suite: the `<DH>_<cipher>_<hash>` tail of a Noise protocol name.
42///
43/// The specification lists both of these and requires a server to have both; a client announces
44/// the one it uses in `client/init`. [`Suite::ChaChaPoly`] is the default because it is the suite
45/// this library has always spoken and the one its pairing wrapping was pinned against.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
47pub enum Suite {
48 /// `25519_ChaChaPoly_SHA256`, the software-friendly suite and the default.
49 #[default]
50 ChaChaPoly,
51 /// `25519_AESGCM_SHA256`, the hardware-accelerated suite.
52 AesGcm,
53}
54
55impl Suite {
56 /// Every suite this implementation has, in the order the specification lists them.
57 pub const ALL: [Suite; 2] = [Suite::ChaChaPoly, Suite::AesGcm];
58
59 /// The name `client/init` carries in `suite`, which is also the `<DH>_<cipher>_<hash>`
60 /// tail of the Noise protocol name.
61 pub const fn wire_name(self) -> &'static str {
62 match self {
63 Suite::ChaChaPoly => "25519_ChaChaPoly_SHA256",
64 Suite::AesGcm => "25519_AESGCM_SHA256",
65 }
66 }
67
68 /// The full Noise protocol name: `Noise_KKpsk2_` followed by [`Suite::wire_name`].
69 pub const fn params(self) -> &'static str {
70 match self {
71 Suite::ChaChaPoly => "Noise_KKpsk2_25519_ChaChaPoly_SHA256",
72 Suite::AesGcm => "Noise_KKpsk2_25519_AESGCM_SHA256",
73 }
74 }
75
76 /// Parses the suite name a `client/init` announces.
77 ///
78 /// `None` means this build does not have the suite. There is deliberately no fallback to
79 /// [`Suite::default`]: a caller that cannot honour the announced suite must refuse it.
80 pub fn from_wire_name(name: &str) -> Option<Suite> {
81 Suite::ALL
82 .into_iter()
83 .find(|suite| suite.wire_name() == name)
84 }
85}
86
87impl fmt::Display for Suite {
88 /// Writes the wire name, so an error names the suite the peer announced.
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(self.wire_name())
91 }
92}
93
94/// Noise protocol parameters of the default suite, [`Suite::ChaChaPoly`].
95pub const NOISE_PARAMS: &str = Suite::ChaChaPoly.params();
96
97/// The published Sentinel PSK, used whenever no paired PSK applies.
98///
99/// Its value is public, so it authenticates nothing. It exists so an unpaired client can
100/// connect before pairing establishes a private PSK.
101pub const SENTINEL_PSK: [u8; 32] = [
102 0x1b, 0x5e, 0x24, 0xdb, 0xc1, 0xae, 0xd9, 0x5f, 0xc2, 0xa5, 0xa3, 0x38, 0xa9, 0x0c, 0x05, 0xdf,
103 0x44, 0xbd, 0x10, 0xf5, 0xec, 0x1f, 0x4c, 0xd6, 0x6c, 0xbf, 0x86, 0x27, 0x27, 0x67, 0xb9, 0xd3,
104];
105
106/// The Sentinel PSK's published id, `psk_id_for(SENTINEL_PSK)`.
107pub const SENTINEL_PSK_ID: &str = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
108
109/// Maximum size of one Noise message, handshake or transport, including the authentication tag.
110///
111/// This is the Noise specification's limit; `snow` does not re-export the constant, so it is
112/// repeated here.
113pub const MAX_MESSAGE_LEN: usize = 65_535;
114
115/// Length of the authentication tag appended to every Noise transport ciphertext.
116pub const TAG_LEN: usize = 16;
117
118/// Largest plaintext that fits into one Noise transport message, including the leading binary
119/// message id byte.
120pub const MAX_PLAINTEXT_LEN: usize = MAX_MESSAGE_LEN - TAG_LEN;
121
122/// Label that Sendspin hashes together with a PSK to derive its id.
123const PSK_ID_LABEL: &[u8] = b"sendspin-psk-id-v1";
124
125/// Payload of Noise handshake message 2: the literal empty JSON object, not zero bytes.
126const HANDSHAKE_MESSAGE_2: &[u8] = b"{}";
127
128/// Unpadded base64url length of a 32-byte key.
129const KEY_CHARS: usize = 43;
130
131/// Derives a PSK id: `base64url(SHA-256("sendspin-psk-id-v1" || psk))`, without padding.
132///
133/// The id is what a server announces in `noise/handshake` message 1 so the client can select
134/// the matching PSK; it is a hash of the key and reveals nothing about its value.
135pub fn psk_id_for(psk: &[u8]) -> String {
136 let mut hasher = Sha256::new();
137 hasher.update(PSK_ID_LABEL);
138 hasher.update(psk);
139 URL_SAFE_NO_PAD.encode(hasher.finalize())
140}
141
142/// A long-lived X25519 keypair that identifies one side of a connection.
143///
144/// Sendspin uses the public key as the `client_id` or `server_id` and the secret key as the
145/// static key of the Noise handshake. Both halves must match: [`Identity::generate`] and
146/// [`Identity::from_secret_base64`] derive the public key from the secret, so an identity built
147/// through them always does.
148#[derive(Clone, Copy)]
149pub struct Identity {
150 /// Public X25519 key as 32 raw bytes; 43 base64url characters once encoded.
151 pub public: [u8; 32],
152 /// Secret X25519 key as 32 raw bytes. Never log this value.
153 pub secret: [u8; 32],
154}
155
156impl Identity {
157 /// Generates a fresh keypair from the operating system's CSPRNG.
158 ///
159 /// # Panics
160 ///
161 /// Panics if the operating system's CSPRNG is unavailable. That is not a recoverable
162 /// condition: a silent fallback would be a weak key.
163 pub fn generate() -> Identity {
164 let params = NOISE_PARAMS
165 .parse()
166 .expect("NOISE_PARAMS is a valid Noise protocol name");
167 let keypair = snow::Builder::new(params)
168 .generate_keypair()
169 .expect("the operating system CSPRNG is available");
170 let secret: [u8; 32] = keypair
171 .private
172 .as_slice()
173 .try_into()
174 .expect("an X25519 secret key is 32 bytes");
175 Identity::from_secret(secret)
176 }
177
178 /// Decodes an identity from its 43-character unpadded base64url secret key.
179 ///
180 /// The public key is derived from the secret. The input must be the canonical encoding of
181 /// exactly 32 bytes; a truncated, padded or non-base64url string is an error. Every 32-byte
182 /// value is a valid secret, so this cannot tell a secret key from a public key: passing a
183 /// public key such as [`Identity::public_base64`] succeeds and silently yields a different
184 /// identity.
185 pub fn from_secret_base64(s: &str) -> Result<Identity> {
186 let secret = decode_key(s).ok_or_else(|| {
187 anyhow!("identity secret is not a canonical 43-character unpadded base64url X25519 key")
188 })?;
189 Ok(Identity::from_secret(secret))
190 }
191
192 /// Returns the public key as 43-character unpadded base64url text.
193 ///
194 /// This is the value to send as `client_id` or `server_id`.
195 pub fn public_base64(&self) -> String {
196 URL_SAFE_NO_PAD.encode(self.public)
197 }
198
199 /// Returns the secret key as 43-character unpadded base64url text.
200 ///
201 /// The value is key material: hand it to [`Identity::from_secret_base64`] to restore an
202 /// identity and treat the text like a password.
203 pub fn secret_base64(&self) -> String {
204 URL_SAFE_NO_PAD.encode(self.secret)
205 }
206
207 /// Builds an identity whose public key is derived from `secret`.
208 fn from_secret(secret: [u8; 32]) -> Identity {
209 Identity {
210 public: public_key_for(&secret),
211 secret,
212 }
213 }
214
215 /// Rejects a hand-built identity whose two halves do not belong together.
216 fn validate(&self) -> Result<()> {
217 if public_key_for(&self.secret) != self.public {
218 bail!("identity public key does not match its secret key");
219 }
220 Ok(())
221 }
222}
223
224impl fmt::Debug for Identity {
225 /// Formats the public key and redacts the secret, so `Debug` output is safe to log.
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 f.debug_struct("Identity")
228 .field("public", &self.public_base64())
229 .field("secret", &"<redacted>")
230 .finish()
231 }
232}
233
234/// Noise responder state for one connection.
235pub struct Responder {
236 handshake: snow::HandshakeState,
237 /// The suite this handshake runs, kept for the transport and for callers that report it.
238 suite: Suite,
239}
240
241impl Responder {
242 /// Builds the responder for the client side of a Sendspin handshake, using the suite the
243 /// prologue's `client/init` announces.
244 ///
245 /// `prologue` must be the exact concatenation of the `client/init` and `server/init` bytes
246 /// as transmitted, in that order. It is mixed into the handshake verbatim, the initiator's
247 /// static public key is read from the `server_id` field of the `server/init` document it
248 /// contains, and the cipher suite from the `suite` field of `client/init`. A prologue that
249 /// is not a sequence of JSON documents, that carries no `server/init`, that carries two of
250 /// them, that announces no suite or that announces one this build does not have is
251 /// rejected; use [`Responder::with_peer`] when the key is already known, as during a
252 /// re-handshake where the prologue is the previous handshake hash.
253 pub fn new(identity: &Identity, prologue: &[u8]) -> Result<Responder> {
254 let peer_public = initiator_key_from_prologue(prologue)?;
255 let suite = suite_from_prologue(prologue)?;
256 Responder::with_peer_suite(identity, &peer_public, suite, prologue)
257 }
258
259 /// Builds the responder for the suite the prologue announces, refusing any other.
260 ///
261 /// This is [`Responder::new`] with an explicit choice, for a caller that must pin the suite.
262 /// A prologue whose `client/init` announces a different suite is an error: honouring the
263 /// caller's suite would hand the peer a handshake it cannot follow, and switching to the
264 /// announced one would be a silent downgrade of what the caller asked for.
265 pub fn with_suite(identity: &Identity, suite: Suite, prologue: &[u8]) -> Result<Responder> {
266 let peer_public = initiator_key_from_prologue(prologue)?;
267 let announced = suite_from_prologue(prologue)?;
268 if announced != suite {
269 bail!(
270 "the `client/init` in the prologue announces the cipher suite `{announced}`, so \
271 this handshake cannot run `{suite}`; a suite the peer did not announce is \
272 refused, never substituted"
273 );
274 }
275 Responder::with_peer_suite(identity, &peer_public, suite, prologue)
276 }
277
278 /// Builds the responder with the initiator's static public key supplied explicitly, for the
279 /// default suite [`Suite::ChaChaPoly`].
280 ///
281 /// Use this when the prologue is not the init exchange, for example on a re-handshake whose
282 /// prologue is the previous handshake hash. `prologue` still reaches Noise unchanged; both
283 /// sides must mix in the same bytes. A re-handshake must keep the suite of the connection it
284 /// replaces, so a caller that can offer more than one suite must use
285 /// [`Responder::with_peer_suite`] and pass the suite the connection already runs.
286 pub fn with_peer(
287 identity: &Identity,
288 peer_public: &[u8; 32],
289 prologue: &[u8],
290 ) -> Result<Responder> {
291 Responder::with_peer_suite(identity, peer_public, Suite::default(), prologue)
292 }
293
294 /// Builds the responder for an explicit peer key and suite.
295 ///
296 /// This is the constructor every other one ends in. It does not read the prologue, so it is
297 /// the one to use on a re-handshake, where the prologue is the previous handshake hash and
298 /// carries no announcement.
299 pub fn with_peer_suite(
300 identity: &Identity,
301 peer_public: &[u8; 32],
302 suite: Suite,
303 prologue: &[u8],
304 ) -> Result<Responder> {
305 identity.validate()?;
306
307 // Keep the published constant honest even if someone edits it.
308 debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
309
310 let params = suite
311 .params()
312 .parse()
313 .context("failed to parse the Noise protocol parameters")?;
314 let handshake = snow::Builder::new(params)
315 .local_private_key(&identity.secret)
316 .context("failed to set the local static key")?
317 .remote_public_key(peer_public)
318 .context("failed to set the peer static key")?
319 .psk(2, &SENTINEL_PSK)
320 .context("failed to set the handshake PSK")?
321 .prologue(prologue)
322 .context("failed to set the Noise prologue")?
323 .build_responder()
324 .context("failed to build the Noise responder")?;
325 Ok(Responder { handshake, suite })
326 }
327
328 /// Returns the cipher suite this handshake runs.
329 pub fn suite(&self) -> Suite {
330 self.suite
331 }
332
333 /// Replaces the pre-shared key used by the rest of the handshake.
334 ///
335 /// The responder starts with the published Sentinel PSK because the key is selected from the
336 /// metadata that message 1 carries. Call this after [`Responder::read_message`] and before
337 /// [`Responder::write_message`]: Noise mixes the key into message 2, so both sides must use
338 /// the same value and the initiator rejects a message sealed with another one.
339 ///
340 /// # Errors
341 /// Fails when the handshake has already mixed in the key, which makes a late change
342 /// impossible.
343 pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
344 self.handshake
345 .set_psk(2, psk)
346 .context("failed to set the Noise handshake PSK")
347 }
348
349 /// Reads one Noise handshake message and returns its decrypted payload.
350 ///
351 /// The payload is returned verbatim. Message 1 carries the PSK metadata
352 /// (`psk_id`, `psk_category`) for the session layer to validate; the handshake itself starts
353 /// with the Sentinel PSK, which [`Responder::set_psk`] can replace.
354 pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
355 read_handshake_payload(&mut self.handshake, msg)
356 }
357
358 /// Writes Noise handshake message 2 and returns it.
359 ///
360 /// The payload is the empty JSON object that Sendspin requires; it is not configurable.
361 pub fn write_message(&mut self) -> Result<Vec<u8>> {
362 write_handshake_payload(&mut self.handshake, HANDSHAKE_MESSAGE_2)
363 }
364
365 /// Returns whether both handshake messages have been processed.
366 pub fn handshake_finished(&self) -> bool {
367 self.handshake.is_handshake_finished()
368 }
369
370 /// Finishes the handshake and switches to transport mode.
371 ///
372 /// Fails if a handshake message is still outstanding, which
373 /// [`Responder::handshake_finished`] reports ahead of time.
374 pub fn into_transport(self) -> Result<TransportState> {
375 transport_from(self.handshake, self.suite)
376 }
377}
378
379/// Noise initiator state for one connection: the server half.
380///
381/// The server always sends the first handshake message, so this type produces message 1 and
382/// consumes message 2. It starts with the published Sentinel PSK; [`Initiator::set_psk`] selects
383/// the key the session will actually use, which message 1 must announce.
384///
385/// The suite is the one the client announced in `client/init`: a server must run exactly that one,
386/// because the client builds its responder for it. There is no fallback - [`Initiator::new`]
387/// refuses a prologue that announces another suite, and [`Initiator::with_announced_suite`] takes
388/// the suite from the announcement so the two cannot disagree.
389pub struct Initiator {
390 handshake: snow::HandshakeState,
391 /// The suite this handshake runs, kept for the transport and for callers that report it.
392 suite: Suite,
393}
394
395impl Initiator {
396 /// Builds the initiator for an explicit peer key and suite.
397 ///
398 /// `prologue` reaches Noise unchanged, so both sides must mix in the same bytes: the exact
399 /// `client/init` and `server/init` of a first handshake, or the previous handshake hash on a
400 /// re-handshake. When the prologue carries a `client/init`, the suite it announces must be
401 /// `suite`; a prologue that carries no announcement - a re-handshake hash, which is not
402 /// JSON - leaves `suite` as the only source, and a suite this build does not have is always
403 /// refused.
404 pub fn new(
405 identity: &Identity,
406 peer_public: &[u8; 32],
407 suite: Suite,
408 prologue: &[u8],
409 ) -> Result<Initiator> {
410 if let Some(announced) = announced_suite_from_prologue(prologue)? {
411 if announced != suite {
412 bail!(
413 "the `client/init` in the prologue announces the cipher suite `{announced}`, \
414 so this handshake cannot run `{suite}`; the suite a peer announced is \
415 refused when it differs, never substituted"
416 );
417 }
418 }
419 Initiator::build(identity, peer_public, suite, prologue)
420 }
421
422 /// Builds the initiator for the suite the prologue's `client/init` announces.
423 ///
424 /// This is the constructor for a first handshake: the announcement decides the suite, so the
425 /// two cannot disagree. A prologue that is not the init exchange, that carries no
426 /// `client/init`, that carries two of them, that announces no suite or that announces one
427 /// this build does not have is rejected; use [`Initiator::new`] on a re-handshake, where the
428 /// prologue is the previous handshake hash.
429 pub fn with_announced_suite(
430 identity: &Identity,
431 peer_public: &[u8; 32],
432 prologue: &[u8],
433 ) -> Result<Initiator> {
434 let suite = suite_from_prologue(prologue)?;
435 Initiator::build(identity, peer_public, suite, prologue)
436 }
437
438 /// Builds the handshake state every constructor ends in.
439 fn build(
440 identity: &Identity,
441 peer_public: &[u8; 32],
442 suite: Suite,
443 prologue: &[u8],
444 ) -> Result<Initiator> {
445 identity.validate()?;
446
447 // Keep the published constant honest even if someone edits it.
448 debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
449
450 let params = suite
451 .params()
452 .parse()
453 .context("failed to parse the Noise protocol parameters")?;
454 let handshake = snow::Builder::new(params)
455 .local_private_key(&identity.secret)
456 .context("failed to set the local static key")?
457 .remote_public_key(peer_public)
458 .context("failed to set the peer static key")?
459 .psk(2, &SENTINEL_PSK)
460 .context("failed to set the handshake PSK")?
461 .prologue(prologue)
462 .context("failed to set the Noise prologue")?
463 .build_initiator()
464 .context("failed to build the Noise initiator")?;
465 Ok(Initiator { handshake, suite })
466 }
467
468 /// Returns the cipher suite this handshake runs.
469 pub fn suite(&self) -> Suite {
470 self.suite
471 }
472
473 /// Replaces the pre-shared key used by the rest of the handshake.
474 ///
475 /// The initiator starts with the published Sentinel PSK. Call this before writing message 1
476 /// when the handshake announces a private key, because message 1's payload names the key this
477 /// call selects; noise mixes the key into message 2 either way, so both sides must use the
478 /// same value or the peer's message 2 does not authenticate.
479 pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
480 self.handshake
481 .set_psk(2, psk)
482 .context("failed to set the Noise handshake PSK")
483 }
484
485 /// Writes Noise handshake message 1 with `payload` and returns the message.
486 ///
487 /// The payload is the PSK metadata (`psk_id`, `psk_category`) the session layer builds; this
488 /// module does not interpret it. It travels encrypted, so it must fit into a Noise message.
489 pub fn write_message(&mut self, payload: &[u8]) -> Result<Vec<u8>> {
490 write_handshake_payload(&mut self.handshake, payload)
491 }
492
493 /// Reads Noise handshake message 2 and returns its decrypted payload.
494 ///
495 /// The payload is returned verbatim; Sendspin requires it to be the empty JSON object, which
496 /// the session layer checks. Fails when the message does not authenticate, which covers a
497 /// message sealed with another PSK, a changed byte and a truncation.
498 pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
499 read_handshake_payload(&mut self.handshake, msg)
500 }
501
502 /// Returns whether both handshake messages have been processed.
503 pub fn handshake_finished(&self) -> bool {
504 self.handshake.is_handshake_finished()
505 }
506
507 /// Finishes the handshake and switches to transport mode.
508 ///
509 /// Returns what [`Responder::into_transport`] returns: the handshake hash a re-handshake
510 /// mixes in and the suite these keys were derived under. Fails if message 2 is still
511 /// outstanding, which [`Initiator::handshake_finished`] reports ahead of time.
512 pub fn into_transport(self) -> Result<TransportState> {
513 transport_from(self.handshake, self.suite)
514 }
515}
516
517/// Reads a handshake message and returns the payload it carries.
518fn read_handshake_payload(handshake: &mut snow::HandshakeState, msg: &[u8]) -> Result<Vec<u8>> {
519 ensure_message_len(msg.len(), "handshake message")?;
520 let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
521 let len = handshake
522 .read_message(msg, &mut payload)
523 .context("failed to read the Noise handshake message")?;
524 payload.truncate(len);
525 Ok(payload)
526}
527
528/// Writes one handshake message carrying `payload`.
529fn write_handshake_payload(
530 handshake: &mut snow::HandshakeState,
531 payload: &[u8],
532) -> Result<Vec<u8>> {
533 let mut message = vec![0u8; MAX_MESSAGE_LEN];
534 let len = handshake
535 .write_message(payload, &mut message)
536 .context("failed to write the Noise handshake message")?;
537 message.truncate(len);
538 Ok(message)
539}
540
541/// Finishes a handshake and switches to transport mode.
542///
543/// `h` is final once the second message has been processed, and `into_transport_mode` consumes the
544/// handshake state that holds it.
545fn transport_from(handshake: snow::HandshakeState, suite: Suite) -> Result<TransportState> {
546 let handshake_hash: [u8; 32] = handshake
547 .get_handshake_hash()
548 .try_into()
549 .context("the Noise handshake hash is not 32 bytes")?;
550 let state = handshake
551 .into_transport_mode()
552 .context("failed to finish the Noise handshake")?;
553 Ok(TransportState {
554 state,
555 handshake_hash,
556 suite,
557 })
558}
559
560/// A Noise transport session: one ciphertext per message.
561///
562/// The nonce advances with every message in each direction; a repeated or reordered ciphertext
563/// fails authentication. Payloads are not fragmented at this layer, so a caller that needs to
564/// send more than a single Noise message can carry has to split the data itself.
565pub struct TransportState {
566 state: snow::TransportState,
567 /// The handshake hash `h` of the handshake that produced these keys.
568 handshake_hash: [u8; 32],
569 /// The cipher suite of the handshake that produced these keys.
570 suite: Suite,
571}
572
573impl TransportState {
574 /// Returns the cipher suite these keys were derived under.
575 ///
576 /// A re-handshake must use it again, and so must anything the specification seals with the
577 /// suite's AEAD, such as a pairing payload.
578 pub fn suite(&self) -> Suite {
579 self.suite
580 }
581
582 /// Returns the handshake hash `h` of the handshake these keys came from.
583 ///
584 /// Noise finalises `h` when the second handshake message is processed, and nothing after that
585 /// changes it. Sendspin uses it once: a [re-handshake](https://github.com/Sendspin/spec/blob/main/connection.md#re-handshake)
586 /// mixes the previous handshake's `h` in as its prologue, so a second handshake that reuses
587 /// these keys must be built with this value. It is a transcript hash, not key material, but it
588 /// must still never be logged.
589 pub fn handshake_hash(&self) -> &[u8; 32] {
590 &self.handshake_hash
591 }
592
593 /// Encrypts one plaintext into a Noise transport message.
594 ///
595 /// Fails if the plaintext does not fit into a single Noise message, that is if it is larger
596 /// than [`MAX_MESSAGE_LEN`] minus the 16-byte authentication tag.
597 pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
598 ensure_plaintext_len(plaintext.len())?;
599 let mut message = vec![0u8; plaintext.len() + TAG_LEN];
600 let len = self
601 .state
602 .write_message(plaintext, &mut message)
603 .context("failed to encrypt the Noise transport message")?;
604 message.truncate(len);
605 Ok(message)
606 }
607
608 /// Decrypts one Noise transport message.
609 ///
610 /// Fails if the ciphertext is longer than a Noise message, shorter than the authentication
611 /// tag, or does not authenticate under the current key and nonce.
612 pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
613 ensure_message_len(ciphertext.len(), "transport message")?;
614 let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
615 let len = self
616 .state
617 .read_message(ciphertext, &mut plaintext)
618 .context("failed to decrypt the Noise transport message")?;
619 plaintext.truncate(len);
620 Ok(plaintext)
621 }
622}
623
624/// Reads the initiator's static public key from a prologue of concatenated init messages.
625///
626/// The prologue is the exact `client/init` followed by `server/init` exchange, so it is parsed
627/// as a stream of top-level JSON documents and the caller passes the two documents without
628/// splitting them. Malformed JSON, a missing `server/init`, a non-canonical `server_id` and a
629/// second `server/init` are all errors: guessing a key here would mean handshaking with a static
630/// key the initiator may not hold.
631fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
632 let mut server_id = None;
633 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
634 {
635 let document = document.context("the prologue is not a sequence of JSON documents")?;
636 if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
637 continue;
638 }
639 if server_id.is_some() {
640 bail!("the prologue contains more than one `server/init` document");
641 }
642 let id = document
643 .pointer("/payload/server_id")
644 .and_then(serde_json::Value::as_str)
645 .ok_or_else(|| {
646 anyhow!("the `server/init` document carries no string `payload.server_id`")
647 })?;
648 server_id = Some(decode_key(id).ok_or_else(|| {
649 anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
650 })?);
651 }
652
653 server_id.ok_or_else(|| {
654 anyhow!(
655 "the prologue contains no `server/init` document with a `server_id`, so the \
656 initiator's static public key is unknown; pass it with `Responder::with_peer`"
657 )
658 })
659}
660
661/// Derives the X25519 public key that belongs to `secret`.
662fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
663 PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
664}
665
666/// Reads the cipher suite the prologue's `client/init` announces.
667///
668/// The suite a handshake runs is the suite the client announced: it is not negotiated, and a
669/// name this build does not have is an error rather than a reason to use [`Suite::default`]. A
670/// prologue with no `client/init`, a missing or non-string `suite` and two `client/init`
671/// documents are errors too, for the same reason a missing `server_id` is: the handshake would
672/// otherwise guess what the peer meant.
673fn suite_from_prologue(prologue: &[u8]) -> Result<Suite> {
674 let mut announced = None;
675 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
676 {
677 let document = document.context("the prologue is not a sequence of JSON documents")?;
678 if let Some(suite) = client_init_suite(&document)? {
679 if announced.is_some() {
680 bail!("the prologue contains more than one `client/init` document");
681 }
682 announced = Some(suite);
683 }
684 }
685
686 announced.ok_or_else(|| {
687 anyhow!(
688 "the prologue contains no `client/init` document with a `suite`, so the cipher suite \
689 is unknown; a first handshake needs the init exchange, pass the suite with \
690 `Responder::with_peer_suite` on a re-handshake"
691 )
692 })
693}
694
695/// Reads the suite a prologue announces, if the prologue is the init exchange at all.
696///
697/// `None` means there is no `client/init` document to read: a re-handshake prologue is the
698/// previous handshake hash, which is not JSON, and carries no announcement. A `client/init` that
699/// carries no usable suite is still an error, so an announcement is never half-read.
700fn announced_suite_from_prologue(prologue: &[u8]) -> Result<Option<Suite>> {
701 let mut announced = None;
702 for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
703 {
704 let Ok(document) = document else {
705 // Not a sequence of JSON documents: no announcement to check against.
706 return Ok(None);
707 };
708 if let Some(suite) = client_init_suite(&document)? {
709 if announced.is_some() {
710 bail!("the prologue contains more than one `client/init` document");
711 }
712 announced = Some(suite);
713 }
714 }
715 Ok(announced)
716}
717
718/// Returns the suite one init document announces, or `None` when it is not a `client/init`.
719fn client_init_suite(document: &serde_json::Value) -> Result<Option<Suite>> {
720 if document.get("type").and_then(serde_json::Value::as_str) != Some("client/init") {
721 return Ok(None);
722 }
723 let name = document
724 .pointer("/payload/suite")
725 .and_then(serde_json::Value::as_str)
726 .ok_or_else(|| {
727 anyhow!(
728 "the `client/init` document carries no string `payload.suite`; the cipher suite \
729 is required and is not assumed to be `{}`",
730 Suite::default()
731 )
732 })?;
733 Ok(Some(Suite::from_wire_name(name).ok_or_else(|| {
734 anyhow!(
735 "the `client/init` document announces the cipher suite `{name}`, which this build \
736 does not have; it supports {}",
737 Suite::ALL
738 .map(Suite::wire_name)
739 .map(|name| format!("`{name}`"))
740 .join(", ")
741 )
742 })?))
743}
744
745/// Rejects a Noise message that exceeds the protocol maximum.
746fn ensure_message_len(len: usize, what: &str) -> Result<()> {
747 if len > MAX_MESSAGE_LEN {
748 bail!(
749 "Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
750 {MAX_MESSAGE_LEN} bytes"
751 );
752 }
753 Ok(())
754}
755
756/// Rejects plaintext that cannot fit into one Noise message.
757fn ensure_plaintext_len(len: usize) -> Result<()> {
758 if len > MAX_PLAINTEXT_LEN {
759 bail!(
760 "plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
761 {MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
762 {TAG_LEN}-byte tag); payloads are not fragmented at this layer"
763 );
764 }
765 Ok(())
766}
767
768/// Returns how much plaintext a message of `len` bytes can carry.
769fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
770 len.checked_sub(TAG_LEN).ok_or_else(|| {
771 anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
772 })
773}
774
775/// Decodes a canonical 32-byte unpadded base64url key.
776fn decode_key(value: &str) -> Option<[u8; 32]> {
777 if value.len() != KEY_CHARS {
778 return None;
779 }
780 let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
781 if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
782 return None;
783 }
784 bytes.try_into().ok()
785}
786
787#[cfg(test)]
788mod tests {
789 use super::*;
790
791 const CLIENT_INIT: &[u8] =
792 br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
793
794 fn server_init(server_id: &str) -> Vec<u8> {
795 format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
796 .into_bytes()
797 }
798
799 fn prologue(server_id: &str) -> Vec<u8> {
800 let mut bytes = CLIENT_INIT.to_vec();
801 bytes.extend_from_slice(&server_init(server_id));
802 bytes
803 }
804
805 #[test]
806 fn the_prologue_carries_the_initiator_static_key() {
807 let identity = Identity::generate();
808 let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
809 .expect("server/init carries server_id");
810 assert_eq!(key, identity.public);
811 }
812
813 #[test]
814 fn a_prologue_without_a_server_init_is_rejected() {
815 let identity = Identity::generate();
816
817 for prologue in [&b""[..], CLIENT_INIT] {
818 let result = Responder::new(&identity, prologue);
819 assert!(
820 result.is_err(),
821 "a prologue without server/init must be rejected"
822 );
823 let err = result.err().expect("the rejection was asserted");
824 let message = format!("{err:#}");
825 assert!(
826 message.contains("server_id") && message.contains("with_peer"),
827 "error should name the missing key and the way out, got: {message}"
828 );
829 }
830
831 // Malformed JSON is a parse error, not a silently skipped document.
832 let result = Responder::new(&identity, b"not json at all");
833 assert!(
834 result.is_err(),
835 "a prologue that is not JSON must be rejected"
836 );
837 let err = result.err().expect("the rejection was asserted");
838 assert!(
839 format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
840 "error should name the malformed prologue, got: {err:#}"
841 );
842 }
843
844 #[test]
845 fn prologue_with_duplicate_server_id_is_rejected() {
846 let identity = Identity::generate();
847 let first = Identity::generate().public_base64();
848 let second = Identity::generate().public_base64();
849 let mut prologue = prologue(&first);
850 prologue.extend_from_slice(&server_init(&second));
851
852 let result = Responder::new(&identity, &prologue);
853 assert!(result.is_err(), "two server/init documents are ambiguous");
854 let err = result.err().expect("the rejection was asserted");
855 assert!(
856 format!("{err:#}").contains("more than one `server/init`"),
857 "error should name the duplicate, got: {err:#}"
858 );
859 }
860
861 #[test]
862 fn an_identity_mismatch_is_rejected_before_the_handshake() {
863 let mut identity = Identity::generate();
864 identity.public = Identity::generate().public;
865 let prologue = prologue(&Identity::generate().public_base64());
866 let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
867 assert!(result.is_err(), "a mismatched identity must be rejected");
868 let err = result.err().expect("the rejection was asserted");
869 assert!(
870 format!("{err:#}").contains("does not match"),
871 "error should name the mismatch, got: {err:#}"
872 );
873 }
874
875 #[test]
876 fn a_server_init_without_a_usable_server_id_is_rejected() {
877 let identity = Identity::generate();
878
879 let mut missing = CLIENT_INIT.to_vec();
880 missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
881 let result = Responder::new(&identity, &missing);
882 assert!(result.is_err(), "a server/init without server_id must fail");
883 assert!(
884 format!("{:#}", result.err().expect("the rejection was asserted"))
885 .contains("payload.server_id"),
886 "the error must name the missing field"
887 );
888
889 let mut wrong_type = CLIENT_INIT.to_vec();
890 wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
891 let result = Responder::new(&identity, &wrong_type);
892 assert!(result.is_err(), "a non-string server_id must fail");
893 assert!(
894 format!("{:#}", result.err().expect("the rejection was asserted"))
895 .contains("payload.server_id")
896 );
897 }
898
899 #[test]
900 fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
901 let identity = Identity::generate();
902
903 // Wrong length, an invalid base64url character, and 43 characters whose unused trailing
904 // bits are not zero: only the canonical encoding of exactly 32 bytes may be accepted.
905 for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
906 let result = Responder::new(&identity, &prologue(server_id));
907 assert!(
908 result.is_err(),
909 "{server_id:?} must not be accepted as a key"
910 );
911 let message = format!("{:#}", result.err().expect("the rejection was asserted"));
912 assert!(
913 message.contains("canonical 43-character"),
914 "the error must name the encoding, got: {message}"
915 );
916 }
917
918 // The canonical form of the same 32-byte secret is accepted and yields that key.
919 let id = "A".repeat(43);
920 assert_eq!(
921 initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
922 {
923 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
924 use base64::Engine as _;
925 let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
926 let mut key = [0u8; 32];
927 key.copy_from_slice(&bytes);
928 key
929 }
930 );
931 }
932
933 #[test]
934 fn identity_debug_redacts_the_secret() {
935 let identity = Identity::generate();
936 let text = format!("{identity:?}");
937 assert!(text.contains(&identity.public_base64()));
938 assert!(!text.contains(&identity.secret_base64()));
939 assert!(text.contains("<redacted>"));
940 }
941}