Skip to main content

syncspin_core/
noise.rs

1//! Sendspin's Noise layer: `Noise_KKpsk2_25519_ChaChaPoly_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
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 is the responder half plus the transport that follows the handshake. It does not
20//! interpret handshake payloads; the session layer validates the `psk_id`/`psk_category`
21//! metadata. This milestone uses the published Sentinel PSK, which is what an unpaired client
22//! uses and which provides no authentication on its own; selecting a different PSK from message 1
23//! arrives with the session layer.
24
25use std::fmt;
26
27use anyhow::{anyhow, bail, Context, Result};
28use base64::engine::general_purpose::URL_SAFE_NO_PAD;
29use base64::Engine as _;
30use sha2::{Digest, Sha256};
31use x25519_dalek::{PublicKey, StaticSecret};
32
33/// Noise protocol parameters used by Sendspin.
34pub const NOISE_PARAMS: &str = "Noise_KKpsk2_25519_ChaChaPoly_SHA256";
35
36/// The published Sentinel PSK, used whenever no paired PSK applies.
37///
38/// Its value is public, so it authenticates nothing. It exists so an unpaired client can
39/// connect before pairing establishes a private PSK.
40pub const SENTINEL_PSK: [u8; 32] = [
41    0x1b, 0x5e, 0x24, 0xdb, 0xc1, 0xae, 0xd9, 0x5f, 0xc2, 0xa5, 0xa3, 0x38, 0xa9, 0x0c, 0x05, 0xdf,
42    0x44, 0xbd, 0x10, 0xf5, 0xec, 0x1f, 0x4c, 0xd6, 0x6c, 0xbf, 0x86, 0x27, 0x27, 0x67, 0xb9, 0xd3,
43];
44
45/// The Sentinel PSK's published id, `psk_id_for(SENTINEL_PSK)`.
46pub const SENTINEL_PSK_ID: &str = "GFsV9tLaSQm9HcFWpKsgYQOr7wFTvNUtkmFwuVz3zoo";
47
48/// Maximum size of one Noise message, handshake or transport, including the authentication tag.
49///
50/// This is the Noise specification's limit; `snow` does not re-export the constant, so it is
51/// repeated here.
52pub const MAX_MESSAGE_LEN: usize = 65_535;
53
54/// Length of the authentication tag appended to every Noise transport ciphertext.
55pub const TAG_LEN: usize = 16;
56
57/// Largest plaintext that fits into one Noise transport message, including the leading binary
58/// message id byte.
59pub const MAX_PLAINTEXT_LEN: usize = MAX_MESSAGE_LEN - TAG_LEN;
60
61/// Label that Sendspin hashes together with a PSK to derive its id.
62const PSK_ID_LABEL: &[u8] = b"sendspin-psk-id-v1";
63
64/// Payload of Noise handshake message 2: the literal empty JSON object, not zero bytes.
65const HANDSHAKE_MESSAGE_2: &[u8] = b"{}";
66
67/// Unpadded base64url length of a 32-byte key.
68const KEY_CHARS: usize = 43;
69
70/// Derives a PSK id: `base64url(SHA-256("sendspin-psk-id-v1" || psk))`, without padding.
71///
72/// The id is what a server announces in `noise/handshake` message 1 so the client can select
73/// the matching PSK; it is a hash of the key and reveals nothing about its value.
74pub fn psk_id_for(psk: &[u8]) -> String {
75    let mut hasher = Sha256::new();
76    hasher.update(PSK_ID_LABEL);
77    hasher.update(psk);
78    URL_SAFE_NO_PAD.encode(hasher.finalize())
79}
80
81/// A long-lived X25519 keypair that identifies one side of a connection.
82///
83/// Sendspin uses the public key as the `client_id` or `server_id` and the secret key as the
84/// static key of the Noise handshake. Both halves must match: [`Identity::generate`] and
85/// [`Identity::from_secret_base64`] derive the public key from the secret, so an identity built
86/// through them always does.
87#[derive(Clone, Copy)]
88pub struct Identity {
89    /// Public X25519 key as 32 raw bytes; 43 base64url characters once encoded.
90    pub public: [u8; 32],
91    /// Secret X25519 key as 32 raw bytes. Never log this value.
92    pub secret: [u8; 32],
93}
94
95impl Identity {
96    /// Generates a fresh keypair from the operating system's CSPRNG.
97    ///
98    /// # Panics
99    ///
100    /// Panics if the operating system's CSPRNG is unavailable. That is not a recoverable
101    /// condition: a silent fallback would be a weak key.
102    pub fn generate() -> Identity {
103        let params = NOISE_PARAMS
104            .parse()
105            .expect("NOISE_PARAMS is a valid Noise protocol name");
106        let keypair = snow::Builder::new(params)
107            .generate_keypair()
108            .expect("the operating system CSPRNG is available");
109        let secret: [u8; 32] = keypair
110            .private
111            .as_slice()
112            .try_into()
113            .expect("an X25519 secret key is 32 bytes");
114        Identity::from_secret(secret)
115    }
116
117    /// Decodes an identity from its 43-character unpadded base64url secret key.
118    ///
119    /// The public key is derived from the secret. The input must be the canonical encoding of
120    /// exactly 32 bytes; a truncated, padded or non-base64url string is an error. Every 32-byte
121    /// value is a valid secret, so this cannot tell a secret key from a public key: passing a
122    /// public key such as [`Identity::public_base64`] succeeds and silently yields a different
123    /// identity.
124    pub fn from_secret_base64(s: &str) -> Result<Identity> {
125        let secret = decode_key(s).ok_or_else(|| {
126            anyhow!("identity secret is not a canonical 43-character unpadded base64url X25519 key")
127        })?;
128        Ok(Identity::from_secret(secret))
129    }
130
131    /// Returns the public key as 43-character unpadded base64url text.
132    ///
133    /// This is the value to send as `client_id` or `server_id`.
134    pub fn public_base64(&self) -> String {
135        URL_SAFE_NO_PAD.encode(self.public)
136    }
137
138    /// Returns the secret key as 43-character unpadded base64url text.
139    ///
140    /// The value is key material: hand it to [`Identity::from_secret_base64`] to restore an
141    /// identity and treat the text like a password.
142    pub fn secret_base64(&self) -> String {
143        URL_SAFE_NO_PAD.encode(self.secret)
144    }
145
146    /// Builds an identity whose public key is derived from `secret`.
147    fn from_secret(secret: [u8; 32]) -> Identity {
148        Identity {
149            public: public_key_for(&secret),
150            secret,
151        }
152    }
153
154    /// Rejects a hand-built identity whose two halves do not belong together.
155    fn validate(&self) -> Result<()> {
156        if public_key_for(&self.secret) != self.public {
157            bail!("identity public key does not match its secret key");
158        }
159        Ok(())
160    }
161}
162
163impl fmt::Debug for Identity {
164    /// Formats the public key and redacts the secret, so `Debug` output is safe to log.
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("Identity")
167            .field("public", &self.public_base64())
168            .field("secret", &"<redacted>")
169            .finish()
170    }
171}
172
173/// Noise responder state for one connection.
174pub struct Responder {
175    handshake: snow::HandshakeState,
176}
177
178impl Responder {
179    /// Builds the responder for the client side of a Sendspin handshake.
180    ///
181    /// `prologue` must be the exact concatenation of the `client/init` and `server/init` bytes
182    /// as transmitted, in that order. It is mixed into the handshake verbatim, and the
183    /// initiator's static public key is read from the `server_id` field of the `server/init`
184    /// document it contains. A prologue that is not a sequence of JSON documents, that carries
185    /// no `server/init`, or that carries two of them is rejected; use [`Responder::with_peer`]
186    /// when the key is already known, as during a re-handshake where the prologue is the
187    /// previous handshake hash.
188    pub fn new(identity: &Identity, prologue: &[u8]) -> Result<Responder> {
189        let peer_public = initiator_key_from_prologue(prologue)?;
190        Responder::with_peer(identity, &peer_public, prologue)
191    }
192
193    /// Builds the responder with the initiator's static public key supplied explicitly.
194    ///
195    /// Use this when the prologue is not the init exchange, for example on a re-handshake whose
196    /// prologue is the previous handshake hash. `prologue` still reaches Noise unchanged; both
197    /// sides must mix in the same bytes.
198    pub fn with_peer(
199        identity: &Identity,
200        peer_public: &[u8; 32],
201        prologue: &[u8],
202    ) -> Result<Responder> {
203        identity.validate()?;
204
205        // Keep the published constant honest even if someone edits it.
206        debug_assert_eq!(psk_id_for(&SENTINEL_PSK), SENTINEL_PSK_ID);
207
208        let params = NOISE_PARAMS
209            .parse()
210            .context("failed to parse the Noise protocol parameters")?;
211        let handshake = snow::Builder::new(params)
212            .local_private_key(&identity.secret)
213            .context("failed to set the local static key")?
214            .remote_public_key(peer_public)
215            .context("failed to set the peer static key")?
216            .psk(2, &SENTINEL_PSK)
217            .context("failed to set the handshake PSK")?
218            .prologue(prologue)
219            .context("failed to set the Noise prologue")?
220            .build_responder()
221            .context("failed to build the Noise responder")?;
222        Ok(Responder { handshake })
223    }
224
225    /// Replaces the pre-shared key used by the rest of the handshake.
226    ///
227    /// The responder starts with the published Sentinel PSK because the key is selected from the
228    /// metadata that message 1 carries. Call this after [`Responder::read_message`] and before
229    /// [`Responder::write_message`]: Noise mixes the key into message 2, so both sides must use
230    /// the same value and the initiator rejects a message sealed with another one.
231    ///
232    /// # Errors
233    /// Fails when the handshake has already mixed in the key, which makes a late change
234    /// impossible.
235    pub fn set_psk(&mut self, psk: &[u8; 32]) -> Result<()> {
236        self.handshake
237            .set_psk(2, psk)
238            .context("failed to set the Noise handshake PSK")
239    }
240
241    /// Reads one Noise handshake message and returns its decrypted payload.
242    ///
243    /// The payload is returned verbatim. Message 1 carries the PSK metadata
244    /// (`psk_id`, `psk_category`) for the session layer to validate; the handshake itself starts
245    /// with the Sentinel PSK, which [`Responder::set_psk`] can replace.
246    pub fn read_message(&mut self, msg: &[u8]) -> Result<Vec<u8>> {
247        ensure_message_len(msg.len(), "handshake message")?;
248        let mut payload = vec![0u8; plaintext_capacity(msg.len(), "handshake message")?];
249        let len = self
250            .handshake
251            .read_message(msg, &mut payload)
252            .context("failed to read the Noise handshake message")?;
253        payload.truncate(len);
254        Ok(payload)
255    }
256
257    /// Writes Noise handshake message 2 and returns it.
258    ///
259    /// The payload is the empty JSON object that Sendspin requires; it is not configurable.
260    pub fn write_message(&mut self) -> Result<Vec<u8>> {
261        let mut message = vec![0u8; MAX_MESSAGE_LEN];
262        let len = self
263            .handshake
264            .write_message(HANDSHAKE_MESSAGE_2, &mut message)
265            .context("failed to write the Noise handshake message")?;
266        message.truncate(len);
267        Ok(message)
268    }
269
270    /// Returns whether both handshake messages have been processed.
271    pub fn handshake_finished(&self) -> bool {
272        self.handshake.is_handshake_finished()
273    }
274
275    /// Finishes the handshake and switches to transport mode.
276    ///
277    /// Fails if a handshake message is still outstanding, which
278    /// [`Responder::handshake_finished`] reports ahead of time.
279    pub fn into_transport(self) -> Result<TransportState> {
280        // `h` is final once the second message has been processed, and `into_transport_mode`
281        // consumes the handshake state that holds it.
282        let handshake_hash: [u8; 32] = self
283            .handshake
284            .get_handshake_hash()
285            .try_into()
286            .context("the Noise handshake hash is not 32 bytes")?;
287        let state = self
288            .handshake
289            .into_transport_mode()
290            .context("failed to finish the Noise handshake")?;
291        Ok(TransportState {
292            state,
293            handshake_hash,
294        })
295    }
296}
297
298/// A Noise transport session: one ciphertext per message.
299///
300/// The nonce advances with every message in each direction; a repeated or reordered ciphertext
301/// fails authentication. Payloads are not fragmented at this layer, so a caller that needs to
302/// send more than a single Noise message can carry has to split the data itself.
303pub struct TransportState {
304    state: snow::TransportState,
305    /// The handshake hash `h` of the handshake that produced these keys.
306    handshake_hash: [u8; 32],
307}
308
309impl TransportState {
310    /// Returns the handshake hash `h` of the handshake these keys came from.
311    ///
312    /// Noise finalises `h` when the second handshake message is processed, and nothing after that
313    /// changes it. Sendspin uses it once: a [re-handshake](https://github.com/Sendspin/spec/blob/main/connection.md#re-handshake)
314    /// mixes the previous handshake's `h` in as its prologue, so a second handshake that reuses
315    /// these keys must be built with this value. It is a transcript hash, not key material, but it
316    /// must still never be logged.
317    pub fn handshake_hash(&self) -> &[u8; 32] {
318        &self.handshake_hash
319    }
320
321    /// Encrypts one plaintext into a Noise transport message.
322    ///
323    /// Fails if the plaintext does not fit into a single Noise message, that is if it is larger
324    /// than [`MAX_MESSAGE_LEN`] minus the 16-byte authentication tag.
325    pub fn encrypt(&mut self, plaintext: &[u8]) -> Result<Vec<u8>> {
326        ensure_plaintext_len(plaintext.len())?;
327        let mut message = vec![0u8; plaintext.len() + TAG_LEN];
328        let len = self
329            .state
330            .write_message(plaintext, &mut message)
331            .context("failed to encrypt the Noise transport message")?;
332        message.truncate(len);
333        Ok(message)
334    }
335
336    /// Decrypts one Noise transport message.
337    ///
338    /// Fails if the ciphertext is longer than a Noise message, shorter than the authentication
339    /// tag, or does not authenticate under the current key and nonce.
340    pub fn decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>> {
341        ensure_message_len(ciphertext.len(), "transport message")?;
342        let mut plaintext = vec![0u8; plaintext_capacity(ciphertext.len(), "transport message")?];
343        let len = self
344            .state
345            .read_message(ciphertext, &mut plaintext)
346            .context("failed to decrypt the Noise transport message")?;
347        plaintext.truncate(len);
348        Ok(plaintext)
349    }
350}
351
352/// Reads the initiator's static public key from a prologue of concatenated init messages.
353///
354/// The prologue is the exact `client/init` followed by `server/init` exchange, so it is parsed
355/// as a stream of top-level JSON documents and the caller passes the two documents without
356/// splitting them. Malformed JSON, a missing `server/init`, a non-canonical `server_id` and a
357/// second `server/init` are all errors: guessing a key here would mean handshaking with a static
358/// key the initiator may not hold.
359fn initiator_key_from_prologue(prologue: &[u8]) -> Result<[u8; 32]> {
360    let mut server_id = None;
361    for document in serde_json::Deserializer::from_slice(prologue).into_iter::<serde_json::Value>()
362    {
363        let document = document.context("the prologue is not a sequence of JSON documents")?;
364        if document.get("type").and_then(serde_json::Value::as_str) != Some("server/init") {
365            continue;
366        }
367        if server_id.is_some() {
368            bail!("the prologue contains more than one `server/init` document");
369        }
370        let id = document
371            .pointer("/payload/server_id")
372            .and_then(serde_json::Value::as_str)
373            .ok_or_else(|| {
374                anyhow!("the `server/init` document carries no string `payload.server_id`")
375            })?;
376        server_id = Some(decode_key(id).ok_or_else(|| {
377            anyhow!("`server_id` is not a canonical 43-character unpadded base64url X25519 key")
378        })?);
379    }
380
381    server_id.ok_or_else(|| {
382        anyhow!(
383            "the prologue contains no `server/init` document with a `server_id`, so the \
384             initiator's static public key is unknown; pass it with `Responder::with_peer`"
385        )
386    })
387}
388
389/// Derives the X25519 public key that belongs to `secret`.
390fn public_key_for(secret: &[u8; 32]) -> [u8; 32] {
391    PublicKey::from(&StaticSecret::from(*secret)).to_bytes()
392}
393
394/// Rejects a Noise message that exceeds the protocol maximum.
395fn ensure_message_len(len: usize, what: &str) -> Result<()> {
396    if len > MAX_MESSAGE_LEN {
397        bail!(
398            "Noise {what} is {len} bytes, exceeding the maximum Noise message size of \
399             {MAX_MESSAGE_LEN} bytes"
400        );
401    }
402    Ok(())
403}
404
405/// Rejects plaintext that cannot fit into one Noise message.
406fn ensure_plaintext_len(len: usize) -> Result<()> {
407    if len > MAX_PLAINTEXT_LEN {
408        bail!(
409            "plaintext is {len} bytes, exceeding the maximum Noise plaintext size of \
410             {MAX_PLAINTEXT_LEN} bytes (a {MAX_MESSAGE_LEN}-byte message including the \
411             {TAG_LEN}-byte tag); payloads are not fragmented at this layer"
412        );
413    }
414    Ok(())
415}
416
417/// Returns how much plaintext a message of `len` bytes can carry.
418fn plaintext_capacity(len: usize, what: &str) -> Result<usize> {
419    len.checked_sub(TAG_LEN).ok_or_else(|| {
420        anyhow!("Noise {what} is {len} bytes, shorter than the {TAG_LEN}-byte authentication tag")
421    })
422}
423
424/// Decodes a canonical 32-byte unpadded base64url key.
425fn decode_key(value: &str) -> Option<[u8; 32]> {
426    if value.len() != KEY_CHARS {
427        return None;
428    }
429    let bytes = URL_SAFE_NO_PAD.decode(value).ok()?;
430    if bytes.len() != 32 || URL_SAFE_NO_PAD.encode(&bytes) != value {
431        return None;
432    }
433    bytes.try_into().ok()
434}
435
436#[cfg(test)]
437mod tests {
438    use super::*;
439
440    const CLIENT_INIT: &[u8] =
441        br#"{"type":"client/init","payload":{"client_id":"test-client","version":1}}"#;
442
443    fn server_init(server_id: &str) -> Vec<u8> {
444        format!(r#"{{"type":"server/init","payload":{{"server_id":"{server_id}","version":1}}}}"#)
445            .into_bytes()
446    }
447
448    fn prologue(server_id: &str) -> Vec<u8> {
449        let mut bytes = CLIENT_INIT.to_vec();
450        bytes.extend_from_slice(&server_init(server_id));
451        bytes
452    }
453
454    #[test]
455    fn the_prologue_carries_the_initiator_static_key() {
456        let identity = Identity::generate();
457        let key = initiator_key_from_prologue(&prologue(&identity.public_base64()))
458            .expect("server/init carries server_id");
459        assert_eq!(key, identity.public);
460    }
461
462    #[test]
463    fn a_prologue_without_a_server_init_is_rejected() {
464        let identity = Identity::generate();
465
466        for prologue in [&b""[..], CLIENT_INIT] {
467            let result = Responder::new(&identity, prologue);
468            assert!(
469                result.is_err(),
470                "a prologue without server/init must be rejected"
471            );
472            let err = result.err().expect("the rejection was asserted");
473            let message = format!("{err:#}");
474            assert!(
475                message.contains("server_id") && message.contains("with_peer"),
476                "error should name the missing key and the way out, got: {message}"
477            );
478        }
479
480        // Malformed JSON is a parse error, not a silently skipped document.
481        let result = Responder::new(&identity, b"not json at all");
482        assert!(
483            result.is_err(),
484            "a prologue that is not JSON must be rejected"
485        );
486        let err = result.err().expect("the rejection was asserted");
487        assert!(
488            format!("{err:#}").contains("prologue is not a sequence of JSON documents"),
489            "error should name the malformed prologue, got: {err:#}"
490        );
491    }
492
493    #[test]
494    fn prologue_with_duplicate_server_id_is_rejected() {
495        let identity = Identity::generate();
496        let first = Identity::generate().public_base64();
497        let second = Identity::generate().public_base64();
498        let mut prologue = prologue(&first);
499        prologue.extend_from_slice(&server_init(&second));
500
501        let result = Responder::new(&identity, &prologue);
502        assert!(result.is_err(), "two server/init documents are ambiguous");
503        let err = result.err().expect("the rejection was asserted");
504        assert!(
505            format!("{err:#}").contains("more than one `server/init`"),
506            "error should name the duplicate, got: {err:#}"
507        );
508    }
509
510    #[test]
511    fn an_identity_mismatch_is_rejected_before_the_handshake() {
512        let mut identity = Identity::generate();
513        identity.public = Identity::generate().public;
514        let prologue = prologue(&Identity::generate().public_base64());
515        let result = Responder::with_peer(&identity, &[0u8; 32], &prologue);
516        assert!(result.is_err(), "a mismatched identity must be rejected");
517        let err = result.err().expect("the rejection was asserted");
518        assert!(
519            format!("{err:#}").contains("does not match"),
520            "error should name the mismatch, got: {err:#}"
521        );
522    }
523
524    #[test]
525    fn a_server_init_without_a_usable_server_id_is_rejected() {
526        let identity = Identity::generate();
527
528        let mut missing = CLIENT_INIT.to_vec();
529        missing.extend_from_slice(br#"{"type":"server/init","payload":{"version":1}}"#);
530        let result = Responder::new(&identity, &missing);
531        assert!(result.is_err(), "a server/init without server_id must fail");
532        assert!(
533            format!("{:#}", result.err().expect("the rejection was asserted"))
534                .contains("payload.server_id"),
535            "the error must name the missing field"
536        );
537
538        let mut wrong_type = CLIENT_INIT.to_vec();
539        wrong_type.extend_from_slice(br#"{"type":"server/init","payload":{"server_id":42}}"#);
540        let result = Responder::new(&identity, &wrong_type);
541        assert!(result.is_err(), "a non-string server_id must fail");
542        assert!(
543            format!("{:#}", result.err().expect("the rejection was asserted"))
544                .contains("payload.server_id")
545        );
546    }
547
548    #[test]
549    fn a_server_id_that_is_not_a_canonical_key_is_rejected() {
550        let identity = Identity::generate();
551
552        // Wrong length, an invalid base64url character, and 43 characters whose unused trailing
553        // bits are not zero: only the canonical encoding of exactly 32 bytes may be accepted.
554        for server_id in ["short", &"!".repeat(43), &"a".repeat(43)] {
555            let result = Responder::new(&identity, &prologue(server_id));
556            assert!(
557                result.is_err(),
558                "{server_id:?} must not be accepted as a key"
559            );
560            let message = format!("{:#}", result.err().expect("the rejection was asserted"));
561            assert!(
562                message.contains("canonical 43-character"),
563                "the error must name the encoding, got: {message}"
564            );
565        }
566
567        // The canonical form of the same 32-byte secret is accepted and yields that key.
568        let id = "A".repeat(43);
569        assert_eq!(
570            initiator_key_from_prologue(&prologue(&id)).expect("a canonical key is accepted"),
571            {
572                use base64::engine::general_purpose::URL_SAFE_NO_PAD;
573                use base64::Engine as _;
574                let bytes = URL_SAFE_NO_PAD.decode(&id).expect("the id is base64url");
575                let mut key = [0u8; 32];
576                key.copy_from_slice(&bytes);
577                key
578            }
579        );
580    }
581
582    #[test]
583    fn identity_debug_redacts_the_secret() {
584        let identity = Identity::generate();
585        let text = format!("{identity:?}");
586        assert!(text.contains(&identity.public_base64()));
587        assert!(!text.contains(&identity.secret_base64()));
588        assert!(text.contains("<redacted>"));
589    }
590}