Skip to main content

macula_rust/
node_key.rs

1//! A macula 12 node's keys, as macula and macula-go hold them: ML-DSA-87 in
2//! pq_pure, and in pq_hybrid the LAMPS composite id-MLDSA87-RSA4096-PSS-SHA512
3//! (draft-ietf-lamps-pq-composite-sigs), which signs with both halves and is
4//! valid only when both verify. An identity key's node_id (D5) solves the
5//! admission puzzle; a CONNECT key is bound to it (see `crate::binding`).
6//! Keys are stored in macula's seed form, readable by their owner only (see
7//! [`NodeKey::save`] and [`NodeKey::load`]).
8//!
9//! The ML-DSA-87 half is macula-mldsa, the implementation macula-pqc signs
10//! TLS with, kept as its 32-byte seed. The RSA-PSS-4096 half is aws-lc-rs,
11//! already linked through rustls: constant-time, with a FIPS path.
12
13mod der;
14mod key_file;
15
16pub use key_file::KeyFileError;
17
18use std::fmt;
19
20use aws_lc_rs::rand::SystemRandom;
21use aws_lc_rs::rsa::{KeyPair as RsaKeyPair, KeySize};
22use aws_lc_rs::signature::{
23    KeyPair as _, UnparsedPublicKey, RSA_PSS_2048_8192_SHA384, RSA_PSS_SHA384,
24};
25use macula_mldsa::{PrivateKey, Zeroizing, ML_DSA_87};
26use sha2::{Digest, Sha256, Sha512};
27
28use crate::profile::Profile;
29
30/// How many leading zero bits an identity key's node_id has: a node generates
31/// its identity key for it ([`NodeKey::generate_identity`]), and stations
32/// check it.
33pub const PUZZLE_DIFFICULTY: u32 = 8;
34
35const MLDSA_PUBLIC_KEY_SIZE: usize = 2592;
36const MLDSA_SIGNATURE_SIZE: usize = 4627;
37const RSA_MODULUS_BYTES: usize = 512;
38const COMPOSITE_PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
39const COMPOSITE_LABEL: &[u8] = b"COMPSIG-MLDSA87-RSA4096-PSS-SHA512";
40const NODE_ID_LABEL: &[u8] = b"MACULA-NODE-ID-V1";
41const KEY_ID_LABEL: &[u8] = b"MACULA-KEY-ID-V1";
42
43/// What a node key is for. Each key serves exactly one purpose.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum Purpose {
46    /// A node's identity key, the key its node_id derives from and that signs
47    /// its bindings, status statements and signed objects.
48    Identity,
49    /// A node's CONNECT key, bound to its identity key, which signs the proof
50    /// of each connection it makes.
51    Connect,
52}
53
54impl Purpose {
55    /// The purpose's name.
56    pub fn name(self) -> &'static str {
57        match self {
58            Purpose::Identity => "identity",
59            Purpose::Connect => "connect",
60        }
61    }
62}
63
64impl fmt::Display for Purpose {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.write_str(self.name())
67    }
68}
69
70/// Why a key operation refused.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub enum KeyError {
73    /// A node_id asked of a key that is not an identity key.
74    NotAnIdentityKey,
75    /// A puzzle difficulty outside 0 to 256.
76    DifficultyOutOfRange(u32),
77    /// The operating system gave no randomness.
78    RandomnessUnavailable,
79    /// Generating a half failed.
80    Generate(&'static str),
81    /// Signing with a half failed.
82    Sign(&'static str),
83}
84
85impl fmt::Display for KeyError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            KeyError::NotAnIdentityKey => f.write_str("not an identity key"),
89            KeyError::DifficultyOutOfRange(d) => {
90                write!(f, "puzzle difficulty {d} is outside 0 to 256")
91            }
92            KeyError::RandomnessUnavailable => {
93                f.write_str("the operating system gave no randomness")
94            }
95            KeyError::Generate(half) => write!(f, "could not generate the {half} half"),
96            KeyError::Sign(half) => write!(f, "could not sign with the {half} half"),
97        }
98    }
99}
100
101impl std::error::Error for KeyError {}
102
103/// The RSA-PSS-4096 half of a pq_hybrid key.
104struct RsaHalf {
105    pair: RsaKeyPair,
106    /// The DER `RSAPublicKey`, as carried after the ML-DSA-87 key.
107    public_der: Vec<u8>,
108}
109
110/// One of a node's keys in its profile: the ML-DSA-87 half, and in pq_hybrid
111/// the RSA-PSS-4096 half. It signs as a whole, never with one half on its own.
112/// Showing it gives its purpose, profile and key id, never a private half.
113pub struct NodeKey {
114    purpose: Purpose,
115    profile: Profile,
116    mldsa_seed: Zeroizing<[u8; 32]>,
117    mldsa_public: Vec<u8>,
118    rsa: Option<RsaHalf>,
119}
120
121impl NodeKey {
122    /// A new key for `purpose` in `profile`.
123    pub fn generate(purpose: Purpose, profile: Profile) -> Result<NodeKey, KeyError> {
124        let (mldsa_public, mldsa_seed) =
125            macula_mldsa::key_gen_seed(ML_DSA_87).map_err(|_| KeyError::RandomnessUnavailable)?;
126        let rsa = if profile.hybrid() {
127            let pair = RsaKeyPair::generate(KeySize::Rsa4096)
128                .map_err(|_| KeyError::Generate("RSA-4096"))?;
129            let public_der = pair.public_key().as_ref().to_vec();
130            Some(RsaHalf { pair, public_der })
131        } else {
132            None
133        };
134        Ok(NodeKey {
135            purpose,
136            profile,
137            mldsa_seed,
138            mldsa_public,
139            rsa,
140        })
141    }
142
143    /// A new identity key in `profile` whose node_id starts with `difficulty`
144    /// zero bits, found in about 2^difficulty tries. Each try makes a new
145    /// ML-DSA-87 half; a pq_hybrid key keeps its RSA-PSS half, since the
146    /// node_id covers both.
147    pub fn generate_identity(profile: Profile, difficulty: u32) -> Result<NodeKey, KeyError> {
148        if difficulty > 256 {
149            return Err(KeyError::DifficultyOutOfRange(difficulty));
150        }
151        let mut key = NodeKey::generate(Purpose::Identity, profile)?;
152        while !puzzle_solved(&node_id_of(&key.public_key(), profile), difficulty) {
153            let (public, seed) = macula_mldsa::key_gen_seed(ML_DSA_87)
154                .map_err(|_| KeyError::RandomnessUnavailable)?;
155            key.mldsa_public = public;
156            key.mldsa_seed = seed;
157        }
158        Ok(key)
159    }
160
161    /// What the key is for.
162    pub fn purpose(&self) -> Purpose {
163        self.purpose
164    }
165
166    /// The profile the key belongs to.
167    pub fn profile(&self) -> Profile {
168        self.profile
169    }
170
171    /// The key as carried (D13): the 2,592-byte ML-DSA-87 key, followed in
172    /// pq_hybrid by the DER `RSAPublicKey`.
173    pub fn public_key(&self) -> Vec<u8> {
174        let mut carried = self.mldsa_public.clone();
175        if let Some(rsa) = &self.rsa {
176            carried.extend_from_slice(&rsa.public_der);
177        }
178        carried
179    }
180
181    /// The node_id of an identity key (D5).
182    pub fn node_id(&self) -> Result<[u8; 32], KeyError> {
183        match self.purpose {
184            Purpose::Identity => Ok(node_id_of(&self.public_key(), self.profile)),
185            Purpose::Connect => Err(KeyError::NotAnIdentityKey),
186        }
187    }
188
189    /// The id that names the key in signed objects: an identity key's
190    /// node_id, and the key id of any other key.
191    pub fn key_id(&self) -> [u8; 32] {
192        match self.purpose {
193            Purpose::Identity => node_id_of(&self.public_key(), self.profile),
194            Purpose::Connect => key_id_of(&self.public_key(), self.profile),
195        }
196    }
197
198    /// Signs `message`: with ML-DSA-87 alone in pq_pure, and in pq_hybrid with
199    /// the composite, where both halves sign the message representative, the
200    /// ML-DSA-87 half with the composite label as its context, and the
201    /// signature is the ML-DSA-87 signature followed by the RSA-PSS one.
202    /// ML-DSA-87 signs hedged and RSA-PSS salted, so each signature is new.
203    pub fn sign(&self, message: &[u8]) -> Result<Vec<u8>, KeyError> {
204        let seed = PrivateKey::Seed(&self.mldsa_seed);
205        let Some(rsa) = &self.rsa else {
206            return macula_mldsa::sign(ML_DSA_87, seed, message, &[])
207                .map_err(|_| KeyError::Sign("ML-DSA-87"));
208        };
209        let representative = composite_representative(message);
210        let mut signature = macula_mldsa::sign(ML_DSA_87, seed, &representative, COMPOSITE_LABEL)
211            .map_err(|_| KeyError::Sign("ML-DSA-87"))?;
212        let mut rsa_signature = vec![0u8; rsa.pair.public_modulus_len()];
213        rsa.pair
214            .sign(
215                &RSA_PSS_SHA384,
216                &SystemRandom::new(),
217                &representative,
218                &mut rsa_signature,
219            )
220            .map_err(|_| KeyError::Sign("RSA-PSS"))?;
221        signature.extend_from_slice(&rsa_signature);
222        Ok(signature)
223    }
224}
225
226impl fmt::Display for NodeKey {
227    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228        write!(
229            f,
230            "{} {} key {}",
231            self.purpose,
232            self.profile,
233            hex_of(&self.key_id())
234        )
235    }
236}
237
238impl fmt::Debug for NodeKey {
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        fmt::Display::fmt(self, f)
241    }
242}
243
244/// Whether `signature` is valid over `message` for a key as carried, under
245/// `profile`: an ML-DSA-87 signature in pq_pure, and in pq_hybrid a composite
246/// whose two halves both verify, with the key in its one carried form.
247/// Malformed input is refused, never panicked on.
248pub fn verify(message: &[u8], signature: &[u8], carried_key: &[u8], profile: Profile) -> bool {
249    if !profile.hybrid() {
250        return signature.len() == MLDSA_SIGNATURE_SIZE
251            && carried_key.len() == MLDSA_PUBLIC_KEY_SIZE
252            && macula_mldsa::verify(ML_DSA_87, carried_key, message, signature, &[]) == Ok(true);
253    }
254    if signature.len() != signature_size(profile) || !carried_key_well_formed(carried_key, profile)
255    {
256        return false;
257    }
258    let representative = composite_representative(message);
259    let (mldsa_public, rsa_public) = carried_key.split_at(MLDSA_PUBLIC_KEY_SIZE);
260    let (mldsa_signature, rsa_signature) = signature.split_at(MLDSA_SIGNATURE_SIZE);
261    let mldsa_valid = macula_mldsa::verify(
262        ML_DSA_87,
263        mldsa_public,
264        &representative,
265        mldsa_signature,
266        COMPOSITE_LABEL,
267    ) == Ok(true);
268    let rsa_valid = UnparsedPublicKey::new(&RSA_PSS_2048_8192_SHA384, rsa_public)
269        .verify(&representative, rsa_signature)
270        .is_ok();
271    mldsa_valid && rsa_valid
272}
273
274/// Whether `key` is a key in its one carried form for `profile` (D13): exactly
275/// 2,592 bytes in pq_pure, and in pq_hybrid the ML-DSA-87 key followed by a DER
276/// `RSAPublicKey` that encodes back to the same bytes, with a 4,096-bit modulus
277/// and exponent 65537. It says nothing about who holds the key.
278pub fn carried_key_well_formed(key: &[u8], profile: Profile) -> bool {
279    if !profile.hybrid() {
280        return key.len() == MLDSA_PUBLIC_KEY_SIZE;
281    }
282    if key.len() <= MLDSA_PUBLIC_KEY_SIZE {
283        return false;
284    }
285    let der = &key[MLDSA_PUBLIC_KEY_SIZE..];
286    der::rsa_public_key_is_4096_f4(der)
287        && aws_lc_rs::rsa::PublicKey::from_der(der).is_ok_and(|parsed| parsed.as_ref() == der)
288}
289
290/// The size of a signature by a node key in `profile`: the ML-DSA-87
291/// signature, followed in pq_hybrid by an RSA-PSS signature as long as the
292/// modulus.
293pub fn signature_size(profile: Profile) -> usize {
294    if profile.hybrid() {
295        MLDSA_SIGNATURE_SIZE + RSA_MODULUS_BYTES
296    } else {
297        MLDSA_SIGNATURE_SIZE
298    }
299}
300
301/// The node_id of an identity key as carried, under `profile` (D5). A node_id
302/// earns no trust on its own: rely on it only after a signature by the same
303/// carried key has verified.
304pub fn node_id_of(carried_key: &[u8], profile: Profile) -> [u8; 32] {
305    labelled_id(NODE_ID_LABEL, carried_key, profile)
306}
307
308/// The key id of a key as carried that is not an identity key. Like a
309/// node_id, it earns no trust on its own.
310pub fn key_id_of(carried_key: &[u8], profile: Profile) -> [u8; 32] {
311    labelled_id(KEY_ID_LABEL, carried_key, profile)
312}
313
314/// SHA-256 over `label`, a zero byte, the length and ASCII name of
315/// `profile`, and a key as carried.
316fn labelled_id(label: &[u8], carried_key: &[u8], profile: Profile) -> [u8; 32] {
317    let name = profile.name();
318    let mut h = Sha256::new();
319    h.update(label);
320    h.update([0, name.len() as u8]);
321    h.update(name.as_bytes());
322    h.update(carried_key);
323    h.finalize().into()
324}
325
326/// Whether `node_id` starts with `difficulty` zero bits. A difficulty above
327/// 256 is never solved.
328pub fn puzzle_solved(node_id: &[u8; 32], difficulty: u32) -> bool {
329    if difficulty > 256 {
330        return false;
331    }
332    let (whole, rest) = ((difficulty / 8) as usize, difficulty % 8);
333    node_id[..whole].iter().all(|&b| b == 0) && (rest == 0 || node_id[whole] >> (8 - rest) == 0)
334}
335
336/// The message both halves of a composite sign: the prefix, the label, a zero
337/// byte for the empty application context, and the SHA-512 of the message.
338fn composite_representative(message: &[u8]) -> Vec<u8> {
339    let mut out = Vec::with_capacity(COMPOSITE_PREFIX.len() + COMPOSITE_LABEL.len() + 1 + 64);
340    out.extend_from_slice(COMPOSITE_PREFIX);
341    out.extend_from_slice(COMPOSITE_LABEL);
342    out.push(0);
343    out.extend_from_slice(&Sha512::digest(message));
344    out
345}
346
347fn hex_of(bytes: &[u8]) -> String {
348    bytes.iter().map(|b| format!("{b:02x}")).collect()
349}