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;
42use zeroize::Zeroizing;
43
44use crate::noise::Suite;
45
46/// The label that derives the key for `wrapped_psk`.
47pub const PSK_LABEL: &[u8] = b"sendspin-pair-psk-wrap-v1";
48
49/// The label that derives the key for `wrapped_nonce_B`.
50pub const NONCE_LABEL: &[u8] = b"sendspin-pair-nonce-wrap-v1";
51
52/// The length of a wrapped value: 32 bytes.
53const VALUE_LEN: usize = 32;
54
55/// The length of the AEAD's authentication tag: 16 bytes.
56const TAG_LEN: usize = 16;
57
58/// The length of a sealed value: ciphertext plus tag, the spec's 48-byte field.
59const SEALED_LEN: usize = VALUE_LEN + TAG_LEN;
60
61/// The nonce number every wrapping uses. A key is derived per field per session, so it seals
62/// exactly one value and the zero nonce never repeats under the same key. Zero is the spec's
63/// twelve zero bytes under either cipher: both render a `u64` into the last eight bytes, and
64/// this value is zero in either byte order.
65const WRAP_NONCE: u64 = 0;
66
67/// Derives `K_wrap = SHA-256(label || sid || ISK)`.
68///
69/// `label` is [`PSK_LABEL`] or [`NONCE_LABEL`], `sid` the CPace session id exactly as the PAKE
70/// used it, and `isk` the 64-byte CPace intermediate session key. The three are concatenated
71/// raw; their lengths are fixed by the protocol, so no delimiter is needed. The suite does not
72/// enter the derivation: both of Sendspin's suites use the same key with a different AEAD.
73pub fn k_wrap(label: &[u8], sid: &[u8], isk: &[u8; 64]) -> [u8; 32] {
74 let mut hasher = Sha256::new();
75 hasher.update(label);
76 hasher.update(sid);
77 hasher.update(isk);
78 hasher.finalize().into()
79}
80
81/// Seals a 32-byte value under `K_wrap` with the AEAD of `suite`, returning ciphertext and tag.
82///
83/// The nonce is twelve zero bytes and the associated data is empty, as the spec requires. A
84/// key is used for one value only, which is what makes the fixed nonce safe.
85///
86/// # Errors
87///
88/// Fails when the build's cipher resolver has no AEAD for `suite`. That is the honest refusal:
89/// sealing under the other suite's cipher would produce a field the peer cannot open.
90///
91/// # Example
92///
93/// ```
94/// use syncspin_core::noise::Suite;
95/// use syncspin_core::pairing::wrap::{unwrap, wrap};
96///
97/// // The key comes from `k_wrap` in a real flow; any 32 bytes will do here.
98/// let key = [0x42; 32];
99/// let value = [0x24; 32];
100/// let sealed = wrap(Suite::ChaChaPoly, &key, &value).expect("the cipher is available");
101/// assert_eq!(unwrap(Suite::ChaChaPoly, &key, &sealed).expect("round trip"), value);
102/// ```
103pub fn wrap(suite: Suite, key: &[u8; 32], value: &[u8; 32]) -> Result<[u8; SEALED_LEN]> {
104 let cipher = cipher(suite, key)?;
105
106 // The AEAD appends its tag, so one buffer holds the whole field. A 32-byte value is far
107 // below the maximum, so sealing cannot fail.
108 let mut sealed = [0u8; SEALED_LEN];
109 let written = cipher.encrypt(WRAP_NONCE, &[], value, &mut sealed);
110 if written != SEALED_LEN {
111 // A short write would return the buffer's zero padding as if it were tag bytes, and the
112 // peer would receive a field that opens under no key. Refuse instead of shipping it, and
113 // do not fall back to an implausible success.
114 return Err(anyhow!(
115 "the cipher wrote {written} of {SEALED_LEN} sealed bytes"
116 ));
117 }
118 Ok(sealed)
119}
120
121/// Opens a 48-byte sealed value under `K_wrap` with the AEAD of `suite`, returning the value.
122///
123/// # Errors
124///
125/// Fails when the tag does not authenticate: a wrong key - a different label, `sid` or `ISK` - a
126/// seal made under the other suite, or any changed byte of the ciphertext or tag. It also fails
127/// when the build's cipher resolver has no AEAD for `suite`. The error names no key, value or
128/// seal bytes.
129pub fn unwrap(suite: Suite, key: &[u8; 32], sealed: &[u8; SEALED_LEN]) -> Result<[u8; 32]> {
130 let cipher = cipher(suite, key)?;
131
132 // A failed authentication may still have written unauthenticated plaintext into the buffer
133 // before the tag check, so the buffer scrubs itself on every exit; only the value that
134 // authenticated is copied out, and that copy belongs to the caller.
135 let mut value = Zeroizing::new([0u8; VALUE_LEN]);
136 let written = cipher
137 .decrypt(WRAP_NONCE, &[], sealed, &mut value[..])
138 .map_err(|_| anyhow!("the wrapped pairing value does not authenticate"))?;
139 if written != VALUE_LEN {
140 // A short read would hand back zero padding as if it were the value.
141 return Err(anyhow!(
142 "the cipher returned {written} of {VALUE_LEN} value bytes"
143 ));
144 }
145 Ok(*value)
146}
147
148/// Builds the suite's AEAD for `key`.
149///
150/// The resolver is `snow`'s default one, the same one the handshake uses, so a build that has a
151/// suite for Noise has it here as well. A missing cipher is an error and not a reason to seal
152/// under the other suite. The panic messages and error strings carry no key material: `set`
153/// cannot fail on a 32-byte key.
154///
155/// The cipher keeps its own copy of `key` and has no way to scrub it, so the key is dropped with
156/// the cipher rather than zeroized here. What this crate can scrub is its own copy: callers wrap
157/// `K_wrap` in [`Zeroizing`] so it is wiped as soon as the seal is made or opened.
158fn cipher(suite: Suite, key: &[u8; 32]) -> Result<Box<dyn Cipher>> {
159 let choice = match suite {
160 Suite::ChaChaPoly => CipherChoice::ChaChaPoly,
161 Suite::AesGcm => CipherChoice::AESGCM,
162 };
163 let mut cipher = DefaultResolver.resolve_cipher(&choice).ok_or_else(|| {
164 anyhow!("the cipher suite `{suite}` is not available in this build, so it cannot seal")
165 })?;
166 cipher.set(key);
167 Ok(cipher)
168}
169
170#[cfg(test)]
171mod tests {
172 use super::*;
173
174 #[test]
175 fn the_sealed_length_is_ciphertext_plus_tag() {
176 assert_eq!(SEALED_LEN, 48, "the spec's wrapped field is 48 bytes");
177 assert_eq!(
178 SEALED_LEN,
179 VALUE_LEN + TAG_LEN,
180 "48 is 32 bytes of ciphertext and a 16-byte tag"
181 );
182 }
183
184 #[test]
185 fn a_wrap_is_deterministic_for_one_key_and_value() {
186 // The nonce is fixed by the spec, so the same key and value must seal identically under
187 // either suite; if this ever changes, the peer derives a different ciphertext for the
188 // same field.
189 let key = [0x11; 32];
190 let value = [0x22; 32];
191 for suite in Suite::ALL {
192 assert_eq!(
193 wrap(suite, &key, &value).expect("the cipher is available"),
194 wrap(suite, &key, &value).expect("the cipher is available")
195 );
196 }
197 }
198
199 #[test]
200 fn the_fixed_nonce_is_zero() {
201 // The wrapped field's nonce is the spec's twelve zero bytes, not the handshake's
202 // counter; a change here would still round-trip against this crate and fail against a
203 // real server.
204 assert_eq!(WRAP_NONCE, 0);
205 }
206}