Skip to main content

rustflexstack/security/pki_client/
distribution.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Peer-to-peer CRL / CTL distribution of an ITS-S (ETSI TS 103 601 V2.1.1
5//! clauses 5.3 and 5.4): the CRL / CTL Distribution Application (CXLDA).
6//!
7//! **Responder (clause 5.4).** A CRL or Delta CTL (ECTL of the TLM, CTL of a
8//! Root CA) received from the DC is verified, applied and broadcast at
9//! frequency `f1` during `d1` (case 1). A neighbour's P2P request for a list the
10//! ITS-S holds in a more recent version starts its broadcast at `f2` during
11//! `d2` (case 2). The broadcast stops at the end of the period, at the
12//! nextUpdate of the list, or when the same or a newer version of the list is
13//! received from another ITS-S (clause 5.4.3). The SM-PDU is sent unsecured at
14//! the GeoNetworking layer (it is signed by its issuer) in a SHB, BTP-B port
15//! 2014 (CTL) or 2015 (CRL).
16//!
17//! **Requester (clause 5.3).** A pending request is inserted in the
18//! `contributedExtensions` of the next CAM (clause 5.3.4: one request per CAM):
19//! `EtsiTs102941CrlRequest` with the thisUpdate of the last CRL of the issuer,
20//! `EtsiTs102941DeltaCtlRequest` with the ctlSequence of its last CTL (absent
21//! when none is known). A request is started on demand, when the CRL of an
22//! issuer passes its nextUpdate, and when a neighbour requests a CTL more
23//! recent than the one held (clause 5.3.6); it ends when the list is received.
24//! A CTL request also ends at the nextUpdate of the CTL held.
25//!
26//! Not implemented: the Full CTL broadcast and its Segmented CTL Response
27//! Message (clause 5.5, optional PICS items R1.1.2 / R1.2.5); a received
28//! `EtsiTs102941FullCtlRequest` is ignored.
29//!
30//! The service owns the [`TrustStore`]; the verify library of the station is
31//! passed to the calls that apply a list. Broadcasts received on the BTP ports
32//! are queued ([`TrustListDistribution::queue_broadcast`]) and applied by
33//! [`TrustListDistribution::process_received`].
34//!
35//! Mirrors `flexstack/security/pki_client/distribution.py`.
36
37use std::collections::{HashMap, HashSet};
38use std::sync::{mpsc, Arc, Mutex, MutexGuard};
39
40use rasn::prelude::*;
41
42use crate::btp::router::BTPRouterHandle;
43use crate::btp::service_access_point::BTPDataRequest;
44use crate::geonet::service_access_point::{
45    CommonNH, HeaderSubType, HeaderType, PacketTransportType, TopoBroadcastHST,
46};
47use crate::security::certificate::Certificate;
48use crate::security::certificate_library::CertificateLibrary;
49use crate::security::ecdsa_backend::EcdsaBackend;
50use crate::security::header_extensions::TrustListRequest;
51use crate::security::pki_client::client::PkiClock;
52use crate::security::pki_client::messages::time32;
53use crate::security::pki_client::transport::PkiTransport;
54use crate::security::pki_client::trust_lists::{
55    ListKind, ListVersion, TrustListError, TrustStore, PSID_CRL, PSID_CTL,
56};
57use crate::security::security_asn::etsi_ts103097_extension_module::{
58    EtsiTs102941CrlRequest, EtsiTs102941CtlRequest,
59};
60use crate::security::security_asn::ieee1609_dot2_base_types::{HashedId8, Time32, Uint32, Uint8};
61use crate::security::sign_service::TrustListRequestProvider;
62use crate::security::sn_sap::SecurityProfile;
63use crate::security::time_service::unix_time_secs;
64use crate::security::verify_service::TrustListListener;
65
66/// BTP-B destination port of the CTL broadcast (ETSI TS 103 601 clause 5.4.4
67/// refers to ETSI TS 103 248; value of TS 103 525-2 SECPKI_ITS-S_CTLDIST_03).
68pub const CTL_PORT: u16 = 2014;
69/// BTP-B destination port of the CRL broadcast (SECPKI_ITS-S_CRLDIST_02).
70pub const CRL_PORT: u16 = 2015;
71
72/// Parameters of the service (PIXITs of TS 103 525-2). Defaults: the
73/// recommended values of TS 103 601 clause 5.4.2 NOTE 1 and NOTE 3.
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct DistributionConfig {
76    /// Broadcast the lists received from the DC (case 1).
77    pub redistribute: bool,
78    /// Hz, case 1.
79    pub f1: f64,
80    /// Seconds, case 1.
81    pub d1: f64,
82    /// Hz, case 2 (answer to a P2P request).
83    pub f2: f64,
84    /// Seconds, case 2.
85    pub d2: f64,
86}
87
88impl Default for DistributionConfig {
89    fn default() -> Self {
90        Self {
91            redistribute: true,
92            f1: 1.0,
93            d1: 7.0 * 24.0 * 3600.0,
94            f2: 1.0,
95            d2: 10.0,
96        }
97    }
98}
99
100type Key = (ListKind, [u8; 8]);
101
102/// A list being broadcast.
103#[derive(Debug, Clone)]
104struct Broadcast {
105    message: Vec<u8>,
106    version: ListVersion,
107    /// 1 / f, seconds.
108    period: f64,
109    /// End of the broadcast period (UTC seconds).
110    until: f64,
111    /// Next transmission (UTC seconds).
112    next_tx: f64,
113}
114
115fn newer_or_same(received: &ListVersion, sent: &ListVersion) -> bool {
116    if received.kind == ListKind::Crl {
117        received.this_update.unwrap_or(0) >= sent.this_update.unwrap_or(0)
118    } else {
119        received.sequence.unwrap_or(0) >= sent.sequence.unwrap_or(0)
120    }
121}
122
123struct Inner {
124    trust: TrustStore,
125    config: DistributionConfig,
126    clock: PkiClock,
127    btp: Option<BTPRouterHandle>,
128    held: HashMap<Key, (Vec<u8>, ListVersion)>,
129    broadcasts: HashMap<Key, Broadcast>,
130    requests: Vec<Key>,
131    rotation: usize,
132    received: Vec<Vec<u8>>,
133}
134
135/// CRL / CTL distribution of the ITS-S (module documentation). Cloning gives
136/// another handle on the same service.
137#[derive(Clone)]
138pub struct TrustListDistribution {
139    inner: Arc<Mutex<Inner>>,
140}
141
142impl TrustListDistribution {
143    /// The service on `trust` (system clock, no BTP router: see
144    /// [`TrustListDistribution::with_btp`]).
145    pub fn new(trust: TrustStore, config: DistributionConfig) -> Self {
146        Self {
147            inner: Arc::new(Mutex::new(Inner {
148                trust,
149                config,
150                clock: Arc::new(unix_time_secs),
151                btp: None,
152                held: HashMap::new(),
153                broadcasts: HashMap::new(),
154                requests: Vec::new(),
155                rotation: 0,
156                received: Vec::new(),
157            })),
158        }
159    }
160
161    /// Use `clock` (UTC seconds) instead of the system time.
162    pub fn with_clock(self, clock: PkiClock) -> Self {
163        self.lock().clock = clock;
164        self
165    }
166
167    /// Send the broadcasts through `btp`.
168    pub fn with_btp(self, btp: BTPRouterHandle) -> Self {
169        self.lock().btp = Some(btp);
170        self
171    }
172
173    fn lock(&self) -> MutexGuard<'_, Inner> {
174        self.inner.lock().unwrap_or_else(|e| e.into_inner())
175    }
176
177    /// Register the CTL and CRL ports (open to unsecured packets) on `btp`; the
178    /// broadcasts received are queued for [`TrustListDistribution::process_received`].
179    pub fn attach(&self, btp: &BTPRouterHandle) {
180        self.lock().btp = Some(btp.clone());
181        let (tx, rx) = mpsc::channel();
182        btp.register_port_accepting_unsecured(CTL_PORT, tx.clone());
183        btp.register_port_accepting_unsecured(CRL_PORT, tx);
184        let service = self.clone();
185        std::thread::spawn(move || {
186            while let Ok(indication) = rx.recv() {
187                service.queue_broadcast(indication.data);
188            }
189        });
190    }
191
192    /// Change the parameters.
193    pub fn set_config(&self, config: DistributionConfig) {
194        self.lock().config = config;
195    }
196
197    /// Read access to the trust store.
198    pub fn with_trust<R>(&self, f: impl FnOnce(&TrustStore) -> R) -> R {
199        f(&self.lock().trust)
200    }
201
202    /// The lists being broadcast.
203    pub fn broadcasting(&self) -> Vec<(ListKind, [u8; 8])> {
204        self.lock().broadcasts.keys().copied().collect()
205    }
206
207    /// Number of the broadcasts queued and not yet processed.
208    pub fn queued(&self) -> usize {
209        self.lock().received.len()
210    }
211
212    /// The pending P2P requests, in turn order.
213    pub fn pending_requests(&self) -> Vec<(ListKind, [u8; 8])> {
214        self.lock().requests.clone()
215    }
216
217    // ── reception ──────────────────────────────────────────────────────────
218
219    /// Queue a CRL / CTL broadcast by a neighbour (payload of BTP port 2014 / 2015).
220    pub fn queue_broadcast(&self, message: Vec<u8>) {
221        self.lock().received.push(message);
222    }
223
224    /// Apply the queued broadcasts; the CA certificates revoked by them.
225    pub fn process_received(
226        &self,
227        library: &mut CertificateLibrary,
228        backend: &EcdsaBackend,
229    ) -> HashSet<[u8; 8]> {
230        let queued = std::mem::take(&mut self.lock().received);
231        let mut revoked = HashSet::new();
232        for message in queued {
233            if let Ok((_, r)) = self.receive(library, backend, &message, false) {
234                revoked.extend(r);
235            }
236        }
237        revoked
238    }
239
240    /// A CRL / CTL received from the DC (`from_dc`) or from a neighbour:
241    /// verified, applied when it is new, then redistributed (case 1) or ending a
242    /// broadcast of the same or an older version (clause 5.4.3). Its version and
243    /// the CA certificates it revokes; an error for a list that does not verify.
244    pub fn receive(
245        &self,
246        library: &mut CertificateLibrary,
247        backend: &EcdsaBackend,
248        message: &[u8],
249        from_dc: bool,
250    ) -> Result<(ListVersion, HashSet<[u8; 8]>), TrustListError> {
251        let mut inner = self.lock();
252        let version = inner.trust.inspect(library, backend, message)?;
253        let key = (version.kind, version.issuer);
254        let (applied, revoked) = match inner.trust.process(library, backend, message) {
255            Ok((_, revoked)) => (true, revoked),
256            Err(e) if e.code == "outdated" || e.code == "outofsequence" => (false, HashSet::new()),
257            Err(e) => return Err(e),
258        };
259        if !from_dc
260            && inner
261                .broadcasts
262                .get(&key)
263                .is_some_and(|current| newer_or_same(&version, &current.version))
264        {
265            inner.broadcasts.remove(&key);
266        }
267        if applied {
268            inner.requests.retain(|k| *k != key);
269            if !version.full {
270                inner.held.insert(key, (message.to_vec(), version.clone()));
271                if from_dc && inner.config.redistribute {
272                    let (f1, d1) = (inner.config.f1, inner.config.d1);
273                    inner.start(key, f1, d1);
274                }
275            }
276        }
277        Ok((version, revoked))
278    }
279
280    /// Download the due lists from the DC / CPOC and redistribute them; the URLs
281    /// fetched and the CA certificates revoked.
282    pub fn refresh(
283        &self,
284        library: &mut CertificateLibrary,
285        backend: &EcdsaBackend,
286        transport: &dyn PkiTransport,
287    ) -> (Vec<String>, HashSet<[u8; 8]>) {
288        let urls = self.lock().trust.due_downloads();
289        let mut revoked = HashSet::new();
290        for url in &urls {
291            if let Ok(message) = transport.get(url) {
292                if let Ok((_, r)) = self.receive(library, backend, &message, true) {
293                    revoked.extend(r);
294                }
295            }
296        }
297        (urls, revoked)
298    }
299
300    /// P2P requests in a verified message of a neighbour (clauses 5.3.6, 5.4.2).
301    pub fn on_requests(&self, requests: &[TrustListRequest]) {
302        let mut inner = self.lock();
303        for request in requests {
304            match request {
305                TrustListRequest::Crl(r) => inner.answer_crl(
306                    request.issuer(),
307                    r.last_known_update.as_ref().map(|t| t.0 .0),
308                ),
309                TrustListRequest::DeltaCtl(r) => inner.answer_ctl(
310                    request.issuer(),
311                    r.last_known_ctl_sequence.as_ref().map(|s| s.0),
312                ),
313                TrustListRequest::FullCtl(_) => {}
314            }
315        }
316    }
317
318    /// The listener to set on the GN router / verify service.
319    pub fn request_listener(&self) -> TrustListListener {
320        let service = self.clone();
321        Arc::new(move |requests: &[TrustListRequest], _at: &Certificate| {
322            service.on_requests(requests)
323        })
324    }
325
326    /// The provider to set on the sign service (`trust_list_request`).
327    pub fn request_provider(&self) -> TrustListRequestProvider {
328        let service = self.clone();
329        Arc::new(move || service.next_request())
330    }
331
332    // ── requests ───────────────────────────────────────────────────────────
333
334    /// Request the next CRL of the Root CA `issuer` (HashedId8) from the neighbours.
335    pub fn request_crl(&self, issuer: [u8; 8]) {
336        self.lock().request((ListKind::Crl, issuer));
337    }
338
339    /// Request the next Delta CTL of the TLM or Root CA `issuer` from the neighbours.
340    pub fn request_ctl(&self, issuer: [u8; 8]) {
341        self.lock().request_ctl(issuer);
342    }
343
344    /// The request to insert in the next CAM (one per CAM, in turn).
345    pub fn next_request(&self) -> Option<TrustListRequest> {
346        let mut inner = self.lock();
347        if inner.requests.is_empty() {
348            return None;
349        }
350        let key = inner.requests[inner.rotation % inner.requests.len()];
351        inner.rotation += 1;
352        let info = inner.trust.lists.get(&key);
353        let issuer = HashedId8(FixedOctetString::from(key.1));
354        Some(if key.0 == ListKind::Crl {
355            TrustListRequest::Crl(EtsiTs102941CrlRequest::new(
356                issuer,
357                info.and_then(|i| i.this_update).map(|t| Time32(Uint32(t))),
358            ))
359        } else {
360            TrustListRequest::DeltaCtl(EtsiTs102941CtlRequest::new(
361                issuer,
362                info.and_then(|i| i.sequence).map(Uint8),
363            ))
364        })
365    }
366
367    // ── timers ─────────────────────────────────────────────────────────────
368
369    /// Send the broadcasts due, end the expired ones and start the requests due
370    /// (to be called periodically).
371    pub fn tick(&self) {
372        let mut inner = self.lock();
373        let now = (inner.clock)();
374        let now32 = time32(now);
375        let keys: Vec<Key> = inner.broadcasts.keys().copied().collect();
376        for key in keys {
377            let b = inner.broadcasts[&key].clone();
378            if now >= b.until || now32 >= b.version.next_update {
379                inner.broadcasts.remove(&key);
380            } else if now >= b.next_tx {
381                inner.send(key, &b.message);
382                if let Some(b) = inner.broadcasts.get_mut(&key) {
383                    b.next_tx = (b.next_tx + b.period).max(now);
384                }
385            }
386        }
387        let expired: Vec<Key> = inner
388            .requests
389            .iter()
390            .copied()
391            .filter(|key| {
392                key.0 != ListKind::Crl
393                    && inner
394                        .trust
395                        .lists
396                        .get(key)
397                        .is_some_and(|i| now32 >= i.next_update)
398            })
399            .collect();
400        inner.requests.retain(|k| !expired.contains(k));
401        let due: Vec<[u8; 8]> = inner
402            .trust
403            .lists
404            .iter()
405            .filter(|((kind, _), info)| *kind == ListKind::Crl && now32 >= info.next_update)
406            .map(|((_, issuer), _)| *issuer)
407            .collect();
408        for issuer in due {
409            inner.request((ListKind::Crl, issuer));
410        }
411    }
412}
413
414impl Inner {
415    fn request(&mut self, key: Key) {
416        if !self.requests.contains(&key) {
417            self.requests.push(key);
418        }
419    }
420
421    fn request_ctl(&mut self, issuer: [u8; 8]) {
422        let kind = if self.trust.tlms.contains_key(&issuer) {
423            ListKind::Ectl
424        } else {
425            ListKind::RcaCtl
426        };
427        self.request((kind, issuer));
428    }
429
430    fn answer_crl(&mut self, issuer: [u8; 8], last_known: Option<u32>) {
431        let key = (ListKind::Crl, issuer);
432        if let Some((_, v)) = self.held.get(&key) {
433            if last_known.is_none_or(|t| v.this_update.unwrap_or(0) > t) {
434                let (f2, d2) = (self.config.f2, self.config.d2);
435                self.start(key, f2, d2);
436            }
437        }
438    }
439
440    fn answer_ctl(&mut self, issuer: [u8; 8], last_known: Option<u8>) {
441        for kind in [ListKind::Ectl, ListKind::RcaCtl] {
442            let key = (kind, issuer);
443            if let Some((_, v)) = self.held.get(&key) {
444                if last_known.is_none_or(|s| v.sequence.unwrap_or(0) > s) {
445                    let (f2, d2) = (self.config.f2, self.config.d2);
446                    self.start(key, f2, d2);
447                }
448            }
449            let held_sequence = self.trust.lists.get(&key).map(|i| i.sequence.unwrap_or(0));
450            if let (Some(held), Some(last)) = (held_sequence, last_known) {
451                if last > held {
452                    self.request_ctl(issuer); // the neighbour knows a newer CTL
453                }
454            }
455        }
456    }
457
458    fn start(&mut self, key: Key, frequency: f64, duration: f64) {
459        let Some((message, version)) = self.held.get(&key).cloned() else {
460            return;
461        };
462        let now = (self.clock)();
463        if self
464            .broadcasts
465            .get(&key)
466            .is_some_and(|b| b.version == version && b.until >= now + duration)
467        {
468            return; // already broadcast for longer
469        }
470        self.broadcasts.insert(
471            key,
472            Broadcast {
473                message: message.clone(),
474                version,
475                period: 1.0 / frequency,
476                until: now + duration,
477                next_tx: now + 1.0 / frequency,
478            },
479        );
480        self.send(key, &message);
481    }
482
483    fn send(&self, key: Key, message: &[u8]) {
484        let Some(btp) = &self.btp else {
485            return;
486        };
487        let crl = key.0 == ListKind::Crl;
488        btp.send_btp_data_request(BTPDataRequest {
489            btp_type: CommonNH::BtpB,
490            destination_port: if crl { CRL_PORT } else { CTL_PORT },
491            gn_packet_transport_type: PacketTransportType {
492                header_type: HeaderType::Tsb,
493                header_sub_type: HeaderSubType::TopoBroadcast(TopoBroadcastHST::SingleHop),
494            },
495            security_profile: SecurityProfile::Unsecured,
496            its_aid: if crl { PSID_CRL } else { PSID_CTL },
497            length: message.len() as u16,
498            data: message.to_vec(),
499            ..BTPDataRequest::new()
500        });
501    }
502}