Skip to main content

pcs/
root_ca_crl.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 */
7use crate::{io, Error, WriteOptions};
8use crate::{DcapArtifactIssuer, Unverified, VerificationType, Verified};
9use pkix::pem::PEM_CRL;
10use serde::{Deserialize, Serialize};
11use std::borrow::Cow;
12use std::path::PathBuf;
13
14#[cfg(feature = "verify")]
15use {mbedtls::x509::{Certificate, Crl}, std::ops::Deref};
16
17#[derive(Serialize, Deserialize, Clone, Debug)]
18enum CrlType {
19    Pem(String),
20    Der(Vec<u8>),
21}
22
23/// Type that represents the Root CA CRL within the Intel PCS infrastructures.
24#[derive(Serialize, Deserialize, Clone, Debug)]
25pub struct RootCaCrl<V: VerificationType = Verified> {
26    /// The CRL itself in PEM format
27    crl: CrlType,
28    #[serde(skip_serializing)]
29    _type: V,
30}
31
32impl RootCaCrl<Unverified> {
33    pub fn new(crl: &[u8]) -> Result<Self, Error> {
34        let crl = Self {
35            crl: CrlType::Der(Vec::from(crl)),
36            _type: Unverified,
37        };
38        Ok(crl)
39    }
40
41    pub fn new_from_pem(crl_pem: &str) -> Result<Self, Error> {
42        let crl = Self {
43            crl: CrlType::Pem(crl_pem.to_string()),
44            _type: Unverified,
45        };
46        Ok(crl)
47    }
48
49    #[cfg(feature = "verify")]
50    pub fn verify<B: Deref<Target = [u8]>>(
51        self,
52        trusted_root_certs: &[B],
53    ) -> Result<RootCaCrl<Verified>, Error> {
54        use mbedtls::x509::Crl;
55
56        let crl = match &self.crl {
57            CrlType::Pem(pem) => crate::as_mbedtls_crl(pem)?,
58            CrlType::Der(der) => {
59                let mut c = Crl::new();
60                c.push_from_der(der.as_slice()).map_err(|_| Error::InvalidCrlFormat)?;
61                c
62            }
63        };
64
65        let crl_signature = crl.signature().map_err(|e| Error::InvalidCrl(e))?;
66        let crl_tbs = crl.tbs_raw().map_err(|e| Error::InvalidCrl(e))?;
67        let mut hash = [0u8; 32];
68        mbedtls::hash::Md::hash(mbedtls::hash::Type::Sha256, &crl_tbs, &mut hash).unwrap();
69
70        // Since we have no way to find the correct CA using its key identifier/serial,
71        // then we just iterate the root certificates manually. If any of it gives OK
72        // verification, then it is the correct CRL
73        let root_ca_found = trusted_root_certs.iter().find_map(|cert_der| {
74            Certificate::from_der(cert_der).map(|mut cert| {
75                let verify = cert.public_key_mut()
76                    .verify(mbedtls::hash::Type::Sha256, &hash, &crl_signature)
77                    .is_ok();
78
79                if verify {
80                    Some(cert)
81                } else {
82                    None
83                }
84            }).unwrap_or(None)
85        });
86
87        if let Some(_) = root_ca_found {
88            let RootCaCrl { crl, .. } = self;
89            Ok(RootCaCrl::<Verified> {
90                crl,
91                _type: Verified,
92            })
93        } else {
94            Err(Error::IncorrectCA)
95        }
96    }
97
98    pub fn read_from_file(input_dir: &str) -> Result<Self, Error> {
99        let filename = crate::PckCrl::<Unverified>::filename_from_ca(DcapArtifactIssuer::SGXRootCA);
100        let crl: Self = io::read_from_file(input_dir, &filename)?;
101        Ok(crl)
102    }
103}
104
105impl<V: VerificationType> RootCaCrl<V> {
106    pub fn write_to_file(
107        &self,
108        output_dir: &str,
109        option: WriteOptions,
110    ) -> Result<Option<PathBuf>, Error> {
111        let filename = crate::PckCrl::<Unverified>::filename_from_ca(DcapArtifactIssuer::SGXRootCA);
112        io::write_to_file(&self, output_dir, &filename, option)
113    }
114
115    pub fn crl_as_der(&self) -> Result<Vec<u8>, Error> {
116        match &self.crl {
117            CrlType::Pem(pem) => pkix::pem::pem_to_der(&pem, Some(PEM_CRL)).ok_or(Error::InvalidCrlFormat),
118            CrlType::Der(der) => Ok(der.clone()),
119        }
120    }
121
122    pub fn crl_as_pem<'a>(&'a self) -> Cow<'a, String> {
123        match &self.crl {
124            CrlType::Pem(pem) => Cow::Borrowed(pem),
125            CrlType::Der(der) => Cow::Owned(pkix::pem::der_to_pem(der, PEM_CRL)),
126        }
127    }
128}
129
130#[cfg(feature = "verify")]
131impl RootCaCrl<Verified> {
132    pub fn push_to_crl_list(&self, out_crl: &mut Crl) -> Result<(), Error> {
133        use crate::CString;
134        match &self.crl {
135            CrlType::Pem(pem) => {
136                let c = CString::new(pem.as_bytes()).map_err(|_| Error::InvalidCrlFormat)?;
137                out_crl.push_from_pem(c.as_bytes_with_nul()).map_err(|_| Error::InvalidCrlFormat)
138            }
139            CrlType::Der(der) => out_crl.push_from_der(der.as_slice()).map_err(|_| Error::InvalidCrlFormat)
140        }
141    }
142}
143
144#[cfg(test)]
145#[cfg(feature = "verify")]
146mod tests {
147    use tempdir::TempDir;
148    use crate::{Unverified, WriteOptionsBuilder};
149    use super::RootCaCrl;
150
151    #[test]
152    fn root_ca_crl_parse() {
153        let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
154        let root_cas = [&root_ca[..]];
155
156        let crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
157        let root_ca_crl = RootCaCrl::new(crl_der).unwrap();
158
159        let root_ca_crl = root_ca_crl.verify(&root_cas).unwrap();
160
161        let temp_dir = TempDir::new("tempdir").unwrap();
162        let path = temp_dir.path().as_os_str().to_str().unwrap();
163        root_ca_crl.write_to_file(&path, WriteOptionsBuilder::new().build()).unwrap();
164
165        let _ = RootCaCrl::<Unverified>::read_from_file(path).unwrap().verify(&root_cas).unwrap();
166    }
167
168    #[test]
169    fn root_ca_crl_der_conversion() {
170        let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
171        let root_cas = [&root_ca[..]];
172
173        let crl_pem = include_str!("../tests/data/IntelSGXRootCA.crl");
174        let root_ca_crl = RootCaCrl::new_from_pem(crl_pem).unwrap();
175
176        let der = root_ca_crl.crl_as_der().unwrap();
177
178        let recreate_root_ca_crl = RootCaCrl::new(&der).unwrap();
179        let recreated_crl = recreate_root_ca_crl.verify(&root_cas).unwrap();
180
181        let pem_again = recreated_crl.crl_as_pem();
182        let recreate_root_ca_crl = RootCaCrl::new_from_pem(pem_again.as_str()).unwrap();
183        recreate_root_ca_crl.verify(&root_cas).unwrap();
184    }
185}