ot_certs/
x509.rs

1// Copyright lowRISC contributors (OpenTitan project).
2// Licensed under the Apache License, Version 2.0, see LICENSE for details.
3// SPDX-License-Identifier: Apache-2.0
4
5use anyhow::{Context, Result, bail, ensure};
6use indexmap::IndexMap;
7use num_bigint_dig::BigUint;
8
9use foreign_types::ForeignTypeRef;
10use openssl::asn1::{Asn1IntegerRef, Asn1ObjectRef, Asn1StringRef, Asn1TimeRef};
11use openssl::bn::{BigNum, BigNumContext, BigNumRef};
12use openssl::ec::{EcGroupRef, EcKey};
13use openssl::ecdsa::EcdsaSig;
14use openssl::nid::Nid;
15use openssl::pkey::PKey;
16use openssl::pkey::Public;
17use openssl::x509::{X509, X509NameRef};
18
19use crate::asn1::der;
20use crate::asn1::x509;
21
22use crate::template::{
23    self, AttributeType, EcCurve, EcPublicKeyInfo, EcdsaSignature, KeyUsage, Name, Signature,
24    SubjectPublicKeyInfo, Value,
25};
26
27pub mod extension;
28
29fn curve_from_ecgroup(group: &EcGroupRef) -> Result<EcCurve> {
30    let Some(name) = group.curve_name() else {
31        bail!("only curves with standard names are supported")
32    };
33    match name {
34        Nid::X9_62_PRIME256V1 => Ok(EcCurve::Prime256v1),
35        _ => bail!("curve {:?} is not supported", name),
36    }
37}
38
39impl TryFrom<&Asn1ObjectRef> for AttributeType {
40    type Error = anyhow::Error;
41
42    fn try_from(obj: &Asn1ObjectRef) -> Result<AttributeType, Self::Error> {
43        // Try to match attriutes that OpenSSL does not known about.
44        for attr in [
45            AttributeType::TpmVendor,
46            AttributeType::TpmModel,
47            AttributeType::TpmVersion,
48        ] {
49            if obj.to_owned().as_slice() == attr.oid().to_der().unwrap().as_slice() {
50                return Ok(attr);
51            }
52        }
53        Ok(match obj.nid() {
54            Nid::COUNTRYNAME => AttributeType::Country,
55            Nid::ORGANIZATIONNAME => AttributeType::Organization,
56            Nid::ORGANIZATIONALUNITNAME => AttributeType::OrganizationalUnit,
57            Nid::STATEORPROVINCENAME => AttributeType::State,
58            Nid::COMMONNAME => AttributeType::CommonName,
59            Nid::SERIALNUMBER => AttributeType::SerialNumber,
60            _ => bail!("unrecognized OID {:?}", obj),
61        })
62    }
63}
64
65fn asn1int_to_bn(field: &str, bn: &Asn1IntegerRef) -> Result<Value<BigUint>> {
66    Ok(Value::literal(BigUint::from_bytes_be(
67        &bn.to_bn()
68            .with_context(|| format!("could not extract {} from certificate", field))?
69            .to_vec(),
70    )))
71}
72
73fn asn1bignum_to_bn(bn: &BigNumRef) -> Value<BigUint> {
74    Value::literal(BigUint::from_bytes_be(&bn.to_vec()))
75}
76
77fn asn1str_to_str(field: &str, s: &Asn1StringRef) -> Result<Value<String>> {
78    Ok(Value::literal(s.to_string().with_context(|| {
79        format!("could not extract {} from certificate", field)
80    })?))
81}
82
83fn asn1time_to_string(time: &Asn1TimeRef) -> Result<Value<String>> {
84    // OpenSSL guarantees that an ASN1_TIME is in fact just a typedef for ASN1_STRING
85    // https://www.openssl.org/docs/man1.1.1/man3/ASN1_TIME_to_generalizedtime.html
86    let time_str = time.as_ptr() as *mut openssl_sys::ASN1_STRING;
87    // SAFETY: the above pointer is guaranteed to be valid since `time` is valid reference.
88    let time_type = unsafe { openssl_sys::ASN1_STRING_type(time_str) };
89    // FIXME: we only support GeneralizedTime and openssl_sys does not export the OpenSSL method to
90    // convert to a GeneralizedTime so we just error out.
91    if time_type == openssl_sys::V_ASN1_UTCTIME {
92        bail!("time uses UtcTime but only GeneralizedTime is supported")
93    }
94    if time_type != openssl_sys::V_ASN1_GENERALIZEDTIME {
95        bail!("time uses type {time_type} but only GeneralizedTime is supported")
96    }
97    // SAFETY: the above pointer is guaranteed to be valid since `time` is valid reference.
98    let time_str = unsafe { Asn1StringRef::from_ptr(time_str) }.as_slice();
99    Ok(Value::literal(
100        std::str::from_utf8(time_str)
101            .context("GeneralizedTime is not a valid UTF8 string")?
102            .to_string(),
103    ))
104}
105
106fn asn1name_to_name(field: &str, name: &X509NameRef) -> Result<Name> {
107    // FIXME The OpenSSL representation of names is a bit odd: it flattens
108    // the sequence of sets into a sequence but for each name entry remembers
109    // the index into the sequence. Unfortunately, we need to call X509_NAME_ENTRY_set
110    // to get the index but this is not exported by openssl-sys. For now, and since
111    // multi-valued RDNs are rare, simply assume that all sets have size 1.
112    let mut name_res = Name::new();
113    for entry in name.entries() {
114        let attr = AttributeType::try_from(entry.object())?;
115        let mut res = IndexMap::new();
116        res.insert(attr, asn1str_to_str(field, entry.data())?);
117        name_res.push(res)
118    }
119    Ok(name_res)
120}
121
122fn extract_ec_pubkey(eckey: &EcKey<Public>) -> Result<EcPublicKeyInfo> {
123    let mut ctx = BigNumContext::new().unwrap();
124    let mut x = BigNum::new().unwrap();
125    let mut y = BigNum::new().unwrap();
126    eckey
127        .public_key()
128        .affine_coordinates(eckey.group(), &mut x, &mut y, &mut ctx)
129        .unwrap();
130    Ok(template::EcPublicKeyInfo {
131        curve: curve_from_ecgroup(eckey.group())?,
132        public_key: template::EcPublicKey {
133            x: asn1bignum_to_bn(&x),
134            y: asn1bignum_to_bn(&y),
135        },
136    })
137}
138
139fn extract_pub_key(pubkey: &PKey<Public>) -> Result<SubjectPublicKeyInfo> {
140    match pubkey.id() {
141        openssl::pkey::Id::EC => Ok(SubjectPublicKeyInfo::EcPublicKey(extract_ec_pubkey(
142            &pubkey.ec_key().unwrap(),
143        )?)),
144        id => bail!("key type {:?} not supported by the parser", id),
145    }
146}
147
148fn extract_ecdsa_signature(x509: &X509) -> Result<EcdsaSignature> {
149    let ecdsa_sig = EcdsaSig::from_der(x509.signature().as_slice())
150        .context("cannot extract ECDSA signature from certificate")?;
151    Ok(EcdsaSignature {
152        r: asn1bignum_to_bn(ecdsa_sig.r()),
153        s: asn1bignum_to_bn(ecdsa_sig.s()),
154    })
155}
156
157fn extract_signature(x509: &X509) -> Result<Signature> {
158    match x509.signature_algorithm().object().nid() {
159        Nid::ECDSA_WITH_SHA256 => Ok(Signature::EcdsaWithSha256 {
160            value: Some(extract_ecdsa_signature(x509)?),
161        }),
162        alg => bail!("unsupported signature algorithm {:?}", alg),
163    }
164}
165
166/// Generate a X509 certificate from a pre-computed TBS and signature.
167pub fn generate_certificate_from_tbs(tbs: Vec<u8>, signature: &Signature) -> Result<Vec<u8>> {
168    // Generate certificate.
169    let tbs = Value::Literal(tbs);
170    let cert =
171        der::Der::generate(|builder| x509::X509::push_certificate(builder, &tbs, signature))?;
172    Ok(cert)
173}
174
175/// Generate a X509 certificate from a template that specifies all variables.
176/// If the template does not specify the values of the signature, a signature
177/// with "zero" values will be generated.
178pub fn generate_certificate(tmpl: &template::Template) -> Result<Vec<u8>> {
179    // Generate TBS.
180    let tbs =
181        der::Der::generate(|builder| x509::X509::push_tbs_certificate(builder, &tmpl.certificate))?;
182    let tbs = Value::Literal(tbs);
183    // Generate certificate.
184    let cert = der::Der::generate(|builder| {
185        x509::X509::push_certificate(builder, &tbs, &tmpl.certificate.signature)
186    })?;
187    Ok(cert)
188}
189
190fn get_subject_alt_name(x509: &X509) -> Result<Name> {
191    let Some(names) = x509.subject_alt_names() else {
192        return Ok(Name::default());
193    };
194    // We expect a single general name.
195    let mut iter = names.iter();
196    let Some(general_name) = iter.next() else {
197        return Ok(Name::default());
198    };
199    ensure!(
200        iter.next().is_none(),
201        "only one general name is supported for subject alt names"
202    );
203    let x509_name_ref = general_name
204        .directory_name()
205        .context("only directory names are supported for subject alt names")?;
206    asn1name_to_name("Subject Alternative Names", x509_name_ref)
207}
208
209/// Parse a X509 certificate
210pub fn parse_certificate(cert: &[u8]) -> Result<template::Certificate> {
211    let x509 = X509::from_der(cert).context("could not parse certificate with openssl")?;
212    let raw_extensions =
213        extension::x509_get_extensions(&x509).context("could not parse X509 extensions")?;
214    let mut private_extensions = Vec::new();
215    let mut basic_constraints = None;
216    let mut key_usage: Option<KeyUsage> = None;
217    let mut auth_key_id = None;
218    let mut subj_key_id = None;
219    for ext in raw_extensions {
220        match ext.object.nid() {
221            // Ignore extensions that are standard and handled by openssl.
222            Nid::BASIC_CONSTRAINTS => {
223                ensure!(
224                    basic_constraints.is_none(),
225                    "certificate contains several basic constraints extensions"
226                );
227                basic_constraints = Some(
228                    extension::parse_basic_constraints(&ext)
229                        .context("could not parse X509 basic constraints")?,
230                );
231            }
232            Nid::KEY_USAGE => {
233                key_usage = Some(
234                    extension::parse_key_usage(&ext).context("could not parse X509 key usage")?,
235                );
236            }
237            Nid::AUTHORITY_KEY_IDENTIFIER => {
238                // Although OpenSSL will parse the authority key identifier correctly, it will sometimes
239                // pretend that it doesn't exist if the certificate is unusual (i.e. all key usage bit
240                // set to false) without showing any error. Since this is very confusing, we may as well
241                // parse it ourselves.
242                auth_key_id = Some(Value::Literal(
243                    extension::parse_authority_key_id(&ext)
244                        .context("could not parse authority key identifier")?,
245                ));
246            }
247            Nid::SUBJECT_ALT_NAME => (),
248            Nid::SUBJECT_KEY_IDENTIFIER => {
249                // Same issue as with authority key identifier.
250                subj_key_id = Some(Value::Literal(
251                    extension::parse_subject_key_id(&ext)
252                        .context("could not parse subject key identifier")?,
253                ));
254            }
255            _ => private_extensions
256                .push(extension::parse_extension(&ext).context("could not parse X509 extension")?),
257        }
258    }
259
260    let subject_public_key_info = extract_pub_key(
261        &x509
262            .public_key()
263            .context("the X509 does not have a valid public key!")?,
264    )?;
265    Ok(template::Certificate {
266        serial_number: asn1int_to_bn("serial number", x509.serial_number())?,
267        issuer: asn1name_to_name("issuer", x509.issuer_name())?,
268        subject: asn1name_to_name("subject", x509.subject_name())?,
269        not_before: asn1time_to_string(x509.not_before())
270            .context("cannot parse not_before time")?,
271        not_after: asn1time_to_string(x509.not_after()).context("cannot parse not_after time")?,
272        subject_public_key_info,
273        authority_key_identifier: auth_key_id,
274        subject_key_identifier: subj_key_id,
275        basic_constraints,
276        key_usage,
277        subject_alt_name: get_subject_alt_name(&x509)?,
278        private_extensions,
279        signature: extract_signature(&x509)?,
280    })
281}