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 connection's suite
23//!
24//! The spec seals with the AEAD of the connection's negotiated cipher suite, so every function
25//! here takes a [`Suite`]: `25519_ChaChaPoly_SHA256` seals with ChaCha20-Poly1305 and
26//! `25519_AESGCM_SHA256` with AES-256-GCM. Both are 32-byte-key, 12-byte-nonce, 16-byte-tag
27//! ciphers, so `K_wrap` and the sealed length are the same under either; only the ciphertext
28//! differs, and a value sealed under one suite does not open under the other.
29//!
30//! The ciphers come from the same resolver `snow` uses for the handshake, which is where the
31//! dependency already sits. A build whose resolver lacks the suite's cipher returns an error and
32//! never falls back to the other suite.
33//!
34//! The module is behind the `pairing-code` feature with [`pake`](super::pake): wrapping exists
35//! only for the code flows.
36
37use anyhow::{anyhow, Result};
38use sha2::{Digest, Sha256};
39use snow::params::CipherChoice;
40use snow::resolvers::{CryptoResolver, DefaultResolver};
41use snow::types::Cipher;
42
43use crate::noise::Suite;
44
45/// The label that derives the key for `wrapped_psk`.
46pub const PSK_LABEL: &[u8] = b"sendspin-pair-psk-wrap-v1";
47
48/// The label that derives the key for `wrapped_nonce_B`.
49pub const NONCE_LABEL: &[u8] = b"sendspin-pair-nonce-wrap-v1";
50
51/// The length of a wrapped value: 32 bytes.
52const VALUE_LEN: usize = 32;
53
54/// The length of the AEAD's authentication tag: 16 bytes.
55const TAG_LEN: usize = 16;
56
57/// The length of a sealed value: ciphertext plus tag, the spec's 48-byte field.
58const SEALED_LEN: usize = VALUE_LEN + TAG_LEN;
59
60/// The nonce number every wrapping uses. A key is derived per field per session, so it seals
61/// exactly one value and the zero nonce never repeats under the same key. Zero is the spec's
62/// twelve zero bytes under either cipher: both render a `u64` into the last eight bytes, and
63/// this value is zero in either byte order.
64const WRAP_NONCE: u64 = 0;
65
66/// Derives `K_wrap = SHA-256(label || sid || ISK)`.
67///
68/// `label` is [`PSK_LABEL`] or [`NONCE_LABEL`], `sid` the CPace session id exactly as the PAKE
69/// used it, and `isk` the 64-byte CPace intermediate session key. The three are concatenated
70/// raw; their lengths are fixed by the protocol, so no delimiter is needed. The suite does not
71/// enter the derivation: both of Sendspin's suites use the same key with a different AEAD.
72pub fn k_wrap(label: &[u8], sid: &[u8], isk: &[u8; 64]) -> [u8; 32] {
73 let mut hasher = Sha256::new();
74 hasher.update(label);
75 hasher.update(sid);
76 hasher.update(isk);
77 hasher.finalize().into()
78}
79
80/// Seals a 32-byte value under `K_wrap` with the AEAD of `suite`, returning ciphertext and tag.
81///
82/// The nonce is twelve zero bytes and the associated data is empty, as the spec requires. A
83/// key is used for one value only, which is what makes the fixed nonce safe.
84///
85/// # Errors
86///
87/// Fails when the build's cipher resolver has no AEAD for `suite`. That is the honest refusal:
88/// sealing under the other suite's cipher would produce a field the peer cannot open.
89///
90/// # Example
91///
92/// ```
93/// use syncspin_core::noise::Suite;
94/// use syncspin_core::pairing::wrap::{unwrap, wrap};
95///
96/// // The key comes from `k_wrap` in a real flow; any 32 bytes will do here.
97/// let key = [0x42; 32];
98/// let value = [0x24; 32];
99/// let sealed = wrap(Suite::ChaChaPoly, &key, &value).expect("the cipher is available");
100/// assert_eq!(unwrap(Suite::ChaChaPoly, &key, &sealed).expect("round trip"), value);
101/// ```
102pub fn wrap(suite: Suite, key: &[u8; 32], value: &[u8; 32]) -> Result<[u8; SEALED_LEN]> {
103 let cipher = cipher(suite, key)?;
104
105 // The AEAD appends its tag, so one buffer holds the whole field. A 32-byte value is far
106 // below the maximum, so sealing cannot fail.
107 let mut sealed = [0u8; SEALED_LEN];
108 let written = cipher.encrypt(WRAP_NONCE, &[], value, &mut sealed);
109 debug_assert_eq!(written, SEALED_LEN, "the AEAD appends a {TAG_LEN}-byte tag");
110 Ok(sealed)
111}
112
113/// Opens a 48-byte sealed value under `K_wrap` with the AEAD of `suite`, returning the value.
114///
115/// # Errors
116///
117/// Fails when the tag does not authenticate: a wrong key - a different label, `sid` or `ISK` - a
118/// seal made under the other suite, or any changed byte of the ciphertext or tag. It also fails
119/// when the build's cipher resolver has no AEAD for `suite`. The error names no key, value or
120/// seal bytes.
121pub fn unwrap(suite: Suite, key: &[u8; 32], sealed: &[u8; SEALED_LEN]) -> Result<[u8; 32]> {
122 let cipher = cipher(suite, key)?;
123
124 let mut value = [0u8; VALUE_LEN];
125 cipher
126 .decrypt(WRAP_NONCE, &[], sealed, &mut value)
127 .map_err(|_| anyhow!("the wrapped pairing value does not authenticate"))?;
128 Ok(value)
129}
130
131/// Builds the suite's AEAD for `key`.
132///
133/// The resolver is `snow`'s default one, the same one the handshake uses, so a build that has a
134/// suite for Noise has it here as well. A missing cipher is an error and not a reason to seal
135/// under the other suite. The panic messages and error strings carry no key material: `set`
136/// cannot fail on a 32-byte key.
137fn cipher(suite: Suite, key: &[u8; 32]) -> Result<Box<dyn Cipher>> {
138 let choice = match suite {
139 Suite::ChaChaPoly => CipherChoice::ChaChaPoly,
140 Suite::AesGcm => CipherChoice::AESGCM,
141 };
142 let mut cipher = DefaultResolver.resolve_cipher(&choice).ok_or_else(|| {
143 anyhow!("the cipher suite `{suite}` is not available in this build, so it cannot seal")
144 })?;
145 cipher.set(key);
146 Ok(cipher)
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152
153 #[test]
154 fn the_sealed_length_is_ciphertext_plus_tag() {
155 assert_eq!(SEALED_LEN, 48, "the spec's wrapped field is 48 bytes");
156 assert_eq!(
157 SEALED_LEN,
158 VALUE_LEN + TAG_LEN,
159 "48 is 32 bytes of ciphertext and a 16-byte tag"
160 );
161 }
162
163 #[test]
164 fn a_wrap_is_deterministic_for_one_key_and_value() {
165 // The nonce is fixed by the spec, so the same key and value must seal identically under
166 // either suite; if this ever changes, the peer derives a different ciphertext for the
167 // same field.
168 let key = [0x11; 32];
169 let value = [0x22; 32];
170 for suite in Suite::ALL {
171 assert_eq!(
172 wrap(suite, &key, &value).expect("the cipher is available"),
173 wrap(suite, &key, &value).expect("the cipher is available")
174 );
175 }
176 }
177
178 #[test]
179 fn the_fixed_nonce_is_zero() {
180 // The wrapped field's nonce is the spec's twelve zero bytes, not the handshake's
181 // counter; a change here would still round-trip against this crate and fail against a
182 // real server.
183 assert_eq!(WRAP_NONCE, 0);
184 }
185}