Skip to main content

pcs/
pckcrl.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 pkix::pem::PEM_CRL;
8use serde::{Deserialize, Serialize};
9use std::path::PathBuf;
10
11#[cfg(feature = "verify")]
12use {
13    mbedtls::alloc::List as MbedtlsList,
14    mbedtls::x509::Certificate,
15    std::convert::TryFrom,
16    std::ffi::CString,
17    std::ops::Deref,
18};
19
20use crate::io::WriteOptions;
21use crate::io::{self};
22use crate::{DcapArtifactIssuer, Error, Unverified, VerificationType, Verified};
23
24#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
25pub struct PckCrl<V: VerificationType = Verified> {
26    pub(crate) crl: String,
27    ca_chain: Vec<String>,
28    #[serde(skip_serializing)]
29    _type: V,
30}
31
32impl PckCrl<Unverified> {
33    pub fn new(crl: String, ca_chain: Vec<String>) -> Result<PckCrl<Unverified>, Error> {
34        let crl = PckCrl {
35            crl,
36            ca_chain,
37            _type: Unverified,
38        };
39        Ok(crl)
40    }
41
42    #[cfg(feature = "verify")]
43    pub fn verify<B: Deref<Target = [u8]>>(
44        self,
45        trusted_root_certs: &[B],
46    ) -> Result<PckCrl<Verified>, Error> {
47        // Check if ca_chain is a valid chain
48        let (chain, root) = crate::create_cert_chain(&self.ca_chain)?;
49        let chain: MbedtlsList<Certificate> = chain.into_iter().collect();
50        let root = std::iter::once(root).collect();
51        let mut err = String::default();
52        Certificate::verify(&chain, &root, None, Some(&mut err))
53            .map_err(|e| Error::InvalidCrl(e))?;
54
55        // Check if the root in self.ca_chain is in `trusted_root_certs`
56        crate::check_root_ca(trusted_root_certs, &root)?;
57
58        // Check if first entry in CA list signed CRL
59        let crl = crate::as_mbedtls_crl(&self.crl)?;
60        let crl_signature = crl.signature().map_err(|e| Error::InvalidCrl(e))?;
61        let crl_tbs = crl.tbs_raw().map_err(|e| Error::InvalidCrl(e))?;
62        let mut hash = [0u8; 32];
63        mbedtls::hash::Md::hash(mbedtls::hash::Type::Sha256, &crl_tbs, &mut hash).unwrap();
64
65        let pck_ca = self
66            .ca_chain
67            .first()
68            .ok_or(Error::InvalidPck("Pck CRL doesn't have a CA".into()))?;
69        let pck_ca = CString::new(pck_ca.as_bytes()).map_err(|_| Error::InvalidCaFormat)?;
70        let mut pck_ca = Certificate::from_pem(pck_ca.as_bytes_with_nul())
71            .map_err(|_| Error::InvalidCaFormat)?;
72        let pck_ca = pck_ca.public_key_mut();
73        pck_ca
74            .verify(mbedtls::hash::Type::Sha256, &hash, &crl_signature)
75            .map_err(|e| Error::InvalidCrl(e))?;
76
77        // Sanity check on Pck CRL
78        self.ca()?;
79
80        let PckCrl { crl, ca_chain, .. } = self;
81        Ok(PckCrl::<Verified> {
82            crl,
83            ca_chain,
84            _type: Verified,
85        })
86    }
87
88    pub fn read_from_file(input_dir: &str, ca: DcapArtifactIssuer) -> Result<Self, Error> {
89        let filename = Self::filename_from_ca(ca);
90        let crl: Self = io::read_from_file(input_dir, &filename)?;
91        Ok(crl)
92    }
93}
94
95impl<V: VerificationType> PckCrl<V> {
96    pub(crate) fn filename_from_ca(ca: DcapArtifactIssuer) -> String {
97        match ca {
98            DcapArtifactIssuer::PCKProcessorCA => String::from("processor.crl"),
99            DcapArtifactIssuer::PCKPlatformCA => String::from("platform.crl"),
100            DcapArtifactIssuer::SGXRootCA => String::from("root.crl"),
101        }
102    }
103
104    #[cfg(feature = "verify")]
105    pub fn filename(&self) -> Result<String, Error> {
106        Ok(Self::filename_from_ca(self.ca()?))
107    }
108
109    #[cfg(feature = "verify")]
110    pub fn write_to_file(
111        &self,
112        output_dir: &str,
113        option: WriteOptions,
114    ) -> Result<Option<PathBuf>, Error> {
115        let filename = self.filename()?;
116        io::write_to_file(&self, output_dir, &filename, option)
117    }
118
119    pub fn write_to_file_as(
120        &self,
121        output_dir: &str,
122        ca: DcapArtifactIssuer,
123        option: WriteOptions,
124    ) -> Result<Option<PathBuf>, Error> {
125        let filename = Self::filename_from_ca(ca);
126        io::write_to_file(&self, output_dir, &filename, option)
127    }
128
129    pub fn crl_as_pem(&self) -> &String {
130        &self.crl
131    }
132
133    pub fn crl_as_der(&self) -> Result<Vec<u8>, Error> {
134        pkix::pem::pem_to_der(&self.crl, Some(PEM_CRL)).ok_or(Error::InvalidCrlFormat)
135    }
136
137    pub fn certificate_chain(&self) -> &Vec<String> {
138        &self.ca_chain
139    }
140
141    #[cfg(feature = "verify")]
142    pub fn ca(&self) -> Result<DcapArtifactIssuer, Error> {
143        let issuer = crate::as_mbedtls_crl(&self.crl)
144            .and_then(|crl| crl.issuer().map_err(|_| Error::InvalidCrlFormat))?;
145        let issuer = DcapArtifactIssuer::try_from(issuer.as_str())?;
146
147        if let DcapArtifactIssuer::SGXRootCA = issuer {
148            // PCK Crls should be signed by the PCKPlatformCA or PCKProcessorCA
149            return Err(Error::InvalidCrlFormat);
150        }
151        Ok(issuer)
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    #[cfg(all(not(target_env = "sgx"), feature = "verify"))]
158    use {super::PckCrl, crate::DcapArtifactIssuer};
159
160    #[cfg(all(not(target_env = "sgx"), feature = "verify"))]
161    #[test]
162    fn read_pck_crl() {
163        let crl =
164            PckCrl::read_from_file("./tests/data/", DcapArtifactIssuer::PCKProcessorCA).unwrap();
165        assert_eq!(crl.ca().unwrap(), DcapArtifactIssuer::PCKProcessorCA);
166        let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
167        let root_cas = [&root_ca[..]];
168        crl.verify(&root_cas).unwrap();
169    }
170
171    #[cfg(all(not(target_env = "sgx"), feature = "verify"))]
172    #[test]
173    fn serialize_deserialize_pck_crl() {
174        let crl =
175            PckCrl::read_from_file("./tests/data/", DcapArtifactIssuer::PCKProcessorCA).unwrap();
176
177        let serialized_bytes = serde_json::ser::to_vec(&crl).unwrap();
178        let crt_deserialized: PckCrl<crate::Unverified> =
179            serde_json::de::from_slice(&serialized_bytes[..]).unwrap();
180        assert_eq!(crt_deserialized, crl);
181    }
182
183    #[cfg(all(not(target_env = "sgx"), feature = "verify"))]
184    #[test]
185    fn read_platform_pck_crl() {
186        let pckcrl =
187            PckCrl::read_from_file("./tests/data/", DcapArtifactIssuer::PCKPlatformCA).unwrap();
188        let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
189        let root_cas = [&root_ca[..]];
190        pckcrl.clone().verify(&root_cas).unwrap();
191        assert_eq!(pckcrl.ca().unwrap(), DcapArtifactIssuer::PCKPlatformCA);
192    }
193}