Skip to main content

rustflexstack/security/pki_client/
canonical.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Canonical key pair of an ITS-S (ETSI TS 102 941 V2.2.1 clause 6.1.2).
5//!
6//! The ITS-S signs its initial enrolment request with the canonical private key
7//! (signer `self`, clause 6.2.3.2.1); the EA verifies it with the canonical
8//! public key registered for the canonical identifier (`itsId`) before the first
9//! request. An unregistered identifier is refused with `unknownits`, a request
10//! signed with another key with `invalidsignature`.
11//!
12//! [`load_or_create_canonical_key`] keeps the key pair in two files:
13//! - `<path>`: the private key, PKCS#8 PEM, mode 0600, created once (never
14//!   overwritten);
15//! - `<path minus .pem>.pub.pem`: the public key, SubjectPublicKeyInfo PEM, to be
16//!   registered with the EA (pythonpki: `ea-tool register --its-id ...
17//!   --public-key ...`).
18//!
19//! The canonical identifier may be assigned (manufacturer) or generated by the
20//! ITS-S (clause 6.1.3); [`canonical_id`] generates a stable one from the public
21//! key: the last 8 octets of SHA-256 over the DER SubjectPublicKeyInfo.
22//!
23//! The formats and the identifier are the same in FlexStack
24//! (`flexstack.security.pki_client.canonical`).
25
26use std::path::{Path, PathBuf};
27
28use p256::pkcs8::{
29    DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey, LineEnding,
30};
31use sha2::{Digest, Sha256};
32
33use super::client::PkiError;
34
35/// The canonical key pair kept on disk.
36#[derive(Debug, Clone)]
37pub struct CanonicalKey {
38    /// Private scalar (32 octets), as [`super::PkiClient::new`] takes it.
39    pub scalar: Vec<u8>,
40    /// Public key, SubjectPublicKeyInfo PEM.
41    pub public_pem: String,
42    pub private_path: PathBuf,
43    pub public_path: PathBuf,
44    /// The private key file was created by this call.
45    pub created: bool,
46}
47
48impl CanonicalKey {
49    /// The canonical identifier generated from the public key ([`canonical_id`]).
50    pub fn its_id(&self) -> [u8; 8] {
51        canonical_id(&self.public_pem).expect("public key PEM written by this module")
52    }
53
54    /// The pythonpki command that registers this ITS-S with the EA (`its_id`
55    /// defaults to [`CanonicalKey::its_id`]).
56    pub fn registration_command(&self, its_id: Option<&[u8]>) -> String {
57        let id = its_id
58            .map(<[u8]>::to_vec)
59            .unwrap_or_else(|| self.its_id().to_vec());
60        format!(
61            "ea-tool register --its-id {} --public-key {}",
62            hex(&id),
63            self.public_path.display()
64        )
65    }
66}
67
68fn hex(bytes: &[u8]) -> String {
69    bytes.iter().map(|b| format!("{b:02x}")).collect()
70}
71
72fn invalid(message: impl Into<String>) -> PkiError {
73    PkiError::Io(std::io::Error::new(
74        std::io::ErrorKind::InvalidData,
75        message.into(),
76    ))
77}
78
79/// `canonical_key.pem` -> `canonical_key.pub.pem`.
80pub fn public_key_path(private_path: &Path) -> PathBuf {
81    let name = private_path
82        .file_name()
83        .map(|n| n.to_string_lossy().into_owned())
84        .unwrap_or_default();
85    let stem = name.strip_suffix(".pem").unwrap_or(&name);
86    private_path.with_file_name(format!("{stem}.pub.pem"))
87}
88
89/// Canonical identifier generated from a public key PEM: the last 8 octets of
90/// SHA-256 over its DER SubjectPublicKeyInfo.
91pub fn canonical_id(public_pem: &str) -> Result<[u8; 8], PkiError> {
92    let key = p256::PublicKey::from_public_key_pem(public_pem)
93        .map_err(|e| invalid(format!("canonical public key: {e}")))?;
94    let der = key
95        .to_public_key_der()
96        .map_err(|e| invalid(format!("canonical public key: {e}")))?;
97    let digest = Sha256::digest(der.as_bytes());
98    let mut id = [0u8; 8];
99    id.copy_from_slice(&digest[24..]);
100    Ok(id)
101}
102
103/// The NIST P-256 private key of a PEM: PKCS#8 (`PRIVATE KEY`) or SEC1 (`EC PRIVATE KEY`).
104fn secret_key(private_pem: &str) -> Result<p256::SecretKey, PkiError> {
105    p256::SecretKey::from_pkcs8_pem(private_pem)
106        .or_else(|_| p256::SecretKey::from_sec1_pem(private_pem))
107        .map_err(|_| invalid("the canonical key must be a NIST P-256 private key (PEM)"))
108}
109
110/// SubjectPublicKeyInfo PEM of a canonical private key PEM (P-256).
111pub fn public_pem(private_pem: &str) -> Result<String, PkiError> {
112    secret_key(private_pem)?
113        .public_key()
114        .to_public_key_pem(LineEnding::LF)
115        .map_err(|e| invalid(format!("canonical public key: {e}")))
116}
117
118fn create_private(path: &Path) -> Result<(), PkiError> {
119    use std::io::Write;
120    let key = p256::SecretKey::random(&mut rand::thread_rng());
121    let pem = key
122        .to_pkcs8_pem(LineEnding::LF)
123        .map_err(|e| invalid(format!("canonical private key: {e}")))?;
124    let mut options = std::fs::OpenOptions::new();
125    options.write(true).create_new(true);
126    #[cfg(unix)]
127    {
128        use std::os::unix::fs::OpenOptionsExt;
129        options.mode(0o600);
130    }
131    options.open(path)?.write_all(pem.as_bytes())?;
132    Ok(())
133}
134
135/// The canonical key pair kept at `path`, created (NIST P-256) when absent.
136pub fn load_or_create_canonical_key(path: &Path) -> Result<CanonicalKey, PkiError> {
137    let public_path = public_key_path(path);
138    let mut created = false;
139    if !path.exists() {
140        if let Some(parent) = path.parent() {
141            std::fs::create_dir_all(parent)?;
142        }
143        create_private(path)?;
144        created = true;
145    }
146    let private_pem = std::fs::read_to_string(path)?;
147    let secret = secret_key(&private_pem)?;
148    let public = public_pem(&private_pem)?;
149    if std::fs::read_to_string(&public_path).ok().as_deref() != Some(public.as_str()) {
150        std::fs::write(&public_path, &public)?;
151    }
152    Ok(CanonicalKey {
153        scalar: secret.to_bytes().to_vec(),
154        public_pem: public,
155        private_path: path.to_path_buf(),
156        public_path,
157        created,
158    })
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use crate::security::pki_client::client::PkiClient;
165    use crate::security::pki_client::ts_pki::{signed_data, Transport, TsPki};
166    use crate::security::security_asn::ieee1609_dot2::SignerIdentifier;
167    use crate::security::security_asn::ieee1609_dot2_base_types::{
168        EccP256CurvePoint, PublicVerificationKey,
169    };
170    use std::sync::atomic::{AtomicU64, Ordering};
171    use std::sync::{Arc, Mutex};
172
173    /// Frozen vector, also in FlexStack (test_canonical.py): the NIST P-256
174    /// private key of RFC 6979 A.2.5 as PKCS#8 PEM, its SubjectPublicKeyInfo PEM
175    /// and the generated canonical identifier.
176    const VECTOR_PRIVATE: &str = "-----BEGIN PRIVATE KEY-----\n\
177MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgya+p2EW6dRZrXCFX\n\
178Z7HWk05Qw9s26JsSe4piKxIPZyGhRANCAARg/tS6JVqdMclh63TGNW1owEm4kjth\n\
179+mzmaWIuYPKftnkD/hAIuLyZpBrp6VYovGTy8bIMLX6fUXejwpTURiKZ\n\
180-----END PRIVATE KEY-----\n";
181    const VECTOR_PUBLIC: &str = "-----BEGIN PUBLIC KEY-----\n\
182MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYP7UuiVanTHJYet0xjVtaMBJuJI7\n\
183Yfps5mliLmDyn7Z5A/4QCLi8maQa6elWKLxk8vGyDC1+n1F3o8KU1EYimQ==\n\
184-----END PUBLIC KEY-----\n";
185    const VECTOR_ITS_ID: [u8; 8] = [0xcb, 0xe0, 0xf0, 0x81, 0x5a, 0x07, 0xec, 0xd4];
186
187    fn temp_dir() -> PathBuf {
188        static NEXT: AtomicU64 = AtomicU64::new(0);
189        std::env::temp_dir().join(format!(
190            "rustflexstack-canonical-{}-{}",
191            std::process::id(),
192            NEXT.fetch_add(1, Ordering::SeqCst)
193        ))
194    }
195
196    /// PublicVerificationKey of a SubjectPublicKeyInfo PEM (as an EA registers it).
197    fn registered(public: &str) -> PublicVerificationKey {
198        use p256::elliptic_curve::sec1::ToEncodedPoint;
199        let point = p256::PublicKey::from_public_key_pem(public)
200            .unwrap()
201            .to_encoded_point(true);
202        let x = point.x().unwrap().to_vec().into();
203        PublicVerificationKey::ecdsaNistP256(if point.as_bytes()[0] == 2 {
204            EccP256CurvePoint::compressed_y_0(x)
205        } else {
206            EccP256CurvePoint::compressed_y_1(x)
207        })
208    }
209
210    #[test]
211    fn created_once_and_private() {
212        let path = temp_dir().join("pki").join("canonical_key.pem");
213        let first = load_or_create_canonical_key(&path).unwrap();
214        assert!(first.created);
215        assert_eq!(first.scalar.len(), 32);
216        assert_eq!(
217            first.public_path,
218            path.with_file_name("canonical_key.pub.pem")
219        );
220        assert_eq!(
221            std::fs::read_to_string(&first.public_path).unwrap(),
222            first.public_pem
223        );
224        #[cfg(unix)]
225        {
226            use std::os::unix::fs::PermissionsExt;
227            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
228            assert_eq!(mode & 0o077, 0);
229        }
230        let second = load_or_create_canonical_key(&path).unwrap();
231        assert!(!second.created);
232        assert_eq!(
233            (second.scalar, second.public_pem),
234            (first.scalar, first.public_pem)
235        );
236    }
237
238    #[test]
239    fn public_file_is_rewritten_from_the_private_key() {
240        let path = temp_dir().join("canonical_key.pem");
241        let key = load_or_create_canonical_key(&path).unwrap();
242        std::fs::write(&key.public_path, "stale").unwrap();
243        load_or_create_canonical_key(&path).unwrap();
244        assert_eq!(
245            std::fs::read_to_string(&key.public_path).unwrap(),
246            key.public_pem
247        );
248        std::fs::remove_file(&key.public_path).unwrap();
249        load_or_create_canonical_key(&path).unwrap();
250        assert_eq!(
251            std::fs::read_to_string(&key.public_path).unwrap(),
252            key.public_pem
253        );
254    }
255
256    #[test]
257    fn frozen_vector() {
258        let path = temp_dir().join("canonical_key.pem");
259        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
260        std::fs::write(&path, VECTOR_PRIVATE).unwrap();
261        let key = load_or_create_canonical_key(&path).unwrap();
262        assert!(!key.created);
263        assert_eq!(key.public_pem, VECTOR_PUBLIC);
264        assert_eq!(public_pem(VECTOR_PRIVATE).unwrap(), VECTOR_PUBLIC);
265        assert_eq!(key.its_id(), VECTOR_ITS_ID);
266        assert_eq!(canonical_id(VECTOR_PUBLIC).unwrap(), VECTOR_ITS_ID);
267        assert_eq!(
268            hex(&key.scalar),
269            "c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721"
270        );
271    }
272
273    #[test]
274    fn sec1_pem_is_read_and_other_keys_refused() {
275        let sec1 = p256::SecretKey::random(&mut rand::thread_rng())
276            .to_sec1_pem(LineEnding::LF)
277            .unwrap();
278        assert!(public_pem(&sec1).unwrap().contains("BEGIN PUBLIC KEY"));
279        let p384 = p384::SecretKey::random(&mut rand::thread_rng())
280            .to_pkcs8_pem(LineEnding::LF)
281            .unwrap();
282        assert!(public_pem(&p384).is_err());
283        assert!(public_pem("junk").is_err());
284        assert!(canonical_id("junk").is_err());
285        let path = temp_dir().join("canonical_key.pem");
286        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
287        std::fs::write(&path, p384.as_bytes()).unwrap();
288        assert!(load_or_create_canonical_key(&path).is_err());
289    }
290
291    #[test]
292    fn public_key_path_and_registration_command() {
293        assert_eq!(
294            public_key_path(Path::new("/x/key.pem")),
295            PathBuf::from("/x/key.pub.pem")
296        );
297        assert_eq!(
298            public_key_path(Path::new("/x/key")),
299            PathBuf::from("/x/key.pub.pem")
300        );
301        let dir = temp_dir();
302        let key = load_or_create_canonical_key(&dir.join("a.pem")).unwrap();
303        assert_eq!(
304            key.registration_command(Some(&[1, 2])),
305            format!(
306                "ea-tool register --its-id 0102 --public-key {}",
307                key.public_path.display()
308            )
309        );
310        assert_eq!(
311            key.registration_command(None),
312            format!(
313                "ea-tool register --its-id {} --public-key {}",
314                hex(&key.its_id()),
315                key.public_path.display()
316            )
317        );
318        let other = load_or_create_canonical_key(&dir.join("b.pem")).unwrap();
319        assert_ne!(key.its_id(), other.its_id());
320    }
321
322    struct Flow {
323        pki: Arc<Mutex<TsPki>>,
324        transport: Transport,
325        dir: PathBuf,
326        key: CanonicalKey,
327    }
328
329    impl Flow {
330        fn new() -> Flow {
331            let pki = Arc::new(Mutex::new(TsPki::new()));
332            let transport = Transport::new(Arc::clone(&pki));
333            let dir = temp_dir();
334            let key = load_or_create_canonical_key(&dir.join("canonical_key.pem")).unwrap();
335            Flow {
336                pki,
337                transport,
338                dir,
339                key,
340            }
341        }
342
343        fn client(&self) -> PkiClient {
344            let p = self.pki.lock().unwrap();
345            PkiClient::new(
346                self.transport.ea_url.clone(),
347                self.transport.aa_url.clone(),
348                p.ea.own.cert.clone(),
349                p.aa.own.cert.clone(),
350                p.root.cert.clone(),
351                Some(self.key.scalar.clone()),
352                self.dir.clone(),
353                Some(self.key.its_id()),
354                None,
355            )
356            .with_transport(Box::new(self.transport.clone()))
357        }
358
359        fn last_signer(&self) -> SignerIdentifier {
360            let p = self.pki.lock().unwrap();
361            signed_data(&p.enrolments.last().unwrap().outer)
362                .signer
363                .clone()
364        }
365    }
366
367    /// Generate (ITS-S) → register the public key (EA) → enrol and get an AT.
368    #[test]
369    fn registered_key_enrols() {
370        let flow = Flow::new();
371        let mut client = flow.client();
372        assert_eq!(
373            client.canonical_public_key(),
374            registered(&flow.key.public_pem)
375        );
376        flow.pki
377            .lock()
378            .unwrap()
379            .register(&flow.key.its_id(), registered(&flow.key.public_pem));
380        client.provision(None, None, None).unwrap();
381        assert!(matches!(flow.last_signer(), SignerIdentifier::R_self(_)));
382        assert_eq!(
383            flow.pki.lock().unwrap().enrolments[0].ec().its_id.to_vec(),
384            flow.key.its_id().to_vec()
385        );
386    }
387
388    #[test]
389    fn unregistered_or_other_key_is_refused() {
390        let flow = Flow::new();
391        assert!(flow.client().enroll(None, None).is_err());
392        let other = load_or_create_canonical_key(&flow.dir.join("other.pem")).unwrap();
393        flow.pki
394            .lock()
395            .unwrap()
396            .register(&flow.key.its_id(), registered(&other.public_pem));
397        assert!(flow.client().enroll(None, None).is_err());
398        let p = flow.pki.lock().unwrap();
399        assert_eq!(p.enrolments.len(), 2);
400        assert!(p.enrolments.iter().all(|r| !r.checks["outer"]));
401    }
402
403    #[test]
404    fn later_runs_rekey_with_the_saved_ec() {
405        let flow = Flow::new();
406        flow.pki
407            .lock()
408            .unwrap()
409            .register(&flow.key.its_id(), registered(&flow.key.public_pem));
410        flow.client().enroll(None, None).unwrap();
411        let mut later = flow.client();
412        assert!(later.load_ec_from_disk(None).is_some());
413        later.enroll(None, None).unwrap();
414        assert!(matches!(flow.last_signer(), SignerIdentifier::digest(_)));
415    }
416}