Skip to main content

rustflexstack/security/
header_extensions.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! ETSI originating HeaderInfo extensions (ETSI TS 103 097 V2.2.1 clause 4.3.2
5//! and module EtsiTs103097ExtensionModule): the peer-to-peer CRL / CTL
6//! requests of ETSI TS 103 601 V2.1.1 clause 5.3.4, carried in
7//! `contributedExtensions`.
8//!
9//! A `ContributedExtensionBlock` of the ETSI contributor (2) holds a sequence
10//! of open types, each the COER encoding of an
11//! `EtsiOriginatingHeaderInfoExtension` (`id` and the open type `content`).
12//!
13//! Mirrors `flexstack/security/header_extensions.py`.
14
15use rasn::prelude::*;
16
17use crate::security::security_asn::etsi_ts103097_extension_module::{
18    EtsiTs102941CrlRequest, EtsiTs102941CtlRequest, EtsiTs102941FullCtlRequest,
19};
20use crate::security::security_asn::ieee1609_dot2::{
21    AnonymousContributedExtensionBlockExtns, ContributedExtensionBlock,
22    ContributedExtensionBlockExtns, ContributedExtensionBlocks, HeaderInfoContributorId,
23};
24
25/// IEEE 1609.2 HeaderInfoContributorId of ETSI TC ITS (TS 103 097 clause 4.3.2).
26pub const ETSI_HEADER_INFO_CONTRIBUTOR_ID: u8 = 2;
27/// EtsiTs103097HeaderInfoExtensionId values (EtsiTs103097ExtensionModule).
28pub const CRL_REQUEST_ID: u8 = 1;
29pub const DELTA_CTL_REQUEST_ID: u8 = 2;
30pub const FULL_CTL_REQUEST_ID: u8 = 3;
31
32/// A peer-to-peer CRL / CTL request (TS 103 601 clause 5.3.4).
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum TrustListRequest {
35    Crl(EtsiTs102941CrlRequest),
36    DeltaCtl(EtsiTs102941CtlRequest),
37    FullCtl(EtsiTs102941FullCtlRequest),
38}
39
40impl TrustListRequest {
41    /// The extension id of the request.
42    pub fn id(&self) -> u8 {
43        match self {
44            TrustListRequest::Crl(_) => CRL_REQUEST_ID,
45            TrustListRequest::DeltaCtl(_) => DELTA_CTL_REQUEST_ID,
46            TrustListRequest::FullCtl(_) => FULL_CTL_REQUEST_ID,
47        }
48    }
49
50    /// The HashedId8 of the TLM / Root CA whose list is requested.
51    pub fn issuer(&self) -> [u8; 8] {
52        let h = match self {
53            TrustListRequest::Crl(r) => &r.issuer_id,
54            TrustListRequest::DeltaCtl(r) => &r.issuer_id,
55            TrustListRequest::FullCtl(r) => &r.issuer_id,
56        };
57        let mut out = [0u8; 8];
58        out.copy_from_slice(h.0.as_ref());
59        out
60    }
61
62    fn content(&self) -> Vec<u8> {
63        match self {
64            TrustListRequest::Crl(r) => rasn::coer::encode(r),
65            TrustListRequest::DeltaCtl(r) => rasn::coer::encode(r),
66            TrustListRequest::FullCtl(r) => rasn::coer::encode(r),
67        }
68        .expect("COER encoding of a request")
69    }
70}
71
72fn length(n: usize) -> Vec<u8> {
73    if n < 128 {
74        return vec![n as u8];
75    }
76    let bytes: Vec<u8> = n
77        .to_be_bytes()
78        .iter()
79        .copied()
80        .skip_while(|b| *b == 0)
81        .collect();
82    let mut out = vec![0x80 | bytes.len() as u8];
83    out.extend(bytes);
84    out
85}
86
87/// COER of the `EtsiOriginatingHeaderInfoExtension` of `request`: id, then the
88/// open type content (length determinant and COER of the request).
89pub fn encode_extension(request: &TrustListRequest) -> Vec<u8> {
90    let content = request.content();
91    let mut out = vec![request.id()];
92    out.extend(length(content.len()));
93    out.extend(content);
94    out
95}
96
97/// Decode an `EtsiOriginatingHeaderInfoExtension`; None for an unknown id or
98/// a malformed extension.
99pub fn decode_extension(bytes: &[u8]) -> Option<TrustListRequest> {
100    let (&id, rest) = bytes.split_first()?;
101    let (&first, rest) = rest.split_first()?;
102    let (len, rest) = if first < 128 {
103        (first as usize, rest)
104    } else {
105        let n = (first & 0x7F) as usize;
106        if n == 0 || n > 4 || rest.len() < n {
107            return None;
108        }
109        let len = rest[..n].iter().fold(0usize, |a, b| (a << 8) | *b as usize);
110        (len, &rest[n..])
111    };
112    if rest.len() != len {
113        return None;
114    }
115    match id {
116        CRL_REQUEST_ID => rasn::coer::decode(rest).ok().map(TrustListRequest::Crl),
117        DELTA_CTL_REQUEST_ID => rasn::coer::decode(rest)
118            .ok()
119            .map(TrustListRequest::DeltaCtl),
120        FULL_CTL_REQUEST_ID => rasn::coer::decode(rest).ok().map(TrustListRequest::FullCtl),
121        _ => None,
122    }
123}
124
125/// `ContributedExtensionBlocks` with one ETSI block carrying `requests`.
126pub fn encode_requests(requests: &[TrustListRequest]) -> ContributedExtensionBlocks {
127    let extns = requests
128        .iter()
129        .map(|r| AnonymousContributedExtensionBlockExtns(OctetString::from(encode_extension(r))))
130        .collect();
131    ContributedExtensionBlocks(vec![ContributedExtensionBlock::new(
132        HeaderInfoContributorId(ETSI_HEADER_INFO_CONTRIBUTOR_ID),
133        ContributedExtensionBlockExtns(extns),
134    )])
135}
136
137/// The CRL / CTL requests in received `contributedExtensions`. Blocks of other
138/// contributors, unknown ids and undecodable extensions are skipped (TS 103 097
139/// clause 4.3.2).
140pub fn decode_requests(blocks: &ContributedExtensionBlocks) -> Vec<TrustListRequest> {
141    blocks
142        .0
143        .iter()
144        .filter(|b| b.contributor_id.0 == ETSI_HEADER_INFO_CONTRIBUTOR_ID)
145        .flat_map(|b| b.extns.0.iter())
146        .filter_map(|e| decode_extension(e.0.as_ref()))
147        .collect()
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    /// COER of HeaderInfo extension additions (X.696 clause 16.4: extension
155    /// presence bitmap over the 4 additions of the TS 103 097 V2.2.1 ASN.1,
156    /// then each addition as an open type). Frozen vectors, also in FlexStack
157    /// (test_canonical_oer). pduFunctionalType was encoded with a length
158    /// octet before the field constraint fix (rasn drops the constraints of a
159    /// delegate type in an extension addition).
160    #[test]
161    fn header_info_extension_additions_coer() {
162        use crate::security::security_asn::ieee1609_dot2::{HeaderInfo, PduFunctionalType};
163        use crate::security::security_asn::ieee1609_dot2_base_types::{
164            HashedId3, Psid, SequenceOfHashedId3,
165        };
166        let pdu = HeaderInfo::new(
167            Psid(rasn::prelude::Integer::from(36)),
168            None,
169            None,
170            None,
171            None,
172            None,
173            None,
174            None,
175            None,
176            Some(PduFunctionalType(2)),
177            None,
178        );
179        let bytes = rasn::coer::encode(&pdu).unwrap();
180        assert_eq!(bytes, vec![0x80, 0x01, 0x24, 0x02, 0x04, 0x20, 0x01, 0x02]);
181        assert_eq!(rasn::coer::decode::<HeaderInfo>(&bytes).unwrap(), pdu);
182        let p2pcd = HeaderInfo::new(
183            Psid(rasn::prelude::Integer::from(36)),
184            None,
185            None,
186            None,
187            None,
188            None,
189            None,
190            Some(SequenceOfHashedId3(vec![HashedId3([1, 2, 3].into())])),
191            None,
192            None,
193            None,
194        );
195        let bytes = rasn::coer::encode(&p2pcd).unwrap();
196        assert_eq!(
197            bytes,
198            vec![0x80, 0x01, 0x24, 0x02, 0x04, 0x80, 0x05, 0x01, 0x01, 0x01, 0x02, 0x03]
199        );
200    }
201    use crate::security::security_asn::ieee1609_dot2::HeaderInfo;
202    use crate::security::security_asn::ieee1609_dot2_base_types::{
203        HashedId8, Psid, Time32, Time64, Uint32, Uint64, Uint8,
204    };
205
206    fn to_hex(bytes: impl AsRef<[u8]>) -> String {
207        bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect()
208    }
209
210    fn issuer() -> HashedId8 {
211        HashedId8(FixedOctetString::from([0x11; 8]))
212    }
213
214    fn crl(last: Option<u32>) -> TrustListRequest {
215        TrustListRequest::Crl(EtsiTs102941CrlRequest::new(
216            issuer(),
217            last.map(|t| Time32(Uint32(t))),
218        ))
219    }
220
221    fn header(requests: &[TrustListRequest]) -> HeaderInfo {
222        let mut h = HeaderInfo::new(
223            Psid(Integer::from(36)),
224            Some(Time64(Uint64(1))),
225            None,
226            None,
227            None,
228            None,
229            None,
230            None,
231            None,
232            None,
233            None,
234        );
235        h.contributed_extensions = Some(encode_requests(requests));
236        h
237    }
238
239    /// COER derived by hand: id 01, content length 0d, CrlRequest = preamble 80
240    /// (lastKnownUpdate present) || issuerId || Time32 00000005.
241    #[test]
242    fn crl_request_encoding() {
243        assert_eq!(
244            to_hex(encode_extension(&crl(Some(5)))),
245            format!("010d80{}00000005", "11".repeat(8))
246        );
247        let delta = TrustListRequest::DeltaCtl(EtsiTs102941CtlRequest::new(issuer(), None));
248        assert_eq!(
249            to_hex(encode_extension(&delta)),
250            format!("020900{}", "11".repeat(8))
251        );
252    }
253
254    /// The same HeaderInfo encodings as FlexStack (frozen from
255    /// `asn_coder.encode("HeaderInfo", ...)`).
256    #[test]
257    fn header_info_vectors() {
258        let delta =
259            TrustListRequest::DeltaCtl(EtsiTs102941CtlRequest::new(issuer(), Some(Uint8(7))));
260        for (request, expected) in [
261            (
262                crl(Some(5)),
263                "c0012400000000000000010204101501010201010f010d80111111111111111100000005",
264            ),
265            (
266                delta,
267                "c0012400000000000000010204101201010201010c020a80111111111111111107",
268            ),
269        ] {
270            let encoded = rasn::coer::encode(&header(std::slice::from_ref(&request))).unwrap();
271            assert_eq!(to_hex(&encoded), expected);
272            let decoded: HeaderInfo = rasn::coer::decode(&encoded).unwrap();
273            assert_eq!(
274                decode_requests(decoded.contributed_extensions.as_ref().unwrap()),
275                vec![request]
276            );
277        }
278    }
279
280    #[test]
281    fn foreign_and_unknown_extensions_skipped() {
282        let mut blocks = encode_requests(&[crl(None)]);
283        blocks.0[0].extns.0.insert(
284            0,
285            AnonymousContributedExtensionBlockExtns(OctetString::from(vec![9, 1, 0])),
286        );
287        blocks.0[0].extns.0.insert(
288            0,
289            AnonymousContributedExtensionBlockExtns(OctetString::from(vec![0xff])),
290        );
291        blocks.0.insert(
292            0,
293            ContributedExtensionBlock::new(
294                HeaderInfoContributorId(1),
295                ContributedExtensionBlockExtns(vec![AnonymousContributedExtensionBlockExtns(
296                    OctetString::from(encode_extension(&crl(Some(1)))),
297                )]),
298            ),
299        );
300        assert_eq!(decode_requests(&blocks), vec![crl(None)]);
301    }
302}