Skip to main content

syncspin_core/pairing/
pake.rs

1//! CPace over X25519 with SHA-512, as Sendspin's code-based pairing uses it.
2//!
3//! The suite is `CPACE-X25519-SHA512` from
4//! [draft-irtf-cfrg-cpace-21](https://datatracker.ietf.org/doc/draft-irtf-cfrg-cpace/21/):
5//! group `G_X25519`, hash SHA-512, mutual confirmation flow. This module implements the
6//! primitives that flow is built from - the generator, the verified scalar multiplication, the
7//! transcript hashing, the intermediate session key and the key-confirmation tags - and pins them
8//! to the draft's vectors in `tests/pake_vectors.rs`. The message flow itself belongs to the
9//! session layer, which knows when a share or a tag crosses the wire.
10//!
11//! # What the generator is
12//!
13//! `generator_string` is `lv_cat(DSI, PRS, zero_bytes(len_zpad), CI, sid)` with the zero padding
14//! sized so that the first SHA-512 block holds exactly the encoded `DSI` and `PRS` (§8.1,
15//! Appendix A.2). The first 32 bytes of its SHA-512 digest are decoded as a u-coordinate
16//! (`decodeUCoordinate(_, 255)` from [RFC 7748]) and mapped with Elligator 2. The associated
17//! data `ADa`/`ADb` is *not* an input: it enters the transcript that the confirmation flow
18//! hashes, not the generator.
19//!
20//! # The transcript and the key confirmation
21//!
22//! Sendspin fixes CPace's initiator-responder mode, so the transcript is
23//! [`transcript_ir`]: `lv_cat(Ya, ADa) || lv_cat(Yb, ADb)`. [`intermediate_session_key`] hashes
24//! `lv_cat(G.DSI_ISK, sid, K)` followed by that transcript. The explicit key confirmation of
25//! §10.4 derives `mac_key = H(b"CPaceMac" || sid || ISK)` and authenticates the sender's own
26//! `lv_cat(share, associated data)` with HMAC-SHA-512, which is [`key_confirmation_tag`].
27//! [`transcript_oc`] is the parallel-execution form: Sendspin does not use it, but the draft's
28//! vectors cover it and keeping it proves the two forms differ only in the ordering step.
29//!
30//! # Representative convention
31//!
32//! CPace hands the map an arbitrary field element. `elligator2::from_representative` instead
33//! expects a representative, a value below `(p-1)/2`, and masks bits 254 and 255 of its input.
34//! The draft's field element can have bit 254 set, and then passing it straight in changes the
35//! point: for the §B.1.1 vector the raw call returns `97ef2dc8...cd72fe23` instead of the
36//! draft's `d04bf6d4...2f05a73f`. `representative` closes the gap exactly: Elligator 2 uses
37//! only `r^2`, so `r` and `-r` map to the same point, and negating a value with bit 254 set
38//! yields one the crate accepts. The §B.1.1 generator matches only with that normalisation.
39//!
40//! # Secret handling
41//!
42//! `PRS`, the scalar, the shared point, `ISK` and the tags derive from the pairing code or from a
43//! scalar. This module returns them as bytes, exactly as [`mod@super::wrap`] does, and never
44//! formats them: no `Debug`, no `Display`, no error string carries a value. [`key_confirmation_tag`]
45//! and [`verify_key_confirmation_tag`] are branch-free over the secret-derived tag.
46//!
47//! The intermediate buffers this module builds are `Zeroizing`: the hashed ISK input, the
48//! MAC-key input and the MAC key itself wipe when the call returns. The returned arrays belong to
49//! the caller, and this crate does not scrub memory it no longer owns - a caller that keeps a
50//! scalar or an ISK past the round should hold it in `Zeroizing` itself.
51//!
52//! # Not reviewed
53//!
54//! Neither this module nor `elligator2` 0.1 has had an external cryptographic review. The
55//! draft vectors pin the arithmetic, not the review.
56
57use anyhow::{bail, Result};
58use hmac::{Hmac, Mac};
59use sha2::{Digest, Sha512};
60use subtle::ConstantTimeEq;
61use zeroize::Zeroizing;
62
63/// `G_X25519.DSI`, the group's domain-separation identifier (§8.2).
64const DSI: &[u8] = b"CPace255";
65
66/// `G.DSI_ISK`, the domain-separation identifier of the ISK (§7.2).
67const DSI_ISK: &[u8] = b"CPace255_ISK";
68
69/// The label that prefixes the MCF MAC key (§10.4).
70const MAC_LABEL: &[u8] = b"CPaceMac";
71
72/// The input block size of SHA-512 in bytes (`H.s_in_bytes`), which `generator_string` pads to.
73const SHA512_BLOCK_LEN: usize = 128;
74
75/// Length of a CPace public share in bytes.
76pub const SHARE_LEN: usize = 32;
77
78/// Length of the intermediate session key in bytes: one SHA-512 output.
79pub const ISK_LEN: usize = 64;
80
81/// Length of a key-confirmation tag in bytes: one HMAC-SHA-512 output.
82pub const TAG_LEN: usize = 64;
83
84/// The field modulus `p = 2^255 - 19`, little-endian.
85const FIELD_MODULUS: [u8; 32] = [
86    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
87    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
88];
89
90/// Derives the CPace generator for this `PRS`, `CI` and `sid`.
91///
92/// Returns the generator's u-coordinate as 32 little-endian bytes, the encoding every group
93/// element in CPace uses. `PRS` is the pairing code's bytes, `CI` the channel identifier (empty
94/// when the parties are identified by their associated data instead) and `sid` the session id.
95///
96/// The function is total: every input hashes to a field element, and Elligator 2 maps every
97/// field element to a curve point.
98///
99/// # Example
100///
101/// ```
102/// use syncspin_core::pairing::pake::generator;
103///
104/// // Draft §B.1.1, X25519 with SHA-512.
105/// let sid = [
106///     0x7e, 0x4b, 0x47, 0x91, 0xd6, 0xa8, 0xef, 0x01, 0x9b, 0x93, 0x6c, 0x79, 0xfb, 0x7f,
107///     0x2c, 0x57,
108/// ];
109/// let g = generator(b"Password", b"\x0bA_initiator\x0bB_responder", &sid);
110/// assert_eq!(
111///     g,
112///     [
113///         0xd0, 0x4b, 0xf6, 0xd4, 0x1f, 0x6a, 0x28, 0x96, 0x32, 0xa2, 0xe9, 0x29, 0xfa, 0x29,
114///         0xbe, 0xbd, 0x51, 0x09, 0x25, 0x12, 0xa7, 0x82, 0x9f, 0xdd, 0xe7, 0xd3, 0x14, 0xb6,
115///         0x2f, 0x05, 0xa7, 0x3f,
116///     ]
117/// );
118/// ```
119pub fn generator(prs: &[u8], ci: &[u8], sid: &[u8]) -> [u8; 32] {
120    let digest = Sha512::digest(generator_string(prs, ci, sid));
121
122    // `decodeUCoordinate(gen_str_hash, G.field_size_bits)`: the top 32 bytes of the digest
123    // with bit 255 ignored.
124    let mut field = [0u8; 32];
125    field.copy_from_slice(&digest[..32]);
126
127    map_to_curve(&field)
128}
129
130/// Maps a field element to `G_X25519` with Elligator 2, the draft's `map_to_curve_elligator2`.
131///
132/// `field` is a 32-byte little-endian field element, the encoding `decodeUCoordinate` produces.
133/// Bit 255 is ignored here, as `decodeUCoordinate(_, 255)` ignores it, so the function is total
134/// over 32-byte strings rather than relying on every caller to mask first. Values at or above
135/// the modulus are reduced, so `map(u) == map(u mod p)`.
136///
137/// The image is a u-coordinate in the same little-endian encoding. The representative
138/// normalisation that `elligator2` needs is inside and branch-free: the element is reduced and,
139/// when it still has bit 254 set, replaced by its negation, which the map cannot distinguish.
140pub fn map_to_curve(field: &[u8; 32]) -> [u8; 32] {
141    let mut element = *field;
142    element[31] &= 0x7f;
143    elligator2::from_representative(&representative(element))
144}
145
146/// Computes `G_X25519.scalar_mult_vfy(scalar, u)`, the verified scalar multiplication.
147///
148/// X25519 clamps the scalar and ignores bit 255 of `u`, exactly as [RFC 7748] specifies, so the
149/// non-canonical encodings of draft §B.1.10 are handled without a separate branch. A result that
150/// is the neutral element means `u` was a low-order point; that is the abort case the draft
151/// requires and the error this function returns.
152///
153/// # Errors
154///
155/// Fails when `u` encodes a low-order point, that is when the shared point is the neutral
156/// element. CPace requires the caller to abort the round in that case.
157pub fn scalar_mult_vfy(scalar: &[u8; 32], u: &[u8; 32]) -> Result<[u8; 32]> {
158    let point = x25519_dalek::x25519(*scalar, *u);
159    // Fold rather than compare: a slice comparison can stop at the first differing byte, which
160    // would make the timing depend on how many leading bytes of a valid point are zero.
161    if is_all_zero(&point) {
162        bail!("the peer's CPace share encodes a low-order point");
163    }
164    Ok(point)
165}
166
167/// Returns whether every byte is zero, touching the whole slice.
168fn is_all_zero(bytes: &[u8]) -> bool {
169    bytes.iter().fold(0u8, |acc, &byte| acc | byte) == 0
170}
171
172/// Computes a public share `Y = G.scalar_mult(scalar, generator)`.
173///
174/// X25519 clamps the scalar, exactly as `G_X25519.sample_scalar` does, so a scalar drawn from the
175/// CSPRNG is used here unchanged. The generator is public, so the low-order check costs nothing
176/// secret and rejects a degenerate generator instead of returning the neutral element.
177///
178/// # Errors
179///
180/// Fails when the group operation yields the neutral element, which only a low-order `generator`
181/// can cause.
182pub fn public_share(scalar: &[u8; 32], generator: &[u8; 32]) -> Result<[u8; 32]> {
183    scalar_mult_vfy(scalar, generator)
184}
185
186/// Concatenates each part with its LEB128 length prepended (`lv_cat` from §6.3).
187///
188/// The length makes the encoding prefix-free, which is what lets the transcript be hashed without
189/// an ambiguity between a share and the associated data that follows it.
190///
191/// # Example
192///
193/// ```
194/// use syncspin_core::pairing::pake::lv_cat;
195///
196/// // Draft §A.1.4.
197/// assert_eq!(
198///     lv_cat(&[b"1234".as_slice(), b"5", b"", b"678"]),
199///     [
200///         0x04, b'1', b'2', b'3', b'4', 0x01, b'5', 0x00, 0x03, b'6', b'7', b'8',
201///     ]
202/// );
203/// ```
204pub fn lv_cat(parts: &[&[u8]]) -> Vec<u8> {
205    let mut joined = Vec::new();
206    for part in parts {
207        push_lv(&mut joined, part);
208    }
209    joined
210}
211
212/// Builds the initiator-responder transcript `lv_cat(Ya, ADa) || lv_cat(Yb, ADb)` (§6.3).
213///
214/// Both sides hash the same ordering: the initiator's share and associated data first, then the
215/// responder's, whichever party computes it. Sendspin's `ADa` is `b"server"` and its `ADb` is
216/// `b"client"`.
217pub fn transcript_ir(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
218    let mut transcript = lv_cat(&[ya, ad_a]);
219    transcript.extend_from_slice(&lv_cat(&[yb, ad_b]));
220    transcript
221}
222
223/// Builds the parallel-execution transcript `o_cat(lv_cat(Ya, ADa), lv_cat(Yb, ADb))` (§6.3).
224///
225/// The two messages are ordered lexicographically and prefixed with `b"oc"`, so neither party has
226/// to know who spoke first. Sendspin fixes an initiator and a responder, so it uses
227/// [`transcript_ir`]; this form exists because the draft's vectors cover it.
228pub fn transcript_oc(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
229    let initiator = lv_cat(&[ya, ad_a]);
230    let responder = lv_cat(&[yb, ad_b]);
231    let mut transcript = Vec::from(b"oc".as_slice());
232    if lexicographically_larger(&initiator, &responder) {
233        transcript.extend_from_slice(&initiator);
234        transcript.extend_from_slice(&responder);
235    } else {
236        transcript.extend_from_slice(&responder);
237        transcript.extend_from_slice(&initiator);
238    }
239    transcript
240}
241
242/// Derives `ISK = H(lv_cat(G.DSI_ISK, sid, K) || transcript)` (§7.2).
243///
244/// `shared_point` is the secret point `K = scalar_mult_vfy(scalar, peer_share)`, and `transcript`
245/// is [`transcript_ir`] or [`transcript_oc`]. The result is the 64-byte intermediate session key,
246/// which the higher-level protocol processes before use: Sendspin derives `K_wrap` from it with
247/// [`super::wrap::k_wrap`].
248///
249/// The value is secret. It is returned as bytes and never formatted.
250pub fn intermediate_session_key(
251    sid: &[u8],
252    shared_point: &[u8],
253    transcript: &[u8],
254) -> [u8; ISK_LEN] {
255    // The hashed input carries the shared point, which is the Diffie-Hellman secret of the
256    // round, so the buffer scrubs itself when the digest returns.
257    let mut input = Zeroizing::new(lv_cat(&[DSI_ISK, sid, shared_point]));
258    input.extend_from_slice(transcript);
259    Sha512::digest(&input[..]).into()
260}
261
262/// Computes the explicit key-confirmation tag of the sender's own message (§10.4).
263///
264/// `mac_key = H(b"CPaceMac" || sid || ISK)`, raw and without length prefixes, then
265/// `T = HMAC-SHA-512(mac_key, lv_cat(share, associated data))`. Passing the initiator's `Ya` and
266/// `ADa` yields `Ta` (`server_kc`); the responder's `Yb` and `ADb` yield `Tb` (`client_kc`).
267///
268/// The tag is secret-derived. It is returned as bytes and never formatted.
269pub fn key_confirmation_tag(
270    sid: &[u8],
271    isk: &[u8; ISK_LEN],
272    share: &[u8],
273    ad: &[u8],
274) -> [u8; TAG_LEN] {
275    // Both buffers hold the ISK, so both scrub themselves when the tag is finalised.
276    let mut key_input = Zeroizing::new(Vec::from(MAC_LABEL));
277    key_input.extend_from_slice(sid);
278    key_input.extend_from_slice(isk);
279    let mac_key = Zeroizing::new(<[u8; 64]>::from(Sha512::digest(&key_input[..])));
280
281    let mut mac = <Hmac<Sha512> as Mac>::new_from_slice(&mac_key[..])
282        .expect("HMAC-SHA-512 accepts a key of any length");
283    mac.update(&lv_cat(&[share, ad]));
284    mac.finalize().into_bytes().into()
285}
286
287/// Returns whether a received tag equals the one this side derived.
288///
289/// The comparison is `subtle::ConstantTimeEq`, which folds every byte of both tags into one
290/// choice instead of stopping at the first mismatch: the tags are derived from `ISK`, and an
291/// early exit would leak how many leading bytes an attacker guessed. Only the single final
292/// result depends on the data, and that result is public - it decides whether the round
293/// continues. Going through the crate rather than an inline `==` is the point: a later edit
294/// cannot turn this into a short-circuiting comparison without deleting an import.
295#[must_use]
296pub fn verify_key_confirmation_tag(expected: &[u8; TAG_LEN], received: &[u8; TAG_LEN]) -> bool {
297    bool::from(expected[..].ct_eq(&received[..]))
298}
299
300/// Returns whether `left` is greater than `right` in the draft's lexicographical order (§A.3.1).
301fn lexicographically_larger(left: &[u8], right: &[u8]) -> bool {
302    for (a, b) in left.iter().zip(right) {
303        if a > b {
304            return true;
305        }
306        if a < b {
307            return false;
308        }
309    }
310    left.len() > right.len()
311}
312
313/// Builds `generator_string(DSI, PRS, CI, sid, H.s_in_bytes)` (§8.1, Appendix A.2).
314fn generator_string(prs: &[u8], ci: &[u8], sid: &[u8]) -> Vec<u8> {
315    // The pad fills the first hash block after the encoded DSI and PRS, leaving room for the
316    // length byte of the pad field itself.
317    let pad = SHA512_BLOCK_LEN.saturating_sub(
318        1 + prepend_len_len(DSI.len()) + DSI.len() + prepend_len_len(prs.len()) + prs.len(),
319    );
320
321    let mut string = Vec::new();
322    push_lv(&mut string, DSI);
323    push_lv(&mut string, prs);
324    push_len(&mut string, pad);
325    string.resize(string.len() + pad, 0);
326    push_lv(&mut string, ci);
327    push_lv(&mut string, sid);
328    string
329}
330
331/// Appends `prepend_len(bytes)`: the LEB128 length followed by the bytes.
332fn push_lv(out: &mut Vec<u8>, bytes: &[u8]) {
333    push_len(out, bytes.len());
334    out.extend_from_slice(bytes);
335}
336
337/// Appends `len` as an unsigned LEB128 integer.
338fn push_len(out: &mut Vec<u8>, mut len: usize) {
339    loop {
340        let byte = (len & 0x7f) as u8;
341        len >>= 7;
342        if len == 0 {
343            out.push(byte);
344            return;
345        }
346        out.push(byte | 0x80);
347    }
348}
349
350/// Returns how many bytes `prepend_len` uses for a value of `len` bytes.
351fn prepend_len_len(len: usize) -> usize {
352    let mut len = len;
353    let mut width = 1;
354    while len >= 0x80 {
355        len >>= 7;
356        width += 1;
357    }
358    width
359}
360
361/// Maps a field element into the representative domain `elligator2` accepts.
362///
363/// The crate's representatives are below `(p-1)/2` and it masks bits 254 and 255 of whatever it
364/// is given. CPace's field element can have bit 254 set, so it is reduced modulo `p` and, when
365/// bit 254 is still set, replaced by its negation. That is exact: Elligator 2 uses only `r^2`,
366/// so `r` and `-r` map to the same point.
367///
368/// Both selections are branch-free. The inputs are derived from the pairing code, which is a
369/// secret, and a data-dependent branch here would leak a bit of the hash output.
370fn representative(field: [u8; 32]) -> [u8; 32] {
371    // `field` is below 2^255 and therefore below 2p, so one subtraction reduces it.
372    let (reduced, borrow) = subtract(&field, &FIELD_MODULUS);
373    let reduced = select(&field, &reduced, borrow.wrapping_sub(1));
374
375    let (negated, _) = subtract(&FIELD_MODULUS, &reduced);
376    select(&reduced, &negated, 0u8.wrapping_sub(reduced[31] >> 6))
377}
378
379/// Subtracts two little-endian 256-bit integers, returning the difference and the borrow.
380fn subtract(a: &[u8; 32], b: &[u8; 32]) -> ([u8; 32], u8) {
381    let mut difference = [0u8; 32];
382    let mut borrow = 0u8;
383    for (i, byte) in difference.iter_mut().enumerate() {
384        let (value, borrowed_a) = a[i].overflowing_sub(b[i]);
385        let (value, borrowed_b) = value.overflowing_sub(borrow);
386        *byte = value;
387        borrow = u8::from(borrowed_a) | u8::from(borrowed_b);
388    }
389    (difference, borrow)
390}
391
392/// Returns `b` when `mask` is all ones and `a` when it is zero, without branching.
393fn select(a: &[u8; 32], b: &[u8; 32], mask: u8) -> [u8; 32] {
394    let mut selected = [0u8; 32];
395    for (i, byte) in selected.iter_mut().enumerate() {
396        *byte = a[i] ^ ((a[i] ^ b[i]) & mask);
397    }
398    selected
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    /// The draft's §B.1.1 `generator_string`, 170 bytes.
406    const DRAFT_GENERATOR_STRING: &str = concat!(
407        "0843506163653235350850617373776f72646d00000000000000000000000000",
408        "0000000000000000000000000000000000000000000000000000000000000000",
409        "0000000000000000000000000000000000000000000000000000000000000000",
410        "0000000000000000000000000000000000000000000000000000000000000000",
411        "180b415f696e69746961746f720b425f726573706f6e646572107e4b4791d6a8",
412        "ef019b936c79fb7f2c57",
413    );
414
415    /// The draft's §B.1.1 SHA-512 digest of that string, first 32 bytes.
416    const DRAFT_HASH: &str = "03998087bdb1a2617bbe25ef5a7c18cd4f84f902328701790958755ee4aed1d3";
417
418    fn hex(bytes: &[u8]) -> String {
419        use std::fmt::Write as _;
420        bytes.iter().fold(String::new(), |mut text, byte| {
421            write!(text, "{byte:02x}").expect("writing into a String cannot fail");
422            text
423        })
424    }
425
426    fn draft_sid() -> [u8; 16] {
427        let mut sid = [0u8; 16];
428        sid.copy_from_slice(
429            &hex_decode("7e4b4791d6a8ef019b936c79fb7f2c57").expect("the vector is hex"),
430        );
431        sid
432    }
433
434    fn hex_decode(value: &str) -> Option<Vec<u8>> {
435        if value.len() % 2 != 0 {
436            return None;
437        }
438        (0..value.len())
439            .step_by(2)
440            .map(|i| u8::from_str_radix(&value[i..i + 2], 16).ok())
441            .collect()
442    }
443
444    #[test]
445    fn the_generator_string_matches_the_draft() {
446        let string = generator_string(b"Password", b"\x0bA_initiator\x0bB_responder", &draft_sid());
447        assert_eq!(
448            string.len(),
449            170,
450            "the draft's generator string is 170 bytes"
451        );
452        assert_eq!(hex(&string), DRAFT_GENERATOR_STRING);
453    }
454
455    #[test]
456    fn the_generator_string_hashes_to_the_draft_digest() {
457        let digest = Sha512::digest(generator_string(
458            b"Password",
459            b"\x0bA_initiator\x0bB_responder",
460            &draft_sid(),
461        ));
462        assert_eq!(hex(&digest[..32]), DRAFT_HASH);
463    }
464
465    #[test]
466    fn is_all_zero_checks_every_byte() {
467        assert!(is_all_zero(&[0u8; 32]), "32 zero bytes are all zero");
468        assert!(is_all_zero(&[]), "an empty slice has no non-zero byte");
469
470        let mut leading = [0u8; 32];
471        leading[0] = 1;
472        assert!(!is_all_zero(&leading), "a non-zero first byte counts");
473
474        let mut trailing = [0u8; 32];
475        trailing[31] = 1;
476        assert!(!is_all_zero(&trailing), "a non-zero last byte counts");
477    }
478
479    #[test]
480    fn a_field_element_above_the_representative_domain_is_negated() {
481        // 2^254 + 1: bit 254 set, which `from_representative` would mask away. Negating it
482        // gives a value the map reads unchanged, and the map is even, so both agree.
483        let mut field = [0u8; 32];
484        field[0] = 1;
485        field[31] = 0x40;
486
487        let canonical = representative(field);
488        assert_eq!(
489            canonical[31] >> 6,
490            0,
491            "the representative has bit 254 clear"
492        );
493        assert_eq!(
494            representative(canonical),
495            canonical,
496            "an already canonical representative stays as it is"
497        );
498    }
499}