Skip to main content

rustflexstack/security/pki_client/
messages.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! ITS-S side of the ETSI TS 102 941 V2.2.1 security management messages:
5//! enrolment (clause 6.2.3.2) and authorization (clause 6.2.3.3), with the
6//! official ASN.1 modules ([`crate::security::pki_asn`]).
7//!
8//! The functions build the request messages and read the responses; they do
9//! no I/O. Times are UTC seconds (`now`) so that callers can inject a clock.
10//!
11//! Enrolment request (clause 6.2.3.2.1, Figure 14):
12//! `EtsiTs103097Data-Encrypted` (certRecipInfo of the EA, ECIES) of an
13//! `EtsiTs103097Data-Signed` (signer self with the canonical key, or digest of
14//! the EC) of `EtsiTs102941Data {v1, enrolmentRequest}` whose content is the
15//! `InnerEcRequestSignedForPop` (signer self, new key) of the `InnerEcRequest`.
16//!
17//! Authorization request (clause 6.2.3.3.1, Figures 17 and 18): encrypted to
18//! the AA, the `EtsiTs102941Data {v1, authorizationRequest}` either signed
19//! with the new AT key (proof of possession) or unsecured; the `InnerAtRequest`
20//! carries `encryptedEcSignature` (encrypted to the EA): the
21//! `EtsiTs103097Data-SignedExternalPayload` by the EC over the SHA-256 hash of
22//! the `SharedAtRequest`.
23//!
24//! Responses (clauses 6.2.3.2.2 and 6.2.3.3.2): encrypted with the request's
25//! AES key (pskRecipInfo), signed by the EA / AA (signer digest), with the
26//! leftmost 16 octets of SHA-256 of the request as requestHash.
27
28use std::fmt;
29
30use aes::Aes128;
31use ccm::aead::{Aead, KeyInit};
32use ccm::consts::{U12, U16};
33use ccm::Ccm;
34use hmac::{Hmac, Mac};
35use rand::RngCore;
36use rasn::prelude::*;
37use sha2::{Digest, Sha256};
38
39use crate::security::certificate::{
40    encode_ieee1609_dot2_data, encode_tbs_data, signing_input, Certificate, OwnCertificate,
41};
42use crate::security::ecdsa_backend::{key_uses_sha384, EcdsaBackend, KeyAlgorithm};
43use crate::security::pki_asn::etsi_ts102941_base_types::{
44    CertificateSubjectAttributes, EcSignature, PublicKeys, TS103097V131,
45};
46use crate::security::pki_asn::etsi_ts102941_messages_itss::{
47    EtsiTs102941Data, EtsiTs102941DataContent,
48};
49use crate::security::pki_asn::etsi_ts102941_types_authorization::{
50    InnerAtRequest, InnerAtResponse, SharedAtRequest,
51};
52use crate::security::pki_asn::etsi_ts102941_types_enrolment::{InnerEcRequest, InnerEcResponse};
53use crate::security::pki_asn::{decode, encode};
54use crate::security::security_asn::ieee1609_dot2::{
55    EncryptedData, EncryptedDataEncryptionKey, HashedData, HeaderInfo, Ieee1609Dot2Content,
56    Ieee1609Dot2Data, One28BitCcmCiphertext, PKRecipientInfo, PreSharedKeyRecipientInfo,
57    RecipientInfo, SequenceOfRecipientInfo, SignedData, SignedDataPayload, SignerIdentifier,
58    SymmetricCiphertext, ToBeSignedData,
59};
60use crate::security::security_asn::ieee1609_dot2_base_types::{
61    BasePublicEncryptionKey, EccP256CurvePoint, EciesP256EncryptedKey, HashAlgorithm, HashedId32,
62    HashedId8, Opaque, Psid, PublicVerificationKey, ServiceSpecificPermissions,
63    SymmetricEncryptionKey, Time64, Uint64, Uint8,
64};
65use crate::security::time_service::{ELAPSED_SECONDS, ITS_EPOCH};
66
67/// ITS-AID "secured certificate request" (ETSI TS 102 965).
68pub const PSID_CERT_REQUEST: u64 = 623;
69/// Certificate request SSP (clause B.4): version 1, then the permission bits.
70pub const SSP_VERSION: u8 = 1;
71pub const SSP_ENROLMENT_REQUEST: u8 = 0x80;
72pub const SSP_AUTHORIZATION_REQUEST: u8 = 0x40;
73/// HTTP content types (Annex C).
74pub const CT_REQUEST: &str = "application/x-its-request";
75pub const CT_RESPONSE: &str = "application/x-its-response";
76
77type Aes128Ccm = Ccm<Aes128, U16, U12>;
78
79/// A response cannot be read or does not match the request (`code` names the check).
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct PkiProtocolError {
82    pub code: String,
83    pub message: String,
84}
85
86impl PkiProtocolError {
87    pub fn new(code: &str, message: impl Into<String>) -> Self {
88        Self {
89            code: code.into(),
90            message: message.into(),
91        }
92    }
93}
94
95impl fmt::Display for PkiProtocolError {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(f, "{}: {}", self.code, self.message)
98    }
99}
100
101impl std::error::Error for PkiProtocolError {}
102
103// ─── Time and permissions ───────────────────────────────────────────────────
104
105/// Time32 (TAI seconds since the ITS epoch, IEEE 1609.2 clause 6.4.15).
106pub fn time32(now: f64) -> u32 {
107    (now as i64 - ITS_EPOCH as i64 + ELAPSED_SECONDS as i64) as u32
108}
109
110/// Time64 (TAI microseconds since the ITS epoch), as generationTime.
111pub fn time64(now: f64) -> u64 {
112    ((now - ITS_EPOCH as f64 + ELAPSED_SECONDS as f64) * 1e6).round() as u64
113}
114
115/// Leftmost 16 octets of SHA-256 of the request's EtsiTs103097Data-Encrypted.
116pub fn request_hash(request: &[u8]) -> [u8; 16] {
117    Sha256::digest(request)[..16].try_into().unwrap()
118}
119
120/// The certificate's appPermissions grant ITS-AID 623 with SSP version 1 and
121/// `bit` (clause B.4: 0x80 enrolment request, 0x40 authorization request).
122pub fn ssp_permits(certificate: &Certificate, bit: u8) -> bool {
123    let Some(permissions) = &certificate.tbs().app_permissions else {
124        return false;
125    };
126    for item in &permissions.0 {
127        if u64::try_from(&item.psid.0).ok() != Some(PSID_CERT_REQUEST) {
128            continue;
129        }
130        let value: Vec<u8> = match &item.ssp {
131            Some(ServiceSpecificPermissions::bitmapSsp(b)) => b.0.to_vec(),
132            Some(ServiceSpecificPermissions::opaque(o)) => o.to_vec(),
133            _ => return false,
134        };
135        return value.len() >= 2 && value[0] == SSP_VERSION && value[1] & bit != 0;
136    }
137    false
138}
139
140/// The SSP an EC requests: version 1, enrolment and authorization requests.
141pub fn certificate_ssp() -> ServiceSpecificPermissions {
142    ServiceSpecificPermissions::bitmapSsp(
143        crate::security::security_asn::ieee1609_dot2_base_types::BitmapSsp(
144            vec![
145                SSP_VERSION,
146                SSP_ENROLMENT_REQUEST | SSP_AUTHORIZATION_REQUEST,
147            ]
148            .into(),
149        ),
150    )
151}
152
153// ─── Signing ────────────────────────────────────────────────────────────────
154
155fn header_info(now: f64) -> HeaderInfo {
156    HeaderInfo::new(
157        Psid(Integer::from(PSID_CERT_REQUEST)),
158        Some(Time64(Uint64(time64(now)))),
159        None,
160        None,
161        None,
162        None,
163        None,
164        None,
165        None,
166        None,
167        None,
168    )
169}
170
171/// SignedDataPayload `data` = unsecured EtsiTs103097Data containing `content`.
172pub fn data_payload(content: Vec<u8>) -> SignedDataPayload {
173    SignedDataPayload::new(
174        Some(Ieee1609Dot2Data::new(
175            Uint8(3),
176            Ieee1609Dot2Content::unsecuredData(Opaque(content.into())),
177        )),
178        None,
179        None,
180    )
181}
182
183/// An EtsiTs103097Data-Signed with headerInfo {psid 623, generationTime} only.
184/// The signer is `self` when `signer` is None (signature input with the empty
185/// signer, IEEE 1609.2 clause 5.3.1), else the digest of `signer`.
186pub fn sign(
187    backend: &EcdsaBackend,
188    key_id: usize,
189    payload: SignedDataPayload,
190    now: f64,
191    signer: Option<&Certificate>,
192) -> Ieee1609Dot2Data {
193    let tbs = ToBeSignedData::new(Box::new(payload), header_info(now));
194    let tbs_bytes = encode_tbs_data(&tbs);
195    let sha384 = key_uses_sha384(&backend.get_public_key(key_id));
196    let (signer_id, signer_bytes) = match signer {
197        None => (SignerIdentifier::R_self(()), Vec::new()),
198        Some(c) => (
199            SignerIdentifier::digest(HashedId8(FixedOctetString::from(c.as_hashedid8()))),
200            c.to_canonical().encode().to_vec(),
201        ),
202    };
203    let signature = backend.sign(&signing_input(&tbs_bytes, &signer_bytes, sha384), key_id);
204    let hash_id = if sha384 {
205        HashAlgorithm::sha384
206    } else {
207        HashAlgorithm::sha256
208    };
209    Ieee1609Dot2Data::new(
210        Uint8(3),
211        Ieee1609Dot2Content::signedData(SignedData::new(hash_id, tbs, signer_id, signature)),
212    )
213}
214
215fn signed(data: &Ieee1609Dot2Data) -> Result<&SignedData, PkiProtocolError> {
216    match &data.content {
217        Ieee1609Dot2Content::signedData(sd) => Ok(sd),
218        _ => Err(PkiProtocolError::new(
219            "badcontenttype",
220            "expected signedData",
221        )),
222    }
223}
224
225/// Content of an EtsiTs103097Data-Signed by `signer` (signer digest, psid 623,
226/// generationTime present, no other header, valid signature); errors otherwise.
227pub fn read_signed(
228    data: &Ieee1609Dot2Data,
229    signer: &Certificate,
230    backend: &EcdsaBackend,
231) -> Result<Vec<u8>, PkiProtocolError> {
232    let sd = signed(data)?;
233    let expected =
234        SignerIdentifier::digest(HashedId8(FixedOctetString::from(signer.as_hashedid8())));
235    if sd.signer != expected {
236        return Err(PkiProtocolError::new(
237            "invalidsignature",
238            "response not signed by the expected authority",
239        ));
240    }
241    let header = &sd.tbs_data.header_info;
242    if *header
243        != HeaderInfo::new(
244            header.psid.clone(),
245            header.generation_time.clone(),
246            None,
247            None,
248            None,
249            None,
250            None,
251            None,
252            None,
253            None,
254            None,
255        )
256        || u64::try_from(&header.psid.0).ok() != Some(PSID_CERT_REQUEST)
257        || header.generation_time.is_none()
258    {
259        return Err(PkiProtocolError::new(
260            "badcontenttype",
261            "unexpected headerInfo",
262        ));
263    }
264    let key = signer
265        .verification_key()
266        .ok_or_else(|| PkiProtocolError::new("invalidsignature", "no verification key"))?;
267    let input = signing_input(
268        &encode_tbs_data(&sd.tbs_data),
269        signer.to_canonical().encode(),
270        key_uses_sha384(&key),
271    );
272    if !backend.verify_with_pk(&input, &sd.signature, &key) {
273        return Err(PkiProtocolError::new(
274            "invalidsignature",
275            "response signature does not verify",
276        ));
277    }
278    match sd.tbs_data.payload.data.as_ref().map(|d| &d.content) {
279        Some(Ieee1609Dot2Content::unsecuredData(o)) => Ok(o.0.to_vec()),
280        _ => Err(PkiProtocolError::new(
281            "badcontenttype",
282            "signed payload is not unsecuredData",
283        )),
284    }
285}
286
287// ─── Encryption (IEEE 1609.2 clauses 5.3.5, 5.3.8; TS 103 097 clause 5.3) ───
288
289fn kdf2(shared: &[u8], p1: &[u8], length: usize) -> Vec<u8> {
290    let mut out = Vec::new();
291    let mut counter: u32 = 1;
292    while out.len() < length {
293        let mut h = Sha256::new();
294        h.update(shared);
295        h.update(counter.to_be_bytes());
296        h.update(p1);
297        out.extend_from_slice(&h.finalize());
298        counter += 1;
299    }
300    out.truncate(length);
301    out
302}
303
304fn sec1(point: &EccP256CurvePoint) -> Option<Vec<u8>> {
305    match point {
306        EccP256CurvePoint::compressed_y_0(x) => Some([&[2u8][..], x.as_ref()].concat()),
307        EccP256CurvePoint::compressed_y_1(x) => Some([&[3u8][..], x.as_ref()].concat()),
308        EccP256CurvePoint::uncompressedP256(u) => {
309            Some([&[4u8][..], u.x.as_ref(), u.y.as_ref()].concat())
310        }
311        _ => None,
312    }
313}
314
315fn point(compressed: &[u8]) -> EccP256CurvePoint {
316    let x = compressed[1..33].to_vec().into();
317    if compressed[0] == 2 {
318        EccP256CurvePoint::compressed_y_0(x)
319    } else {
320        EccP256CurvePoint::compressed_y_1(x)
321    }
322}
323
324/// (compressed ephemeral public key, shared x) for a NIST P-256 recipient.
325fn ecdh_p256(recipient: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
326    use p256::elliptic_curve::sec1::ToEncodedPoint;
327    let public = p256::PublicKey::from_sec1_bytes(recipient).ok()?;
328    let ephemeral = p256::SecretKey::random(&mut rand::thread_rng());
329    let shared = p256::ecdh::diffie_hellman(ephemeral.to_nonzero_scalar(), public.as_affine());
330    Some((
331        ephemeral
332            .public_key()
333            .to_encoded_point(true)
334            .as_bytes()
335            .to_vec(),
336        shared.raw_secret_bytes().to_vec(),
337    ))
338}
339
340/// (compressed ephemeral public key, shared x) for a brainpoolP256r1 recipient.
341fn ecdh_bp256(recipient: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
342    use ecdsa_v017::elliptic_curve::point::AffineCoordinates;
343    use ecdsa_v017::elliptic_curve::sec1::ToSec1Point;
344    use ecdsa_v017::elliptic_curve::{PublicKey, SecretKey};
345    type C = bp256::BrainpoolP256r1;
346    let public = PublicKey::<C>::from_sec1_bytes(recipient).ok()?;
347    let ephemeral = loop {
348        let mut bytes = [0u8; 32];
349        rand::thread_rng().fill_bytes(&mut bytes);
350        if let Ok(key) = SecretKey::<C>::from_slice(&bytes) {
351            break key;
352        }
353    };
354    let shared = (public.to_projective() * *ephemeral.to_nonzero_scalar()).to_affine();
355    Some((
356        ephemeral
357            .public_key()
358            .to_sec1_point(true)
359            .as_bytes()
360            .to_vec(),
361        shared.x().to_vec(),
362    ))
363}
364
365/// HashedId8 of the COER SymmetricEncryptionKey {aes128Ccm} holding `key`
366/// (pskRecipInfo, IEEE 1609.2 clause 6.3.34).
367pub fn psk_id(key: &[u8; 16]) -> [u8; 8] {
368    let encoded = encode(&SymmetricEncryptionKey::aes128Ccm(key.to_vec().into()));
369    Sha256::digest(encoded)[24..].try_into().unwrap()
370}
371
372/// EtsiTs103097Data-Encrypted for the encryption key of `certificate`: one
373/// certRecipInfo (its HashedId8), ECIES (fresh ephemeral key, KDF2 with P1 =
374/// SHA-256 of the canonical certificate, MAC1) on the AES-128-CCM key, which
375/// encrypts `plaintext` with a fresh nonce. Returns the data and the AES key.
376pub fn encrypt_to(
377    certificate: &Certificate,
378    plaintext: &[u8],
379) -> Result<(Ieee1609Dot2Data, [u8; 16]), PkiProtocolError> {
380    let key = certificate.tbs().encryption_key.as_ref().ok_or_else(|| {
381        PkiProtocolError::new(
382            "invalidencryptionkey",
383            "recipient certificate has no encryptionKey",
384        )
385    })?;
386    let invalid = || PkiProtocolError::new("invalidencryptionkey", "invalid recipient key");
387    let (brainpool, recipient) = match &key.public_key {
388        BasePublicEncryptionKey::eciesNistP256(p) => (false, sec1(p).ok_or_else(invalid)?),
389        BasePublicEncryptionKey::eciesBrainpoolP256r1(p) => (true, sec1(p).ok_or_else(invalid)?),
390        _ => {
391            return Err(PkiProtocolError::new(
392                "unknownencryptionalgorithm",
393                "unsupported curve",
394            ))
395        }
396    };
397    let (v, shared) = if brainpool {
398        ecdh_bp256(&recipient)
399    } else {
400        ecdh_p256(&recipient)
401    }
402    .ok_or_else(invalid)?;
403    let p1 = Sha256::digest(certificate.to_canonical().encode());
404    let keys = kdf2(&shared, &p1, 48);
405    let mut session_key = [0u8; 16];
406    let mut nonce = [0u8; 12];
407    rand::thread_rng().fill_bytes(&mut session_key);
408    rand::thread_rng().fill_bytes(&mut nonce);
409    let c: Vec<u8> = session_key
410        .iter()
411        .zip(&keys[..16])
412        .map(|(a, b)| a ^ b)
413        .collect();
414    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(&keys[16..]).expect("HMAC key");
415    mac.update(&c);
416    let tag = mac.finalize().into_bytes()[..16].to_vec();
417    let encrypted_key = EciesP256EncryptedKey {
418        v: point(&v),
419        c: c.into(),
420        t: tag.into(),
421    };
422    let enc_key = if brainpool {
423        EncryptedDataEncryptionKey::eciesBrainpoolP256r1(encrypted_key)
424    } else {
425        EncryptedDataEncryptionKey::eciesNistP256(encrypted_key)
426    };
427    let ciphertext = Aes128Ccm::new_from_slice(&session_key)
428        .expect("AES key")
429        .encrypt((&nonce).into(), plaintext)
430        .map_err(|_| PkiProtocolError::new("encryptionfailed", "AES-CCM"))?;
431    let data = Ieee1609Dot2Data::new(
432        Uint8(3),
433        Ieee1609Dot2Content::encryptedData(EncryptedData::new(
434            SequenceOfRecipientInfo(vec![RecipientInfo::certRecipInfo(PKRecipientInfo::new(
435                HashedId8(FixedOctetString::from(certificate.as_hashedid8())),
436                enc_key,
437            ))]),
438            SymmetricCiphertext::aes128ccm(One28BitCcmCiphertext::new(
439                nonce.to_vec().into(),
440                Opaque(ciphertext.into()),
441            )),
442        )),
443    );
444    Ok((data, session_key))
445}
446
447/// Decrypt a response encrypted with the request's AES key (exactly one
448/// pskRecipInfo with [`psk_id`]); returns the decoded inner Ieee1609Dot2Data.
449pub fn decrypt_psk(
450    response: &[u8],
451    session_key: &[u8; 16],
452) -> Result<Ieee1609Dot2Data, PkiProtocolError> {
453    let data: Ieee1609Dot2Data = decode(response).map_err(|e| {
454        PkiProtocolError::new("cantparse", format!("cannot decode the response: {e}"))
455    })?;
456    let Ieee1609Dot2Content::encryptedData(encrypted) = data.content else {
457        return Err(PkiProtocolError::new(
458            "badcontenttype",
459            "expected encryptedData",
460        ));
461    };
462    let expected = vec![RecipientInfo::pskRecipInfo(PreSharedKeyRecipientInfo(
463        HashedId8(FixedOctetString::from(psk_id(session_key))),
464    ))];
465    if encrypted.recipients.0 != expected {
466        return Err(PkiProtocolError::new(
467            "imnottherecipient",
468            "no pskRecipInfo for the request's key",
469        ));
470    }
471    let SymmetricCiphertext::aes128ccm(ciphertext) = encrypted.ciphertext else {
472        return Err(PkiProtocolError::new(
473            "badcontenttype",
474            "expected aes128ccm",
475        ));
476    };
477    let failed = || PkiProtocolError::new("decryptionfailed", "cannot decrypt the response");
478    let nonce: [u8; 12] = ciphertext.nonce.as_ref().try_into().map_err(|_| failed())?;
479    let plaintext = Aes128Ccm::new_from_slice(session_key)
480        .expect("AES key")
481        .decrypt((&nonce).into(), ciphertext.ccm_ciphertext.0.as_ref())
482        .map_err(|_| failed())?;
483    decode(&plaintext).map_err(|_| failed())
484}
485
486// ─── Requests ───────────────────────────────────────────────────────────────
487
488/// A request sent: its encoding, AES key and the new key pair to certify.
489#[derive(Debug, Clone)]
490pub struct PendingRequest {
491    pub message: Vec<u8>,
492    pub session_key: [u8; 16],
493    pub key_id: usize,
494}
495
496impl PendingRequest {
497    /// requestHash the response shall carry.
498    pub fn request_hash(&self) -> [u8; 16] {
499        request_hash(&self.message)
500    }
501}
502
503/// EnrolmentRequestMessage (clause 6.2.3.2.1). Initial request (`current_ec`
504/// None): itsId = canonical identifier `its_id`, outer signer self with the
505/// canonical key `signer_key`. Re-keying: itsId = HashedId8(EC), outer signer
506/// digest(EC) with the EC key. A new verification key pair is generated.
507#[allow(clippy::too_many_arguments)]
508pub fn build_enrolment_request(
509    backend: &mut EcdsaBackend,
510    ea: &Certificate,
511    its_id: &[u8],
512    signer_key: usize,
513    current_ec: Option<&OwnCertificate>,
514    attributes: CertificateSubjectAttributes,
515    now: f64,
516    algorithm: KeyAlgorithm,
517) -> Result<PendingRequest, PkiProtocolError> {
518    let key_id = backend.create_key_with(algorithm);
519    let (its_id, signer_key) = match current_ec {
520        Some(ec) => (ec.as_hashedid8().to_vec(), ec.key_id),
521        None => (its_id.to_vec(), signer_key),
522    };
523    let inner = InnerEcRequest::new(
524        its_id.into(),
525        TS103097V131,
526        PublicKeys::new(backend.get_public_key(key_id), None),
527        attributes,
528    );
529    let pop = sign(backend, key_id, data_payload(encode(&inner)), now, None);
530    let etsi = encode(&EtsiTs102941Data::new(
531        EtsiTs102941DataContent::enrolmentRequest(pop),
532    ));
533    let outer = sign(
534        backend,
535        signer_key,
536        data_payload(etsi),
537        now,
538        current_ec.map(|c| &c.cert),
539    );
540    let (encrypted, session_key) = encrypt_to(ea, &encode_ieee1609_dot2_data(&outer))?;
541    Ok(PendingRequest {
542        message: encode_ieee1609_dot2_data(&encrypted),
543        session_key,
544        key_id,
545    })
546}
547
548fn read_response(
549    response: &[u8],
550    request: &PendingRequest,
551    authority: &Certificate,
552    backend: &EcdsaBackend,
553) -> Result<EtsiTs102941DataContent, PkiProtocolError> {
554    let signed = decrypt_psk(response, &request.session_key)?;
555    let etsi: EtsiTs102941Data = decode(&read_signed(&signed, authority, backend)?)
556        .map_err(|e| PkiProtocolError::new("cantparse", e.to_string()))?;
557    Ok(etsi.content)
558}
559
560/// InnerEcResponse of an EnrolmentResponseMessage (clause 6.2.3.2.2).
561pub fn read_enrolment_response(
562    response: &[u8],
563    request: &PendingRequest,
564    ea: &Certificate,
565    backend: &EcdsaBackend,
566) -> Result<InnerEcResponse, PkiProtocolError> {
567    match read_response(response, request, ea, backend)? {
568        EtsiTs102941DataContent::enrolmentResponse(inner)
569            if inner.request_hash.as_ref() == request.request_hash() =>
570        {
571            Ok(inner)
572        }
573        EtsiTs102941DataContent::enrolmentResponse(_) => Err(PkiProtocolError::new(
574            "badcontenttype",
575            "requestHash does not match the request",
576        )),
577        _ => Err(PkiProtocolError::new(
578            "badcontenttype",
579            "expected enrolmentResponse",
580        )),
581    }
582}
583
584/// keyTag: HMAC-SHA256 with `hmac_key` over the serialization of the
585/// verificationKey and of the encryptionKey (if present), leftmost 128 bits.
586pub fn key_tag(hmac_key: &[u8], public_keys: &PublicKeys) -> [u8; 16] {
587    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(hmac_key).expect("HMAC key");
588    mac.update(&encode(&public_keys.verification_key));
589    if let Some(key) = &public_keys.encryption_key {
590        mac.update(&encode(key));
591    }
592    mac.finalize().into_bytes()[..16].try_into().unwrap()
593}
594
595/// AuthorizationRequestMessage (`pop` false) or
596/// AuthorizationRequestMessageWithPop (clause 6.2.3.3.1), with privacy
597/// (encryptedEcSignature to the EA). A new key pair and hmacKey are generated.
598#[allow(clippy::too_many_arguments)]
599pub fn build_authorization_request(
600    backend: &mut EcdsaBackend,
601    aa: &Certificate,
602    ea: &Certificate,
603    ec_own: &OwnCertificate,
604    attributes: CertificateSubjectAttributes,
605    now: f64,
606    pop: bool,
607    algorithm: KeyAlgorithm,
608) -> Result<PendingRequest, PkiProtocolError> {
609    let key_id = backend.create_key_with(algorithm);
610    let public_keys = PublicKeys::new(backend.get_public_key(key_id), None);
611    let mut hmac_key = [0u8; 32];
612    rand::thread_rng().fill_bytes(&mut hmac_key);
613    let shared = SharedAtRequest::new(
614        HashedId8(FixedOctetString::from(ea.as_hashedid8())),
615        FixedOctetString::from(key_tag(&hmac_key, &public_keys)),
616        TS103097V131,
617        attributes,
618    );
619    let hash: [u8; 32] = Sha256::digest(encode(&shared)).into();
620    let external = SignedDataPayload::new(
621        None,
622        Some(HashedData::sha256HashedData(HashedId32(
623            FixedOctetString::from(hash),
624        ))),
625        None,
626    );
627    let ec_signature = sign(backend, ec_own.key_id, external, now, Some(&ec_own.cert));
628    let (encrypted_signature, _) = encrypt_to(ea, &encode_ieee1609_dot2_data(&ec_signature))?;
629    let inner = InnerAtRequest::new(
630        public_keys,
631        FixedOctetString::from(hmac_key),
632        shared,
633        EcSignature::encryptedEcSignature(encrypted_signature),
634    );
635    let etsi = encode(&EtsiTs102941Data::new(
636        EtsiTs102941DataContent::authorizationRequest(inner),
637    ));
638    let plaintext = if pop {
639        sign(backend, key_id, data_payload(etsi), now, None)
640    } else {
641        Ieee1609Dot2Data::new(
642            Uint8(3),
643            Ieee1609Dot2Content::unsecuredData(Opaque(etsi.into())),
644        )
645    };
646    let (encrypted, session_key) = encrypt_to(aa, &encode_ieee1609_dot2_data(&plaintext))?;
647    Ok(PendingRequest {
648        message: encode_ieee1609_dot2_data(&encrypted),
649        session_key,
650        key_id,
651    })
652}
653
654/// InnerAtResponse of an AuthorizationResponseMessage (clause 6.2.3.3.2).
655pub fn read_authorization_response(
656    response: &[u8],
657    request: &PendingRequest,
658    aa: &Certificate,
659    backend: &EcdsaBackend,
660) -> Result<InnerAtResponse, PkiProtocolError> {
661    match read_response(response, request, aa, backend)? {
662        EtsiTs102941DataContent::authorizationResponse(inner)
663            if inner.request_hash.as_ref() == request.request_hash() =>
664        {
665            Ok(inner)
666        }
667        EtsiTs102941DataContent::authorizationResponse(_) => Err(PkiProtocolError::new(
668            "badcontenttype",
669            "requestHash does not match the request",
670        )),
671        _ => Err(PkiProtocolError::new(
672            "badcontenttype",
673            "expected authorizationResponse",
674        )),
675    }
676}
677
678/// The verification key certified by `certificate` equals `key` (both canonical).
679pub fn certifies(certificate: &Certificate, key: &PublicVerificationKey) -> bool {
680    use crate::security::security_asn::ieee1609_dot2::VerificationKeyIndicator;
681    let mut probe = certificate.base().clone();
682    probe.to_be_signed.verify_key_indicator =
683        VerificationKeyIndicator::verificationKey(key.clone());
684    let ours = Certificate::from_asn(
685        crate::security::security_asn::etsi_ts103097_module::EtsiTs103097Certificate(
686            crate::security::security_asn::ieee1609_dot2::Certificate(probe),
687        ),
688        None,
689    )
690    .to_canonical();
691    ours.tbs().verify_key_indicator == certificate.to_canonical().tbs().verify_key_indicator
692}