Skip to main content

rustflexstack/security/pki_client/
client.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! [`PkiClient`]: the ITS-S side of the ETSI TS 102 941 V2.2.1 security
5//! management (enrolment with the EA, authorization with the AA).
6//!
7//! States (ETSI TS 103 525-2 V2.1.1 clause 4.2.1):
8//! - `initialized`: no valid Enrolment Credential (EC); the next enrolment is
9//!   an initial request (canonical identifier and canonical key);
10//! - `enrolled`: a valid EC; the next enrolment is a re-keying request when the
11//!   EC permits signing enrolment requests (SSP of ITS-AID 623, clause B.4);
12//! - `authorized`: a valid EC and a valid Authorization Ticket (AT).
13//!
14//! A failed request leaves the state as it was; an expired EC or AT no longer
15//! counts. Revocation (CRL, see [`super::trust_lists`]) of the EA, AA or Root
16//! CA of the own certificates drops them ([`PkiClient::revoke`]).
17
18use std::collections::HashSet;
19use std::fmt;
20use std::path::PathBuf;
21use std::sync::Arc;
22
23use rasn::types::Integer;
24
25use crate::security::certificate::{Certificate, OwnCertificate};
26use crate::security::ecdsa_backend::EcdsaBackend;
27use crate::security::pki_asn::decode;
28use crate::security::pki_asn::etsi_ts102941_base_types::CertificateSubjectAttributes;
29use crate::security::pki_client::authorization::{authorize, AuthorizationError};
30use crate::security::pki_client::enrolment::{enroll, EnrolmentError};
31use crate::security::pki_client::messages::{self, time32, time64};
32use crate::security::pki_client::transport::{
33    HttpTransport, PkiSleep, PkiTransport, Retry, RetryPolicy,
34};
35use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
36use crate::security::security_asn::ieee1609_dot2_base_types::{
37    Duration, Psid, PsidSsp, PublicVerificationKey, SequenceOfPsidSsp, Time32, Uint16, Uint32,
38    ValidityPeriod,
39};
40use crate::security::time_service::unix_time_secs;
41use crate::security::validity::valid_at;
42
43/// UTC seconds since the Unix epoch.
44pub type PkiClock = Arc<dyn Fn() -> f64 + Send + Sync>;
45
46/// State of the ITS-S (TS 103 525-2 clause 4.2.1).
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum PkiState {
49    Initialized,
50    Enrolled,
51    Authorized,
52}
53
54/// Error of a [`PkiClient`] operation.
55#[derive(Debug)]
56pub enum PkiError {
57    Enrolment(EnrolmentError),
58    Authorization(AuthorizationError),
59    Io(std::io::Error),
60    InvalidState(String),
61}
62
63impl fmt::Display for PkiError {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        match self {
66            PkiError::Enrolment(e) => write!(f, "Enrolment error: {e}"),
67            PkiError::Authorization(e) => write!(f, "Authorization error: {e}"),
68            PkiError::Io(e) => write!(f, "I/O error: {e}"),
69            PkiError::InvalidState(s) => write!(f, "Invalid state: {s}"),
70        }
71    }
72}
73
74impl std::error::Error for PkiError {}
75
76impl From<EnrolmentError> for PkiError {
77    fn from(e: EnrolmentError) -> Self {
78        PkiError::Enrolment(e)
79    }
80}
81
82impl From<AuthorizationError> for PkiError {
83    fn from(e: AuthorizationError) -> Self {
84        PkiError::Authorization(e)
85    }
86}
87
88impl From<std::io::Error> for PkiError {
89    fn from(e: std::io::Error) -> Self {
90        PkiError::Io(e)
91    }
92}
93
94/// ITS-S PKI client (see the module documentation).
95pub struct PkiClient {
96    /// Access points of the EA and the AA (the requests are POSTed to them).
97    pub ea_url: String,
98    pub aa_url: String,
99    pub ea_cert: Certificate,
100    pub aa_cert: Certificate,
101    pub rca_cert: Certificate,
102    pub certs_dir: PathBuf,
103    /// Canonical identifier (InnerEcRequest.itsId of an initial request).
104    pub its_id: Vec<u8>,
105    pub backend: EcdsaBackend,
106    /// Send authorization requests with proof of possession (clause 6.2.3.3.1).
107    pub pop: bool,
108    /// Repetition of an enrolment request without response (ETSI TS 103 601
109    /// V2.1.1 clause 5.1, mandatory for every ITS-S); None sends it once.
110    pub enrolment_retry: Option<RetryPolicy>,
111    /// Repetition of an authorization request (clause 5.2): for an ITS-S
112    /// without privacy requirements only, hence off (None) by default.
113    pub authorization_retry: Option<RetryPolicy>,
114    /// Wait between two transmissions (`std::thread::sleep` by default).
115    pub sleep: PkiSleep,
116    canonical_key: usize,
117    clock: PkiClock,
118    transport: Box<dyn PkiTransport>,
119    ec_own: Option<OwnCertificate>,
120    at_own: Option<OwnCertificate>,
121}
122
123impl PkiClient {
124    /// A client; `canonical_key_bytes` is the private scalar of the canonical key
125    /// registered with the EA (a key is generated without it, see
126    /// [`PkiClient::canonical_public_key`]). `http_timeout_secs` configures the
127    /// default HTTP transport.
128    #[allow(clippy::too_many_arguments)]
129    pub fn new(
130        ea_url: impl Into<String>,
131        aa_url: impl Into<String>,
132        ea_cert: Certificate,
133        aa_cert: Certificate,
134        rca_cert: Certificate,
135        canonical_key_bytes: Option<Vec<u8>>,
136        certs_dir: impl Into<PathBuf>,
137        its_id: Option<[u8; 8]>,
138        http_timeout_secs: Option<u64>,
139    ) -> Self {
140        let mut backend = EcdsaBackend::new();
141        let canonical_key = match canonical_key_bytes {
142            Some(bytes) => backend.import_signing_key(&bytes),
143            None => backend.create_key(),
144        };
145        Self {
146            ea_url: ea_url.into(),
147            aa_url: aa_url.into(),
148            ea_cert,
149            aa_cert,
150            rca_cert,
151            certs_dir: certs_dir.into(),
152            its_id: its_id.unwrap_or([0u8; 8]).to_vec(),
153            backend,
154            pop: true,
155            enrolment_retry: Some(RetryPolicy::default()),
156            authorization_retry: None,
157            sleep: Arc::new(|s| std::thread::sleep(std::time::Duration::from_secs_f64(s))),
158            canonical_key,
159            clock: Arc::new(unix_time_secs),
160            transport: Box::new(HttpTransport::new(std::time::Duration::from_secs(
161                http_timeout_secs.unwrap_or(30),
162            ))),
163            ec_own: None,
164            at_own: None,
165        }
166    }
167
168    /// Use `transport` instead of HTTP.
169    pub fn with_transport(mut self, transport: Box<dyn PkiTransport>) -> Self {
170        self.transport = transport;
171        self
172    }
173
174    /// Use `clock` (UTC seconds) instead of the system time.
175    pub fn with_clock(mut self, clock: PkiClock) -> Self {
176        self.clock = clock;
177        self
178    }
179
180    /// Canonical identifier of any length (default: 8 octets given to `new`).
181    pub fn with_its_id(mut self, its_id: Vec<u8>) -> Self {
182        self.its_id = its_id;
183        self
184    }
185
186    fn now(&self) -> f64 {
187        (self.clock)()
188    }
189
190    fn valid(&self, certificate: Option<&OwnCertificate>) -> bool {
191        certificate.is_some_and(|c| valid_at(&c.cert, time64(self.now())))
192    }
193
194    /// The current EC, if valid.
195    pub fn ec(&self) -> Option<&OwnCertificate> {
196        self.ec_own
197            .as_ref()
198            .filter(|_| self.valid(self.ec_own.as_ref()))
199    }
200
201    /// The current AT, if valid (and the EC too).
202    pub fn at(&self) -> Option<&OwnCertificate> {
203        self.ec()?;
204        self.at_own
205            .as_ref()
206            .filter(|_| self.valid(self.at_own.as_ref()))
207    }
208
209    /// `initialized`, `enrolled` or `authorized`.
210    pub fn state(&self) -> PkiState {
211        match (self.ec(), self.at()) {
212            (None, _) => PkiState::Initialized,
213            (Some(_), None) => PkiState::Enrolled,
214            (Some(_), Some(_)) => PkiState::Authorized,
215        }
216    }
217
218    /// The canonical verification key (to be registered with the EA).
219    pub fn canonical_public_key(&self) -> PublicVerificationKey {
220        self.backend.get_public_key(self.canonical_key)
221    }
222
223    /// Apply revoked CA certificates (HashedId8): an EC whose EA or Root CA is
224    /// revoked is dropped (`initialized`); an AT whose AA (or Root CA) is
225    /// revoked is dropped (`enrolled`).
226    pub fn revoke(&mut self, revoked: &HashSet<[u8; 8]>) {
227        let rca = revoked.contains(&self.rca_cert.as_hashedid8());
228        if rca || revoked.contains(&self.ea_cert.as_hashedid8()) {
229            self.ec_own = None;
230            self.at_own = None;
231        }
232        if rca || revoked.contains(&self.aa_cert.as_hashedid8()) {
233            self.at_own = None;
234        }
235    }
236
237    fn attributes(
238        &self,
239        app_permissions: SequenceOfPsidSsp,
240        duration: Option<Duration>,
241    ) -> CertificateSubjectAttributes {
242        CertificateSubjectAttributes::new(
243            None,
244            duration.map(|d| ValidityPeriod::new(Time32(Uint32(time32(self.now()))), d)),
245            None,
246            None,
247            Some(app_permissions),
248            None,
249        )
250    }
251
252    /// Request an EC (clause 6.2.3.2): a re-keying request when the current EC
253    /// is valid and permits enrolment requests, an initial request otherwise.
254    /// The EC is saved to `<certs_dir>/ec.{cert,pem}`.
255    pub fn enroll(
256        &mut self,
257        app_permissions: Option<SequenceOfPsidSsp>,
258        validity_years: Option<u16>,
259    ) -> Result<OwnCertificate, PkiError> {
260        let permissions = app_permissions.unwrap_or_else(|| {
261            SequenceOfPsidSsp(vec![PsidSsp::new(
262                Psid(Integer::from(messages::PSID_CERT_REQUEST)),
263                Some(messages::certificate_ssp()),
264            )])
265        });
266        let current = self
267            .ec()
268            .filter(|ec| messages::ssp_permits(&ec.cert, messages::SSP_ENROLMENT_REQUEST))
269            .cloned();
270        let attributes = self.attributes(
271            permissions,
272            validity_years.map(|y| Duration::years(Uint16(y))),
273        );
274        let now = self.now();
275        let retry = self.retry(self.enrolment_retry);
276        let ec = enroll(
277            self.transport.as_ref(),
278            &self.ea_url,
279            &self.ea_cert,
280            &mut self.backend,
281            &self.its_id,
282            self.canonical_key,
283            current.as_ref(),
284            attributes,
285            now,
286            retry.as_ref(),
287        )?;
288        self.ec_own = Some(ec.clone());
289        self.save_cert(&ec, "ec")?;
290        Ok(ec)
291    }
292
293    /// Request an AT (clause 6.2.3.3) with the EC (ecSignature). The AT is
294    /// saved to `<certs_dir>/at.{cert,pem}`.
295    pub fn authorize(
296        &mut self,
297        ec_own: Option<&OwnCertificate>,
298        app_permissions: Option<SequenceOfPsidSsp>,
299        validity_hours: Option<u16>,
300    ) -> Result<OwnCertificate, PkiError> {
301        let ec = match ec_own {
302            Some(ec) => ec.clone(),
303            None => self
304                .ec()
305                .cloned()
306                .ok_or_else(|| PkiError::InvalidState("No valid EC: enroll() first".into()))?,
307        };
308        if !messages::ssp_permits(&ec.cert, messages::SSP_AUTHORIZATION_REQUEST) {
309            return Err(AuthorizationError::new(
310                "deniedpermissions",
311                "the EC does not permit authorization requests",
312            )
313            .into());
314        }
315        let permissions = app_permissions.unwrap_or_else(|| {
316            SequenceOfPsidSsp(vec![
317                PsidSsp::new(Psid(Integer::from(36)), None),
318                PsidSsp::new(Psid(Integer::from(37)), None),
319            ])
320        });
321        let attributes = self.attributes(
322            permissions,
323            validity_hours.map(|h| Duration::hours(Uint16(h))),
324        );
325        let now = self.now();
326        let retry = self.retry(self.authorization_retry);
327        let at = authorize(
328            self.transport.as_ref(),
329            &self.aa_url,
330            &self.aa_cert,
331            &self.ea_cert,
332            &ec,
333            &mut self.backend,
334            attributes,
335            now,
336            self.pop,
337            retry.as_ref(),
338        )?;
339        self.at_own = Some(at.clone());
340        self.save_cert(&at, "at")?;
341        Ok(at)
342    }
343
344    fn retry(&self, policy: Option<RetryPolicy>) -> Option<Retry> {
345        policy.map(|policy| Retry {
346            policy,
347            clock: Arc::clone(&self.clock),
348            sleep: Arc::clone(&self.sleep),
349        })
350    }
351
352    /// Enrol (when not enrolled) and request an AT; returns the AT.
353    pub fn provision(
354        &mut self,
355        app_permissions: Option<SequenceOfPsidSsp>,
356        ec_validity_years: Option<u16>,
357        at_validity_hours: Option<u16>,
358    ) -> Result<OwnCertificate, PkiError> {
359        if self.ec().is_none() {
360            self.enroll(None, ec_validity_years)?;
361        }
362        self.authorize(None, app_permissions, at_validity_hours)
363    }
364
365    /// Save a certificate (COER) and its private scalar to
366    /// `<certs_dir>/<name>.cert` and `<certs_dir>/<name>.pem`.
367    pub fn save_cert(&self, cert: &OwnCertificate, name: &str) -> Result<(), PkiError> {
368        std::fs::create_dir_all(&self.certs_dir)?;
369        std::fs::write(
370            self.certs_dir.join(format!("{name}.cert")),
371            cert.cert.encode(),
372        )?;
373        std::fs::write(
374            self.certs_dir.join(format!("{name}.pem")),
375            self.backend.export_signing_key(cert.key_id),
376        )?;
377        Ok(())
378    }
379
380    fn load(&mut self, name: &str, issuer: &Certificate) -> Option<OwnCertificate> {
381        let cert_bytes = std::fs::read(self.certs_dir.join(format!("{name}.cert"))).ok()?;
382        let key_bytes = std::fs::read(self.certs_dir.join(format!("{name}.pem"))).ok()?;
383        if key_bytes.len() != 32 || p256::SecretKey::from_slice(&key_bytes).is_err() {
384            return None;
385        }
386        let certificate: EtsiTs103097Certificate = decode(&cert_bytes).ok()?;
387        let key_id = self.backend.import_signing_key(&key_bytes);
388        Some(OwnCertificate::new(
389            Certificate::from_asn(certificate, Some(issuer.clone())),
390            key_id,
391        ))
392    }
393
394    /// Load a previously issued EC (None if absent or unreadable).
395    pub fn load_ec_from_disk(&mut self, name: Option<&str>) -> Option<OwnCertificate> {
396        let ea = self.ea_cert.clone();
397        let ec = self.load(name.unwrap_or("ec"), &ea)?;
398        self.ec_own = Some(ec.clone());
399        Some(ec)
400    }
401
402    /// Load a previously issued AT (None if absent or unreadable).
403    pub fn load_at_from_disk(&mut self, name: Option<&str>) -> Option<OwnCertificate> {
404        let aa = self.aa_cert.clone();
405        let at = self.load(name.unwrap_or("at"), &aa)?;
406        self.at_own = Some(at.clone());
407        Some(at)
408    }
409}