Skip to main content

syncspin_core/pairing/
wrap.rs

1//! Wrapping a pairing payload under the CPace output.
2//!
3//! The code-based flows never send two values in clear: the new long-term PSK and, in the
4//! Dynamic Pairing Code Flow, the commitment opening `nonce_B`. Each is sealed under the PAKE's
5//! intermediate session key with a key derived per field:
6//!
7//! ```text
8//! K_wrap = SHA-256(label || sid || ISK)
9//! sealed = AEAD(K_wrap, nonce = 12 zero bytes, aad = empty, value)
10//! ```
11//!
12//! The concatenation is raw - no separator, no length prefix, no NUL terminator - and `ISK` is
13//! the 64-byte CPace intermediate session key. The label separates the two fields, so a
14//! `wrapped_nonce_B` cannot be replayed as a `wrapped_psk`; the `sid` binds the seal to one CPace
15//! session, so a man in the middle that relays between two handshakes, whose differing `h` gives
16//! each leg a different `sid`, derives a key on neither leg.
17//!
18//! A value is 32 bytes and its sealed form 48: the ciphertext plus a 16-byte authentication tag.
19//! A payload that fails to authenticate is an error, never a zero or partially decrypted value,
20//! and neither [`Debug`] output nor an error string ever carries the key, the value or the seal.
21//!
22//! # The AEAD is the suite's
23//!
24//! The spec seals with the AEAD of the connection's negotiated cipher suite. Sendspin defines
25//! two suites - `25519_ChaChaPoly_SHA256` and `25519_AESGCM_SHA256` - and this crate offers the
26//! first only ([`NOISE_SUITE`](crate::messages::NOISE_SUITE)), so the AEAD here is
27//! ChaCha20-Poly1305. Offering `25519_AESGCM_SHA256` would mean selecting the AEAD from the
28//! suite rather than fixing it in this module.
29//!
30//! The module is behind the `pairing-code` feature with [`pake`](super::pake): wrapping exists
31//! only for the code flows, and the default build keeps no AEAD of its own.
32
33use anyhow::{anyhow, Result};
34use chacha20poly1305::aead::{AeadInPlace, KeyInit};
35use chacha20poly1305::{ChaCha20Poly1305, Nonce, Tag};
36use sha2::{Digest, Sha256};
37
38/// The label that derives the key for `wrapped_psk`.
39pub const PSK_LABEL: &[u8] = b"sendspin-pair-psk-wrap-v1";
40
41/// The label that derives the key for `wrapped_nonce_B`.
42pub const NONCE_LABEL: &[u8] = b"sendspin-pair-nonce-wrap-v1";
43
44/// The length of a wrapped value: 32 bytes.
45const VALUE_LEN: usize = 32;
46
47/// The length of the AEAD's authentication tag: 16 bytes.
48const TAG_LEN: usize = 16;
49
50/// The length of a sealed value: ciphertext plus tag, the spec's 48-byte field.
51const SEALED_LEN: usize = VALUE_LEN + TAG_LEN;
52
53/// The nonce every wrapping uses. A key is derived per field per session, so it seals exactly
54/// one value and the zero nonce never repeats under the same key.
55const NONCE_BYTES: [u8; 12] = [0u8; 12];
56
57/// Derives `K_wrap = SHA-256(label || sid || ISK)`.
58///
59/// `label` is [`PSK_LABEL`] or [`NONCE_LABEL`], `sid` the CPace session id exactly as the PAKE
60/// used it, and `isk` the 64-byte CPace intermediate session key. The three are concatenated
61/// raw; their lengths are fixed by the protocol, so no delimiter is needed.
62pub fn k_wrap(label: &[u8], sid: &[u8], isk: &[u8; 64]) -> [u8; 32] {
63    let mut hasher = Sha256::new();
64    hasher.update(label);
65    hasher.update(sid);
66    hasher.update(isk);
67    hasher.finalize().into()
68}
69
70/// Seals a 32-byte value under `K_wrap`, returning the 48-byte ciphertext and tag.
71///
72/// The nonce is twelve zero bytes and the associated data is empty, as the spec requires. A
73/// key is used for one value only, which is what makes the fixed nonce safe.
74///
75/// # Example
76///
77/// ```
78/// use syncspin_core::pairing::wrap::{unwrap, wrap};
79///
80/// // The key comes from `k_wrap` in a real flow; any 32 bytes will do here.
81/// let key = [0x42; 32];
82/// let value = [0x24; 32];
83/// assert_eq!(unwrap(&key, &wrap(&key, &value)).expect("round trip"), value);
84/// ```
85pub fn wrap(key: &[u8; 32], value: &[u8; 32]) -> [u8; SEALED_LEN] {
86    let mut sealed = [0u8; SEALED_LEN];
87    sealed[..VALUE_LEN].copy_from_slice(value);
88
89    // In-place detached keeps the encryption allocation-free; the tag is appended by hand to
90    // match the spec's ciphertext-plus-tag field. A 32-byte value is far below the AEAD's
91    // maximum, so sealing cannot fail.
92    let tag = cipher(key)
93        .encrypt_in_place_detached(&nonce(), &[], &mut sealed[..VALUE_LEN])
94        .expect("ChaCha20-Poly1305 always seals a 32-byte value");
95    sealed[VALUE_LEN..].copy_from_slice(&tag);
96    sealed
97}
98
99/// Opens a 48-byte sealed value under `K_wrap`, returning the 32-byte value.
100///
101/// # Errors
102///
103/// Fails when the tag does not authenticate: a wrong key - a different label, `sid` or `ISK` -
104/// or any changed byte of the ciphertext or tag. The error names no key, value or seal bytes.
105pub fn unwrap(key: &[u8; 32], sealed: &[u8; SEALED_LEN]) -> Result<[u8; 32]> {
106    let mut value = [0u8; VALUE_LEN];
107    value.copy_from_slice(&sealed[..VALUE_LEN]);
108    let tag = Tag::from_slice(&sealed[VALUE_LEN..]);
109
110    cipher(key)
111        .decrypt_in_place_detached(&nonce(), &[], &mut value, tag)
112        .map_err(|_| anyhow!("the wrapped pairing value does not authenticate"))?;
113    Ok(value)
114}
115
116/// Builds the cipher for `key`.
117///
118/// `new_from_slice` only fails on a key of the wrong length, and `key` is exactly 32 bytes, so
119/// the failure is unreachable. The panic message carries no key material.
120fn cipher(key: &[u8; 32]) -> ChaCha20Poly1305 {
121    ChaCha20Poly1305::new_from_slice(key).expect("a ChaCha20-Poly1305 key is 32 bytes")
122}
123
124/// Returns the fixed wrapping nonce.
125fn nonce() -> Nonce {
126    Nonce::from(NONCE_BYTES)
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn the_sealed_length_is_ciphertext_plus_tag() {
135        assert_eq!(SEALED_LEN, 48, "the spec's wrapped field is 48 bytes");
136        assert_eq!(
137            SEALED_LEN,
138            VALUE_LEN + TAG_LEN,
139            "48 is 32 bytes of ciphertext and a 16-byte tag"
140        );
141    }
142
143    #[test]
144    fn a_wrap_is_deterministic_for_one_key_and_value() {
145        // The nonce is fixed by the spec, so the same key and value must seal identically; if
146        // this ever changes, the peer derives a different ciphertext for the same field.
147        let key = [0x11; 32];
148        let value = [0x22; 32];
149        assert_eq!(wrap(&key, &value), wrap(&key, &value));
150    }
151}