Skip to main content

rustflexstack/security/
pki_asn.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! ASN.1 types of the ETSI TS 102 941 V2.2.1 ITS-S messages (official modules
5//! of <https://forge.etsi.org/rep/ITS/asn1/pki_ts102941>, tag v2.2.1):
6//! `EtsiTs102941BaseTypes`, `EtsiTs102941TypesEnrolment`,
7//! `EtsiTs102941TypesAuthorization`, `EtsiTs102941TrustLists`,
8//! `EtsiTs102941TypesLinkCertificate` and `EtsiTs102941MessagesItss`.
9//!
10//! `#[non_exhaustive]` marks the extensible types (`...`), as in the code
11//! generated for the other modules. Subtype constraints (`WITH COMPONENTS`)
12//! are checked by the PKI client, not by the types. The alternatives of
13//! `EtsiTs102941DataContent` added for butterfly key expansion carry IEEE
14//! 1609.2.1 types; butterfly is not implemented and they are kept as OCTET
15//! STRINGs, as the IEEE 1609.2.1 stubs of the Python stack (rasn cannot decode
16//! [`rasn::types::Any`] in OER: it panics), which does not affect the other
17//! alternatives.
18//! The encodings are checked against frozen vectors produced from the official
19//! module text (Python stack, `test_pki_coder.py`).
20
21#![allow(
22    non_camel_case_types,
23    non_snake_case,
24    clippy::too_many_arguments,
25    clippy::large_enum_variant
26)]
27
28use rasn::prelude::*;
29
30use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
31use crate::security::security_asn::ieee1609_dot2::{
32    CertificateId, HashedData, Ieee1609Dot2Data, SequenceOfPsidGroupPermissions,
33};
34use crate::security::security_asn::ieee1609_dot2_base_types::{
35    GeographicRegion, HashedId8, PublicEncryptionKey, PublicVerificationKey, SequenceOfPsidSsp,
36    SubjectAssurance, Time32, ValidityPeriod,
37};
38
39/// `EtsiTs102941BaseTypes`.
40pub mod etsi_ts102941_base_types {
41    use super::*;
42
43    /// `CertificateFormat ::= INTEGER {ts103097v131 (1)} (1..255)`.
44    #[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq, Hash)]
45    #[rasn(delegate, value("1..=255"))]
46    pub struct CertificateFormat(pub u8);
47
48    /// ts103097v131.
49    pub const TS103097V131: CertificateFormat = CertificateFormat(1);
50
51    /// `CertificateSubjectAttributes` (extensible).
52    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash, Default)]
53    #[rasn(automatic_tags)]
54    #[non_exhaustive]
55    pub struct CertificateSubjectAttributes {
56        pub id: Option<CertificateId>,
57        #[rasn(identifier = "validityPeriod")]
58        pub validity_period: Option<ValidityPeriod>,
59        pub region: Option<GeographicRegion>,
60        #[rasn(identifier = "assuranceLevel")]
61        pub assurance_level: Option<SubjectAssurance>,
62        #[rasn(identifier = "appPermissions")]
63        pub app_permissions: Option<SequenceOfPsidSsp>,
64        #[rasn(identifier = "certIssuePermissions")]
65        pub cert_issue_permissions: Option<SequenceOfPsidGroupPermissions>,
66    }
67
68    impl CertificateSubjectAttributes {
69        pub fn new(
70            id: Option<CertificateId>,
71            validity_period: Option<ValidityPeriod>,
72            region: Option<GeographicRegion>,
73            assurance_level: Option<SubjectAssurance>,
74            app_permissions: Option<SequenceOfPsidSsp>,
75            cert_issue_permissions: Option<SequenceOfPsidGroupPermissions>,
76        ) -> Self {
77            Self {
78                id,
79                validity_period,
80                region,
81                assurance_level,
82                app_permissions,
83                cert_issue_permissions,
84            }
85        }
86    }
87
88    /// `EcSignature`: the EC signature of the SharedAtRequest, encrypted for the
89    /// EA (privacy) or not.
90    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
91    #[rasn(choice, automatic_tags)]
92    pub enum EcSignature {
93        encryptedEcSignature(Ieee1609Dot2Data),
94        ecSignature(Ieee1609Dot2Data),
95    }
96
97    /// `PublicKeys` (not extensible).
98    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
99    #[rasn(automatic_tags)]
100    pub struct PublicKeys {
101        #[rasn(identifier = "verificationKey")]
102        pub verification_key: PublicVerificationKey,
103        #[rasn(identifier = "encryptionKey")]
104        pub encryption_key: Option<PublicEncryptionKey>,
105    }
106
107    impl PublicKeys {
108        pub fn new(
109            verification_key: PublicVerificationKey,
110            encryption_key: Option<PublicEncryptionKey>,
111        ) -> Self {
112            Self {
113                verification_key,
114                encryption_key,
115            }
116        }
117    }
118}
119
120/// `EtsiTs102941TypesEnrolment`.
121pub mod etsi_ts102941_types_enrolment {
122    use super::etsi_ts102941_base_types::*;
123    use super::*;
124
125    /// `EnrolmentResponseCode` (extensible).
126    #[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq, Hash)]
127    #[rasn(enumerated)]
128    #[non_exhaustive]
129    pub enum EnrolmentResponseCode {
130        ok = 0,
131        cantparse = 1,
132        badcontenttype = 2,
133        imnottherecipient = 3,
134        unknownencryptionalgorithm = 4,
135        decryptionfailed = 5,
136        unknownits = 6,
137        invalidsignature = 7,
138        invalidencryptionkey = 8,
139        baditsstatus = 9,
140        incompleterequest = 10,
141        deniedpermissions = 11,
142        invalidkeys = 12,
143        deniedrequest = 13,
144    }
145
146    /// `InnerEcRequestSignedForPop ::= EtsiTs103097Data-Signed{InnerEcRequest}`.
147    pub type InnerEcRequestSignedForPop = Ieee1609Dot2Data;
148
149    /// `InnerEcRequest` (extensible).
150    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
151    #[rasn(automatic_tags)]
152    #[non_exhaustive]
153    pub struct InnerEcRequest {
154        #[rasn(identifier = "itsId")]
155        pub its_id: OctetString,
156        #[rasn(identifier = "certificateFormat")]
157        pub certificate_format: CertificateFormat,
158        #[rasn(identifier = "publicKeys")]
159        pub public_keys: PublicKeys,
160        #[rasn(identifier = "requestedSubjectAttributes")]
161        pub requested_subject_attributes: CertificateSubjectAttributes,
162    }
163
164    impl InnerEcRequest {
165        pub fn new(
166            its_id: OctetString,
167            certificate_format: CertificateFormat,
168            public_keys: PublicKeys,
169            requested_subject_attributes: CertificateSubjectAttributes,
170        ) -> Self {
171            Self {
172                its_id,
173                certificate_format,
174                public_keys,
175                requested_subject_attributes,
176            }
177        }
178    }
179
180    /// `InnerEcResponse` (extensible).
181    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
182    #[rasn(automatic_tags)]
183    #[non_exhaustive]
184    pub struct InnerEcResponse {
185        #[rasn(identifier = "requestHash")]
186        pub request_hash: FixedOctetString<16>,
187        #[rasn(identifier = "responseCode")]
188        pub response_code: EnrolmentResponseCode,
189        pub certificate: Option<EtsiTs103097Certificate>,
190    }
191
192    impl InnerEcResponse {
193        pub fn new(
194            request_hash: FixedOctetString<16>,
195            response_code: EnrolmentResponseCode,
196            certificate: Option<EtsiTs103097Certificate>,
197        ) -> Self {
198            Self {
199                request_hash,
200                response_code,
201                certificate,
202            }
203        }
204    }
205}
206
207/// `EtsiTs102941TypesAuthorization`.
208pub mod etsi_ts102941_types_authorization {
209    use super::etsi_ts102941_base_types::*;
210    use super::*;
211
212    /// `AuthorizationResponseCode` (extensible).
213    #[derive(AsnType, Debug, Clone, Copy, Decode, Encode, PartialEq, Eq, Hash)]
214    #[rasn(enumerated)]
215    #[non_exhaustive]
216    pub enum AuthorizationResponseCode {
217        ok = 0,
218        #[rasn(identifier = "its-aa-cantparse")]
219        its_aa_cantparse = 1,
220        #[rasn(identifier = "its-aa-badcontenttype")]
221        its_aa_badcontenttype = 2,
222        #[rasn(identifier = "its-aa-imnottherecipient")]
223        its_aa_imnottherecipient = 3,
224        #[rasn(identifier = "its-aa-unknownencryptionalgorithm")]
225        its_aa_unknownencryptionalgorithm = 4,
226        #[rasn(identifier = "its-aa-decryptionfailed")]
227        its_aa_decryptionfailed = 5,
228        #[rasn(identifier = "its-aa-keysdontmatch")]
229        its_aa_keysdontmatch = 6,
230        #[rasn(identifier = "its-aa-incompleterequest")]
231        its_aa_incompleterequest = 7,
232        #[rasn(identifier = "its-aa-invalidencryptionkey")]
233        its_aa_invalidencryptionkey = 8,
234        #[rasn(identifier = "its-aa-outofsyncrequest")]
235        its_aa_outofsyncrequest = 9,
236        #[rasn(identifier = "its-aa-unknownea")]
237        its_aa_unknownea = 10,
238        #[rasn(identifier = "its-aa-invalidea")]
239        its_aa_invalidea = 11,
240        #[rasn(identifier = "its-aa-deniedpermissions")]
241        its_aa_deniedpermissions = 12,
242        #[rasn(identifier = "aa-ea-cantreachea")]
243        aa_ea_cantreachea = 13,
244        #[rasn(identifier = "ea-aa-cantparse")]
245        ea_aa_cantparse = 14,
246        #[rasn(identifier = "ea-aa-badcontenttype")]
247        ea_aa_badcontenttype = 15,
248        #[rasn(identifier = "ea-aa-imnottherecipient")]
249        ea_aa_imnottherecipient = 16,
250        #[rasn(identifier = "ea-aa-unknownencryptionalgorithm")]
251        ea_aa_unknownencryptionalgorithm = 17,
252        #[rasn(identifier = "ea-aa-decryptionfailed")]
253        ea_aa_decryptionfailed = 18,
254        invalidaa = 19,
255        invalidaasignature = 20,
256        wrongea = 21,
257        unknownits = 22,
258        invalidsignature = 23,
259        invalidencryptionkey = 24,
260        deniedpermissions = 25,
261        deniedtoomanycerts = 26,
262    }
263
264    /// `InnerAtRequest` (extensible).
265    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
266    #[rasn(automatic_tags)]
267    #[non_exhaustive]
268    pub struct InnerAtRequest {
269        #[rasn(identifier = "publicKeys")]
270        pub public_keys: PublicKeys,
271        #[rasn(identifier = "hmacKey")]
272        pub hmac_key: FixedOctetString<32>,
273        #[rasn(identifier = "sharedAtRequest")]
274        pub shared_at_request: SharedAtRequest,
275        #[rasn(identifier = "ecSignature")]
276        pub ec_signature: EcSignature,
277    }
278
279    impl InnerAtRequest {
280        pub fn new(
281            public_keys: PublicKeys,
282            hmac_key: FixedOctetString<32>,
283            shared_at_request: SharedAtRequest,
284            ec_signature: EcSignature,
285        ) -> Self {
286            Self {
287                public_keys,
288                hmac_key,
289                shared_at_request,
290                ec_signature,
291            }
292        }
293    }
294
295    /// `SharedAtRequest` (extensible).
296    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
297    #[rasn(automatic_tags)]
298    #[non_exhaustive]
299    pub struct SharedAtRequest {
300        #[rasn(identifier = "eaId")]
301        pub ea_id: HashedId8,
302        #[rasn(identifier = "keyTag")]
303        pub key_tag: FixedOctetString<16>,
304        #[rasn(identifier = "certificateFormat")]
305        pub certificate_format: CertificateFormat,
306        #[rasn(identifier = "requestedSubjectAttributes")]
307        pub requested_subject_attributes: CertificateSubjectAttributes,
308    }
309
310    impl SharedAtRequest {
311        pub fn new(
312            ea_id: HashedId8,
313            key_tag: FixedOctetString<16>,
314            certificate_format: CertificateFormat,
315            requested_subject_attributes: CertificateSubjectAttributes,
316        ) -> Self {
317            Self {
318                ea_id,
319                key_tag,
320                certificate_format,
321                requested_subject_attributes,
322            }
323        }
324    }
325
326    /// `InnerAtResponse` (extensible).
327    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
328    #[rasn(automatic_tags)]
329    #[non_exhaustive]
330    pub struct InnerAtResponse {
331        #[rasn(identifier = "requestHash")]
332        pub request_hash: FixedOctetString<16>,
333        #[rasn(identifier = "responseCode")]
334        pub response_code: AuthorizationResponseCode,
335        pub certificate: Option<EtsiTs103097Certificate>,
336    }
337
338    impl InnerAtResponse {
339        pub fn new(
340            request_hash: FixedOctetString<16>,
341            response_code: AuthorizationResponseCode,
342            certificate: Option<EtsiTs103097Certificate>,
343        ) -> Self {
344            Self {
345                request_hash,
346                response_code,
347                certificate,
348            }
349        }
350    }
351}
352
353/// `EtsiTs102941TrustLists`.
354pub mod etsi_ts102941_trust_lists {
355    use super::*;
356
357    /// `Url ::= IA5String`.
358    pub type Url = Ia5String;
359    /// `CrlEntry ::= HashedId8`.
360    pub type CrlEntry = HashedId8;
361
362    /// `ToBeSignedCrl` (extensible); `version` is `Version ::= INTEGER {v1(1)}`.
363    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
364    #[rasn(automatic_tags)]
365    #[non_exhaustive]
366    pub struct ToBeSignedCrl {
367        pub version: Integer,
368        #[rasn(identifier = "thisUpdate")]
369        pub this_update: Time32,
370        #[rasn(identifier = "nextUpdate")]
371        pub next_update: Time32,
372        pub entries: SequenceOf<CrlEntry>,
373    }
374
375    impl ToBeSignedCrl {
376        pub fn new(
377            version: Integer,
378            this_update: Time32,
379            next_update: Time32,
380            entries: SequenceOf<CrlEntry>,
381        ) -> Self {
382            Self {
383                version,
384                this_update,
385                next_update,
386                entries,
387            }
388        }
389    }
390
391    /// `CtlFormat` (extensible); `ToBeSignedTlmCtl` and `ToBeSignedRcaCtl` are
392    /// subtypes of it (full or delta CTL, allowed entries).
393    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
394    #[rasn(automatic_tags)]
395    #[non_exhaustive]
396    pub struct CtlFormat {
397        pub version: Integer,
398        #[rasn(identifier = "nextUpdate")]
399        pub next_update: Time32,
400        #[rasn(identifier = "isFullCtl")]
401        pub is_full_ctl: bool,
402        #[rasn(identifier = "ctlSequence", value("0..=255"))]
403        pub ctl_sequence: u8,
404        #[rasn(identifier = "ctlCommands")]
405        pub ctl_commands: SequenceOf<CtlCommand>,
406    }
407
408    impl CtlFormat {
409        pub fn new(
410            version: Integer,
411            next_update: Time32,
412            is_full_ctl: bool,
413            ctl_sequence: u8,
414            ctl_commands: SequenceOf<CtlCommand>,
415        ) -> Self {
416            Self {
417                version,
418                next_update,
419                is_full_ctl,
420                ctl_sequence,
421                ctl_commands,
422            }
423        }
424    }
425
426    pub type ToBeSignedTlmCtl = CtlFormat;
427    pub type ToBeSignedRcaCtl = CtlFormat;
428
429    /// `CtlCommand` (extensible).
430    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
431    #[rasn(choice, automatic_tags)]
432    #[non_exhaustive]
433    pub enum CtlCommand {
434        add(CtlEntry),
435        delete(CtlDelete),
436    }
437
438    /// `CtlEntry` (extensible).
439    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
440    #[rasn(choice, automatic_tags)]
441    #[non_exhaustive]
442    pub enum CtlEntry {
443        rca(RootCaEntry),
444        ea(EaEntry),
445        aa(AaEntry),
446        dc(DcEntry),
447        tlm(TlmEntry),
448    }
449
450    /// `CtlDelete` (extensible).
451    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
452    #[rasn(choice, automatic_tags)]
453    #[non_exhaustive]
454    pub enum CtlDelete {
455        cert(HashedId8),
456        dc(Url),
457    }
458
459    /// `TlmEntry`.
460    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
461    #[rasn(automatic_tags)]
462    pub struct TlmEntry {
463        #[rasn(identifier = "selfSignedTLMCertificate")]
464        pub self_signed_tlm_certificate: EtsiTs103097Certificate,
465        #[rasn(identifier = "successorTo")]
466        pub successor_to: Option<EtsiTs103097Certificate>,
467        #[rasn(identifier = "accessPoint")]
468        pub access_point: Url,
469    }
470
471    /// `RootCaEntry`.
472    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
473    #[rasn(automatic_tags)]
474    pub struct RootCaEntry {
475        #[rasn(identifier = "selfsignedRootCa")]
476        pub selfsigned_root_ca: EtsiTs103097Certificate,
477        #[rasn(identifier = "successorTo")]
478        pub successor_to: Option<EtsiTs103097Certificate>,
479    }
480
481    /// `EaEntry`.
482    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
483    #[rasn(automatic_tags)]
484    pub struct EaEntry {
485        #[rasn(identifier = "eaCertificate")]
486        pub ea_certificate: EtsiTs103097Certificate,
487        #[rasn(identifier = "aaAccessPoint")]
488        pub aa_access_point: Url,
489        #[rasn(identifier = "itsAccessPoint")]
490        pub its_access_point: Option<Url>,
491    }
492
493    /// `AaEntry`.
494    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
495    #[rasn(automatic_tags)]
496    pub struct AaEntry {
497        #[rasn(identifier = "aaCertificate")]
498        pub aa_certificate: EtsiTs103097Certificate,
499        #[rasn(identifier = "accessPoint")]
500        pub access_point: Url,
501    }
502
503    /// `DcEntry`.
504    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
505    #[rasn(automatic_tags)]
506    pub struct DcEntry {
507        pub url: Url,
508        pub cert: SequenceOf<HashedId8>,
509    }
510}
511
512/// `EtsiTs102941TypesLinkCertificate`.
513pub mod etsi_ts102941_types_link_certificate {
514    use super::*;
515
516    /// `ToBeSignedLinkCertificate` (extensible); the TLM and RCA variants are the same type.
517    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
518    #[rasn(automatic_tags)]
519    #[non_exhaustive]
520    pub struct ToBeSignedLinkCertificate {
521        #[rasn(identifier = "expiryTime")]
522        pub expiry_time: Time32,
523        #[rasn(identifier = "certificateHash")]
524        pub certificate_hash: HashedData,
525    }
526
527    pub type ToBeSignedLinkCertificateTlm = ToBeSignedLinkCertificate;
528}
529
530/// `EtsiTs102941MessagesItss`.
531pub mod etsi_ts102941_messages_itss {
532    use super::etsi_ts102941_trust_lists::*;
533    use super::etsi_ts102941_types_authorization::*;
534    use super::etsi_ts102941_types_enrolment::*;
535    use super::etsi_ts102941_types_link_certificate::*;
536    use super::*;
537
538    /// `EtsiTs102941Data`; `version` is `Version (v1)`, i.e. the value 1.
539    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
540    #[rasn(automatic_tags)]
541    pub struct EtsiTs102941Data {
542        #[rasn(value("1"))]
543        pub version: u8,
544        pub content: EtsiTs102941DataContent,
545    }
546
547    impl EtsiTs102941Data {
548        /// Version v1 with `content`.
549        pub fn new(content: EtsiTs102941DataContent) -> Self {
550            Self {
551                version: 1,
552                content,
553            }
554        }
555    }
556
557    /// `EtsiTs102941DataContent` (extensible).
558    #[derive(AsnType, Debug, Clone, Decode, Encode, PartialEq, Eq, Hash)]
559    #[rasn(choice, automatic_tags)]
560    #[non_exhaustive]
561    pub enum EtsiTs102941DataContent {
562        enrolmentRequest(InnerEcRequestSignedForPop),
563        enrolmentResponse(InnerEcResponse),
564        authorizationRequest(InnerAtRequest),
565        authorizationResponse(InnerAtResponse),
566        certificateRevocationList(ToBeSignedCrl),
567        certificateTrustListTlm(ToBeSignedTlmCtl),
568        certificateTrustListRca(ToBeSignedRcaCtl),
569        authorizationValidationRequest(()),
570        authorizationValidationResponse(()),
571        caCertificateRequest(()),
572        #[rasn(extension_addition)]
573        linkCertificateTlm(ToBeSignedLinkCertificateTlm),
574        #[rasn(extension_addition)]
575        singleSignedLinkCertificateRca(()),
576        #[rasn(extension_addition)]
577        doubleSignedlinkCertificateRca(()),
578        #[rasn(extension_addition)]
579        butterflyAuthorizationRequest(OctetString),
580        #[rasn(extension_addition)]
581        x509SignedbutterflyAuthorizationRequest(OctetString),
582        #[rasn(extension_addition)]
583        butterflyAuthorizationResponse(OctetString),
584        #[rasn(extension_addition)]
585        butterflyCertificateRequest(()),
586        #[rasn(extension_addition)]
587        butterflyCertificateResponse(()),
588        #[rasn(extension_addition)]
589        butterflyAtDownloadRequest(OctetString),
590    }
591}
592
593/// COER encoding.
594pub fn encode<T: Encode>(value: &T) -> Vec<u8> {
595    rasn::coer::encode(value).expect("COER encoding of a PKI type")
596}
597
598/// COER decoding.
599pub fn decode<T: Decode>(data: &[u8]) -> Result<T, rasn::error::DecodeError> {
600    rasn::coer::decode(data)
601}
602
603#[cfg(test)]
604mod tests {
605    use super::etsi_ts102941_base_types::*;
606    use super::etsi_ts102941_messages_itss::*;
607    use super::etsi_ts102941_trust_lists::*;
608    use super::etsi_ts102941_types_authorization::*;
609    use super::etsi_ts102941_types_enrolment::*;
610    use super::*;
611    use crate::security::security_asn::ieee1609_dot2_base_types::{
612        BasePublicEncryptionKey, BitmapSsp, Duration, EccP256CurvePoint, Psid, PsidSsp,
613        ServiceSpecificPermissions, SymmAlgorithm, Uint16, Uint32,
614    };
615
616    /// Frozen COER encodings of the official types, produced by asn1tools from
617    /// the forge.etsi.org module text (FlexStack `test_pki_coder.py`).
618    const INNER_EC_REQUEST: &str = "000831323334353637380180808211111111111111111111111111111111111111111111111111111111111111110080832222222222222222222222222222222222222222222222222222222222222222240000006486000101018002026f81030201c0";
619    const INNER_EC_RESPONSE: &str = "00abababababababababababababababab0d";
620    const SHARED_AT_REQUEST: &str =
621        "00aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb01040102000124000125";
622    const INNER_AT_RESPONSE: &str = "00cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd0a";
623    const CRL: &str = "0184000101000000050000000601010101010101010101";
624    const RCA_CTL: &str = "0186000101000000070003010280830b68747470733a2f2f64632f0101020202020202020281800303030303030303";
625    const AT_REQUEST: &str = "0182000080834444444444444444444444444444444444444444444444444444444444444444555555555555555555555555555555555555555555555555555555555555555500aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb01040101000124800382010182666666666666666680827777777777777777777777777777777777777777777777777777777777777777888888888888888888888888888888889999999999999999999999999999999980121212121212121212121212143434343434343434343434343434343434343434";
626
627    fn psid_ssp(psid: i64, ssp: Option<&[u8]>) -> PsidSsp {
628        PsidSsp::new(
629            Psid(Integer::from(psid)),
630            ssp.map(|s| ServiceSpecificPermissions::bitmapSsp(BitmapSsp(s.to_vec().into()))),
631        )
632    }
633
634    fn check<T: Encode + Decode + PartialEq + std::fmt::Debug>(value: T, vector: &str) {
635        let encoded = encode(&value);
636        assert_eq!(hex(&encoded), vector);
637        assert_eq!(decode::<T>(&encoded).unwrap(), value);
638    }
639
640    fn hex(data: &[u8]) -> String {
641        data.iter().map(|b| format!("{b:02x}")).collect()
642    }
643
644    /// A butterfly alternative (extension addition 13) decodes, as an OCTET STRING
645    /// (IEEE 1609.2.1 stub), instead of panicking as `Any` did; the encoding of the
646    /// Python stack (`018d0403010203`).
647    #[test]
648    fn butterfly_alternative_decodes() {
649        use super::etsi_ts102941_messages_itss::{EtsiTs102941Data, EtsiTs102941DataContent};
650        let bytes = [0x01, 0x8d, 0x04, 0x03, 0x01, 0x02, 0x03];
651        let data: EtsiTs102941Data = decode(&bytes).unwrap();
652        assert!(matches!(
653            &data.content,
654            EtsiTs102941DataContent::butterflyAuthorizationRequest(o) if o.as_ref() == [1, 2, 3]
655        ));
656        assert_eq!(encode(&data), bytes);
657    }
658
659    /// The official ETSI TS 102 941 V2.2.1 encodings: extension bits in the
660    /// preambles, CHOICE indexes (CRL 4, RCA CTL 6), Version length-prefixed in
661    /// CtlFormat / ToBeSignedCrl and one octet in EtsiTs102941Data.
662    #[test]
663    fn official_encodings() {
664        let attributes = CertificateSubjectAttributes::new(
665            None,
666            Some(ValidityPeriod::new(
667                Time32(Uint32(100)),
668                Duration::years(Uint16(1)),
669            )),
670            None,
671            None,
672            Some(SequenceOfPsidSsp(vec![psid_ssp(623, Some(&[1, 0xC0]))])),
673            None,
674        );
675        check(
676            InnerEcRequest::new(
677                b"12345678".to_vec().into(),
678                TS103097V131,
679                PublicKeys::new(
680                    PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::compressed_y_0(
681                        vec![0x11; 32].into(),
682                    )),
683                    Some(PublicEncryptionKey::new(
684                        SymmAlgorithm::aes128Ccm,
685                        BasePublicEncryptionKey::eciesNistP256(EccP256CurvePoint::compressed_y_1(
686                            vec![0x22; 32].into(),
687                        )),
688                    )),
689                ),
690                attributes,
691            ),
692            INNER_EC_REQUEST,
693        );
694        check(
695            InnerEcResponse::new(
696                FixedOctetString::from([0xAB; 16]),
697                EnrolmentResponseCode::deniedrequest,
698                None,
699            ),
700            INNER_EC_RESPONSE,
701        );
702        check(
703            SharedAtRequest::new(
704                HashedId8(FixedOctetString::from([0xAA; 8])),
705                FixedOctetString::from([0xBB; 16]),
706                TS103097V131,
707                CertificateSubjectAttributes::new(
708                    None,
709                    None,
710                    None,
711                    None,
712                    Some(SequenceOfPsidSsp(vec![
713                        psid_ssp(36, None),
714                        psid_ssp(37, None),
715                    ])),
716                    None,
717                ),
718            ),
719            SHARED_AT_REQUEST,
720        );
721        check(
722            InnerAtResponse::new(
723                FixedOctetString::from([0xCD; 16]),
724                AuthorizationResponseCode::its_aa_unknownea,
725                None,
726            ),
727            INNER_AT_RESPONSE,
728        );
729        check(
730            EtsiTs102941Data::new(EtsiTs102941DataContent::certificateRevocationList(
731                ToBeSignedCrl::new(
732                    Integer::from(1),
733                    Time32(Uint32(5)),
734                    Time32(Uint32(6)),
735                    vec![HashedId8(FixedOctetString::from([1; 8]))],
736                ),
737            )),
738            CRL,
739        );
740        check(
741            EtsiTs102941Data::new(EtsiTs102941DataContent::certificateTrustListRca(
742                CtlFormat::new(
743                    Integer::from(1),
744                    Time32(Uint32(7)),
745                    false,
746                    3,
747                    vec![
748                        CtlCommand::add(CtlEntry::dc(DcEntry {
749                            url: Ia5String::try_from("https://dc/".to_string()).unwrap(),
750                            cert: vec![HashedId8(FixedOctetString::from([2; 8]))],
751                        })),
752                        CtlCommand::delete(CtlDelete::cert(HashedId8(FixedOctetString::from(
753                            [3; 8],
754                        )))),
755                    ],
756                ),
757            )),
758            RCA_CTL,
759        );
760        // EcSignature: encryptedEcSignature is alternative 0 (80h)
761        use crate::security::security_asn::ieee1609_dot2::{
762            EncryptedData, EncryptedDataEncryptionKey, Ieee1609Dot2Content, One28BitCcmCiphertext,
763            PKRecipientInfo, RecipientInfo, SequenceOfRecipientInfo, SymmetricCiphertext,
764        };
765        use crate::security::security_asn::ieee1609_dot2_base_types::{
766            EciesP256EncryptedKey, Opaque, Uint8,
767        };
768        let encrypted = Ieee1609Dot2Data::new(
769            Uint8(3),
770            Ieee1609Dot2Content::encryptedData(EncryptedData::new(
771                SequenceOfRecipientInfo(vec![RecipientInfo::certRecipInfo(PKRecipientInfo::new(
772                    HashedId8(FixedOctetString::from([0x66; 8])),
773                    EncryptedDataEncryptionKey::eciesNistP256(EciesP256EncryptedKey {
774                        v: EccP256CurvePoint::compressed_y_0(vec![0x77; 32].into()),
775                        c: vec![0x88; 16].into(),
776                        t: vec![0x99; 16].into(),
777                    }),
778                ))]),
779                SymmetricCiphertext::aes128ccm(One28BitCcmCiphertext::new(
780                    vec![0x12; 12].into(),
781                    Opaque(vec![0x34; 20].into()),
782                )),
783            )),
784        );
785        check(
786            EtsiTs102941Data::new(EtsiTs102941DataContent::authorizationRequest(
787                InnerAtRequest::new(
788                    PublicKeys::new(
789                        PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::compressed_y_1(
790                            vec![0x44; 32].into(),
791                        )),
792                        None,
793                    ),
794                    FixedOctetString::from([0x55; 32]),
795                    SharedAtRequest::new(
796                        HashedId8(FixedOctetString::from([0xAA; 8])),
797                        FixedOctetString::from([0xBB; 16]),
798                        TS103097V131,
799                        CertificateSubjectAttributes::new(
800                            None,
801                            None,
802                            None,
803                            None,
804                            Some(SequenceOfPsidSsp(vec![psid_ssp(36, None)])),
805                            None,
806                        ),
807                    ),
808                    EcSignature::encryptedEcSignature(encrypted),
809                ),
810            )),
811            AT_REQUEST,
812        );
813    }
814}