Skip to main content

dcap_artifact_retrieval/provisioning_client/
azure.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 */
7
8use pcs::{CpuSvn, EncPpid, PceId, PceIsvsvn, PckCert, QeId, Unverified};
9use rustc_serialize::hex::ToHex;
10use serde::Deserialize;
11use std::time::Duration;
12
13use super::common::PckCertsApiNotSupported;
14use super::intel::{
15    PckCrlApi, QeIdApi, RootCaCrlApi, TcbEvaluationDataNumbersApi, TcbInfoApi, INTEL_BASE_URL,
16};
17use super::{
18    Client, ClientBuilder, Fetcher, PckCertIn, PckCertService, PcsVersion, ProvisioningServiceApi,
19    StatusCode,
20};
21use crate::Error;
22
23/// A Provisioning Certificate client builder for Azure. It is based on the internal logic of the Azure DCAP
24/// provider. Only the PCK certificates are downloaded from Azure. For others Intel is contacted.
25/// This is required because Azure by default provides an older `tcbinfo` with a `next_update`
26/// field in the past (see PROD-5800).
27/// For info on the Azure DCAP provider: <https://github.com/microsoft/Azure-DCAP-Client>
28pub struct AzureProvisioningClientBuilder {
29    api_version: PcsVersion,
30    client_builder: ClientBuilder,
31}
32
33impl AzureProvisioningClientBuilder {
34    pub fn new(api_version: PcsVersion) -> Self {
35        Self {
36            api_version,
37            client_builder: ClientBuilder::new(),
38        }
39    }
40
41    pub fn set_retry_timeout(mut self, retry_timeout: Duration) -> Self {
42        self.client_builder = self.client_builder.set_retry_timeout(retry_timeout);
43        self
44    }
45
46    pub fn build<F: for<'a> Fetcher<'a>>(self, fetcher: F) -> Client<F> {
47        let pck_certs = PckCertsApiNotSupported;
48        let pck_cert = PckCertApi::new(self.api_version.clone());
49        let pck_crl = PckCrlApi::new(self.api_version.clone());
50        let qeid = QeIdApi::new(self.api_version.clone());
51        let sgx_tcbinfo = TcbInfoApi::new(self.api_version.clone());
52        let tdx_tcbinfo = TcbInfoApi::new(self.api_version.clone());
53        let sgx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(INTEL_BASE_URL.into());
54        let tdx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(INTEL_BASE_URL.into());
55        let root_ca_crl = RootCaCrlApi::new();
56
57        self.client_builder.build(
58            pck_certs,
59            pck_cert,
60            pck_crl,
61            qeid,
62            sgx_tcbinfo,
63            tdx_tcbinfo,
64            sgx_evaluation_data_numbers,
65            tdx_evaluation_data_numbers,
66            root_ca_crl,
67            fetcher,
68        )
69    }
70}
71
72pub struct PckCertApi {
73    api_version: PcsVersion,
74}
75
76impl PckCertApi {
77    // Constants from the Azure DCAP client:
78    // (host of primary URL is down)
79    const SECONDARY_CERT_URL: &'static str = "https://global.acccache.azure.net/sgx/certification";
80    const DEFAULT_CLIENT_ID: &'static str = "production_client";
81    const API_VERSION_07_2021: &'static str = "2021-07-22-preview";
82}
83
84impl PckCertApi {
85    pub(crate) fn new(api_version: PcsVersion) -> PckCertApi {
86        PckCertApi { api_version }
87    }
88}
89
90impl<'inp> PckCertService<'inp> for PckCertApi {
91    fn build_input(
92        &'inp self,
93        encrypted_ppid: Option<&'inp EncPpid>,
94        pce_id: &'inp PceId,
95        cpu_svn: &'inp CpuSvn,
96        pce_isvsvn: PceIsvsvn,
97        qe_id: Option<&'inp QeId>,
98    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
99        PckCertIn {
100            encrypted_ppid,
101            pce_id,
102            cpu_svn,
103            pce_isvsvn,
104            qe_id,
105            api_version: self.api_version,
106            api_key: &None,
107        }
108    }
109}
110
111impl<'inp> ProvisioningServiceApi<'inp> for PckCertApi {
112    type Input = PckCertIn<'inp>;
113    type Output = PckCert<Unverified>;
114
115    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
116        // Re-implements `build_pck_cert_url` from Azure's DCAP Client
117        // https://github.com/microsoft/Azure-DCAP-Client/blob/master/src/dcap_provider.cpp#L677
118        fn build_pck_cert_url(
119            pce_id: &PceId,
120            cpu_svn: &CpuSvn,
121            pce_isvsvn: PceIsvsvn,
122            qe_id: &QeId,
123            api_version: PcsVersion,
124        ) -> String {
125            // Constants from the Azure DCAP client:
126            // (host of primary URL is down)
127            let base_url = PckCertApi::SECONDARY_CERT_URL;
128            let version = api_version as u8;
129            let qeid = qe_id.to_hex();
130            let cpusvn = cpu_svn.to_hex();
131            let pcesvn = pce_isvsvn.to_le_bytes().to_hex();
132            let pceid = pce_id.to_le_bytes().to_hex();
133            let clientid = PckCertApi::DEFAULT_CLIENT_ID;
134            let api_version = PckCertApi::API_VERSION_07_2021;
135            format!("{base_url}/v{version}/pckcert?qeid={qeid}&cpusvn={cpusvn}&pcesvn={pcesvn}&pceid={pceid}&clientid={clientid}&api-version={api_version}")
136        }
137
138        let qe_id = input.qe_id.ok_or(Error::NoQeID)?;
139        let url = build_pck_cert_url(
140            input.pce_id,
141            input.cpu_svn,
142            input.pce_isvsvn,
143            qe_id,
144            input.api_version,
145        );
146        Ok((url, Vec::new()))
147    }
148
149    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
150        match &status_code {
151            StatusCode::Ok => Ok(()),
152            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
153            StatusCode::Unauthorized => Err(Error::PCSError(
154                status_code,
155                "Failed to authenticate or authorize the request (check your PCS key)",
156            )),
157            StatusCode::NotFound => Err(Error::PCSError(
158                status_code,
159                "Cannot find the requested certificate",
160            )),
161            StatusCode::InternalServerError => Err(Error::PCSError(
162                status_code,
163                "PCS suffered from an internal server error",
164            )),
165            StatusCode::ServiceUnavailable => Err(Error::PCSError(
166                status_code,
167                "PCS is temporarily unavailable",
168            )),
169            StatusCode::Gone => Err(Error::PCSError(
170                status_code,
171                "Collateral is no longer available",
172            )),
173            _ => Err(Error::PCSError(
174                status_code.clone(),
175                "Unexpected response from PCS server",
176            )),
177        }
178    }
179
180    fn parse_response(
181        &self,
182        response_body: String,
183        _response_headers: Vec<(String, String)>,
184        _api_version: PcsVersion,
185    ) -> Result<PckCert<Unverified>, Error> {
186        #[derive(Deserialize)]
187        struct AzurePckCertResp {
188            #[serde(rename = "pckCert")]
189            pck_cert: String,
190            // Azure funny business: the `sgx-Pck-Certificate-Issuer-Chain` field is percent
191            // encoded. The `pck_cert` field is not.
192            #[serde(rename = "sgx-Pck-Certificate-Issuer-Chain")]
193            cert_chain: String,
194        }
195
196        let AzurePckCertResp {
197            pck_cert,
198            cert_chain,
199        } = serde_json::from_str(&response_body)
200            .map_err(|e| Error::PCSDecodeError(format!("{}", e).into()))?;
201
202        let cert_chain: Vec<String> = percent_encoding::percent_decode_str(&cert_chain)
203            .decode_utf8()
204            .map_err(|e| Error::PCSDecodeError(format!("{}", e).into()))?
205            .split_inclusive("-----END CERTIFICATE-----\n")
206            .map(|c| c.trim().to_string())
207            .collect();
208        Ok(PckCert::new(pck_cert, cert_chain))
209    }
210}
211
212#[cfg(all(test, feature = "reqwest"))]
213mod tests {
214    use assert_matches::assert_matches;
215    use std::convert::TryFrom;
216    use std::path::PathBuf;
217    use std::time::Duration;
218
219    use pcs::{Fmspc, PckID};
220
221    use crate::provisioning_client::{
222        test_helpers, AzureProvisioningClientBuilder, DcapArtifactIssuer, PcsVersion,
223        ProvisioningClient,
224    };
225    use crate::{reqwest_client, Error, StatusCode};
226
227    const PCKID_TEST_FILE: &str = "./tests/data/azure_icelake_pckid.csv";
228
229    const TIME_RETRY_TIMEOUT: Duration = Duration::from_secs(180);
230
231    #[test]
232    pub fn pcks_azure() {
233        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
234            .set_retry_timeout(TIME_RETRY_TIMEOUT)
235            .build(reqwest_client());
236        let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
237        let root_cas = [&root_ca[..]];
238
239        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
240            .unwrap()
241            .iter()
242        {
243            let pck = client
244                .pckcert(
245                    None,
246                    &pckid.pce_id,
247                    &pckid.cpu_svn,
248                    pckid.pce_isvsvn,
249                    Some(&pckid.qe_id),
250                )
251                .unwrap();
252
253            let pck = pck.verify(&root_cas, None).unwrap();
254            assert_eq!(
255                test_helpers::get_cert_subject(&pck.ca_chain().last().unwrap()),
256                "Intel SGX Root CA"
257            );
258            assert_eq!(
259                test_helpers::get_cert_subject(&pck.pck_pem()),
260                "Intel SGX PCK Certificate"
261            );
262
263            let fmspc = pck.fmspc().unwrap();
264            assert!(client.sgx_tcbinfo(&fmspc, None).is_ok());
265        }
266    }
267
268    #[test]
269    pub fn pck_crl() {
270        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
271            .set_retry_timeout(TIME_RETRY_TIMEOUT)
272            .build(reqwest_client());
273        assert!(client.pckcrl(DcapArtifactIssuer::PCKProcessorCA).is_ok());
274        assert!(client.pckcrl(DcapArtifactIssuer::PCKPlatformCA).is_ok());
275    }
276
277    #[test]
278    pub fn qe_identity() {
279        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
280            .set_retry_timeout(TIME_RETRY_TIMEOUT)
281            .build(reqwest_client());
282        assert!(client.qe_identity(None).is_ok());
283    }
284
285    #[test]
286    pub fn gone_artifacts() {
287        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
288            .set_retry_timeout(TIME_RETRY_TIMEOUT)
289            .build(reqwest_client());
290        let fmspc = Fmspc::try_from("90806f000000").unwrap();
291        assert_matches!(
292            client.qe_identity(Some(15)),
293            Err(Error::PCSError(StatusCode::Gone, _))
294        );
295        assert_matches!(
296            client.sgx_tcbinfo(&fmspc, Some(15)),
297            Err(Error::PCSError(StatusCode::Gone, _))
298        );
299    }
300
301    #[test]
302    pub fn test_pckcerts_with_fallback() {
303        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
304            .set_retry_timeout(TIME_RETRY_TIMEOUT)
305            .build(reqwest_client());
306
307        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
308            .unwrap()
309            .iter()
310        {
311            let pckcerts = client.pckcerts_with_fallback(&pckid).unwrap();
312            println!("Found {} PCK certs.", pckcerts.as_pck_certs().len());
313
314            let tcb_info = client
315                .sgx_tcbinfo(&pckcerts.fmspc().unwrap(), None)
316                .unwrap();
317            let tcb_data = tcb_info.data().unwrap();
318
319            let selected = pckcerts
320                .select_pck(&tcb_data, &pckid.cpu_svn, pckid.pce_isvsvn, pckid.pce_id)
321                .unwrap();
322
323            let pck = client
324                .pckcert(
325                    Some(&pckid.enc_ppid),
326                    &pckid.pce_id,
327                    &pckid.cpu_svn,
328                    pckid.pce_isvsvn,
329                    Some(&pckid.qe_id),
330                )
331                .unwrap();
332
333            assert_eq!(
334                format!("{:?}", selected.sgx_extension().unwrap()),
335                format!("{:?}", pck.sgx_extension().unwrap())
336            );
337        }
338    }
339
340    #[test]
341    pub fn sgx_tcb_evaluation_data_numbers() {
342        let client = AzureProvisioningClientBuilder::new(PcsVersion::V4)
343            .set_retry_timeout(TIME_RETRY_TIMEOUT)
344            .build(reqwest_client());
345        assert!(client.sgx_tcb_evaluation_data_numbers().is_ok());
346    }
347}