Skip to main content

rustflexstack/security/
verify_service.rs

1//! Verify service — ETSI TS 103 097 message verification.
2//!
3//! Decodes a received `Ieee1609Dot2Data` envelope, validates the signer
4//! chain, checks per-profile header constraints, and verifies the ECDSA
5//! signature.
6
7use crate::security::certificate::{
8    encode_tbs_data, signing_input, try_decode_ieee1609_dot2_data, Certificate,
9};
10use crate::security::certificate_library::CertificateLibrary;
11use crate::security::ecdsa_backend::key_uses_sha384;
12use crate::security::ecdsa_backend::EcdsaBackend;
13use crate::security::header_extensions::{decode_requests, TrustListRequest};
14use crate::security::security_asn::ieee1609_dot2::{
15    Ieee1609Dot2Content, SignedData, SignerIdentifier,
16};
17use crate::security::sign_service::SignService;
18use crate::security::sn_sap::{ReportVerify, SNVerifyConfirm, SNVerifyRequest};
19use crate::security::validity::{app_permission, location_permitted, valid_at};
20
21/// Message verification service.
22pub struct VerifyService<'a> {
23    pub backend: &'a EcdsaBackend,
24    pub cert_library: &'a mut CertificateLibrary,
25    pub sign_service: Option<&'a mut SignService>,
26    /// Receiver of the P2P CRL / CTL requests of the verified messages.
27    pub trust_list_listener: Option<TrustListListener>,
28}
29
30/// Receiver of the P2P CRL / CTL requests of a verified message and its AT
31/// (ETSI TS 103 601 V2.1.1 clause 5.3), set by the distribution service.
32pub type TrustListListener =
33    std::sync::Arc<dyn Fn(&[TrustListRequest], &Certificate) + Send + Sync>;
34
35impl<'a> VerifyService<'a> {
36    pub fn new(
37        backend: &'a EcdsaBackend,
38        cert_library: &'a mut CertificateLibrary,
39        sign_service: Option<&'a mut SignService>,
40    ) -> Self {
41        Self {
42            backend,
43            cert_library,
44            sign_service,
45            trust_list_listener: None,
46        }
47    }
48
49    /// Verify a signed message request and dispatch any P2PCD/unknown-cert events
50    /// to the associated `SignService` if configured.
51    pub fn verify(&mut self, request: &SNVerifyRequest) -> SNVerifyConfirm {
52        let (confirm, events) = verify_message(request, self.backend, self.cert_library);
53        if let Some(ref mut sign_svc) = self.sign_service {
54            for event in events {
55                match event {
56                    VerifyEvent::UnknownAt(h8) => sign_svc.notify_unknown_at(&h8),
57                    VerifyEvent::KnownAt(h8) => sign_svc.notify_known_at(&h8),
58                    VerifyEvent::InlineP2pcdRequest(h3s) => {
59                        sign_svc.notify_inline_p2pcd_request(&h3s);
60                    }
61                    VerifyEvent::ReceivedCaCertificate(cert) => {
62                        sign_svc.notify_received_ca_certificate(*cert);
63                    }
64                    VerifyEvent::TrustListRequests(requests, at) => {
65                        if let Some(listener) = &self.trust_list_listener {
66                            listener(&requests, &at);
67                        }
68                    }
69                }
70            }
71        }
72        confirm
73    }
74}
75
76const PSID_CAM: u64 = 36;
77const PSID_DENM: u64 = 37;
78const PROTOCOL_VERSION: u8 = 3;
79
80fn confirm(
81    report: ReportVerify,
82    at: Option<&Certificate>,
83    psid: u64,
84    permissions: Vec<u8>,
85    plain_message: Vec<u8>,
86) -> SNVerifyConfirm {
87    SNVerifyConfirm {
88        report,
89        certificate_id: at.map(|c| c.as_hashedid8().to_vec()).unwrap_or_default(),
90        its_aid: psid,
91        permissions,
92        plain_message,
93    }
94}
95
96/// The tbsData octets of a received Ieee1609Dot2Data signedData:
97/// protocolVersion (1 octet), the Ieee1609Dot2Content tag of signedData
98/// (0x81), hashId (1 octet), then tbsData, signer and signature (SignedData
99/// has no extension marker). `None` when the message does not end with the
100/// encodings of its signer and signature.
101fn received_tbs_data<'a>(message: &'a [u8], signed_data: &SignedData) -> Option<&'a [u8]> {
102    if message.len() < 3 || message[1] != 0x81 {
103        return None;
104    }
105    let mut tail = rasn::coer::encode(&signed_data.signer).ok()?;
106    tail.extend(rasn::coer::encode(&signed_data.signature).ok()?);
107    if message.len() < 3 + tail.len() || !message.ends_with(&tail) {
108        return None;
109    }
110    Some(&message[3..message.len() - tail.len()])
111}
112
113/// Stateless verification (ETSI TS 103 097 V2.2.1 clauses 5 and 7; IEEE Std
114/// 1609.2-2016 clauses 5.2.3.2.2 and 5.3.1). Checks, in order (the first
115/// failing one gives the report):
116///
117/// 1. decodable signed data with protocolVersion 3 (clause 5.1);
118/// 2. signer identifier: certificate (exactly one) or digest; DENMs always
119///    use a certificate (clause 7.1.2);
120/// 3. the signer certificate is a known, valid authorization ticket;
121/// 4. headerInfo: generationTime present, p2pcdLearningRequest and
122///    missingCrlIdentifier absent (clause 5.2); CAM (clause 7.1.1) and DENM
123///    (clause 7.1.2) profiles;
124/// 5. the PSID is in the appPermissions of the AT (the SSP is returned);
125/// 6. the generationTime lies in the validity period of the AT chain;
126/// 7. the generationLocation, when present, lies in the region of the chain;
127/// 8. the signature, over Hash(Hash(tbsData) || Hash(AT)), with an algorithm
128///    matching the verification key.
129///
130/// Mirrors `flexstack/security/verify_service.py`.
131pub fn verify_message(
132    request: &SNVerifyRequest,
133    backend: &EcdsaBackend,
134    cert_library: &mut CertificateLibrary,
135) -> (SNVerifyConfirm, Vec<VerifyEvent>) {
136    let mut events = Vec::new();
137
138    // 1. Decoding and protocol version
139    let Some(data) = try_decode_ieee1609_dot2_data(&request.message) else {
140        return (
141            confirm(ReportVerify::IncompatibleProtocol, None, 0, vec![], vec![]),
142            events,
143        );
144    };
145    let signed_data = match &data.content {
146        Ieee1609Dot2Content::signedData(sd) => sd,
147        _ => {
148            return (
149                confirm(ReportVerify::UnsignedMessage, None, 0, vec![], vec![]),
150                events,
151            );
152        }
153    };
154    let inner_version_ok = signed_data
155        .tbs_data
156        .payload
157        .data
158        .as_ref()
159        .is_none_or(|inner| inner.protocol_version.0 == PROTOCOL_VERSION);
160    if data.protocol_version.0 != PROTOCOL_VERSION || !inner_version_ok {
161        return (
162            confirm(ReportVerify::IncompatibleProtocol, None, 0, vec![], vec![]),
163            events,
164        );
165    }
166    let tbs_bytes = encode_tbs_data(&signed_data.tbs_data);
167    let header = &signed_data.tbs_data.header_info;
168    let psid = u64::try_from(&header.psid.0).unwrap_or(0);
169    let signer = &signed_data.signer;
170    let fail =
171        |report: ReportVerify, at: Option<&Certificate>| confirm(report, at, psid, vec![], vec![]);
172
173    // P2PCD response (IEEE 1609.2 clause 8.2.4, TS 103 097 clause 7.1.1): a
174    // requested CA certificate is learned when it verifies under a known issuer,
175    // before the chain of this message is checked (the answering CAM may be
176    // signed by an AT of that CA).
177    if let Some(ref cert_asn) = header.requested_certificate {
178        use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
179        cert_library.learn_ca_certificate(
180            backend,
181            Certificate::from_asn(EtsiTs103097Certificate(cert_asn.clone()), None),
182        );
183    }
184
185    // 2-3. Signer identifier and authorization ticket
186    if psid == PSID_DENM && !matches!(signer, SignerIdentifier::certificate(_)) {
187        return (
188            fail(ReportVerify::UnsupportedSignerIdentifierType, None),
189            events,
190        );
191    }
192    let at: Certificate = match signer {
193        SignerIdentifier::certificate(seq) => {
194            let certs_asn = &seq.0;
195            if certs_asn.len() != 1 {
196                return (
197                    fail(ReportVerify::UnsupportedSignerIdentifierType, None),
198                    events,
199                );
200            }
201            let cert_vec: Vec<Certificate> = certs_asn
202                .iter()
203                .map(|c| {
204                    use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
205                    Certificate::from_asn(EtsiTs103097Certificate(c.clone()), None)
206                })
207                .collect();
208            match cert_library.verify_sequence_of_certificates(&cert_vec, backend) {
209                Some(at) => at,
210                None => {
211                    use crate::security::security_asn::ieee1609_dot2::IssuerIdentifier;
212                    if let IssuerIdentifier::sha256AndDigest(h)
213                    | IssuerIdentifier::sha384AndDigest(h) = &certs_asn[0].0.issuer
214                    {
215                        let mut h8 = [0u8; 8];
216                        h8.copy_from_slice(h.0.as_ref());
217                        events.push(VerifyEvent::UnknownAt(h8));
218                    }
219                    return (fail(ReportVerify::InconsistentChain, None), events);
220                }
221            }
222        }
223        SignerIdentifier::digest(h) => {
224            let mut key = [0u8; 8];
225            key.copy_from_slice(h.0.as_ref());
226            match cert_library.get_authorization_ticket_by_hashedid8(&key) {
227                Some(at) => at.clone(),
228                None => {
229                    events.push(VerifyEvent::UnknownAt(key));
230                    return (fail(ReportVerify::SignerCertificateNotFound, None), events);
231                }
232            }
233        }
234        // 'self' is not allowed (clause 5.2)
235        _ => {
236            return (
237                fail(ReportVerify::UnsupportedSignerIdentifierType, None),
238                events,
239            )
240        }
241    };
242    // Verification key: explicit, or reconstructed from an implicit AT
243    // (IEEE 1609.2 clause 5.3.2)
244    let vk_owned = match at.verification_key() {
245        Some(pk) if at.is_authorization_ticket() => pk,
246        _ => return (fail(ReportVerify::InvalidCertificate, Some(&at)), events),
247    };
248    let vk = &vk_owned;
249
250    // 4. headerInfo (clauses 5.2, 7.1.1, 7.1.2)
251    let Some(generation_time) = &header.generation_time else {
252        return (fail(ReportVerify::InvalidTimestamp, Some(&at)), events);
253    };
254    if header.p2pcd_learning_request.is_some() || header.missing_crl_identifier.is_some() {
255        return (fail(ReportVerify::IncompatibleProtocol, Some(&at)), events);
256    }
257    let cam_violation = psid == PSID_CAM
258        && (header.generation_location.is_some()
259            || header.expiry_time.is_some()
260            || header.encryption_key.is_some());
261    let denm_violation = psid == PSID_DENM
262        && (header.generation_location.is_none()
263            || header.expiry_time.is_some()
264            || header.encryption_key.is_some()
265            || header.inline_p2pcd_request.is_some()
266            || header.requested_certificate.is_some());
267    if cam_violation || denm_violation {
268        return (fail(ReportVerify::IncompatibleProtocol, Some(&at)), events);
269    }
270
271    // 5. PSID permitted by the AT (IEEE 1609.2 clause 5.2.3.2.2)
272    let (permitted, ssp) = app_permission(at.tbs(), psid);
273    if !permitted {
274        return (fail(ReportVerify::InvalidCertificate, Some(&at)), events);
275    }
276
277    // 6-7. Time and region consistency with the certificate chain
278    if !valid_at(&at, generation_time.0 .0) {
279        return (fail(ReportVerify::InvalidTimestamp, Some(&at)), events);
280    }
281    if let Some(location) = &header.generation_location {
282        if !location_permitted(&at, location.latitude.0 .0, location.longitude.0 .0) {
283            return (fail(ReportVerify::InvalidMobilityData, Some(&at)), events);
284        }
285    }
286
287    // 8. Signature over Hash(Hash(tbsData) || Hash(AT)) (IEEE 1609.2 clause 5.3.1)
288    let at_canonical = at.to_canonical();
289    let payload = signing_input(&tbs_bytes, at_canonical.encode(), key_uses_sha384(vk));
290    if !backend.verify_with_pk(&payload, &signed_data.signature, vk) {
291        // The signer encoded tbsData with its own ASN.1 version: another
292        // number of HeaderInfo extension additions gives another extension
293        // presence bitmap (X.696 clause 16.4), e.g. IEEE 1609.2-2016 modules.
294        // The signature covers the octets the signer encoded (clause 6.3.4),
295        // so they are verified as received.
296        let received = received_tbs_data(&request.message, signed_data);
297        let verified = received
298            .filter(|octets| *octets != tbs_bytes.as_slice())
299            .is_some_and(|octets| {
300                let payload = signing_input(octets, at_canonical.encode(), key_uses_sha384(vk));
301                backend.verify_with_pk(&payload, &signed_data.signature, vk)
302            });
303        if !verified {
304            return (fail(ReportVerify::FalseSignature, Some(&at)), events);
305        }
306    }
307
308    // Extract the plain message
309    let plain_message = match &signed_data.tbs_data.payload.data {
310        Some(inner) => match &inner.content {
311            Ieee1609Dot2Content::unsecuredData(opaque) => opaque.0.to_vec(),
312            _ => vec![],
313        },
314        None => vec![],
315    };
316
317    // P2PCD events. An AT received as certificate signer is now known: it is
318    // no longer requested in inlineP2pcdRequest (TS 103 097 clause 7.1.1).
319    if matches!(signer, SignerIdentifier::certificate(_)) {
320        events.push(VerifyEvent::KnownAt(at.as_hashedid8()));
321    }
322    if let Some(ref req) = header.inline_p2pcd_request {
323        let h3s: Vec<[u8; 3]> = req
324            .0
325            .iter()
326            .map(|h| {
327                let mut arr = [0u8; 3];
328                arr.copy_from_slice(h.0.as_ref());
329                arr
330            })
331            .collect();
332        events.push(VerifyEvent::InlineP2pcdRequest(h3s));
333    }
334    if let Some(ref cert_asn) = header.requested_certificate {
335        use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
336        let c = Certificate::from_asn(EtsiTs103097Certificate(cert_asn.clone()), None);
337        events.push(VerifyEvent::ReceivedCaCertificate(Box::new(c)));
338    }
339    if let Some(ref blocks) = header.contributed_extensions {
340        let requests = decode_requests(blocks);
341        if !requests.is_empty() {
342            events.push(VerifyEvent::TrustListRequests(
343                requests,
344                Box::new(at.clone()),
345            ));
346        }
347    }
348
349    (
350        confirm(
351            ReportVerify::Success,
352            Some(&at),
353            psid,
354            ssp.unwrap_or_default(),
355            plain_message,
356        ),
357        events,
358    )
359}
360
361/// Events produced during verification that should be forwarded to the
362/// sign service for P2PCD handling.
363#[derive(Debug)]
364pub enum VerifyEvent {
365    UnknownAt([u8; 8]),
366    /// HashedId8 of an AT learned from a certificate signer.
367    KnownAt([u8; 8]),
368    InlineP2pcdRequest(Vec<[u8; 3]>),
369    ReceivedCaCertificate(Box<Certificate>),
370    /// P2P CRL / CTL requests in the contributedExtensions of a verified
371    /// message (ETSI TS 103 601 V2.1.1 clause 5.3), with the signing AT.
372    TrustListRequests(Vec<TrustListRequest>, Box<Certificate>),
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378    use crate::security::certificate::OwnCertificate;
379    use crate::security::certificate_library::CertificateLibrary;
380    use crate::security::ecdsa_backend::EcdsaBackend;
381    use crate::security::security_asn::ieee1609_dot2::{
382        CertificateId, EndEntityType, PsidGroupPermissions, SequenceOfPsidGroupPermissions,
383        SubjectPermissions, ToBeSignedCertificate, VerificationKeyIndicator,
384    };
385    use crate::security::security_asn::ieee1609_dot2_base_types::{
386        CrlSeries, Duration as AsnDuration, EccP256CurvePoint, HashedId3, Psid, PsidSsp,
387        PublicVerificationKey, SequenceOfPsidSsp, Time32, Uint16, Uint32, ValidityPeriod,
388    };
389    use crate::security::sign_service::SignService;
390    use crate::security::sn_sap::{GenerationLocation, SNSignRequest, SNVerifyRequest};
391    use rasn::prelude::*;
392
393    fn make_root_tbs() -> ToBeSignedCertificate {
394        let validity = ValidityPeriod::new(Time32(Uint32(0)), AsnDuration::years(Uint16(30)));
395        let perms = SequenceOfPsidGroupPermissions(vec![PsidGroupPermissions::new(
396            SubjectPermissions::all(()),
397            Integer::from(1),
398            Integer::from(0),
399            {
400                let mut bits = FixedBitString::<8>::default();
401                bits.set(0, true);
402                EndEntityType(bits)
403            },
404        )]);
405        let pk =
406            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
407        ToBeSignedCertificate::new(
408            CertificateId::none(()),
409            HashedId3(FixedOctetString::from([0u8; 3])),
410            CrlSeries(Uint16(0)),
411            validity,
412            None,
413            None,
414            None,
415            Some(perms),
416            None,
417            None,
418            None,
419            VerificationKeyIndicator::verificationKey(pk),
420            None,
421            None,
422            None,
423            None,
424        )
425    }
426
427    fn make_at_tbs(its_aid: i64) -> ToBeSignedCertificate {
428        // Valid now: started a minute ago, one year long
429        let now_s =
430            (crate::security::time_service::timestamp_its_microseconds() / 1_000_000) as u32;
431        let validity =
432            ValidityPeriod::new(Time32(Uint32(now_s - 60)), AsnDuration::years(Uint16(1)));
433        let app_perms = SequenceOfPsidSsp(vec![PsidSsp::new(Psid(Integer::from(its_aid)), None)]);
434        let pk =
435            PublicVerificationKey::ecdsaNistP256(EccP256CurvePoint::x_only(vec![0u8; 32].into()));
436        ToBeSignedCertificate::new(
437            CertificateId::none(()),
438            HashedId3(FixedOctetString::from([0u8; 3])),
439            CrlSeries(Uint16(0)),
440            validity,
441            None,
442            None,
443            Some(app_perms),
444            None,
445            None,
446            None,
447            None,
448            VerificationKeyIndicator::verificationKey(pk),
449            None,
450            None,
451            None,
452            None,
453        )
454    }
455
456    fn sign_cam_message(svc: &mut SignService) -> Vec<u8> {
457        let req = SNSignRequest {
458            tbs_message: vec![0xCA, 0xFE],
459            its_aid: 36,
460            permissions: vec![],
461            generation_location: None,
462        };
463        svc.sign_request(&req).sec_message
464    }
465
466    fn sign_denm_message(svc: &mut SignService) -> Vec<u8> {
467        let req = SNSignRequest {
468            tbs_message: vec![0xDE, 0x01],
469            its_aid: 37,
470            permissions: vec![],
471            generation_location: Some(GenerationLocation {
472                latitude: 415520000,
473                longitude: 21340000,
474                elevation: 0xF000,
475            }),
476        };
477        svc.sign_request(&req).sec_message
478    }
479
480    fn setup() -> (EcdsaBackend, CertificateLibrary, SignService) {
481        let mut backend = EcdsaBackend::new();
482        let root = OwnCertificate::initialize_self_signed(&mut backend, make_root_tbs());
483        let aa = OwnCertificate::initialize_issued(&mut backend, make_root_tbs(), &root);
484        let at_cam = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(36), &aa);
485        let at_denm = OwnCertificate::initialize_issued(&mut backend, make_at_tbs(37), &aa);
486
487        let lib = CertificateLibrary::new(
488            &backend,
489            vec![root.cert.clone()],
490            vec![aa.cert.clone()],
491            vec![],
492        );
493        let mut svc = SignService::new(backend, lib);
494        svc.add_own_certificate(at_cam);
495        svc.add_own_certificate(at_denm);
496
497        // Build verify library from certs stored in sign service
498        let verify_lib = CertificateLibrary::new(
499            &svc.backend,
500            svc.cert_library
501                .known_root_certificates
502                .values()
503                .cloned()
504                .collect(),
505            svc.cert_library
506                .known_authorization_authorities
507                .values()
508                .cloned()
509                .collect(),
510            svc.cert_library
511                .known_authorization_tickets
512                .values()
513                .cloned()
514                .collect(),
515        );
516
517        (EcdsaBackend::new(), verify_lib, svc)
518    }
519
520    #[test]
521    fn verify_cam_signed_message() {
522        let (_, _, mut svc) = setup();
523        let sec_msg = sign_cam_message(&mut svc);
524
525        // Verify using sign service's own backend and cert library
526        let req = SNVerifyRequest { message: sec_msg };
527        let mut verify_lib = CertificateLibrary::new(
528            &svc.backend,
529            svc.cert_library
530                .known_root_certificates
531                .values()
532                .cloned()
533                .collect(),
534            svc.cert_library
535                .known_authorization_authorities
536                .values()
537                .cloned()
538                .collect(),
539            svc.cert_library
540                .known_authorization_tickets
541                .values()
542                .cloned()
543                .collect(),
544        );
545        let (confirm, _events) = verify_message(&req, &svc.backend, &mut verify_lib);
546        assert_eq!(confirm.report, ReportVerify::Success);
547        assert_eq!(confirm.its_aid, 36);
548        assert_eq!(confirm.plain_message, vec![0xCA, 0xFE]);
549    }
550
551    #[test]
552    fn verify_denm_signed_message() {
553        let (_, _, mut svc) = setup();
554        let sec_msg = sign_denm_message(&mut svc);
555
556        let req = SNVerifyRequest { message: sec_msg };
557        let mut verify_lib = CertificateLibrary::new(
558            &svc.backend,
559            svc.cert_library
560                .known_root_certificates
561                .values()
562                .cloned()
563                .collect(),
564            svc.cert_library
565                .known_authorization_authorities
566                .values()
567                .cloned()
568                .collect(),
569            svc.cert_library
570                .known_authorization_tickets
571                .values()
572                .cloned()
573                .collect(),
574        );
575        let (confirm, _events) = verify_message(&req, &svc.backend, &mut verify_lib);
576        assert_eq!(confirm.report, ReportVerify::Success);
577        assert_eq!(confirm.its_aid, 37);
578    }
579
580    #[test]
581    fn verify_tampered_message_fails() {
582        let (_, _, mut svc) = setup();
583        let mut sec_msg = sign_cam_message(&mut svc);
584
585        // Tamper with the message
586        if let Some(b) = sec_msg.last_mut() {
587            *b ^= 0xFF;
588        }
589
590        let req = SNVerifyRequest { message: sec_msg };
591        let mut verify_lib = CertificateLibrary::new(
592            &svc.backend,
593            svc.cert_library
594                .known_root_certificates
595                .values()
596                .cloned()
597                .collect(),
598            svc.cert_library
599                .known_authorization_authorities
600                .values()
601                .cloned()
602                .collect(),
603            svc.cert_library
604                .known_authorization_tickets
605                .values()
606                .cloned()
607                .collect(),
608        );
609        let (confirm, _) = verify_message(&req, &svc.backend, &mut verify_lib);
610        assert_ne!(confirm.report, ReportVerify::Success);
611    }
612
613    #[test]
614    fn verify_event_variants() {
615        let ev1 = VerifyEvent::UnknownAt([1; 8]);
616        let ev2 = VerifyEvent::InlineP2pcdRequest(vec![[1, 2, 3]]);
617        // Just ensure they can be constructed and formatted
618        assert!(format!("{:?}", ev1).contains("UnknownAt"));
619        assert!(format!("{:?}", ev2).contains("InlineP2pcdRequest"));
620    }
621
622    #[test]
623    fn test_verify_service_instance_verify() {
624        let (_, _, mut svc) = setup();
625        let sec_msg = sign_cam_message(&mut svc);
626        let req = SNVerifyRequest { message: sec_msg };
627        let verify_backend = EcdsaBackend::new();
628        let mut verify_lib = CertificateLibrary::new(
629            &verify_backend,
630            svc.cert_library
631                .known_root_certificates
632                .values()
633                .cloned()
634                .collect(),
635            svc.cert_library
636                .known_authorization_authorities
637                .values()
638                .cloned()
639                .collect(),
640            vec![],
641        );
642        let mut verifier = VerifyService::new(&verify_backend, &mut verify_lib, Some(&mut svc));
643        let confirm = verifier.verify(&req);
644        assert_eq!(confirm.report, ReportVerify::Success);
645    }
646
647    // ── Traced to ETSI TS 103 096-2 test purposes (mirrors Python
648    //    tests/flexstack/security/test_signed_message_conformance.py) ────────
649
650    fn receiver_library(svc: &SignService) -> CertificateLibrary {
651        // Trusts the same Root CA and AA, but has never seen the AT.
652        CertificateLibrary::new(
653            &svc.backend,
654            svc.cert_library
655                .known_root_certificates
656                .values()
657                .cloned()
658                .collect(),
659            svc.cert_library
660                .known_authorization_authorities
661                .values()
662                .cloned()
663                .collect(),
664            vec![],
665        )
666    }
667
668    fn cam_request(payload: &[u8]) -> SNSignRequest {
669        SNSignRequest {
670            tbs_message: payload.to_vec(),
671            its_aid: 36,
672            permissions: vec![],
673            generation_location: None,
674        }
675    }
676
677    /// ETSI TS 103 097 clause 5.1, ETSI TS 103 097 clause 7.1.1,
678    /// ETSI TS 103 097 clause 7.1.1: version 3, signedData, psid AID_CAM, generationTime only,
679    /// unsecured inner data carrying the CAM payload.
680    #[test]
681    fn signed_cam_header_conformance() {
682        use crate::security::certificate::decode_ieee1609_dot2_data;
683        use crate::security::security_asn::ieee1609_dot2::{Ieee1609Dot2Content, SignerIdentifier};
684        let (_, _, mut svc) = setup();
685        let msg = svc
686            .sign_cam_at(&cam_request(&[0xCA, 0xFE]), Some(100.0))
687            .sec_message;
688        let dot2 = decode_ieee1609_dot2_data(&msg);
689        assert_eq!(dot2.protocol_version.0, 3);
690        let Ieee1609Dot2Content::signedData(sd) = dot2.content else {
691            panic!("expected signedData");
692        };
693        let hi = &sd.tbs_data.header_info;
694        assert_eq!(u64::try_from(&hi.psid.0).unwrap(), 36);
695        assert!(hi.generation_time.is_some());
696        assert!(hi.expiry_time.is_none());
697        assert!(hi.generation_location.is_none());
698        assert!(hi.encryption_key.is_none());
699        assert!(hi.p2pcd_learning_request.is_none());
700        assert!(hi.missing_crl_identifier.is_none());
701        let inner = sd.tbs_data.payload.data.as_ref().expect("payload data");
702        assert_eq!(inner.protocol_version.0, 3);
703        match &inner.content {
704            Ieee1609Dot2Content::unsecuredData(o) => assert_eq!(o.0.as_ref(), &[0xCA, 0xFE]),
705            _ => panic!("expected unsecuredData"),
706        }
707        assert!(matches!(sd.signer, SignerIdentifier::certificate(_)));
708    }
709
710    /// ETSI TS 103 097 clause 7.1.2: psid AID_DENM,
711    /// generationTime and generationLocation, certificate signer.
712    #[test]
713    fn signed_denm_header_conformance() {
714        use crate::security::certificate::decode_ieee1609_dot2_data;
715        use crate::security::security_asn::ieee1609_dot2::{Ieee1609Dot2Content, SignerIdentifier};
716        let (_, _, mut svc) = setup();
717        let msg = sign_denm_message(&mut svc);
718        let dot2 = decode_ieee1609_dot2_data(&msg);
719        assert_eq!(dot2.protocol_version.0, 3);
720        let Ieee1609Dot2Content::signedData(sd) = dot2.content else {
721            panic!("expected signedData");
722        };
723        let hi = &sd.tbs_data.header_info;
724        assert_eq!(u64::try_from(&hi.psid.0).unwrap(), 37);
725        assert!(hi.generation_time.is_some());
726        assert!(hi.generation_location.is_some());
727        assert!(hi.expiry_time.is_none());
728        assert!(hi.encryption_key.is_none());
729        assert!(hi.p2pcd_learning_request.is_none());
730        assert!(hi.missing_crl_identifier.is_none());
731        assert!(matches!(sd.signer, SignerIdentifier::certificate(_)));
732    }
733
734    /// ETSI TS 103 097 clause 7.1.1: an independent receiver accepts
735    /// a certificate-signed CAM and then a digest-signed CAM from the same AT.
736    #[test]
737    fn digest_signed_cam_accepted_once_certificate_known() {
738        let (_, _, mut svc) = setup();
739        let mut lib = receiver_library(&svc);
740        let first = svc
741            .sign_cam_at(&cam_request(b"first"), Some(100.0))
742            .sec_message;
743        let second = svc
744            .sign_cam_at(&cam_request(b"second"), Some(100.5))
745            .sec_message;
746
747        let (c1, _) = verify_message(&SNVerifyRequest { message: first }, &svc.backend, &mut lib);
748        assert_eq!(c1.report, ReportVerify::Success);
749        let (c2, _) = verify_message(&SNVerifyRequest { message: second }, &svc.backend, &mut lib);
750        assert_eq!(c2.report, ReportVerify::Success);
751        assert_eq!(c2.plain_message, b"second".to_vec());
752    }
753
754    /// ETSI TS 103 097 clause 7.1.1 (receiver side): a digest of an unknown AT
755    /// cannot be verified; the signer is reported as not found.
756    #[test]
757    fn digest_signed_cam_from_unknown_at_not_accepted() {
758        let (_, _, mut svc) = setup();
759        let mut lib = receiver_library(&svc);
760        let _first = svc.sign_cam_at(&cam_request(b"first"), Some(100.0)); // not delivered
761        let second = svc
762            .sign_cam_at(&cam_request(b"second"), Some(100.5))
763            .sec_message;
764        let (c, _) = verify_message(&SNVerifyRequest { message: second }, &svc.backend, &mut lib);
765        assert_eq!(c.report, ReportVerify::SignerCertificateNotFound);
766    }
767
768    /// Decode a signed message, let `f` modify its headerInfo/signer, re-encode.
769    /// The checks under test run before signature verification, so the stale
770    /// signature does not mask the expected report.
771    fn mutate_signed(
772        msg: &[u8],
773        f: impl FnOnce(&mut crate::security::security_asn::ieee1609_dot2::SignedData),
774    ) -> Vec<u8> {
775        use crate::security::certificate::{decode_ieee1609_dot2_data, encode_ieee1609_dot2_data};
776        use crate::security::security_asn::ieee1609_dot2::Ieee1609Dot2Content;
777        let mut dot2 = decode_ieee1609_dot2_data(msg);
778        match &mut dot2.content {
779            Ieee1609Dot2Content::signedData(sd) => f(sd),
780            _ => panic!("expected signedData"),
781        }
782        encode_ieee1609_dot2_data(&dot2)
783    }
784
785    fn verify_at_receiver(svc: &SignService, msg: Vec<u8>) -> ReportVerify {
786        let mut lib = CertificateLibrary::new(
787            &svc.backend,
788            svc.cert_library
789                .known_root_certificates
790                .values()
791                .cloned()
792                .collect(),
793            svc.cert_library
794                .known_authorization_authorities
795                .values()
796                .cloned()
797                .collect(),
798            svc.cert_library
799                .known_authorization_tickets
800                .values()
801                .cloned()
802                .collect(),
803        );
804        verify_message(&SNVerifyRequest { message: msg }, &svc.backend, &mut lib)
805            .0
806            .report
807    }
808
809    fn hashed_id3() -> crate::security::security_asn::ieee1609_dot2_base_types::HashedId3 {
810        crate::security::security_asn::ieee1609_dot2_base_types::HashedId3(FixedOctetString::from(
811            [1u8, 2, 3],
812        ))
813    }
814
815    /// ETSI TS 103 097 clause 7.1.1: CAM with p2pcdLearningRequest is discarded.
816    #[test]
817    fn cam_with_p2pcd_learning_request_rejected() {
818        let (_, _, mut svc) = setup();
819        let msg = svc
820            .sign_cam_at(&cam_request(b"cam"), Some(100.0))
821            .sec_message;
822        let bad = mutate_signed(&msg, |sd| {
823            sd.tbs_data.header_info.p2pcd_learning_request = Some(hashed_id3());
824        });
825        assert_eq!(
826            verify_at_receiver(&svc, bad),
827            ReportVerify::IncompatibleProtocol
828        );
829    }
830
831    /// ETSI TS 103 097 clause 7.1.2: DENM without generationLocation is discarded.
832    #[test]
833    fn denm_without_generation_location_rejected() {
834        let (_, _, mut svc) = setup();
835        let bad = mutate_signed(&sign_denm_message(&mut svc), |sd| {
836            sd.tbs_data.header_info.generation_location = None;
837        });
838        assert_eq!(
839            verify_at_receiver(&svc, bad),
840            ReportVerify::IncompatibleProtocol
841        );
842    }
843
844    /// ETSI TS 103 097 clause 7.1.2: DENM with expiryTime is discarded.
845    #[test]
846    fn denm_with_expiry_time_rejected() {
847        use crate::security::security_asn::ieee1609_dot2_base_types::{Time64, Uint64};
848        let (_, _, mut svc) = setup();
849        let bad = mutate_signed(&sign_denm_message(&mut svc), |sd| {
850            sd.tbs_data.header_info.expiry_time = Some(Time64(Uint64(1)));
851        });
852        assert_eq!(
853            verify_at_receiver(&svc, bad),
854            ReportVerify::IncompatibleProtocol
855        );
856    }
857
858    /// ETSI TS 103 097 clause 5.2: DENM with p2pcdLearningRequest is discarded.
859    #[test]
860    fn denm_with_p2pcd_learning_request_rejected() {
861        let (_, _, mut svc) = setup();
862        let bad = mutate_signed(&sign_denm_message(&mut svc), |sd| {
863            sd.tbs_data.header_info.p2pcd_learning_request = Some(hashed_id3());
864        });
865        assert_eq!(
866            verify_at_receiver(&svc, bad),
867            ReportVerify::IncompatibleProtocol
868        );
869    }
870
871    /// ETSI TS 103 097 clause 6 (digest case): a DENM whose signer is a
872    /// digest instead of a certificate is discarded.
873    #[test]
874    fn denm_signed_with_digest_rejected() {
875        use crate::security::security_asn::ieee1609_dot2::SignerIdentifier;
876        use crate::security::security_asn::ieee1609_dot2_base_types::HashedId8;
877        let (_, _, mut svc) = setup();
878        let bad = mutate_signed(&sign_denm_message(&mut svc), |sd| {
879            sd.signer = SignerIdentifier::digest(HashedId8(FixedOctetString::from([0u8; 8])));
880        });
881        assert_eq!(
882            verify_at_receiver(&svc, bad),
883            ReportVerify::UnsupportedSignerIdentifierType
884        );
885    }
886}
887
888/// Receive and send checks with real certificate chains (ETSI TS 103 097
889/// V2.2.1, IEEE Std 1609.2-2016 clauses 5.2.3.2.2 and 5.3.1), traced to ETSI
890/// TS 103 096-2 V2.1.1. Mirrors `tests/flexstack/security/test_security_checks.py`.
891#[cfg(test)]
892pub(crate) mod security_checks {
893    use super::*;
894    use crate::security::certificate::{
895        decode_ieee1609_dot2_data, encode_ieee1609_dot2_data, OwnCertificate,
896    };
897    use crate::security::certificate_library::CertificateLibrary;
898    use crate::security::ecdsa_backend::{EcdsaBackend, KeyAlgorithm};
899    use crate::security::security_asn::ieee1609_dot2::IssuerIdentifier;
900    use crate::security::security_asn::ieee1609_dot2::VerificationKeyIndicator;
901    use crate::security::security_asn::ieee1609_dot2::{
902        CertificateId, EndEntityType, Ieee1609Dot2Content, MissingCrlIdentifier,
903        PsidGroupPermissions, SequenceOfPsidGroupPermissions, SignedData, SubjectPermissions,
904        ToBeSignedCertificate,
905    };
906    use crate::security::security_asn::ieee1609_dot2_base_types::HashAlgorithm;
907    use crate::security::security_asn::ieee1609_dot2_base_types::{
908        BitmapSsp, CircularRegion, CrlSeries, Duration as AsnDuration, EccP256CurvePoint,
909        Elevation, EncryptionKey, GeographicRegion, HashedId3, Latitude, Longitude,
910        NinetyDegreeInt, OneEightyDegreeInt, Psid, PsidSsp, PublicVerificationKey,
911        SequenceOfPsidSsp, ServiceSpecificPermissions, Signature as Ieee1609Signature,
912        SymmetricEncryptionKey, ThreeDLocation, Time32, Time64, TwoDLocation, Uint16, Uint32,
913        Uint64, ValidityPeriod,
914    };
915    use crate::security::sign_service::{SignService, SigningError};
916    use crate::security::sn_sap::{GenerationLocation, SNSignRequest, SNVerifyRequest};
917    use crate::security::time_service::timestamp_its_microseconds;
918    use rasn::prelude::*;
919    use sha2::{Digest, Sha256};
920
921    const INSIDE: (i32, i32) = (415520000, 21340000);
922    const OUTSIDE: (i32, i32) = (425520000, 21340000); // ~111 km north
923
924    fn now_s() -> u32 {
925        (timestamp_its_microseconds() / 1_000_000) as u32
926    }
927
928    fn key() -> VerificationKeyIndicator {
929        VerificationKeyIndicator::verificationKey(PublicVerificationKey::ecdsaNistP256(
930            EccP256CurvePoint::x_only(vec![0u8; 32].into()),
931        ))
932    }
933
934    fn tbs(
935        validity: ValidityPeriod,
936        region: Option<GeographicRegion>,
937        app: Option<SequenceOfPsidSsp>,
938        issue: Option<SequenceOfPsidGroupPermissions>,
939    ) -> ToBeSignedCertificate {
940        ToBeSignedCertificate::new(
941            CertificateId::none(()),
942            HashedId3(FixedOctetString::from([0u8; 3])),
943            CrlSeries(Uint16(0)),
944            validity,
945            region,
946            None,
947            app,
948            issue,
949            None,
950            None,
951            None,
952            key(),
953            None,
954            None,
955            None,
956            None,
957        )
958    }
959
960    pub(crate) fn ca_tbs() -> ToBeSignedCertificate {
961        let perms = SequenceOfPsidGroupPermissions(vec![PsidGroupPermissions::new(
962            SubjectPermissions::all(()),
963            Integer::from(1),
964            Integer::from(0),
965            {
966                let mut bits = FixedBitString::<8>::default();
967                bits.set(0, true);
968                EndEntityType(bits)
969            },
970        )]);
971        let validity =
972            ValidityPeriod::new(Time32(Uint32(now_s() - 60)), AsnDuration::years(Uint16(1)));
973        tbs(validity, None, None, Some(perms))
974    }
975
976    pub(crate) fn at_tbs(
977        start_offset: i64,
978        duration: AsnDuration,
979        region: Option<GeographicRegion>,
980    ) -> ToBeSignedCertificate {
981        let app = SequenceOfPsidSsp(vec![
982            PsidSsp::new(
983                Psid(Integer::from(36)),
984                Some(ServiceSpecificPermissions::bitmapSsp(BitmapSsp(
985                    vec![2u8, 0x02, 0x00].into(),
986                ))),
987            ),
988            PsidSsp::new(Psid(Integer::from(37)), None),
989        ]);
990        let start = (now_s() as i64 + start_offset) as u32;
991        tbs(
992            ValidityPeriod::new(Time32(Uint32(start)), duration),
993            region,
994            Some(app),
995            None,
996        )
997    }
998
999    fn circle() -> GeographicRegion {
1000        GeographicRegion::circularRegion(CircularRegion::new(
1001            TwoDLocation::new(
1002                Latitude(NinetyDegreeInt(INSIDE.0)),
1003                Longitude(OneEightyDegreeInt(INSIDE.1)),
1004            ),
1005            Uint16(5000),
1006        ))
1007    }
1008
1009    fn ca_tbs_with_region(region: Option<GeographicRegion>) -> ToBeSignedCertificate {
1010        let mut tbs = ca_tbs();
1011        tbs.region = region;
1012        tbs
1013    }
1014
1015    struct Fixture {
1016        svc: SignService,
1017        root: Certificate,
1018        aa: Certificate,
1019        aa_owner: OwnCertificate,
1020    }
1021
1022    impl Fixture {
1023        fn new(at: ToBeSignedCertificate) -> Self {
1024            Self::chain(ca_tbs(), ca_tbs(), at)
1025        }
1026
1027        /// Root -> AA -> AT chain with the given toBeSigned contents.
1028        fn chain(
1029            root: ToBeSignedCertificate,
1030            aa: ToBeSignedCertificate,
1031            at: ToBeSignedCertificate,
1032        ) -> Self {
1033            let mut backend = EcdsaBackend::new();
1034            let root = OwnCertificate::initialize_self_signed(&mut backend, root);
1035            let aa = OwnCertificate::initialize_issued(&mut backend, aa, &root);
1036            let at = OwnCertificate::initialize_issued(&mut backend, at, &aa);
1037            let lib = CertificateLibrary::new(
1038                &backend,
1039                vec![root.cert.clone()],
1040                vec![aa.cert.clone()],
1041                vec![],
1042            );
1043            let mut svc = SignService::new(backend, lib);
1044            svc.add_own_certificate(at);
1045            Fixture {
1046                svc,
1047                root: root.cert,
1048                aa: aa.cert.clone(),
1049                aa_owner: aa,
1050            }
1051        }
1052
1053        fn valid() -> Self {
1054            Self::new(at_tbs(-60, AsnDuration::hours(Uint16(1)), None))
1055        }
1056
1057        /// Root -> AA -> AT chain whose three keys are on `algorithm`.
1058        fn on_curve(algorithm: KeyAlgorithm) -> Self {
1059            let mut backend = EcdsaBackend::new();
1060            let root =
1061                OwnCertificate::initialize_self_signed_with(&mut backend, ca_tbs(), algorithm);
1062            let aa =
1063                OwnCertificate::initialize_issued_with(&mut backend, ca_tbs(), &root, algorithm);
1064            let at = OwnCertificate::initialize_issued_with(
1065                &mut backend,
1066                at_tbs(-60, AsnDuration::hours(Uint16(1)), None),
1067                &aa,
1068                algorithm,
1069            );
1070            let lib = CertificateLibrary::new(
1071                &backend,
1072                vec![root.cert.clone()],
1073                vec![aa.cert.clone()],
1074                vec![],
1075            );
1076            let mut svc = SignService::new(backend, lib);
1077            svc.add_own_certificate(at);
1078            Fixture {
1079                svc,
1080                root: root.cert,
1081                aa: aa.cert.clone(),
1082                aa_owner: aa,
1083            }
1084        }
1085
1086        /// Chain whose AT is an implicit certificate issued with ECQV.
1087        fn implicit() -> Self {
1088            let mut backend = EcdsaBackend::new();
1089            let root = OwnCertificate::initialize_self_signed(&mut backend, ca_tbs());
1090            let aa = OwnCertificate::initialize_issued(&mut backend, ca_tbs(), &root);
1091            let at = aa.issue_implicit_certificate(
1092                &mut backend,
1093                at_tbs(-60, AsnDuration::hours(Uint16(1)), None),
1094            );
1095            let lib = CertificateLibrary::new(
1096                &backend,
1097                vec![root.cert.clone()],
1098                vec![aa.cert.clone()],
1099                vec![],
1100            );
1101            let mut svc = SignService::new(backend, lib);
1102            svc.add_own_certificate(at);
1103            Fixture {
1104                svc,
1105                root: root.cert,
1106                aa: aa.cert.clone(),
1107                aa_owner: aa,
1108            }
1109        }
1110
1111        fn try_sign(
1112            &mut self,
1113            psid: u64,
1114            location: Option<(i32, i32)>,
1115            permissions: &[u8],
1116        ) -> Result<Vec<u8>, SigningError> {
1117            if psid == 36 {
1118                self.svc.cam_state_mut().requested_own_certificate = true;
1119            }
1120            self.svc
1121                .try_sign_request(&SNSignRequest {
1122                    tbs_message: b"payload".to_vec(),
1123                    its_aid: psid,
1124                    permissions: permissions.to_vec(),
1125                    generation_location: location.map(|(latitude, longitude)| GenerationLocation {
1126                        latitude,
1127                        longitude,
1128                        elevation: 0xF000,
1129                    }),
1130                })
1131                .map(|c| c.sec_message)
1132        }
1133
1134        fn sign(&mut self, psid: u64) -> Vec<u8> {
1135            let location = (psid == 37).then_some(INSIDE);
1136            self.try_sign(psid, location, &[]).unwrap()
1137        }
1138
1139        fn verify(&self, message: Vec<u8>) -> SNVerifyConfirm {
1140            let mut lib = CertificateLibrary::new(
1141                &self.svc.backend,
1142                vec![self.root.clone()],
1143                vec![self.aa.clone()],
1144                vec![],
1145            );
1146            verify_message(&SNVerifyRequest { message }, &self.svc.backend, &mut lib).0
1147        }
1148    }
1149
1150    fn mutated(msg: &[u8], f: impl FnOnce(&mut SignedData)) -> Vec<u8> {
1151        let mut dot2 = decode_ieee1609_dot2_data(msg);
1152        match &mut dot2.content {
1153            Ieee1609Dot2Content::signedData(sd) => f(sd),
1154            _ => panic!("expected signedData"),
1155        }
1156        encode_ieee1609_dot2_data(&dot2)
1157    }
1158
1159    fn location(lat: i32, lon: i32) -> ThreeDLocation {
1160        ThreeDLocation {
1161            latitude: Latitude(NinetyDegreeInt(lat)),
1162            longitude: Longitude(OneEightyDegreeInt(lon)),
1163            elevation: Elevation(Uint16(0xF000)),
1164        }
1165    }
1166
1167    /// Own chains on every IEEE 1609.2 PublicVerificationKey curve: the
1168    /// issuer choice, the self-signed hash, hashId and the signature follow
1169    /// the curve, and the messages verify.
1170    #[test]
1171    fn chain_on_every_curve_signs_and_verifies() {
1172        for (algorithm, sha384) in [
1173            (KeyAlgorithm::NistP256, false),
1174            (KeyAlgorithm::BrainpoolP256r1, false),
1175            (KeyAlgorithm::BrainpoolP384r1, true),
1176            (KeyAlgorithm::NistP384, true),
1177        ] {
1178            let mut f = Fixture::on_curve(algorithm);
1179            assert_eq!(
1180                matches!(
1181                    f.root.base().issuer,
1182                    IssuerIdentifier::R_self(HashAlgorithm::sha384)
1183                ),
1184                sha384
1185            );
1186            assert_eq!(
1187                matches!(f.aa.base().issuer, IssuerIdentifier::sha384AndDigest(_)),
1188                sha384
1189            );
1190            for psid in [36, 37] {
1191                let msg = f.sign(psid);
1192                let Ieee1609Dot2Content::signedData(sd) = decode_ieee1609_dot2_data(&msg).content
1193                else {
1194                    panic!("signedData")
1195                };
1196                assert_eq!(sd.hash_id == HashAlgorithm::sha384, sha384, "{algorithm:?}");
1197                let expected = match algorithm {
1198                    KeyAlgorithm::NistP256 => {
1199                        matches!(sd.signature, Ieee1609Signature::ecdsaNistP256Signature(_))
1200                    }
1201                    KeyAlgorithm::BrainpoolP256r1 => matches!(
1202                        sd.signature,
1203                        Ieee1609Signature::ecdsaBrainpoolP256r1Signature(_)
1204                    ),
1205                    KeyAlgorithm::BrainpoolP384r1 => matches!(
1206                        sd.signature,
1207                        Ieee1609Signature::ecdsaBrainpoolP384r1Signature(_)
1208                    ),
1209                    KeyAlgorithm::NistP384 => {
1210                        matches!(sd.signature, Ieee1609Signature::ecdsaNistP384Signature(_))
1211                    }
1212                };
1213                assert!(expected, "{algorithm:?}");
1214                assert_eq!(
1215                    f.verify(msg).report,
1216                    ReportVerify::Success,
1217                    "{algorithm:?} {psid}"
1218                );
1219            }
1220        }
1221    }
1222
1223    #[test]
1224    fn signing_input_is_hash_of_hashes() {
1225        let input = signing_input(b"data", b"cert", false);
1226        assert_eq!(&input[..32], &Sha256::digest(b"data")[..]);
1227        assert_eq!(&input[32..], &Sha256::digest(b"cert")[..]);
1228        assert_eq!(
1229            &signing_input(b"data", &[], false)[32..],
1230            &Sha256::digest(b"")[..]
1231        );
1232    }
1233
1234    /// IEEE 1609.2 clause 5.3.1: signature over Hash(Hash(tbs) || Hash(AT)).
1235    #[test]
1236    fn message_signature_covers_the_signer_certificate() {
1237        let mut f = Fixture::valid();
1238        let msg = f.sign(36);
1239        let dot2 = decode_ieee1609_dot2_data(&msg);
1240        let Ieee1609Dot2Content::signedData(sd) = &dot2.content else {
1241            panic!("expected signedData")
1242        };
1243        let at = f.svc.get_present_at(36).unwrap();
1244        let pk = f.svc.backend.get_public_key(at.key_id);
1245        let tbs = encode_tbs_data(&sd.tbs_data);
1246        let canonical = at.to_canonical().encode().to_vec();
1247        assert!(f.svc.backend.verify_with_pk(
1248            &signing_input(&tbs, &canonical, false),
1249            &sd.signature,
1250            &pk
1251        ));
1252        assert!(!f.svc.backend.verify_with_pk(&tbs, &sd.signature, &pk));
1253    }
1254
1255    /// ETSI TS 103 097 clause 7.1.1: ITS-AID and SSP of the signer returned.
1256    #[test]
1257    fn valid_cam_reports_its_aid_and_ssp() {
1258        let mut f = Fixture::valid();
1259        let msg = f.sign(36);
1260        let c = f.verify(msg);
1261        assert_eq!(c.report, ReportVerify::Success);
1262        assert_eq!(c.its_aid, 36);
1263        assert_eq!(c.permissions, vec![2u8, 0x02, 0x00]);
1264    }
1265
1266    /// ETSI TS 103 097 clause 5.1.
1267    #[test]
1268    fn protocol_version_other_than_3() {
1269        let mut f = Fixture::valid();
1270        let msg = f.sign(36);
1271        for version in [2u8, 4] {
1272            let mut bad = msg.clone();
1273            bad[0] = version;
1274            assert_eq!(f.verify(bad).report, ReportVerify::IncompatibleProtocol);
1275        }
1276    }
1277
1278    type HeaderMutation = Box<dyn Fn(&mut SignedData)>;
1279
1280    fn header_cases() -> Vec<(&'static str, HeaderMutation)> {
1281        vec![
1282            (
1283                "generationLocation",
1284                Box::new(|sd: &mut SignedData| {
1285                    sd.tbs_data.header_info.generation_location = Some(location(INSIDE.0, INSIDE.1))
1286                }),
1287            ),
1288            (
1289                "expiryTime",
1290                Box::new(|sd: &mut SignedData| {
1291                    sd.tbs_data.header_info.expiry_time = Some(Time64(Uint64(1)))
1292                }),
1293            ),
1294            (
1295                "missingCrlIdentifier",
1296                Box::new(|sd: &mut SignedData| {
1297                    sd.tbs_data.header_info.missing_crl_identifier = Some(MissingCrlIdentifier {
1298                        craca_id: HashedId3(FixedOctetString::from([0u8; 3])),
1299                        crl_series: CrlSeries(Uint16(0)),
1300                    })
1301                }),
1302            ),
1303            (
1304                "encryptionKey",
1305                Box::new(|sd: &mut SignedData| {
1306                    sd.tbs_data.header_info.encryption_key = Some(EncryptionKey::symmetric(
1307                        SymmetricEncryptionKey::aes128Ccm(vec![0u8; 16].into()),
1308                    ))
1309                }),
1310            ),
1311        ]
1312    }
1313
1314    /// ETSI TS 103 097 clause 7.1.1.
1315    #[test]
1316    fn cam_forbidden_header_fields() {
1317        let mut f = Fixture::valid();
1318        for (name, mutate) in header_cases() {
1319            let bad = mutated(&f.sign(36), |sd| mutate(sd));
1320            assert_eq!(
1321                f.verify(bad).report,
1322                ReportVerify::IncompatibleProtocol,
1323                "{name}"
1324            );
1325        }
1326    }
1327
1328    /// ETSI TS 103 097 clause 5.2, ETSI TS 103 097 clause 7.1.2.
1329    #[test]
1330    fn denm_forbidden_header_fields() {
1331        let mut f = Fixture::valid();
1332        for (name, mutate) in header_cases().into_iter().skip(2) {
1333            let bad = mutated(&f.sign(37), |sd| mutate(sd));
1334            assert_eq!(
1335                f.verify(bad).report,
1336                ReportVerify::IncompatibleProtocol,
1337                "{name}"
1338            );
1339        }
1340    }
1341
1342    /// IEEE 1609.2 clause 5.2.3.2.2: the AT does not permit the PSID.
1343    #[test]
1344    fn psid_not_in_app_permissions() {
1345        let mut f = Fixture::valid();
1346        let bad = mutated(&f.sign(36), |sd| {
1347            sd.tbs_data.header_info.psid = Psid(Integer::from(99))
1348        });
1349        assert_eq!(f.verify(bad).report, ReportVerify::InvalidCertificate);
1350    }
1351
1352    /// IEEE 1609.2 clause 5.2.3.2.2: generationTime inside the AT validity.
1353    #[test]
1354    fn generation_time_outside_certificate_validity() {
1355        let mut f = Fixture::valid();
1356        let start_us = (now_s() as u64 - 60) * 1_000_000;
1357        let bad = mutated(&f.sign(36), |sd| {
1358            sd.tbs_data.header_info.generation_time = Some(Time64(Uint64(start_us - 10_000_000)))
1359        });
1360        assert_eq!(f.verify(bad).report, ReportVerify::InvalidTimestamp);
1361    }
1362
1363    /// ETSI TS 103 097 clause 6.
1364    #[test]
1365    fn signer_self_is_unsupported() {
1366        let mut f = Fixture::valid();
1367        let bad = mutated(&f.sign(36), |sd| sd.signer = SignerIdentifier::R_self(()));
1368        assert_eq!(
1369            f.verify(bad).report,
1370            ReportVerify::UnsupportedSignerIdentifierType
1371        );
1372    }
1373
1374    /// ETSI TS 103 097 clause 6.
1375    #[test]
1376    fn signature_algorithm_not_matching_the_key() {
1377        let mut f = Fixture::valid();
1378        for psid in [36, 37] {
1379            let bad = mutated(&f.sign(psid), |sd| {
1380                if let Ieee1609Signature::ecdsaNistP256Signature(s) = &sd.signature {
1381                    sd.signature = Ieee1609Signature::ecdsaBrainpoolP256r1Signature(s.clone());
1382                }
1383            });
1384            assert_eq!(f.verify(bad).report, ReportVerify::FalseSignature);
1385        }
1386    }
1387
1388    /// ETSI TS 103 097 clause 6.
1389    #[test]
1390    fn altered_signature() {
1391        let mut f = Fixture::valid();
1392        let bad = mutated(&f.sign(37), |sd| {
1393            if let Ieee1609Signature::ecdsaNistP256Signature(s) = &mut sd.signature {
1394                let mut b = s.s_sig.to_vec();
1395                *b.last_mut().unwrap() ^= 0x01;
1396                s.s_sig = b.into();
1397            }
1398        });
1399        assert_eq!(f.verify(bad).report, ReportVerify::FalseSignature);
1400    }
1401
1402    /// ETSI TS 103 097 clause 7.1.1: rSig as compressed-y-0 / compressed-y-1.
1403    #[test]
1404    fn compressed_r_signature_accepted() {
1405        let mut f = Fixture::valid();
1406        for y1 in [false, true] {
1407            let msg = mutated(&f.sign(36), |sd| {
1408                if let Ieee1609Signature::ecdsaNistP256Signature(s) = &mut sd.signature {
1409                    if let EccP256CurvePoint::x_only(r) = &s.r_sig {
1410                        s.r_sig = if y1 {
1411                            EccP256CurvePoint::compressed_y_1(r.clone())
1412                        } else {
1413                            EccP256CurvePoint::compressed_y_0(r.clone())
1414                        };
1415                    }
1416                }
1417            });
1418            assert_eq!(f.verify(msg).report, ReportVerify::Success);
1419        }
1420    }
1421
1422    /// IEEE 1609.2 clause 5.2.3.2.2 (circular),
1423    /// ETSI TS 103 097 clause 7.1.2 and region consistency on reception.
1424    #[test]
1425    fn region_restriction() {
1426        let mut f = Fixture::new(at_tbs(-60, AsnDuration::hours(Uint16(1)), Some(circle())));
1427        let msg = f.try_sign(37, Some(INSIDE), &[]).unwrap();
1428        assert_eq!(f.verify(msg.clone()).report, ReportVerify::Success);
1429        assert!(f.try_sign(37, Some(OUTSIDE), &[]).is_err());
1430        assert!(f.try_sign(36, Some(OUTSIDE), &[]).is_err());
1431        let bad = mutated(&msg, |sd| {
1432            sd.tbs_data.header_info.generation_location = Some(location(OUTSIDE.0, OUTSIDE.1))
1433        });
1434        assert_eq!(f.verify(bad).report, ReportVerify::InvalidMobilityData);
1435    }
1436
1437    /// IEEE 1609.2 clause 6.4.17: AT restricted to an identifiedRegion of 8
1438    /// entries, one containing the position (synthetic geometry registered
1439    /// for UnCountryId 9400..9407). The DENM is signed with the position
1440    /// inside that entry and accepted; outside every entry the station does
1441    /// not sign and a receiver rejects the location.
1442    #[test]
1443    fn identified_region_restriction() {
1444        use crate::security::security_asn::ieee1609_dot2_base_types::{
1445            IdentifiedRegion, SequenceOfIdentifiedRegion, UnCountryId,
1446        };
1447        use crate::security::validity::{register_identified_region, RegionKey};
1448        for i in 0..8u16 {
1449            let south = 340000000 + i as i32 * 15000000;
1450            let north = south + 10000000;
1451            register_identified_region(
1452                RegionKey::country(9400 + i),
1453                &[vec![
1454                    (south, 0),
1455                    (north, 0),
1456                    (north, 30000000),
1457                    (south, 30000000),
1458                ]],
1459            );
1460        }
1461        let region = GeographicRegion::identifiedRegion(SequenceOfIdentifiedRegion(
1462            (0..8)
1463                .map(|i| IdentifiedRegion::countryOnly(UnCountryId(Uint16(9400 + i))))
1464                .collect(),
1465        ));
1466        let mut f = Fixture::new(at_tbs(-60, AsnDuration::hours(Uint16(1)), Some(region)));
1467        let msg = f.try_sign(37, Some(INSIDE), &[]).unwrap();
1468        let data = decode_ieee1609_dot2_data(&msg);
1469        let Ieee1609Dot2Content::signedData(sd) = &data.content else {
1470            panic!("not signed")
1471        };
1472        let loc = sd
1473            .tbs_data
1474            .header_info
1475            .generation_location
1476            .as_ref()
1477            .unwrap();
1478        assert_eq!((loc.latitude.0 .0, loc.longitude.0 .0), INSIDE);
1479        assert_eq!(f.verify(msg.clone()).report, ReportVerify::Success);
1480        assert!(f.try_sign(37, Some(OUTSIDE), &[]).is_err());
1481        let bad = mutated(&msg, |sd| {
1482            sd.tbs_data.header_info.generation_location = Some(location(OUTSIDE.0, OUTSIDE.1))
1483        });
1484        assert_eq!(f.verify(bad).report, ReportVerify::InvalidMobilityData);
1485    }
1486
1487    /// IEEE 1609.2 clause 5.2.3.2.2 (region of the AA; region of
1488    /// the root, AA without region) and IEEE 1609.2 clause 5.2.3.2.2 (no DENM outside the
1489    /// region of the AA): an AT without region inherits the closest one in its
1490    /// chain, on transmission and on reception.
1491    #[test]
1492    fn region_inherited_from_aa_and_root() {
1493        let at = || at_tbs(-60, AsnDuration::hours(Uint16(1)), None);
1494        let chains = [
1495            (ca_tbs_with_region(Some(circle())), ca_tbs(), "root"),
1496            (ca_tbs(), ca_tbs_with_region(Some(circle())), "AA"),
1497        ];
1498        for (root, aa, holder) in chains {
1499            let mut f = Fixture::chain(root, aa, at());
1500            let msg = f.try_sign(37, Some(INSIDE), &[]).unwrap();
1501            assert_eq!(
1502                f.verify(msg.clone()).report,
1503                ReportVerify::Success,
1504                "{holder}"
1505            );
1506            assert!(f.try_sign(37, Some(OUTSIDE), &[]).is_err(), "{holder}");
1507            // IEEE 1609.2 clause 5.2.3.2.2 (region variant)
1508            assert!(f.try_sign(36, Some(OUTSIDE), &[]).is_err(), "{holder}");
1509            let bad = mutated(&msg, |sd| {
1510                sd.tbs_data.header_info.generation_location = Some(location(OUTSIDE.0, OUTSIDE.1))
1511            });
1512            assert_eq!(
1513                f.verify(bad).report,
1514                ReportVerify::InvalidMobilityData,
1515                "{holder}"
1516            );
1517        }
1518    }
1519
1520    /// ETSI TS 103 097 clause 7.1.2: the signed payload is an
1521    /// Ieee1609Dot2Data (protocol version 3) of type unsecuredData holding the
1522    /// DENM, which the receiver returns as the plain message.
1523    #[test]
1524    fn signed_denm_payload_is_unsecured_data() {
1525        let mut f = Fixture::valid();
1526        let msg = f.sign(37);
1527        let dot2 = decode_ieee1609_dot2_data(&msg);
1528        let Ieee1609Dot2Content::signedData(sd) = &dot2.content else {
1529            panic!("expected signedData")
1530        };
1531        let inner = sd.tbs_data.payload.data.as_ref().expect("payload data");
1532        assert_eq!(inner.protocol_version.0, 3);
1533        let Ieee1609Dot2Content::unsecuredData(data) = &inner.content else {
1534            panic!("expected unsecuredData")
1535        };
1536        assert_eq!(data.0.as_ref(), b"payload");
1537        assert!(sd.tbs_data.payload.ext_data_hash.is_none());
1538        let confirm = f.verify(msg);
1539        assert_eq!(confirm.report, ReportVerify::Success);
1540        assert_eq!(confirm.plain_message, b"payload");
1541    }
1542
1543    /// ETSI TS 103 097 clause 7.1.3: a message of another
1544    /// ITS-AID carries that psid and a generationTime, and is accepted.
1545    #[test]
1546    fn other_its_aid_header_has_psid_and_generation_time() {
1547        let mut tbs = at_tbs(-60, AsnDuration::hours(Uint16(1)), None);
1548        if let Some(app) = tbs.app_permissions.as_mut() {
1549            app.0.push(PsidSsp::new(Psid(Integer::from(139)), None));
1550        }
1551        let mut f = Fixture::new(tbs);
1552        let before = timestamp_its_microseconds();
1553        let msg = f.try_sign(139, None, &[]).unwrap();
1554        let dot2 = decode_ieee1609_dot2_data(&msg);
1555        let Ieee1609Dot2Content::signedData(sd) = &dot2.content else {
1556            panic!("expected signedData")
1557        };
1558        let header = &sd.tbs_data.header_info;
1559        assert_eq!(u64::try_from(&header.psid.0).ok(), Some(139));
1560        let time = header
1561            .generation_time
1562            .as_ref()
1563            .expect("generationTime")
1564            .0
1565             .0;
1566        assert!(time + 1_000_000 >= before && time <= timestamp_its_microseconds() + 1_000_000);
1567        // First message: the certificate, so any receiver can verify it
1568        assert!(matches!(&sd.signer, SignerIdentifier::certificate(_)));
1569        let confirm = f.verify(msg);
1570        assert_eq!(confirm.report, ReportVerify::Success);
1571        assert_eq!(confirm.its_aid, 139);
1572        // Within 1 s: the digest, verifiable by a receiver that knows the AT
1573        let msg = f.try_sign(139, None, &[]).unwrap();
1574        let at = f.svc.get_present_at(139).unwrap().cert.clone();
1575        let sd = signed_data(&msg);
1576        assert!(
1577            matches!(&sd.signer, SignerIdentifier::digest(h) if h.0.as_ref() == at.as_hashedid8())
1578        );
1579        assert_eq!(
1580            f.verify(msg.clone()).report,
1581            ReportVerify::SignerCertificateNotFound
1582        );
1583        let mut lib = CertificateLibrary::new(
1584            &f.svc.backend,
1585            vec![f.root.clone()],
1586            vec![f.aa.clone()],
1587            vec![at],
1588        );
1589        let confirm = verify_message(&SNVerifyRequest { message: msg }, &f.svc.backend, &mut lib).0;
1590        assert_eq!(confirm.report, ReportVerify::Success);
1591    }
1592
1593    /// Compressed SEC1 point (02/03 || x) of the public key of scalar `d`.
1594    macro_rules! brainpool_sign {
1595        ($curve:ty, $d:expr, $k:expr, $digest:expr) => {{
1596            use ecdsa_v017::elliptic_curve::sec1::ToSec1Point;
1597            use ecdsa_v017::elliptic_curve::SecretKey;
1598            let d = SecretKey::<$curve>::from_slice($d)
1599                .unwrap()
1600                .to_nonzero_scalar();
1601            let k = SecretKey::<$curve>::from_slice($k)
1602                .unwrap()
1603                .to_nonzero_scalar();
1604            let public = SecretKey::<$curve>::from_slice($d)
1605                .unwrap()
1606                .public_key()
1607                .to_sec1_point(true)
1608                .as_bytes()
1609                .to_vec();
1610            let (sig, _) = ecdsa_v017::hazmat::sign_prehashed::<$curve>(&d, &k, $digest).unwrap();
1611            (public, sig.to_bytes().to_vec())
1612        }};
1613    }
1614
1615    /// CAM (36) or DENM (37) signed with a brainpoolP256r1 / P384r1 AT issued
1616    /// by the fixture's AA: the fixture's message with its signer replaced by
1617    /// that AT and its signature recomputed over Hash(Hash(tbs) || Hash(AT))
1618    /// (ECDSA with a fixed nonce, test only).
1619    fn brainpool_message(f: &mut Fixture, psid: u64, p384: bool) -> Vec<u8> {
1620        use crate::security::certificate::{encode_tbs_data, signing_input};
1621        use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
1622        use crate::security::security_asn::ieee1609_dot2::Certificate as AsnCertificate;
1623        use crate::security::security_asn::ieee1609_dot2::{
1624            CertificateBase, CertificateType, IssuerIdentifier, SequenceOfCertificate,
1625        };
1626        use crate::security::security_asn::ieee1609_dot2_base_types::{
1627            EccP384CurvePoint, EcdsaP256Signature, EcdsaP384Signature, HashAlgorithm, Uint8,
1628        };
1629        use sha2::Sha384;
1630
1631        // Key pair (the signature depends on the message, so it is computed
1632        // twice: once for the key, once over the final message).
1633        let size = if p384 { 48 } else { 32 };
1634        let (d, k) = (vec![7u8; size], vec![9u8; size]);
1635        let public = if p384 {
1636            brainpool_sign!(bp384::BrainpoolP384r1, &d, &k, &[1u8; 48]).0
1637        } else {
1638            brainpool_sign!(bp256::BrainpoolP256r1, &d, &k, &[1u8; 32]).0
1639        };
1640        let x = public[1..].to_vec();
1641        let key = match (p384, public[0]) {
1642            (false, 2) => PublicVerificationKey::ecdsaBrainpoolP256r1(
1643                EccP256CurvePoint::compressed_y_0(x.into()),
1644            ),
1645            (false, _) => PublicVerificationKey::ecdsaBrainpoolP256r1(
1646                EccP256CurvePoint::compressed_y_1(x.into()),
1647            ),
1648            (true, 2) => PublicVerificationKey::ecdsaBrainpoolP384r1(
1649                EccP384CurvePoint::compressed_y_0(x.into()),
1650            ),
1651            (true, _) => PublicVerificationKey::ecdsaBrainpoolP384r1(
1652                EccP384CurvePoint::compressed_y_1(x.into()),
1653            ),
1654        };
1655        let mut tbs_cert = at_tbs(-60, AsnDuration::hours(Uint16(1)), None);
1656        tbs_cert.verify_key_indicator = VerificationKeyIndicator::verificationKey(key);
1657        let unsigned = Certificate::from_asn(
1658            EtsiTs103097Certificate(AsnCertificate(CertificateBase::new(
1659                Uint8(3),
1660                CertificateType::explicit,
1661                IssuerIdentifier::R_self(HashAlgorithm::sha256),
1662                tbs_cert,
1663                None,
1664            ))),
1665            None,
1666        );
1667        let at = f.aa_owner.issue_certificate(&f.svc.backend, &unsigned);
1668
1669        let location = (psid == 37).then_some(INSIDE);
1670        let template = f.try_sign(psid, location, &[]).unwrap();
1671        let mut dot2 = decode_ieee1609_dot2_data(&template);
1672        let Ieee1609Dot2Content::signedData(sd) = &mut dot2.content else {
1673            panic!("expected signedData")
1674        };
1675        sd.signer = SignerIdentifier::certificate(SequenceOfCertificate(vec![at.inner.0.clone()]));
1676        let input = signing_input(
1677            &encode_tbs_data(&sd.tbs_data),
1678            at.to_canonical().encode(),
1679            p384,
1680        );
1681        sd.signature = if p384 {
1682            sd.hash_id = HashAlgorithm::sha384;
1683            let rs = brainpool_sign!(bp384::BrainpoolP384r1, &d, &k, &Sha384::digest(&input)).1;
1684            Ieee1609Signature::ecdsaBrainpoolP384r1Signature(EcdsaP384Signature {
1685                r_sig: EccP384CurvePoint::x_only(rs[..48].to_vec().into()),
1686                s_sig: rs[48..].to_vec().into(),
1687            })
1688        } else {
1689            let rs = brainpool_sign!(bp256::BrainpoolP256r1, &d, &k, &Sha256::digest(&input)).1;
1690            Ieee1609Signature::ecdsaBrainpoolP256r1Signature(EcdsaP256Signature {
1691                r_sig: EccP256CurvePoint::x_only(rs[..32].to_vec().into()),
1692                s_sig: rs[32..].to_vec().into(),
1693            })
1694        };
1695        encode_ieee1609_dot2_data(&dot2)
1696    }
1697
1698    /// ETSI TS 103 097 clause 7.1.1, ETSI TS 103 097 clause 7.1.2: CAMs and
1699    /// DENMs signed with brainpoolP256r1 / brainpoolP384r1 ATs are accepted;
1700    /// an altered signature is not.
1701    #[test]
1702    fn brainpool_signed_cam_and_denm_accepted() {
1703        let mut f = Fixture::valid();
1704        for p384 in [false, true] {
1705            for psid in [36u64, 37] {
1706                let msg = brainpool_message(&mut f, psid, p384);
1707                let confirm = f.verify(msg.clone());
1708                assert_eq!(
1709                    confirm.report,
1710                    ReportVerify::Success,
1711                    "psid {psid} p384 {p384}"
1712                );
1713                assert_eq!(confirm.plain_message, b"payload");
1714                let bad = mutated(&msg, |sd| {
1715                    if let Ieee1609Signature::ecdsaBrainpoolP256r1Signature(sig) = &mut sd.signature
1716                    {
1717                        sig.s_sig = vec![1u8; 32].into();
1718                    }
1719                    if let Ieee1609Signature::ecdsaBrainpoolP384r1Signature(sig) = &mut sd.signature
1720                    {
1721                        sig.s_sig = vec![1u8; 48].into();
1722                    }
1723                });
1724                assert_eq!(f.verify(bad).report, ReportVerify::FalseSignature);
1725            }
1726        }
1727    }
1728
1729    /// Region kinds of the TP permutation tables, each with the position
1730    /// INSIDE in one entry and OUTSIDE in none: B circular; C rectangular
1731    /// with 8 entries (IEEE 1609.2 clause 6.4.17); D polygonal with 8 points
1732    /// (IEEE 1609.2 clause 6.4.17); E identified with 8 entries (IEEE 1609.2 clause 6.4.17,
1733    /// synthetic geometry for UnCountryId 9500..9507).
1734    fn region_kinds() -> Vec<(&'static str, GeographicRegion)> {
1735        use crate::security::security_asn::ieee1609_dot2_base_types::{
1736            IdentifiedRegion, PolygonalRegion, RectangularRegion, SequenceOfIdentifiedRegion,
1737            SequenceOfRectangularRegion, UnCountryId,
1738        };
1739        use crate::security::validity::{register_identified_region, RegionKey};
1740        let point = |lat: i32, lon: i32| {
1741            TwoDLocation::new(
1742                Latitude(NinetyDegreeInt(lat)),
1743                Longitude(OneEightyDegreeInt(lon)),
1744            )
1745        };
1746        // 8 boxes 41.5-41.6 N, 0.2 deg wide, 0.3 deg apart; the 6th holds INSIDE
1747        let rects = (0..8)
1748            .map(|i| {
1749                let west = 5340000 + i * 3000000;
1750                RectangularRegion::new(point(416000000, west), point(415000000, west + 2000000))
1751            })
1752            .collect();
1753        let (c_lat, c_lon) = INSIDE;
1754        let octagon = [
1755            (1000000, -400000),
1756            (1000000, 400000),
1757            (400000, 1000000),
1758            (-400000, 1000000),
1759            (-1000000, 400000),
1760            (-1000000, -400000),
1761            (-400000, -1000000),
1762            (400000, -1000000),
1763        ]
1764        .iter()
1765        .map(|(dlat, dlon)| point(c_lat + dlat, c_lon + dlon))
1766        .collect();
1767        for i in 0..8u16 {
1768            let south = 340000000 + i as i32 * 15000000;
1769            let north = south + 10000000;
1770            register_identified_region(
1771                RegionKey::country(9500 + i),
1772                &[vec![
1773                    (south, 0),
1774                    (north, 0),
1775                    (north, 30000000),
1776                    (south, 30000000),
1777                ]],
1778            );
1779        }
1780        let identified = (0..8)
1781            .map(|i| IdentifiedRegion::countryOnly(UnCountryId(Uint16(9500 + i))))
1782            .collect();
1783        vec![
1784            ("B circular", circle()),
1785            (
1786                "C rectangular x8",
1787                GeographicRegion::rectangularRegion(SequenceOfRectangularRegion(rects)),
1788            ),
1789            (
1790                "D polygonal x8",
1791                GeographicRegion::polygonalRegion(PolygonalRegion(octagon)),
1792            ),
1793            (
1794                "E identified x8",
1795                GeographicRegion::identifiedRegion(SequenceOfIdentifiedRegion(identified)),
1796            ),
1797        ]
1798    }
1799
1800    /// IEEE 1609.2 clause 5.2.3.2.2, IEEE 1609.2 clause 6.4.17,
1801    /// IEEE 1609.2 clause 6.4.17 (DENM sent with generationLocation inside the region),
1802    /// ETSI TS 103 097 clause 7.1.2 and ETSI TS 103 097 clause 7.1.1 (accepted by a receiver),
1803    /// IEEE 1609.2 clause 5.2.3.2.2 (not sent outside) for every region kind.
1804    #[test]
1805    fn every_region_kind_end_to_end() {
1806        for (kind, region) in region_kinds() {
1807            let mut f = Fixture::new(at_tbs(-60, AsnDuration::hours(Uint16(1)), Some(region)));
1808            let denm = f.try_sign(37, Some(INSIDE), &[]).unwrap();
1809            let dot2 = decode_ieee1609_dot2_data(&denm);
1810            let Ieee1609Dot2Content::signedData(sd) = &dot2.content else {
1811                panic!("not signed")
1812            };
1813            let loc = sd
1814                .tbs_data
1815                .header_info
1816                .generation_location
1817                .as_ref()
1818                .unwrap();
1819            assert_eq!((loc.latitude.0 .0, loc.longitude.0 .0), INSIDE, "{kind}");
1820            assert_eq!(
1821                f.verify(denm.clone()).report,
1822                ReportVerify::Success,
1823                "{kind}"
1824            );
1825            let cam = f.sign(36);
1826            assert_eq!(f.verify(cam).report, ReportVerify::Success, "{kind}");
1827            assert!(f.try_sign(37, Some(OUTSIDE), &[]).is_err(), "{kind}");
1828            let bad = mutated(&denm, |sd| {
1829                sd.tbs_data.header_info.generation_location = Some(location(OUTSIDE.0, OUTSIDE.1))
1830            });
1831            assert_eq!(
1832                f.verify(bad).report,
1833                ReportVerify::InvalidMobilityData,
1834                "{kind}"
1835            );
1836        }
1837    }
1838
1839    // ── Content of sent CAMs / DENMs (TS 103 096-2 clauses 6.2.2, 6.2.3) ──
1840
1841    /// AT valid for 1 h with the given PSIDs (no SSP).
1842    fn at_tbs_with_psids(psids: &[u64]) -> ToBeSignedCertificate {
1843        let mut tbs = at_tbs(-60, AsnDuration::hours(Uint16(1)), None);
1844        tbs.app_permissions = Some(SequenceOfPsidSsp(
1845            psids
1846                .iter()
1847                .map(|p| PsidSsp::new(Psid(Integer::from(*p)), None))
1848                .collect(),
1849        ));
1850        tbs
1851    }
1852
1853    fn signed_data(msg: &[u8]) -> SignedData {
1854        match decode_ieee1609_dot2_data(msg).content {
1855            Ieee1609Dot2Content::signedData(sd) => sd,
1856            _ => panic!("expected signedData"),
1857        }
1858    }
1859
1860    fn signer_tbs(sd: &SignedData) -> ToBeSignedCertificate {
1861        match &sd.signer {
1862            SignerIdentifier::certificate(certs) => certs.0[0].0.to_be_signed.clone(),
1863            _ => panic!("expected certificate signer"),
1864        }
1865    }
1866
1867    /// IEEE 1609.2 clause 5.2.3.2.2: CUR_TIME - 5 min <=
1868    /// generationTime <= CUR_TIME + 5 min, inside the validity period of the
1869    /// signing AT.
1870    #[test]
1871    fn generation_time_inside_at_validity() {
1872        use crate::security::validity::validity_window_us;
1873        let mut f = Fixture::valid();
1874        for psid in [36u64, 37] {
1875            let now = timestamp_its_microseconds();
1876            let sd = signed_data(&f.sign(psid));
1877            let time = sd
1878                .tbs_data
1879                .header_info
1880                .generation_time
1881                .as_ref()
1882                .unwrap()
1883                .0
1884                 .0;
1885            assert!(time.abs_diff(now) <= 300_000_000, "psid {psid}");
1886            let (start, end) = validity_window_us(&signer_tbs(&sd));
1887            assert!(start <= time && time <= end, "psid {psid}");
1888        }
1889    }
1890
1891    /// IEEE 1609.2 clause 5.2.3.2.2.
1892    #[test]
1893    fn signer_app_permissions_contain_the_psid() {
1894        use crate::security::validity::app_permission;
1895        let mut f = Fixture::valid();
1896        for psid in [36u64, 37] {
1897            let sd = signed_data(&f.sign(psid));
1898            assert!(app_permission(&signer_tbs(&sd), psid).0, "psid {psid}");
1899        }
1900    }
1901
1902    /// IEEE 1609.2 clause 5.2.3.2.2: the only AT lacks the PSID.
1903    #[test]
1904    fn no_message_without_permitted_at() {
1905        let mut f = Fixture::new(at_tbs_with_psids(&[139]));
1906        assert!(f.try_sign(36, None, &[]).is_err());
1907        assert!(f.try_sign(37, Some(INSIDE), &[]).is_err());
1908    }
1909
1910    /// IEEE 1609.2 clause 6.3.30 (A, NIST P-256).
1911    #[test]
1912    fn signature_r_is_x_only_or_compressed() {
1913        let mut f = Fixture::valid();
1914        let sd = signed_data(&f.sign(36));
1915        let Ieee1609Signature::ecdsaNistP256Signature(sig) = &sd.signature else {
1916            panic!("expected ecdsaNistP256Signature")
1917        };
1918        assert!(matches!(
1919            sig.r_sig,
1920            EccP256CurvePoint::x_only(_)
1921                | EccP256CurvePoint::compressed_y_0(_)
1922                | EccP256CurvePoint::compressed_y_1(_)
1923        ));
1924    }
1925
1926    /// IEEE 1609.2 clause 5.2.3.2.2 (8 appPermissions, AID_CAM last).
1927    #[test]
1928    fn at_with_8_app_permissions() {
1929        let psids: Vec<u64> = (130..137).chain([36]).collect();
1930        let mut f = Fixture::new(at_tbs_with_psids(&psids));
1931        let msg = f.sign(36);
1932        assert_eq!(
1933            u64::try_from(&signed_data(&msg).tbs_data.header_info.psid.0).ok(),
1934            Some(36)
1935        );
1936        assert_eq!(f.verify(msg).report, ReportVerify::Success);
1937    }
1938
1939    /// IEEE 1609.2 clause 5.2.3.2.2 (8 certIssuePermissions in the AA, AID_CAM
1940    /// last); without AID_CAM the AT is not a valid CAM signer.
1941    #[test]
1942    fn aa_with_8_cert_issue_permissions() {
1943        use crate::security::security_asn::ieee1609_dot2_base_types::{
1944            PsidSspRange, SequenceOfPsidSspRange,
1945        };
1946        let aa = |psids: Vec<u64>| {
1947            let mut tbs = ca_tbs();
1948            tbs.cert_issue_permissions = Some(SequenceOfPsidGroupPermissions(
1949                psids
1950                    .into_iter()
1951                    .map(|p| {
1952                        PsidGroupPermissions::new(
1953                            SubjectPermissions::explicit(SequenceOfPsidSspRange(vec![
1954                                PsidSspRange::new(Psid(Integer::from(p)), None),
1955                            ])),
1956                            Integer::from(0),
1957                            Integer::from(0),
1958                            {
1959                                let mut bits = FixedBitString::<8>::default();
1960                                bits.set(0, true);
1961                                EndEntityType(bits)
1962                            },
1963                        )
1964                    })
1965                    .collect(),
1966            ));
1967            tbs
1968        };
1969        let mut f = Fixture::chain(
1970            ca_tbs(),
1971            aa((130..137).chain([36]).collect()),
1972            at_tbs_with_psids(&[36]),
1973        );
1974        let msg = f.sign(36);
1975        assert_eq!(f.verify(msg).report, ReportVerify::Success);
1976        let mut f = Fixture::chain(ca_tbs(), aa((130..138).collect()), at_tbs_with_psids(&[36]));
1977        match f.try_sign(36, None, &[]) {
1978            Err(_) => {}
1979            Ok(msg) => assert_ne!(f.verify(msg).report, ReportVerify::Success),
1980        }
1981    }
1982
1983    // ── Secured Beacons (TS 103 836-4-1 clause 10.3.6.2 step 2) ──────────
1984
1985    fn beacon_request() -> crate::geonet::service_access_point::GNDataRequest {
1986        use crate::geonet::service_access_point::*;
1987        GNDataRequest {
1988            upper_protocol_entity: CommonNH::Any,
1989            packet_transport_type: PacketTransportType {
1990                header_type: HeaderType::Beacon,
1991                header_sub_type: HeaderSubType::Unspecified(UnspecifiedHST::Unspecified),
1992            },
1993            communication_profile: CommunicationProfile::Unspecified,
1994            traffic_class: TrafficClass {
1995                scf: false,
1996                channel_offload: false,
1997                tc_id: 0,
1998            },
1999            security_profile: crate::security::sn_sap::SecurityProfile::NoSecurity,
2000            its_aid: 0,
2001            security_permissions: vec![],
2002            max_hop_limit: 1,
2003            max_packet_lifetime: None,
2004            destination: None,
2005            length: 0,
2006            data: vec![],
2007            area: Area {
2008                latitude: 0,
2009                longitude: 0,
2010                a: 0,
2011                b: 0,
2012                angle: 0,
2013            },
2014        }
2015    }
2016
2017    fn gn_station(
2018        n: u8,
2019        sign: Option<SignService>,
2020        verify: Option<(EcdsaBackend, CertificateLibrary)>,
2021    ) -> (
2022        crate::geonet::router::Router,
2023        std::sync::mpsc::Receiver<Vec<u8>>,
2024    ) {
2025        use crate::geonet::gn_address::{GNAddress, M, MID, ST};
2026        use crate::geonet::mib::{GnSecurity, Mib};
2027        use crate::geonet::position_vector::Tst;
2028        let mut mib = Mib::new();
2029        mib.itsGnSecurity = GnSecurity::Enabled;
2030        mib.itsGnBeaconServiceRetransmitTimer = 0;
2031        mib.itsGnLocalGnAddr =
2032            GNAddress::new(M::GnUnicast, ST::Unknown, MID::new([2, 0, 0, 0, 0, n]));
2033        let (ll_tx, ll_rx) = std::sync::mpsc::channel();
2034        let (btp_tx, _btp_rx) = std::sync::mpsc::channel();
2035        let (backend, library) = verify.unzip();
2036        let mut router =
2037            crate::geonet::router::Router::new(mib, ll_tx, btp_tx, sign, backend, library);
2038        router.ego_position_vector.latitude = INSIDE.0 as u32;
2039        router.ego_position_vector.longitude = INSIDE.1 as u32;
2040        router.ego_position_vector.pai = true;
2041        router.ego_position_vector.tst = Tst::set_in_normal_timestamp_milliseconds(
2042            std::time::SystemTime::now()
2043                .duration_since(std::time::UNIX_EPOCH)
2044                .unwrap()
2045                .as_millis() as u64,
2046        );
2047        (router, ll_rx)
2048    }
2049
2050    /// Secured Beacons sent by one GN router and verified by another:
2051    /// ETSI TS 103 097 clause 7.1.3 (signedData; generationTime
2052    /// inside the AT validity), GENMSG_06_BV (unsecuredData payload),
2053    /// GENMSG_07_BV (AT appPermissions contain ITS-AID 141). Messages other
2054    /// than CAM and DENM carry the certificate once per second and the digest
2055    /// otherwise (TS 103 097 clause 7.1.3 does not constrain the signer).
2056    #[test]
2057    fn secured_beacon_sent_and_verified() {
2058        use crate::geonet::basic_header::{BasicHeader, BasicNH};
2059        use crate::geonet::gn_address::{GNAddress, M, MID, ST};
2060        use crate::security::validity::{app_permission, validity_window_us};
2061        let f = Fixture::new(at_tbs_with_psids(&[36, 37, 141]));
2062        let at = f.svc.get_present_at(141).unwrap().cert.clone();
2063        let Fixture { svc, root, aa, .. } = f;
2064        let backend = svc.backend.clone();
2065        let now = timestamp_its_microseconds();
2066        let (mut sender, ll_rx) = gn_station(1, Some(svc), None);
2067        sender.gn_data_request(beacon_request());
2068        let packets: Vec<Vec<u8>> = ll_rx.try_iter().collect();
2069        assert_eq!(packets.len(), 1);
2070        let basic = BasicHeader::decode(packets[0][0..4].try_into().unwrap());
2071        assert!(matches!(basic.nh, BasicNH::SecuredPacket));
2072        let sd = signed_data(&packets[0][4..]); // GENMSG_01
2073        let header = &sd.tbs_data.header_info;
2074        assert_eq!(u64::try_from(&header.psid.0).ok(), Some(141));
2075        let time = header.generation_time.as_ref().unwrap().0 .0; // GENMSG_05
2076        let (start, end) = validity_window_us(at.tbs());
2077        assert!(start <= time && time <= end);
2078        assert!(time.abs_diff(now) <= 600_000_000);
2079        let inner = sd.tbs_data.payload.data.as_ref().unwrap(); // GENMSG_06
2080        let Ieee1609Dot2Content::unsecuredData(data) = &inner.content else {
2081            panic!("expected unsecuredData")
2082        };
2083        assert_eq!(data.0.len(), 8 + 24);
2084        // GENMSG_05 / GENMSG_07: the signer certificate is the AT, valid at
2085        // generationTime and permitting ITS-AID 141
2086        let signer = signer_tbs(&sd);
2087        let (start, end) = validity_window_us(&signer);
2088        assert!(start <= time && time <= end);
2089        assert!(app_permission(&signer, 141).0);
2090        assert_eq!(signer, *at.tbs());
2091        let library = |ats: Vec<Certificate>| {
2092            CertificateLibrary::new(&backend, vec![root.clone()], vec![aa.clone()], ats)
2093        };
2094        let sender_addr = GNAddress::new(M::GnUnicast, ST::Unknown, MID::new([2, 0, 0, 0, 0, 1]));
2095        // A receiver that never heard from the sender verifies it
2096        let (mut receiver, _) = gn_station(7, None, Some((backend.clone(), library(vec![]))));
2097        receiver.process_basic_header(&packets[0]);
2098        assert!(receiver
2099            .location_table
2100            .get_entry_ref(&sender_addr)
2101            .is_some());
2102        // The next Beacon within 1 s carries the digest: a stranger cannot verify it
2103        sender.gn_data_request(beacon_request());
2104        let next: Vec<Vec<u8>> = ll_rx.try_iter().collect();
2105        let sd = signed_data(&next[0][4..]);
2106        assert!(
2107            matches!(&sd.signer, SignerIdentifier::digest(h) if h.0.as_ref() == at.as_hashedid8())
2108        );
2109        let (mut stranger, _) = gn_station(8, None, Some((backend.clone(), library(vec![]))));
2110        stranger.process_basic_header(&next[0]);
2111        assert!(stranger
2112            .location_table
2113            .get_entry_ref(&sender_addr)
2114            .is_none());
2115    }
2116
2117    /// No AT for ITS-AID 141: no Beacon.
2118    #[test]
2119    fn no_beacon_without_gn_mgmt_permission() {
2120        let Fixture { svc, .. } = Fixture::valid();
2121        let (mut sender, ll_rx) = gn_station(1, Some(svc), None);
2122        sender.gn_data_request(beacon_request());
2123        assert!(ll_rx.try_recv().is_err());
2124    }
2125
2126    // ── P2PCD between stations (TS 103 097 clause 7.1.1) ─────────────────
2127    // Mirrors TestPeerToPeerCertificateDistribution; the IUT is station `a`
2128    // and the 1 s certificate timer is driven explicitly (base 100 s).
2129
2130    struct Pki {
2131        backend: EcdsaBackend,
2132        root: OwnCertificate,
2133    }
2134
2135    impl Pki {
2136        fn new() -> Self {
2137            let mut backend = EcdsaBackend::new();
2138            let root = OwnCertificate::initialize_self_signed(&mut backend, ca_tbs());
2139            Pki { backend, root }
2140        }
2141        fn aa(&mut self) -> OwnCertificate {
2142            OwnCertificate::initialize_issued(&mut self.backend, ca_tbs(), &self.root)
2143        }
2144        fn station(&mut self, aa: &OwnCertificate, known_aas: &[&OwnCertificate]) -> Station {
2145            let at = OwnCertificate::initialize_issued(
2146                &mut self.backend,
2147                at_tbs(-60, AsnDuration::hours(Uint16(1)), None),
2148                aa,
2149            );
2150            let mut aas = vec![aa.cert.clone()];
2151            aas.extend(known_aas.iter().map(|k| k.cert.clone()));
2152            let backend = self.backend.clone();
2153            let library = |b: &EcdsaBackend| {
2154                CertificateLibrary::new(b, vec![self.root.cert.clone()], aas.clone(), vec![])
2155            };
2156            let verify_library = library(&backend);
2157            let mut svc = SignService::new(backend.clone(), library(&backend));
2158            svc.add_own_certificate(at.clone());
2159            Station {
2160                svc,
2161                backend,
2162                verify_library,
2163                at: at.cert,
2164            }
2165        }
2166    }
2167
2168    struct Station {
2169        svc: SignService,
2170        backend: EcdsaBackend,
2171        verify_library: CertificateLibrary,
2172        at: Certificate,
2173    }
2174
2175    impl Station {
2176        fn cam(&mut self, t: f64) -> Vec<u8> {
2177            let request = SNSignRequest {
2178                tbs_message: b"cam".to_vec(),
2179                its_aid: 36,
2180                permissions: vec![],
2181                generation_location: None,
2182            };
2183            self.svc
2184                .try_sign_cam_at(&request, Some(100.0 + t))
2185                .unwrap()
2186                .sec_message
2187        }
2188        fn receive(&mut self, message: &[u8]) -> ReportVerify {
2189            VerifyService::new(&self.backend, &mut self.verify_library, Some(&mut self.svc))
2190                .verify(&SNVerifyRequest {
2191                    message: message.to_vec(),
2192                })
2193                .report
2194        }
2195    }
2196
2197    fn h3(certificate: &Certificate) -> [u8; 3] {
2198        let h8 = certificate.as_hashedid8();
2199        [h8[5], h8[6], h8[7]]
2200    }
2201
2202    /// (signer is a certificate, inlineP2pcdRequest, requestedCertificate digest)
2203    type CamFields = (bool, Option<Vec<[u8; 3]>>, Option<[u8; 8]>);
2204
2205    fn cam_fields(message: &[u8]) -> CamFields {
2206        use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
2207        let sd = signed_data(message);
2208        let header = &sd.tbs_data.header_info;
2209        let inline = header.inline_p2pcd_request.as_ref().map(|r| {
2210            r.0.iter()
2211                .map(|h| [h.0[0], h.0[1], h.0[2]])
2212                .collect::<Vec<_>>()
2213        });
2214        let requested = header.requested_certificate.as_ref().map(|c| {
2215            Certificate::from_asn(EtsiTs103097Certificate(c.clone()), None).as_hashedid8()
2216        });
2217        (
2218            matches!(sd.signer, SignerIdentifier::certificate(_)),
2219            inline,
2220            requested,
2221        )
2222    }
2223
2224    /// ETSI TS 103 097 clause 7.1.1 (certificate in the next CAM)
2225    /// (inlineP2pcdRequest with the unknown digest), CAM_09_BV (timer
2226    /// restarted); the request stops once the AT is learned.
2227    #[test]
2228    fn p2pcd_unknown_at_signer_digest() {
2229        let mut pki = Pki::new();
2230        let (aa1, aa2) = (pki.aa(), pki.aa());
2231        let mut a = pki.station(&aa1, &[&aa2]);
2232        let mut b = pki.station(&aa2, &[&aa1]);
2233        assert!(cam_fields(&a.cam(0.0)).0); // TIME_1
2234        let b_certificate = b.cam(0.0);
2235        let b_digest = b.cam(0.1);
2236        assert!(!cam_fields(&b_digest).0);
2237        assert_eq!(
2238            a.receive(&b_digest),
2239            ReportVerify::SignerCertificateNotFound
2240        );
2241        let (certificate, inline, _) = cam_fields(&a.cam(0.4)); // TIME_3
2242        assert!(certificate); // CAM_08
2243        assert_eq!(inline, Some(vec![h3(&b.at)])); // CAM_10
2244        assert!(!cam_fields(&a.cam(1.3)).0); // CAM_09: < 1 s after TIME_3
2245        assert!(cam_fields(&a.cam(1.45)).0); // about 1 s after TIME_3
2246        assert_eq!(a.receive(&b_certificate), ReportVerify::Success);
2247        assert_eq!(cam_fields(&a.cam(1.5)).1, None);
2248    }
2249
2250    /// ETSI TS 103 097 clause 7.1.1 (A, sha256AndDigest).
2251    #[test]
2252    fn p2pcd_unknown_aa_of_signer_certificate() {
2253        let mut pki = Pki::new();
2254        let (aa1, aa2) = (pki.aa(), pki.aa());
2255        let mut a = pki.station(&aa1, &[]);
2256        let mut b = pki.station(&aa2, &[&aa1]);
2257        assert_eq!(a.receive(&b.cam(0.0)), ReportVerify::InconsistentChain);
2258        assert_eq!(cam_fields(&a.cam(0.3)).1, Some(vec![h3(&aa2.cert)]));
2259    }
2260
2261    /// ETSI TS 103 097 clause 7.1.1.
2262    #[test]
2263    fn p2pcd_request_for_own_at() {
2264        let mut pki = Pki::new();
2265        let (aa1, aa2) = (pki.aa(), pki.aa());
2266        let mut a = pki.station(&aa1, &[&aa2]);
2267        let mut b = pki.station(&aa2, &[&aa1]);
2268        a.cam(0.0);
2269        let b_first = b.cam(0.0);
2270        assert_eq!(a.receive(&b_first), ReportVerify::Success);
2271        let a_digest = a.cam(0.1);
2272        b.receive(&a_digest); // digest unknown to B
2273        let b_request = b.cam(0.15);
2274        assert_eq!(cam_fields(&b_request).1, Some(vec![h3(&a.at)]));
2275        assert_eq!(a.receive(&b_request), ReportVerify::Success);
2276        let sd = signed_data(&a.cam(0.3));
2277        let SignerIdentifier::certificate(certs) = &sd.signer else {
2278            panic!("expected certificate signer")
2279        };
2280        assert_eq!(certs.0[0], a.at.inner.0);
2281    }
2282
2283    /// B, which does not know AA1, asks for it after A's certificate CAM.
2284    fn p2pcd_request_for_aa1(
2285        pki: &mut Pki,
2286        aa1: &OwnCertificate,
2287        aa2: &OwnCertificate,
2288        b_at: f64,
2289    ) -> (Station, Vec<u8>) {
2290        let mut a = pki.station(aa1, &[aa2]);
2291        let mut b = pki.station(aa2, &[]);
2292        let a_first = a.cam(0.0); // TIME_1
2293        assert_eq!(b.receive(&a_first), ReportVerify::InconsistentChain);
2294        let b_request = b.cam(b_at);
2295        assert_eq!(cam_fields(&b_request).1, Some(vec![h3(&aa1.cert)]));
2296        (a, b_request)
2297    }
2298
2299    /// IEEE 1609.2 clause 8.2.4: once the requested AA arrives
2300    /// (requestedCertificate), the requester verifies the CAMs of its ATs. The
2301    /// AA is learned before the chain of the answering CAM is checked.
2302    #[test]
2303    fn p2pcd_requested_aa_is_learned_by_the_requester() {
2304        let mut pki = Pki::new();
2305        let (aa1, aa2) = (pki.aa(), pki.aa());
2306        let mut a = pki.station(&aa1, &[&aa2]);
2307        let mut b = pki.station(&aa2, &[]);
2308        let a_first = a.cam(0.0);
2309        assert_eq!(b.receive(&a_first), ReportVerify::InconsistentChain); // AA1 unknown to B
2310        let b_request = b.cam(0.2);
2311        assert_eq!(a.receive(&b_request), ReportVerify::Success); // B asks for AA1
2312        let answer = a.cam(0.4);
2313        assert_eq!(cam_fields(&answer).2, Some(aa1.cert.as_hashedid8()));
2314        b.receive(&answer);
2315        assert!(b
2316            .verify_library
2317            .known_authorization_authorities
2318            .contains_key(&aa1.cert.as_hashedid8()));
2319        let a_certificate = a.cam(1.2);
2320        assert_eq!(b.receive(&a_certificate), ReportVerify::Success);
2321    }
2322
2323    /// ETSI TS 103 097 clause 7.1.1.
2324    #[test]
2325    fn p2pcd_request_for_issuing_aa() {
2326        let mut pki = Pki::new();
2327        let (aa1, aa2) = (pki.aa(), pki.aa());
2328        let (mut a, b_request) = p2pcd_request_for_aa1(&mut pki, &aa1, &aa2, 0.2);
2329        assert_eq!(a.receive(&b_request), ReportVerify::Success);
2330        let (certificate, _, requested) = cam_fields(&a.cam(0.4));
2331        assert!(!certificate);
2332        assert_eq!(requested, Some(aa1.cert.as_hashedid8()));
2333        assert_eq!(cam_fields(&a.cam(0.5)).2, None);
2334    }
2335
2336    /// ETSI TS 103 097 clause 7.1.1.
2337    #[test]
2338    fn p2pcd_request_for_known_aa_not_issuer() {
2339        let mut pki = Pki::new();
2340        let (aa1, aa2, aa_n) = (pki.aa(), pki.aa(), pki.aa());
2341        let mut a = pki.station(&aa1, &[&aa2, &aa_n]);
2342        a.cam(0.0);
2343        let mut b = pki.station(&aa2, &[&aa1]);
2344        let mut d = pki.station(&aa_n, &[]); // AT issued by AA_N
2345        let d_cam = d.cam(0.0);
2346        b.receive(&d_cam); // B does not know AA_N
2347        let b_request = b.cam(0.2);
2348        assert_eq!(cam_fields(&b_request).1, Some(vec![h3(&aa_n.cert)]));
2349        assert_eq!(a.receive(&b_request), ReportVerify::Success);
2350        let (certificate, _, requested) = cam_fields(&a.cam(0.4));
2351        assert!(!certificate);
2352        assert_eq!(requested, Some(aa_n.cert.as_hashedid8()));
2353    }
2354
2355    /// ETSI TS 103 097 clause 7.1.1.
2356    #[test]
2357    fn p2pcd_request_already_answered_by_another_station() {
2358        let mut pki = Pki::new();
2359        let (aa1, aa2) = (pki.aa(), pki.aa());
2360        let (mut a, b_request) = p2pcd_request_for_aa1(&mut pki, &aa1, &aa2, 0.2);
2361        let mut c = pki.station(&aa2, &[&aa1]);
2362        let c_first = c.cam(0.0);
2363        assert_eq!(a.receive(&c_first), ReportVerify::Success); // A learns C's AT
2364        assert_eq!(a.receive(&b_request), ReportVerify::Success); // TIME_2
2365        c.receive(&b_request);
2366        let c_answer = c.cam(0.25);
2367        assert_eq!(cam_fields(&c_answer).2, Some(aa1.cert.as_hashedid8()));
2368        assert_eq!(a.receive(&c_answer), ReportVerify::Success); // TIME_3
2369        assert_eq!(cam_fields(&a.cam(0.3)).2, None); // TIME_4
2370    }
2371
2372    /// ETSI TS 103 097 clause 7.1.1.
2373    #[test]
2374    fn p2pcd_request_kept_pending_while_signer_is_certificate() {
2375        let mut pki = Pki::new();
2376        let (aa1, aa2) = (pki.aa(), pki.aa());
2377        let (mut a, b_request) = p2pcd_request_for_aa1(&mut pki, &aa1, &aa2, 0.9);
2378        assert_eq!(a.receive(&b_request), ReportVerify::Success); // TIME_2 = 0.9
2379        let (certificate, _, requested) = cam_fields(&a.cam(1.05));
2380        assert!(certificate); // CAM_16
2381        assert_eq!(requested, None);
2382        let (certificate, _, requested) = cam_fields(&a.cam(1.2));
2383        assert!(!certificate); // CAM_17
2384        assert_eq!(requested, Some(aa1.cert.as_hashedid8()));
2385    }
2386
2387    /// IEEE 1609.2 clause 5.2.3.2.2.
2388    #[test]
2389    fn expired_and_not_yet_valid_at() {
2390        for start in [-7200i64, 3600] {
2391            let mut f = Fixture::new(at_tbs(start, AsnDuration::hours(Uint16(1)), None));
2392            assert!(f.try_sign(36, None, &[]).is_err());
2393            assert!(f.try_sign(37, Some(INSIDE), &[]).is_err());
2394        }
2395    }
2396
2397    /// The CAM AT SSP grants emergency (0x02) only: a safety-car request is refused.
2398    #[test]
2399    fn ssp_not_granted() {
2400        let mut f = Fixture::valid();
2401        assert!(f.try_sign(36, None, &[0, 0x02]).is_ok());
2402        assert_eq!(
2403            f.try_sign(36, None, &[0, 0x01]),
2404            Err(SigningError::NoAuthorizationTicket(36))
2405        );
2406    }
2407
2408    fn hex(s: &str) -> Vec<u8> {
2409        (0..s.len())
2410            .step_by(2)
2411            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
2412            .collect()
2413    }
2414
2415    // Frozen vector, also in FlexStack (test_verify_service): a CAM signed by
2416    // Vanetza (commit 3b9a544, IEEE 1609.2-2016 ASN.1 with 2 HeaderInfo
2417    // extension additions) carrying an inlineP2pcdRequest, captured in the
2418    // signed interop matrix (FlexStackBenchmarking/interop), and the Root CA
2419    // and AA of that run. Vanetza encodes the extension presence bitmap with
2420    // 2 bits (02 06 80); this stack's ASN.1 has 4 (02 04 80).
2421    const VANETZA_ROOT: &str = "800300810008810f696e7465726f702d726f6f742d636100000000002b0d1cdd860001010180810102808082c5c5cf6fa9f7e3ccd67d16a5aab17ee1727ebf4ab1ee2f0ce3d90076f2a629318080ed258011549d01048319db4848c0a550c169d17d2a0d7204fe4768064afbbcd7e2c6c2ae5dce3db11cc3ae7f636a888c8cf811470d7c767dbd64083a418c8dea";
2422    const VANETZA_AA: &str = "80030080d3dd2cb18f37f08508810a696e7465726f702d616100000000002b0d1cdd860001010100800104800124818001258180018d818002027e818080835db6d0c1c41584004070f700aa23cb2688273c9a04811e6dfa1c26ce95e1d545808086ad69ddbaad6d2eb2f14ff9c479b51995dc7dc7203f234576dc98324af55adb2e80f61000922868dcaad628afb8fc539ff47196bb1ead45550220f0a3e50775";
2423    const VANETZA_CAM: &str = "0381004003805120500080002d01008000aa05e7e4cd642b6fc60418ab2b97014b2570800000000000000007d10000020200000003c6e50059ca02930d929eee1ffffffc23b7743e0000000000003fe9ed0737feebfff600c00124000290e9aca0f1530206800501011ad738810101800300803c82cf6a9b7294cb108300000000002b0d1cdd860001010480012481040303ffff80012581060502ffffffff00018d0002027e808082b7cd8f1efe5880b4779bf967150bdb36b31cb690da293eea789f377241dcff78808005c8c38854e7b3f7e2ed55fdbbe7dcebe3c3baaf990e8f9cd38074f583e69651093804732abbb13c20432d042d06edf02a7e12fd87ed7fc3c5dfc336182370e080805fd37ee613809ec114e8ac105725784c363164d5928f8c577b94089d81fb6e818c4f30264948f7134f93b06950fad28992206a26474bd57e3a7ff4b70fc8b3e2";
2424
2425    /// IEEE 1609.2 clause 6.3.4: the signature covers the tbsData octets the
2426    /// signer encoded. A CAM from a stack whose ASN.1 has another number of
2427    /// HeaderInfo extension additions verifies over the octets received; any
2428    /// change of those octets is still refused.
2429    #[test]
2430    fn tbs_data_of_another_asn1_version_verified_as_received() {
2431        let backend = EcdsaBackend::new();
2432        let root = Certificate::from_bytes(&hex(VANETZA_ROOT), None);
2433        let aa = Certificate::from_bytes(&hex(VANETZA_AA), Some(root.clone()));
2434        let message = hex(VANETZA_CAM);
2435        let data = decode_ieee1609_dot2_data(&message);
2436        let Ieee1609Dot2Content::signedData(sd) = &data.content else {
2437            panic!("signedData");
2438        };
2439        let received = received_tbs_data(&message, sd).unwrap();
2440        assert_ne!(received, encode_tbs_data(&sd.tbs_data).as_slice());
2441        assert!(received.windows(3).any(|w| w == [0x02, 0x06, 0x80])); // 2-bit bitmap
2442
2443        let mut library =
2444            CertificateLibrary::new(&backend, vec![root.clone()], vec![aa.clone()], vec![]);
2445        let request = SNVerifyRequest {
2446            message: message.clone(),
2447        };
2448        let (confirm, _) = verify_message(&request, &backend, &mut library);
2449        assert_eq!(confirm.report, ReportVerify::Success);
2450        assert_eq!(confirm.its_aid, 36);
2451
2452        // One octet of the CAM payload changed: refused.
2453        let mut altered = message.clone();
2454        altered[60] ^= 0x01;
2455        let mut library = CertificateLibrary::new(&backend, vec![root], vec![aa], vec![]);
2456        let (confirm, _) = verify_message(
2457            &SNVerifyRequest { message: altered },
2458            &backend,
2459            &mut library,
2460        );
2461        assert_ne!(confirm.report, ReportVerify::Success);
2462    }
2463
2464    /// ETSI TS 103 097 clause 7.1.1, ETSI TS 103 097 clause 7.1.2:
2465    /// brainpoolP256r1 / P384r1 signatures produced by python-ecdsa (an
2466    /// independent implementation) over b"flexstack-1609.2".
2467    #[test]
2468    fn brainpool_signatures_from_python_ecdsa() {
2469        use crate::security::security_asn::ieee1609_dot2_base_types::{
2470            EccP384CurvePoint, EcdsaP256Signature, EcdsaP384Signature,
2471        };
2472        let backend = EcdsaBackend::new();
2473        let msg = b"flexstack-1609.2";
2474        let pk = hex("020344a89044af35b4b4d49dcbe0161861c295a732726b86d5369888a46e803e83");
2475        let sig = hex("36e847d6d97af111a3acd434994939200356ffbde0902c0d4e4ea2c79ac9b4316f5869ab9176121909db4ba988f42a75bde36e48bde3719a35837814430b0561");
2476        let key = PublicVerificationKey::ecdsaBrainpoolP256r1(EccP256CurvePoint::compressed_y_0(
2477            pk[1..].to_vec().into(),
2478        ));
2479        let signature = Ieee1609Signature::ecdsaBrainpoolP256r1Signature(EcdsaP256Signature {
2480            r_sig: EccP256CurvePoint::x_only(sig[..32].to_vec().into()),
2481            s_sig: sig[32..].to_vec().into(),
2482        });
2483        assert!(backend.verify_with_pk(msg, &signature, &key));
2484        assert!(!backend.verify_with_pk(b"other", &signature, &key));
2485
2486        let pk = hex("03442e807e24c3afdeb51dad662976233534ed153a186ae7739b379738406f11c3400e7016f241bdab88b4a29d77996f6b");
2487        let sig = hex("53e04860c70ced9288a1ef64bb93e87fc9cdc751f0b40f077e2a9687f192b629fd7dab26ae63c60297e7ef240c6d7a3c4a3126bc4022fca8cde51a748ed391aa1d52aa4afef8fe0d2bb3992175c48dc4b4442992feda4f557e0659f6c2d0f018");
2488        let key = PublicVerificationKey::ecdsaBrainpoolP384r1(EccP384CurvePoint::compressed_y_1(
2489            pk[1..].to_vec().into(),
2490        ));
2491        let signature = Ieee1609Signature::ecdsaBrainpoolP384r1Signature(EcdsaP384Signature {
2492            r_sig: EccP384CurvePoint::x_only(sig[..48].to_vec().into()),
2493            s_sig: sig[48..].to_vec().into(),
2494        });
2495        assert!(backend.verify_with_pk(msg, &signature, &key));
2496        assert!(!backend.verify_with_pk(b"other", &signature, &key));
2497    }
2498
2499    // ── Implicit certificates (IEEE Std 1609.2-2016 clause 5.3.2) ────────
2500
2501    /// IEEE 1609.2 clause 5.3.2.
2502    #[test]
2503    fn signed_cam_with_unknown_implicit_at_accepted() {
2504        let mut f = Fixture::implicit();
2505        let msg = f.sign(36);
2506        let dot2 = decode_ieee1609_dot2_data(&msg);
2507        let Ieee1609Dot2Content::signedData(sd) = &dot2.content else {
2508            panic!("expected signedData")
2509        };
2510        let SignerIdentifier::certificate(certs) = &sd.signer else {
2511            panic!("expected certificate signer")
2512        };
2513        assert!(matches!(
2514            certs.0[0].0.r_type,
2515            crate::security::security_asn::ieee1609_dot2::CertificateType::implicit
2516        ));
2517        assert_eq!(f.verify(msg).report, ReportVerify::Success);
2518    }
2519
2520    /// The reconstructed public key is the public key of the private key d_U.
2521    #[test]
2522    fn reconstructed_key_matches_private_key() {
2523        let f = Fixture::implicit();
2524        let at = f.svc.get_present_at(36).unwrap();
2525        let expected = f.svc.backend.get_public_key_compressed(at.key_id, false);
2526        assert_eq!(at.cert.verification_key(), Some(expected));
2527    }
2528
2529    /// IEEE 1609.2 clause 5.3.2: digest signer once the implicit AT is known.
2530    #[test]
2531    fn digest_signed_cam_with_known_implicit_at_accepted() {
2532        let mut f = Fixture::implicit();
2533        let first = f.sign(36);
2534        let second = f
2535            .svc
2536            .try_sign_request(&SNSignRequest {
2537                tbs_message: b"x".to_vec(),
2538                its_aid: 36,
2539                permissions: vec![],
2540                generation_location: None,
2541            })
2542            .unwrap()
2543            .sec_message;
2544        let mut lib = CertificateLibrary::new(
2545            &f.svc.backend,
2546            vec![f.root.clone()],
2547            vec![f.aa.clone()],
2548            vec![],
2549        );
2550        for msg in [first, second] {
2551            let report =
2552                verify_message(&SNVerifyRequest { message: msg }, &f.svc.backend, &mut lib)
2553                    .0
2554                    .report;
2555            assert_eq!(report, ReportVerify::Success);
2556        }
2557    }
2558
2559    /// IEEE 1609.2 clause 5.3.2: an implicit AT carrying a signature is rejected.
2560    #[test]
2561    fn implicit_at_with_signature_rejected() {
2562        use crate::security::security_asn::ieee1609_dot2_base_types::EcdsaP256Signature;
2563        let mut f = Fixture::implicit();
2564        let bad = mutated(&f.sign(36), |sd| {
2565            if let SignerIdentifier::certificate(certs) = &mut sd.signer {
2566                certs.0[0].0.signature = Some(Ieee1609Signature::ecdsaNistP256Signature(
2567                    EcdsaP256Signature {
2568                        r_sig: EccP256CurvePoint::x_only(vec![1u8; 32].into()),
2569                        s_sig: vec![1u8; 32].into(),
2570                    },
2571                ));
2572            }
2573        });
2574        assert_ne!(f.verify(bad).report, ReportVerify::Success);
2575    }
2576
2577    /// Implicit AT built as ETSI itscertgen does (ecc_recvalue / ecc_reconstruct),
2578    /// independently of FlexStack's issuer: H = SHA-256(SHA-256(tbs) || SHA-256(issuer)),
2579    /// e = H >> 1, r = e*k_eph + d_CA, d_U = e*k_req + r, P_U = (k_eph + k_req)*G.
2580    #[test]
2581    fn etsi_itscertgen_construction() {
2582        use crate::security::certificate::encode_tbs_certificate;
2583        use crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate;
2584        use crate::security::security_asn::ieee1609_dot2::{
2585            Certificate as AsnCertificate, CertificateBase, CertificateType, IssuerIdentifier,
2586        };
2587        use crate::security::security_asn::ieee1609_dot2_base_types::{HashedId8, Uint8};
2588        use p256::elliptic_curve::ff::PrimeField;
2589        use p256::elliptic_curve::sec1::ToEncodedPoint;
2590        let mut backend = EcdsaBackend::new();
2591        let root = OwnCertificate::initialize_self_signed(&mut backend, ca_tbs());
2592        let aa = OwnCertificate::initialize_issued(&mut backend, ca_tbs(), &root);
2593        let scalar = |v: u64| p256::Scalar::from(v);
2594        let (k_req, k_eph) = (scalar(0x1234567890ABCDEF), scalar(0xFEDCBA0987654321));
2595        let p_u = (p256::ProjectivePoint::GENERATOR * (k_req + k_eph)).to_affine();
2596        let enc = p_u.to_encoded_point(true);
2597        let x = enc.x().unwrap().to_vec().into();
2598        let rv = if enc.as_bytes()[0] == 2 {
2599            EccP256CurvePoint::compressed_y_0(x)
2600        } else {
2601            EccP256CurvePoint::compressed_y_1(x)
2602        };
2603        let mut tbs = at_tbs(-60, AsnDuration::hours(Uint16(1)), None);
2604        tbs.verify_key_indicator = VerificationKeyIndicator::reconstructionValue(rv);
2605        let tbs_hash = Sha256::digest(encode_tbs_certificate(&tbs));
2606        let issuer_hash = Sha256::digest(aa.to_canonical().encode());
2607        let h = Sha256::digest([tbs_hash.to_vec(), issuer_hash.to_vec()].concat());
2608        // e = H >> 1 (BN_rshift1)
2609        let mut e_bytes = [0u8; 32];
2610        let mut carry = 0u8;
2611        for (i, b) in h.iter().enumerate() {
2612            e_bytes[i] = (b >> 1) | carry;
2613            carry = b << 7;
2614        }
2615        let e = p256::Scalar::from_repr(e_bytes.into()).unwrap();
2616        let d_ca_bytes: [u8; 32] = backend.export_signing_key(aa.key_id).try_into().unwrap();
2617        let d_ca = p256::Scalar::from_repr(d_ca_bytes.into()).unwrap();
2618        let r = e * k_eph + d_ca;
2619        let d_u = e * k_req + r;
2620        let key_id = backend.import_signing_key(&d_u.to_repr());
2621        let base = CertificateBase::new(
2622            Uint8(3),
2623            CertificateType::implicit,
2624            IssuerIdentifier::sha256AndDigest(HashedId8(FixedOctetString::from(aa.as_hashedid8()))),
2625            tbs,
2626            None,
2627        );
2628        let at = OwnCertificate {
2629            cert: Certificate::from_asn(
2630                EtsiTs103097Certificate(AsnCertificate(base)),
2631                Some(aa.cert.clone()),
2632            ),
2633            key_id,
2634        };
2635        let lib = CertificateLibrary::new(
2636            &backend,
2637            vec![root.cert.clone()],
2638            vec![aa.cert.clone()],
2639            vec![],
2640        );
2641        let mut svc = SignService::new(backend, lib);
2642        svc.add_own_certificate(at);
2643        let mut f = Fixture {
2644            svc,
2645            root: root.cert,
2646            aa: aa.cert.clone(),
2647            aa_owner: aa,
2648        };
2649        let msg = f.sign(36);
2650        assert_eq!(f.verify(msg).report, ReportVerify::Success);
2651    }
2652
2653    /// Cross-stack check: an implicit AT issued and a CAM signed by the
2654    /// Python stack (FlexStack `issue_implicit_certificate`, frozen vector) is
2655    /// accepted by the Rust stack, so both compute the same ECQV hash and key.
2656    #[test]
2657    fn implicit_chain_from_python_stack_accepted() {
2658        let root = Certificate::from_bytes(&hex("8003008100088104726f6f7400000000002b07b1c48600010101a081010200808082287d95660dcbdc278e1b049bd352c887d38af31920b084acb38dc64db192e4ec80809b9b6cccd6007b447e049ac5b21148daa0a7f0d40ab201335873dfa37ab4f18ce1997c1376a50fead8593d332915352bf8f8ff9ec98ac17af3931b37452e000c"), None);
2659        let aa = Certificate::from_bytes(&hex("80030080071385b16a71bf1e088102616100000000002b07b1c48600010101208100808083805d409ad4e781e920ac8455474c86a089adfee49426e8b1b03bcba90e9ad6438080b3ecad670ff3b781f06a3610519e568bf6b105082bb72a1b123aca9f14308151a963aa37f1582199ea8daf867aaaa9ec16cd2a4ed5ab87905bf9b55efd7d895e"), Some(root.clone()));
2660        let msg = hex("038100400380077061796c6f6164400124000290962c1d82d881010100030180a2786da969824bec108300000000002b07b1c486000101028001248104030202000001258183575795eeeb1284dc0e22af76a9596dd98f772821af7c23f32b0ad46beb31182880804ceef7e825c48e9f9c6db614a8895bef7d23335ae3fdaa8d1ab323a4f1640a1cabde90321aba0fcb7940a3eb541f4c30201c38bb363d4621eb4062d884074e2b");
2661        let backend = EcdsaBackend::new();
2662        let mut lib = CertificateLibrary::new(&backend, vec![root], vec![aa], vec![]);
2663        let confirm = verify_message(&SNVerifyRequest { message: msg }, &backend, &mut lib).0;
2664        assert_eq!(confirm.report, ReportVerify::Success);
2665        assert_eq!(confirm.permissions, vec![2u8, 0x02, 0x00]);
2666    }
2667}