Skip to main content

rustflexstack/security/pki_client/
trust_lists.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! CTL and CRL use by an ITS-S (ETSI TS 102 941 V2.2.1 clauses 6.3.1 to
5//! 6.3.6, Annexes D and E).
6//!
7//! [`TrustStore`] reads the TLM CTL (ECTL), the Root CA CTLs and the CRLs,
8//! checks that each is signed by its issuer (a trusted TLM, a trusted Root CA)
9//! with the ITS-AID and SSP of the CTL / CRL service (clauses B.2, B.3), and
10//! updates the trust information of a [`CertificateLibrary`]:
11//! - ECTL: Root CA entries become trust anchors; a full ECTL also withdraws
12//!   the Root CAs it no longer lists; TLM entries add a TLM; the TLM entry's
13//!   access point is the CPOC;
14//! - Root CA CTL: AA (and EA) entries of that Root CA; DC entries give the DC
15//!   of the listed Root CAs; delete commands withdraw entries;
16//! - CRL: the listed CA certificates are revoked; [`TrustStore::process`]
17//!   returns them so that the caller can drop the own EC / AT
18//!   ([`super::PkiClient::revoke`]).
19//!
20//! When a CTL or CRL passes its nextUpdate, [`TrustStore::due_downloads`]
21//! gives the URLs to fetch from the CPOC (`getectl`) or the DC (`getctl`,
22//! `getcrl`) and [`TrustStore::refresh`] fetches and applies them.
23
24use std::collections::{HashMap, HashSet};
25use std::fmt;
26
27use crate::security::certificate::{encode_tbs_data, signing_input, Certificate};
28use crate::security::certificate_library::CertificateLibrary;
29use crate::security::ecdsa_backend::{key_uses_sha384, EcdsaBackend};
30use crate::security::pki_asn::decode;
31use crate::security::pki_asn::etsi_ts102941_messages_itss::{
32    EtsiTs102941Data, EtsiTs102941DataContent,
33};
34use crate::security::pki_asn::etsi_ts102941_trust_lists::{
35    CtlCommand, CtlDelete, CtlEntry, CtlFormat, EaEntry, ToBeSignedCrl,
36};
37use crate::security::pki_client::client::PkiClock;
38use crate::security::pki_client::messages::time32;
39use crate::security::pki_client::transport::PkiTransport;
40use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
41use crate::security::security_asn::ieee1609_dot2::{
42    Ieee1609Dot2Content, Ieee1609Dot2Data, SignedData, SignerIdentifier,
43};
44use crate::security::security_asn::ieee1609_dot2_base_types::ServiceSpecificPermissions;
45use crate::security::time_service::unix_time_secs;
46
47/// ITS-AIDs of the CRL and CTL services (ETSI TS 102 965).
48pub const PSID_CRL: u64 = 622;
49pub const PSID_CTL: u64 = 624;
50/// CTL SSP bits (clause B.2, Table B.2).
51pub const SSP_TLM_ENTRIES: u8 = 0x80;
52pub const SSP_RCA_ENTRIES: u8 = 0x40;
53pub const SSP_EA_ENTRIES: u8 = 0x20;
54pub const SSP_AA_ENTRIES: u8 = 0x10;
55pub const SSP_DC_ENTRIES: u8 = 0x08;
56
57/// A CTL or CRL is rejected; `code` names the failed check.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct TrustListError {
60    pub code: String,
61    pub message: String,
62}
63
64impl TrustListError {
65    fn new(code: &str, message: impl Into<String>) -> Self {
66        Self {
67            code: code.into(),
68            message: message.into(),
69        }
70    }
71}
72
73impl fmt::Display for TrustListError {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(f, "{}: {}", self.code, self.message)
76    }
77}
78
79impl std::error::Error for TrustListError {}
80
81/// Kind of list.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
83pub enum ListKind {
84    Ectl,
85    RcaCtl,
86    Crl,
87}
88
89/// The last CTL or CRL applied for an issuer.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct ListInfo {
92    pub issuer: [u8; 8],
93    pub kind: ListKind,
94    /// Time32.
95    pub next_update: u32,
96    /// ctlSequence (CTL).
97    pub sequence: Option<u8>,
98    /// thisUpdate (CRL).
99    pub this_update: Option<u32>,
100    /// HashedId8 added by this list (CTL) or revoked (CRL).
101    pub entries: HashSet<[u8; 8]>,
102}
103
104fn hex(h: &[u8; 8]) -> String {
105    h.iter().map(|b| format!("{b:02X}")).collect()
106}
107
108fn hashed(h: &crate::security::security_asn::ieee1609_dot2_base_types::HashedId8) -> [u8; 8] {
109    h.0.as_ref().try_into().unwrap()
110}
111
112fn certificate(asn: &EtsiTs103097Certificate) -> Certificate {
113    Certificate::from_asn(asn.clone(), None)
114}
115
116/// Issuer and version of a verified CTL / CRL message ([`TrustStore::inspect`]).
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct ListVersion {
119    pub kind: ListKind,
120    /// HashedId8 of the TLM or Root CA.
121    pub issuer: [u8; 8],
122    /// isFullCtl (false for a CRL).
123    pub full: bool,
124    /// ctlSequence (CTL).
125    pub sequence: Option<u8>,
126    /// thisUpdate (CRL).
127    pub this_update: Option<u32>,
128    /// Time32.
129    pub next_update: u32,
130}
131
132enum Opened {
133    Ctl(CtlFormat),
134    Crl(ToBeSignedCrl),
135}
136
137/// Trust information of an ITS-S built from CTLs and CRLs (module documentation).
138pub struct TrustStore {
139    pub tlms: HashMap<[u8; 8], Certificate>,
140    pub lists: HashMap<(ListKind, [u8; 8]), ListInfo>,
141    pub cpoc_url: Option<String>,
142    /// Root CA HashedId8 -> DC access point.
143    pub dc_urls: HashMap<[u8; 8], String>,
144    /// EA HashedId8 -> EaEntry.
145    pub ea_entries: HashMap<[u8; 8], EaEntry>,
146    clock: PkiClock,
147}
148
149impl TrustStore {
150    /// A store trusting `tlm_certificates` (installed out of band).
151    pub fn new(tlm_certificates: Vec<Certificate>) -> Self {
152        Self {
153            tlms: tlm_certificates
154                .into_iter()
155                .map(|c| (c.as_hashedid8(), c))
156                .collect(),
157            lists: HashMap::new(),
158            cpoc_url: None,
159            dc_urls: HashMap::new(),
160            ea_entries: HashMap::new(),
161            clock: std::sync::Arc::new(unix_time_secs),
162        }
163    }
164
165    /// Use `clock` (UTC seconds) instead of the system time.
166    pub fn with_clock(mut self, clock: PkiClock) -> Self {
167        self.clock = clock;
168        self
169    }
170
171    fn issuer(
172        signed: &SignedData,
173        anchors: &HashMap<[u8; 8], Certificate>,
174        library: &CertificateLibrary,
175    ) -> Result<Certificate, TrustListError> {
176        let h = match &signed.signer {
177            SignerIdentifier::certificate(seq) => {
178                let first = seq
179                    .0
180                    .first()
181                    .ok_or_else(|| TrustListError::new("invalidsigner", "empty"))?;
182                certificate(&EtsiTs103097Certificate(first.clone())).as_hashedid8()
183            }
184            SignerIdentifier::digest(d) => hashed(d),
185            _ => return Err(TrustListError::new("invalidsigner", "signer self")),
186        };
187        if library.revoked.contains(&h) {
188            return Err(TrustListError::new(
189                "unknownissuer",
190                format!("issuer {} is revoked", hex(&h)),
191            ));
192        }
193        anchors.get(&h).cloned().ok_or_else(|| {
194            TrustListError::new(
195                "unknownissuer",
196                format!("issuer {} is not trusted", hex(&h)),
197            )
198        })
199    }
200
201    fn verify(
202        signed: &SignedData,
203        issuer: &Certificate,
204        psid: u64,
205        backend: &EcdsaBackend,
206    ) -> Result<(), TrustListError> {
207        if u64::try_from(&signed.tbs_data.header_info.psid.0).ok() != Some(psid) {
208            return Err(TrustListError::new(
209                "badpsid",
210                format!("expected psid {psid}"),
211            ));
212        }
213        let key = issuer
214            .verification_key()
215            .ok_or_else(|| TrustListError::new("invalidsignature", "no verification key"))?;
216        let input = signing_input(
217            &encode_tbs_data(&signed.tbs_data),
218            issuer.to_canonical().encode(),
219            key_uses_sha384(&key),
220        );
221        if backend.verify_with_pk(&input, &signed.signature, &key) {
222            Ok(())
223        } else {
224            Err(TrustListError::new(
225                "invalidsignature",
226                "the signature does not verify",
227            ))
228        }
229    }
230
231    /// (the issuer's appPermissions contain `psid`, its SSP octets).
232    fn permission(issuer: &Certificate, psid: u64) -> (bool, Vec<u8>) {
233        for item in issuer.tbs().app_permissions.iter().flat_map(|p| p.0.iter()) {
234            if u64::try_from(&item.psid.0).ok() == Some(psid) {
235                let ssp = match &item.ssp {
236                    Some(ServiceSpecificPermissions::bitmapSsp(b)) => b.0.to_vec(),
237                    Some(ServiceSpecificPermissions::opaque(o)) => o.to_vec(),
238                    _ => Vec::new(),
239                };
240                return (true, ssp);
241            }
242        }
243        (false, Vec::new())
244    }
245
246    /// Verify and apply a TlmCertificateTrustListMessage, an
247    /// RcaCertificateTrustListMessage or a CertificateRevocationListMessage to
248    /// `library`; returns the kind and, for a CRL, the revoked HashedId8.
249    pub fn process(
250        &mut self,
251        library: &mut CertificateLibrary,
252        backend: &EcdsaBackend,
253        message: &[u8],
254    ) -> Result<(ListKind, HashSet<[u8; 8]>), TrustListError> {
255        match self.open(library, backend, message)? {
256            (kind, Opened::Ctl(ctl), issuer) => {
257                self.apply_ctl(library, backend, &issuer, &ctl, kind)?;
258                Ok((kind, HashSet::new()))
259            }
260            (kind, Opened::Crl(crl), issuer) => Ok((kind, self.apply_crl(library, &issuer, &crl)?)),
261        }
262    }
263
264    /// Verify the signature of a CTL / CRL message (as [`TrustStore::process`])
265    /// without applying it; its issuer and version.
266    pub fn inspect(
267        &self,
268        library: &mut CertificateLibrary,
269        backend: &EcdsaBackend,
270        message: &[u8],
271    ) -> Result<ListVersion, TrustListError> {
272        let (kind, opened, issuer) = self.open(library, backend, message)?;
273        let issuer = issuer.as_hashedid8();
274        Ok(match opened {
275            Opened::Ctl(ctl) => ListVersion {
276                kind,
277                issuer,
278                full: ctl.is_full_ctl,
279                sequence: Some(ctl.ctl_sequence),
280                this_update: None,
281                next_update: ctl.next_update.0 .0,
282            },
283            Opened::Crl(crl) => ListVersion {
284                kind,
285                issuer,
286                full: false,
287                sequence: None,
288                this_update: Some(crl.this_update.0 .0),
289                next_update: crl.next_update.0 .0,
290            },
291        })
292    }
293
294    /// Decode a CTL / CRL message and verify its signer and signature.
295    fn open(
296        &self,
297        library: &mut CertificateLibrary,
298        backend: &EcdsaBackend,
299        message: &[u8],
300    ) -> Result<(ListKind, Opened, Certificate), TrustListError> {
301        let data: Ieee1609Dot2Data =
302            decode(message).map_err(|e| TrustListError::new("cantparse", e.to_string()))?;
303        let Ieee1609Dot2Content::signedData(signed) = &data.content else {
304            return Err(TrustListError::new("badcontenttype", "expected signedData"));
305        };
306        let payload = match signed.tbs_data.payload.data.as_ref().map(|d| &d.content) {
307            Some(Ieee1609Dot2Content::unsecuredData(o)) => o.0.to_vec(),
308            _ => {
309                return Err(TrustListError::new(
310                    "badcontenttype",
311                    "payload is not unsecuredData",
312                ))
313            }
314        };
315        let etsi: EtsiTs102941Data =
316            decode(&payload).map_err(|e| TrustListError::new("cantparse", e.to_string()))?;
317        match etsi.content {
318            EtsiTs102941DataContent::certificateTrustListTlm(ctl) => {
319                let issuer = Self::issuer(signed, &self.tlms, library)?;
320                Self::verify(signed, &issuer, PSID_CTL, backend)?;
321                Ok((ListKind::Ectl, Opened::Ctl(ctl), issuer))
322            }
323            EtsiTs102941DataContent::certificateTrustListRca(ctl) => {
324                let roots = library.known_root_certificates.clone();
325                let issuer = Self::issuer(signed, &roots, library)?;
326                Self::verify(signed, &issuer, PSID_CTL, backend)?;
327                Ok((ListKind::RcaCtl, Opened::Ctl(ctl), issuer))
328            }
329            EtsiTs102941DataContent::certificateRevocationList(crl) => {
330                let roots = library.known_root_certificates.clone();
331                let issuer = Self::issuer(signed, &roots, library)?;
332                Self::verify(signed, &issuer, PSID_CRL, backend)?;
333                Ok((ListKind::Crl, Opened::Crl(crl), issuer))
334            }
335            _ => Err(TrustListError::new("badcontenttype", "not a CTL or CRL")),
336        }
337    }
338
339    fn apply_ctl(
340        &mut self,
341        library: &mut CertificateLibrary,
342        backend: &EcdsaBackend,
343        issuer: &Certificate,
344        ctl: &CtlFormat,
345        kind: ListKind,
346    ) -> Result<(), TrustListError> {
347        let issuer_id = issuer.as_hashedid8();
348        let previous = self.lists.get(&(kind, issuer_id)).cloned();
349        let full = ctl.is_full_ctl;
350        if let Some(p) = &previous {
351            if p.sequence == Some(ctl.ctl_sequence) {
352                return Err(TrustListError::new(
353                    "outdated",
354                    "ctlSequence already applied",
355                ));
356            }
357            if !full && ctl.ctl_sequence != p.sequence.unwrap_or(0).wrapping_add(1) {
358                return Err(TrustListError::new(
359                    "outofsequence",
360                    "delta CTL does not follow the last CTL",
361                ));
362            }
363        }
364        let (_, allowed) = Self::permission(issuer, PSID_CTL);
365        for command in &ctl.ctl_commands {
366            match command {
367                CtlCommand::add(entry) => {
368                    let bit = match entry {
369                        CtlEntry::tlm(_) => SSP_TLM_ENTRIES,
370                        CtlEntry::rca(_) => SSP_RCA_ENTRIES,
371                        CtlEntry::ea(_) => SSP_EA_ENTRIES,
372                        CtlEntry::aa(_) => SSP_AA_ENTRIES,
373                        CtlEntry::dc(_) => SSP_DC_ENTRIES,
374                    };
375                    if allowed.len() < 2 || allowed[0] != 1 || allowed[1] & bit == 0 {
376                        return Err(TrustListError::new(
377                            "deniedpermissions",
378                            "entry not permitted by the SSP",
379                        ));
380                    }
381                }
382                CtlCommand::delete(_) if full => {
383                    return Err(TrustListError::new(
384                        "badcontenttype",
385                        "a full CTL contains no delete command",
386                    ));
387                }
388                _ => {}
389            }
390        }
391        let mut entries = match (&previous, full) {
392            (Some(p), false) => p.entries.clone(),
393            _ => HashSet::new(),
394        };
395        for command in &ctl.ctl_commands {
396            match command {
397                CtlCommand::add(entry) => {
398                    entries.extend(self.add(library, backend, issuer_id, entry))
399                }
400                CtlCommand::delete(delete) => {
401                    if let Some(h) = self.delete(library, delete) {
402                        entries.remove(&h);
403                    }
404                }
405            }
406        }
407        if let (Some(p), true) = (&previous, full) {
408            for h in p.entries.difference(&entries) {
409                library.remove_certificate(h); // withdrawn by the full CTL
410            }
411        }
412        self.lists.insert(
413            (kind, issuer_id),
414            ListInfo {
415                issuer: issuer_id,
416                kind,
417                next_update: ctl.next_update.0 .0,
418                sequence: Some(ctl.ctl_sequence),
419                this_update: None,
420                entries,
421            },
422        );
423        Ok(())
424    }
425
426    fn add(
427        &mut self,
428        library: &mut CertificateLibrary,
429        backend: &EcdsaBackend,
430        issuer_id: [u8; 8],
431        entry: &CtlEntry,
432    ) -> Option<[u8; 8]> {
433        match entry {
434            CtlEntry::rca(e) => {
435                let root = certificate(&e.selfsigned_root_ca);
436                let h = root.as_hashedid8();
437                library.add_root_certificate(backend, root);
438                library
439                    .known_root_certificates
440                    .contains_key(&h)
441                    .then_some(h)
442            }
443            CtlEntry::tlm(e) => {
444                let tlm = certificate(&e.self_signed_tlm_certificate);
445                if tlm.verify(backend) {
446                    self.tlms.insert(tlm.as_hashedid8(), tlm);
447                }
448                self.cpoc_url = Some(e.access_point.to_string());
449                None
450            }
451            CtlEntry::aa(e) => {
452                let root = library.known_root_certificates.get(&issuer_id).cloned();
453                let aa = Certificate::from_asn(e.aa_certificate.clone(), root);
454                let h = aa.as_hashedid8();
455                library.add_authorization_authority(backend, aa);
456                library
457                    .known_authorization_authorities
458                    .contains_key(&h)
459                    .then_some(h)
460            }
461            CtlEntry::ea(e) => {
462                self.ea_entries
463                    .insert(certificate(&e.ea_certificate).as_hashedid8(), e.clone());
464                None
465            }
466            CtlEntry::dc(e) => {
467                for root in &e.cert {
468                    self.dc_urls.insert(hashed(root), e.url.to_string());
469                }
470                None
471            }
472        }
473    }
474
475    fn delete(&mut self, library: &mut CertificateLibrary, delete: &CtlDelete) -> Option<[u8; 8]> {
476        match delete {
477            CtlDelete::cert(h) => {
478                let h = hashed(h);
479                library.remove_certificate(&h);
480                self.tlms.remove(&h);
481                self.ea_entries.remove(&h);
482                Some(h)
483            }
484            CtlDelete::dc(url) => {
485                let url = url.to_string();
486                self.dc_urls.retain(|_, u| *u != url);
487                None
488            }
489        }
490    }
491
492    fn apply_crl(
493        &mut self,
494        library: &mut CertificateLibrary,
495        issuer: &Certificate,
496        crl: &ToBeSignedCrl,
497    ) -> Result<HashSet<[u8; 8]>, TrustListError> {
498        let issuer_id = issuer.as_hashedid8();
499        let (permitted, ssp) = Self::permission(issuer, PSID_CRL);
500        if !permitted || ssp.first() != Some(&1) {
501            return Err(TrustListError::new(
502                "deniedpermissions",
503                "issuer may not sign CRLs",
504            ));
505        }
506        if let Some(p) = self.lists.get(&(ListKind::Crl, issuer_id)) {
507            if crl.this_update.0 .0 <= p.this_update.unwrap_or(0) {
508                return Err(TrustListError::new(
509                    "outdated",
510                    "not newer than the last CRL",
511                ));
512            }
513        }
514        let revoked: HashSet<[u8; 8]> = crl.entries.iter().map(hashed).collect();
515        library.revoke(&revoked);
516        self.lists.insert(
517            (ListKind::Crl, issuer_id),
518            ListInfo {
519                issuer: issuer_id,
520                kind: ListKind::Crl,
521                next_update: crl.next_update.0 .0,
522                sequence: None,
523                this_update: Some(crl.this_update.0 .0),
524                entries: revoked.clone(),
525            },
526        );
527        Ok(revoked)
528    }
529
530    /// URLs of the lists past their nextUpdate: ECTL from the CPOC (Annex E.4),
531    /// Root CA CTL and CRL from the Root CA's DC (Annex D).
532    pub fn due_downloads(&self) -> Vec<String> {
533        let now = time32((self.clock)());
534        let mut urls = Vec::new();
535        for ((kind, issuer), info) in &self.lists {
536            if info.next_update > now {
537                continue;
538            }
539            match kind {
540                ListKind::Ectl => {
541                    if let Some(cpoc) = &self.cpoc_url {
542                        urls.push(format!(
543                            "{}/getectl/{}",
544                            cpoc.trim_end_matches('/'),
545                            hex(issuer)
546                        ));
547                    }
548                }
549                ListKind::RcaCtl | ListKind::Crl => {
550                    if let Some(dc) = self.dc_urls.get(issuer) {
551                        let path = if *kind == ListKind::RcaCtl {
552                            "getctl"
553                        } else {
554                            "getcrl"
555                        };
556                        urls.push(format!(
557                            "{}/{}/{}",
558                            dc.trim_end_matches('/'),
559                            path,
560                            hex(issuer)
561                        ));
562                    }
563                }
564            }
565        }
566        urls.sort();
567        urls
568    }
569
570    /// Fetch and apply the due lists; returns the URLs fetched and the CA
571    /// certificates revoked by the CRLs fetched.
572    pub fn refresh(
573        &mut self,
574        library: &mut CertificateLibrary,
575        backend: &EcdsaBackend,
576        transport: &dyn PkiTransport,
577    ) -> (Vec<String>, HashSet<[u8; 8]>) {
578        let urls = self.due_downloads();
579        let mut revoked = HashSet::new();
580        for url in &urls {
581            if let Ok(message) = transport.get(url) {
582                if let Ok((_, r)) = self.process(library, backend, &message) {
583                    revoked.extend(r);
584                }
585            }
586        }
587        (urls, revoked)
588    }
589}