Skip to main content

rustflexstack/security/pki_client/
enrolment.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2024 Fundació Privada Internet i Innovació Digital a Catalunya (i2CAT)
3
4//! Enrolment of an ITS-S with an EA (ETSI TS 102 941 V2.2.1 clause 6.2.3.2):
5//! request an Enrolment Credential (EC). The message construction is in
6//! [`super::messages`]; this module sends the request and checks the response.
7
8use std::fmt;
9
10use crate::security::certificate::{Certificate, OwnCertificate};
11use crate::security::ecdsa_backend::{EcdsaBackend, KeyAlgorithm};
12use crate::security::pki_asn::etsi_ts102941_base_types::CertificateSubjectAttributes;
13use crate::security::pki_asn::etsi_ts102941_types_enrolment::EnrolmentResponseCode;
14use crate::security::pki_client::messages::{self, PkiProtocolError, CT_REQUEST};
15use crate::security::pki_client::transport::{
16    post_with_retry, PkiTransport, PkiTransportError, Retry,
17};
18
19/// The enrolment failed: `code` is the EnrolmentResponseCode returned by the EA
20/// (e.g. `deniedrequest`) or the name of the failed check of the response.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct EnrolmentError {
23    pub code: String,
24    pub message: String,
25}
26
27impl EnrolmentError {
28    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
29        Self {
30            code: code.into(),
31            message: message.into(),
32        }
33    }
34}
35
36impl fmt::Display for EnrolmentError {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        write!(f, "{}: {}", self.code, self.message)
39    }
40}
41
42impl std::error::Error for EnrolmentError {}
43
44impl From<PkiProtocolError> for EnrolmentError {
45    fn from(e: PkiProtocolError) -> Self {
46        Self::new(e.code, e.message)
47    }
48}
49
50impl From<PkiTransportError> for EnrolmentError {
51    fn from(e: PkiTransportError) -> Self {
52        Self::new("transport", e.0)
53    }
54}
55
56/// ASN.1 name of an EnrolmentResponseCode (as in the ETSI module).
57pub fn response_code_name(code: EnrolmentResponseCode) -> String {
58    format!("{code:?}")
59}
60
61/// Send an EnrolmentRequestMessage to `ea_url` and return the issued EC. An
62/// initial request (`current_ec` None) uses the canonical identifier `its_id`
63/// and the canonical key `canonical_key`; a re-keying request uses the EC
64/// identifier and key (clause 6.2.3.2.1). With `retry` the same message is
65/// repeated while no response is received (ETSI TS 103 601 V2.1.1 clause 5.1).
66#[allow(clippy::too_many_arguments)]
67pub fn enroll(
68    transport: &dyn PkiTransport,
69    ea_url: &str,
70    ea_cert: &Certificate,
71    backend: &mut EcdsaBackend,
72    its_id: &[u8],
73    canonical_key: usize,
74    current_ec: Option<&OwnCertificate>,
75    attributes: CertificateSubjectAttributes,
76    now: f64,
77    retry: Option<&Retry>,
78) -> Result<OwnCertificate, EnrolmentError> {
79    let request = messages::build_enrolment_request(
80        backend,
81        ea_cert,
82        its_id,
83        canonical_key,
84        current_ec,
85        attributes,
86        now,
87        KeyAlgorithm::NistP256,
88    )?;
89    let response = post_with_retry(transport, ea_url, &request.message, CT_REQUEST, retry)?;
90    let inner = messages::read_enrolment_response(&response, &request, ea_cert, backend)?;
91    if inner.response_code != EnrolmentResponseCode::ok {
92        let code = response_code_name(inner.response_code);
93        return Err(EnrolmentError::new(
94            code.clone(),
95            format!("EA rejected the request: {code}"),
96        ));
97    }
98    let certificate = inner
99        .certificate
100        .ok_or_else(|| EnrolmentError::new("cantparse", "positive response without EC"))?;
101    let ec = Certificate::from_asn(certificate, Some(ea_cert.clone()));
102    if !messages::certifies(&ec, &backend.get_public_key(request.key_id)) {
103        return Err(EnrolmentError::new(
104            "invalidkeys",
105            "the EC does not certify the requested verification key",
106        ));
107    }
108    if !ec.check_corresponding_issuer(ea_cert) {
109        return Err(EnrolmentError::new(
110            "invalidsignature",
111            "the EC is not issued by the EA",
112        ));
113    }
114    Ok(OwnCertificate::new(ec, request.key_id))
115}