Skip to main content

dcap_artifact_retrieval/provisioning_client/
intel.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
8//! Interface to the Intel DCAP attestation API.
9//!
10//! Origins:
11//! - <https://api.portal.trustedservices.intel.com/provisioning-certification>
12//! - <https://download.01.org/intel-sgx/dcap-1.1/linux/docs/Intel_SGX_PCK_Certificate_CRL_Spec-1.1.pdf>
13
14use pcs::{
15    CpuSvn, DcapArtifactIssuer, EncPpid, Fmspc, PceId, PceIsvsvn, PckCert, PckCerts, PckCrl,
16    PlatformType, PlatformTypeForTcbInfo, QeId, QeIdentitySigned, RawTcbEvaluationDataNumbers,
17    RootCaCrl, TcbInfo, Unverified,
18};
19use rustc_serialize::hex::ToHex;
20use std::borrow::Cow;
21use std::marker::PhantomData;
22use std::time::Duration;
23
24use super::{common::*, RootCaCrlIn, RootCaCrlService};
25use super::{
26    Client, ClientBuilder, Fetcher, PckCertIn, PckCertService, PckCertsIn, PckCertsService,
27    PckCrlIn, PckCrlService, PcsVersion, ProvisioningServiceApi, QeIdIn, QeIdService, StatusCode,
28    TcbEvaluationDataNumbersIn, TcbEvaluationDataNumbersService, TcbInfoIn, TcbInfoService,
29    WithApiVersion,
30};
31use crate::provisioning_client::PlatformApiTag;
32use crate::Error;
33
34pub(crate) const INTEL_BASE_URL: &'static str = "https://api.trustedservices.intel.com";
35const SUBSCRIPTION_KEY_HEADER: &'static str = "Ocp-Apim-Subscription-Key";
36
37pub struct IntelProvisioningClientBuilder {
38    api_key: Option<String>,
39    api_version: PcsVersion,
40    client_builder: ClientBuilder,
41}
42
43impl IntelProvisioningClientBuilder {
44    pub fn new(api_version: PcsVersion) -> Self {
45        Self {
46            api_version,
47            api_key: None,
48            client_builder: ClientBuilder::new(),
49        }
50    }
51
52    pub fn set_api_key(&mut self, api_key: String) -> &mut Self {
53        self.api_key = Some(api_key);
54        self
55    }
56
57    pub fn set_retry_timeout(mut self, retry_timeout: Duration) -> Self {
58        self.client_builder = self.client_builder.set_retry_timeout(retry_timeout);
59        self
60    }
61
62    pub fn build<F: for<'a> Fetcher<'a>>(self, fetcher: F) -> Client<F> {
63        let pck_certs = PckCertsApi::new(self.api_version.clone(), self.api_key.clone());
64        let pck_cert = PckCertApi::new(self.api_version.clone(), self.api_key.clone());
65        let pck_crl = PckCrlApi::new(self.api_version.clone());
66        let qeid = QeIdApi::new(self.api_version.clone());
67        let sgx_tcbinfo = TcbInfoApi::new(self.api_version.clone());
68        let tdx_tcbinfo = TcbInfoApi::new(self.api_version.clone());
69        let sgx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(INTEL_BASE_URL.into());
70        let tdx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(INTEL_BASE_URL.into());
71        let root_ca_crl = RootCaCrlApi::new();
72
73        self.client_builder.build(
74            pck_certs,
75            pck_cert,
76            pck_crl,
77            qeid,
78            sgx_tcbinfo,
79            tdx_tcbinfo,
80            sgx_evaluation_data_numbers,
81            tdx_evaluation_data_numbers,
82            root_ca_crl,
83            fetcher,
84        )
85    }
86}
87
88pub struct PckCertsApi {
89    api_key: Option<String>,
90    api_version: PcsVersion,
91}
92
93impl PckCertsApi {
94    pub(crate) fn new(api_version: PcsVersion, api_key: Option<String>) -> PckCertsApi {
95        PckCertsApi {
96            api_version,
97            api_key,
98        }
99    }
100}
101
102impl<'inp> PckCertsService<'inp> for PckCertsApi {
103    fn build_input(
104        &'inp self,
105        enc_ppid: &'inp EncPpid,
106        pce_id: PceId,
107    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
108        PckCertsIn {
109            enc_ppid,
110            pce_id,
111            api_key: &self.api_key,
112            api_version: self.api_version.clone(),
113        }
114    }
115}
116
117impl<'inp> PckCertService<'inp> for PckCertApi {
118    fn build_input(
119        &'inp self,
120        encrypted_ppid: Option<&'inp EncPpid>,
121        pce_id: &'inp PceId,
122        cpu_svn: &'inp CpuSvn,
123        pce_isvsvn: PceIsvsvn,
124        qe_id: Option<&'inp QeId>,
125    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
126        PckCertIn {
127            encrypted_ppid,
128            pce_id,
129            cpu_svn,
130            pce_isvsvn,
131            qe_id,
132            api_key: &self.api_key,
133            api_version: self.api_version,
134        }
135    }
136}
137
138/// Implementation of pckcerts
139/// <https://api.portal.trustedservices.intel.com/documentation#pcs-certificates-v4>
140impl<'inp> ProvisioningServiceApi<'inp> for PckCertsApi {
141    type Input = PckCertsIn<'inp>;
142    type Output = PckCerts;
143
144    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
145        let api_version = input.api_version as u8;
146        let encrypted_ppid = input.enc_ppid.to_hex();
147        let pce_id = input.pce_id.to_le_bytes().to_hex();
148        let url = format!(
149            "{}/sgx/certification/v{}/pckcerts?encrypted_ppid={}&pceid={}",
150            INTEL_BASE_URL, api_version, encrypted_ppid, pce_id,
151        );
152        let headers = if let Some(api_key) = &input.api_key {
153            vec![(SUBSCRIPTION_KEY_HEADER.to_owned(), api_key.to_string())]
154        } else {
155            Vec::new()
156        };
157        Ok((url, headers))
158    }
159
160    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
161        match status_code {
162            StatusCode::Ok => Ok(()),
163            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
164            StatusCode::Unauthorized => Err(Error::PCSError(
165                status_code,
166                "Failed to authenticate or authorize the request (check your PCS key)",
167            )),
168            StatusCode::NotFound => Err(Error::PCSError(
169                status_code,
170                "Cannot find the requested certificate",
171            )),
172            StatusCode::TooManyRequests => Err(Error::PCSError(status_code, "Too many requests")),
173            StatusCode::InternalServerError => Err(Error::PCSError(
174                status_code,
175                "PCS suffered from an internal server error",
176            )),
177            StatusCode::ServiceUnavailable => Err(Error::PCSError(
178                status_code,
179                "PCS is temporarily unavailable",
180            )),
181            _ => Err(Error::PCSError(
182                status_code,
183                "Unexpected response from PCS server",
184            )),
185        }
186    }
187
188    fn parse_response(
189        &self,
190        response_body: String,
191        response_headers: Vec<(String, String)>,
192        _api_version: PcsVersion,
193    ) -> Result<Self::Output, Error> {
194        let ca_chain = parse_issuer_header(&response_headers, PCK_CERTIFICATE_ISSUER_CHAIN_HEADER)?;
195        PckCerts::parse(&response_body, ca_chain).map_err(|e| Error::OfflineAttestationError(e))
196    }
197}
198
199pub struct PckCertApi {
200    api_key: Option<String>,
201    api_version: PcsVersion,
202}
203
204impl PckCertApi {
205    pub(crate) fn new(api_version: PcsVersion, api_key: Option<String>) -> PckCertApi {
206        PckCertApi {
207            api_version,
208            api_key,
209        }
210    }
211}
212
213/// Implementation of pckcert
214/// <https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-certificate-v4>
215impl<'inp> ProvisioningServiceApi<'inp> for PckCertApi {
216    type Input = PckCertIn<'inp>;
217    type Output = PckCert<Unverified>;
218
219    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
220        let api_version = input.api_version as u8;
221        let encrypted_ppid = input
222            .encrypted_ppid
223            .ok_or(Error::NoEncPPID)
224            .map(|e_ppid| e_ppid.to_hex())?;
225        let cpusvn = input.cpu_svn.to_hex();
226        let pce_isvsvn = input.pce_isvsvn.to_le_bytes().to_hex();
227        let pce_id = input.pce_id.to_le_bytes().to_hex();
228        let url = format!(
229            "{}/sgx/certification/v{}/pckcert?encrypted_ppid={}&cpusvn={}&pcesvn={}&pceid={}",
230            INTEL_BASE_URL, api_version, encrypted_ppid, cpusvn, pce_isvsvn, pce_id,
231        );
232        let headers = if let Some(api_key) = input.api_key {
233            vec![(SUBSCRIPTION_KEY_HEADER.to_owned(), api_key.to_string())]
234        } else {
235            Vec::new()
236        };
237        Ok((url, headers))
238    }
239
240    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
241        match status_code {
242            StatusCode::Ok => Ok(()),
243            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
244            StatusCode::Unauthorized => Err(Error::PCSError(
245                status_code,
246                "Failed to authenticate or authorize the request (check your PCS key)",
247            )),
248            StatusCode::NotFound => Err(Error::PCSError(
249                status_code,
250                "Cannot find the requested certificate",
251            )),
252            StatusCode::TooManyRequests => Err(Error::PCSError(status_code, "Too many requests")),
253            StatusCode::InternalServerError => Err(Error::PCSError(
254                status_code,
255                "PCS suffered from an internal server error",
256            )),
257            StatusCode::ServiceUnavailable => Err(Error::PCSError(
258                status_code,
259                "PCS is temporarily unavailable",
260            )),
261            _ => Err(Error::PCSError(
262                status_code,
263                "Unexpected response from PCS server",
264            )),
265        }
266    }
267
268    fn parse_response(
269        &self,
270        response_body: String,
271        response_headers: Vec<(String, String)>,
272        _api_version: PcsVersion,
273    ) -> Result<Self::Output, Error> {
274        let ca_chain = parse_issuer_header(&response_headers, PCK_CERTIFICATE_ISSUER_CHAIN_HEADER)?;
275        Ok(PckCert::new(response_body, ca_chain))
276    }
277}
278
279pub struct PckCrlApi {
280    api_version: PcsVersion,
281}
282
283impl PckCrlApi {
284    pub fn new(api_version: PcsVersion) -> Self {
285        PckCrlApi { api_version }
286    }
287}
288
289impl<'inp> PckCrlService<'inp> for PckCrlApi {
290    fn build_input(
291        &'inp self,
292        ca: DcapArtifactIssuer,
293    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
294        PckCrlIn {
295            api_version: self.api_version.clone(),
296            ca,
297        }
298    }
299}
300
301/// Implementation of pckcrl
302/// See: <https://api.portal.trustedservices.intel.com/documentation#pcs-revocation-v4>
303impl<'inp> ProvisioningServiceApi<'inp> for PckCrlApi {
304    type Input = PckCrlIn;
305    type Output = PckCrl<Unverified>;
306
307    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
308        let ca = match input.ca {
309            DcapArtifactIssuer::PCKProcessorCA => "processor",
310            DcapArtifactIssuer::PCKPlatformCA => "platform",
311            DcapArtifactIssuer::SGXRootCA => {
312                return Err(Error::PCSError(
313                    StatusCode::BadRequest,
314                    "Invalid ca parameter",
315                ));
316            }
317        };
318        let url = format!(
319            "{}/sgx/certification/v{}/pckcrl?ca={}&encoding=pem",
320            INTEL_BASE_URL, input.api_version as u8, ca,
321        );
322        Ok((url, Vec::new()))
323    }
324
325    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
326        match &status_code {
327            StatusCode::Ok => Ok(()),
328            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
329            StatusCode::Unauthorized => Err(Error::PCSError(
330                status_code,
331                "Failed to authenticate or authorize the request (check your PCS key)",
332            )),
333            StatusCode::InternalServerError => Err(Error::PCSError(
334                status_code,
335                "PCS suffered from an internal server error",
336            )),
337            StatusCode::ServiceUnavailable => Err(Error::PCSError(
338                status_code,
339                "PCS is temporarily unavailable",
340            )),
341            __ => Err(Error::PCSError(
342                status_code,
343                "Unexpected response from PCS server",
344            )),
345        }
346    }
347
348    fn parse_response(
349        &self,
350        response_body: String,
351        response_headers: Vec<(String, String)>,
352        _api_version: PcsVersion,
353    ) -> Result<Self::Output, Error> {
354        let ca_chain = parse_issuer_header(&response_headers, PCK_CRL_ISSUER_CHAIN_HEADER)?;
355        let crl = PckCrl::new(response_body, ca_chain)?;
356        Ok(crl)
357    }
358}
359
360pub struct TcbInfoApi<T> {
361    api_version: PcsVersion,
362    _type: PhantomData<T>,
363}
364
365impl<T: PlatformType> TcbInfoApi<T> {
366    pub fn new(api_version: PcsVersion) -> Self {
367        TcbInfoApi {
368            api_version,
369            _type: PhantomData,
370        }
371    }
372}
373
374impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> TcbInfoService<'inp, T> for TcbInfoApi<T> {
375    fn build_input(
376        &'inp self,
377        fmspc: &'inp Fmspc,
378        tcb_evaluation_data_number: Option<u16>,
379    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
380        TcbInfoIn {
381            api_version: self.api_version.clone(),
382            fmspc,
383            tcb_evaluation_data_number,
384        }
385    }
386}
387
388// Implementation of Get TCB Info
389// <https://api.portal.trustedservices.intel.com/documentation#pcs-tcb-info-v4>>
390impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> ProvisioningServiceApi<'inp>
391    for TcbInfoApi<T>
392{
393    type Input = TcbInfoIn<'inp>;
394    type Output = TcbInfo<T>;
395
396    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
397        let api_version = input.api_version as u8;
398        let fmspc = input.fmspc.as_bytes().to_hex();
399        let url = if let Some(evaluation_data_number) = input.tcb_evaluation_data_number {
400            format!(
401                "{}/{}/certification/v{}/tcb?fmspc={}&tcbEvaluationDataNumber={}",
402                INTEL_BASE_URL,
403                T::tag(),
404                api_version,
405                fmspc,
406                evaluation_data_number
407            )
408        } else {
409            format!(
410                "{}/{}/certification/v{}/tcb?fmspc={}&update=early",
411                INTEL_BASE_URL,
412                T::tag(),
413                api_version,
414                fmspc,
415            )
416        };
417        Ok((url, Vec::new()))
418    }
419
420    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
421        match &status_code {
422            StatusCode::Ok => Ok(()),
423            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
424            StatusCode::Unauthorized => Err(Error::PCSError(
425                status_code,
426                "Failed to authenticate or authorize the request (check your PCS key)",
427            )),
428            StatusCode::NotFound => Err(Error::PCSError(status_code, "TCB info cannot be found")),
429            StatusCode::Gone => Err(Error::PCSError(status_code, "TCB info no longer available")),
430            StatusCode::InternalServerError => Err(Error::PCSError(
431                status_code,
432                "PCS suffered from an internal server error",
433            )),
434            StatusCode::ServiceUnavailable => Err(Error::PCSError(
435                status_code,
436                "PCS is temporarily unavailable",
437            )),
438            __ => Err(Error::PCSError(
439                status_code,
440                "Unexpected response from PCS server",
441            )),
442        }
443    }
444
445    #[allow(deprecated)]
446    fn parse_response(
447        &self,
448        response_body: String,
449        response_headers: Vec<(String, String)>,
450        api_version: PcsVersion,
451    ) -> Result<Self::Output, Error> {
452        let key = match api_version {
453            PcsVersion::V3 => TCB_INFO_ISSUER_CHAIN_HEADER_V3,
454            PcsVersion::V4 => TCB_INFO_ISSUER_CHAIN_HEADER_V4,
455        };
456        let ca_chain = parse_issuer_header(&response_headers, key)?;
457        let tcb_info = TcbInfo::parse(&response_body, ca_chain)?;
458        Ok(tcb_info)
459    }
460}
461
462pub struct QeIdApi {
463    api_version: PcsVersion,
464}
465
466impl QeIdApi {
467    pub fn new(api_version: PcsVersion) -> Self {
468        QeIdApi { api_version }
469    }
470}
471
472impl<'inp> QeIdService<'inp> for QeIdApi {
473    fn build_input(
474        &'inp self,
475        tcb_evaluation_data_number: Option<u16>,
476    ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
477        QeIdIn {
478            api_version: self.api_version.clone(),
479            tcb_evaluation_data_number,
480        }
481    }
482}
483
484/// Implementation of qe/identity
485/// <https://api.portal.trustedservices.intel.com/documentation#pcs-certificates-v://api.portal.trustedservices.intel.com/documentation#pcs-qe-identity-v4>
486impl<'inp> ProvisioningServiceApi<'inp> for QeIdApi {
487    type Input = QeIdIn;
488    type Output = QeIdentitySigned;
489
490    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
491        let api_version = input.api_version as u8;
492        let url = if let Some(tcb_evaluation_data_number) = input.tcb_evaluation_data_number {
493            format!(
494                "{}/sgx/certification/v{}/qe/identity?tcbEvaluationDataNumber={}",
495                INTEL_BASE_URL, api_version, tcb_evaluation_data_number
496            )
497        } else {
498            format!(
499                "{}/sgx/certification/v{}/qe/identity?update=early",
500                INTEL_BASE_URL, api_version,
501            )
502        };
503        Ok((url, Vec::new()))
504    }
505
506    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
507        match &status_code {
508            StatusCode::Ok => Ok(()),
509            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
510            StatusCode::Unauthorized => Err(Error::PCSError(
511                status_code,
512                "Failed to authenticate or authorize the request (check your PCS key)",
513            )),
514            StatusCode::NotFound => {
515                Err(Error::PCSError(status_code, "QE identity Cannot be found"))
516            }
517            StatusCode::InternalServerError => Err(Error::PCSError(
518                status_code,
519                "PCS suffered from an internal server error",
520            )),
521            StatusCode::ServiceUnavailable => Err(Error::PCSError(
522                status_code,
523                "PCS is temporarily unavailable",
524            )),
525            __ => Err(Error::PCSError(
526                status_code,
527                "Unexpected response from PCS server",
528            )),
529        }
530    }
531
532    fn parse_response(
533        &self,
534        response_body: String,
535        response_headers: Vec<(String, String)>,
536        _api_version: PcsVersion,
537    ) -> Result<Self::Output, Error> {
538        let ca_chain = parse_issuer_header(&response_headers, ENCLAVE_ID_ISSUER_CHAIN_HEADER)?;
539        let id = QeIdentitySigned::parse(&response_body, ca_chain)?;
540        Ok(id)
541    }
542}
543
544pub struct TcbEvaluationDataNumbersApi<T: PlatformTypeForTcbInfo> {
545    base_url: Cow<'static, str>,
546    _platform: PhantomData<T>,
547}
548
549impl<T: PlatformTypeForTcbInfo> TcbEvaluationDataNumbersApi<T> {
550    pub fn new(base_url: Cow<'static, str>) -> Self {
551        TcbEvaluationDataNumbersApi {
552            base_url,
553            _platform: PhantomData,
554        }
555    }
556}
557
558impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> TcbEvaluationDataNumbersService<'inp, T>
559    for TcbEvaluationDataNumbersApi<T>
560{
561    fn build_input(&self) -> <Self as ProvisioningServiceApi<'inp>>::Input {
562        TcbEvaluationDataNumbersIn
563    }
564}
565
566/// Implementation of TCB Evaluation Data Numbers endpoint
567/// <https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-retrieve-tcbevalnumbers-v4>
568impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> ProvisioningServiceApi<'inp>
569    for TcbEvaluationDataNumbersApi<T>
570{
571    type Input = TcbEvaluationDataNumbersIn;
572    type Output = RawTcbEvaluationDataNumbers<T>;
573
574    fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
575        let url = format!(
576            "{}/{}/certification/v{}/tcbevaluationdatanumbers",
577            self.base_url,
578            T::tag(),
579            input.api_version() as u8,
580        );
581        Ok((url, Vec::new()))
582    }
583
584    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
585        match &status_code {
586            StatusCode::Ok => Ok(()),
587            StatusCode::InternalServerError => Err(Error::PCSError(
588                status_code,
589                "PCS suffered from an internal server error",
590            )),
591            StatusCode::ServiceUnavailable => Err(Error::PCSError(
592                status_code,
593                "PCS is temporarily unavailable",
594            )),
595            __ => Err(Error::PCSError(
596                status_code,
597                "Unexpected response from PCS server",
598            )),
599        }
600    }
601
602    fn parse_response(
603        &self,
604        response_body: String,
605        response_headers: Vec<(String, String)>,
606        _api_version: PcsVersion,
607    ) -> Result<Self::Output, Error> {
608        let ca_chain =
609            parse_issuer_header(&response_headers, TCB_EVALUATION_DATA_NUMBERS_ISSUER_CHAIN)?;
610        RawTcbEvaluationDataNumbers::parse(&response_body, ca_chain).map_err(|e| e.into())
611    }
612}
613
614pub struct RootCaCrlApi;
615
616impl RootCaCrlApi {
617    pub fn new() -> Self {
618        RootCaCrlApi
619    }
620}
621
622impl<'inp> RootCaCrlService<'inp> for RootCaCrlApi {
623    fn build_input(&'inp self) -> <Self as ProvisioningServiceApi<'inp>>::Input {
624        RootCaCrlIn
625    }
626}
627
628impl<'inp> ProvisioningServiceApi<'inp> for RootCaCrlApi {
629    type Input = RootCaCrlIn;
630    type Output = RootCaCrl<Unverified>;
631
632    fn build_request(&self, _input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
633        let url = format!("https://certificates.trustedservices.intel.com/IntelSGXRootCA.crl");
634        Ok((url, Vec::new()))
635    }
636
637    fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
638        match &status_code {
639            StatusCode::Ok => Ok(()),
640            StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
641            StatusCode::Unauthorized => Err(Error::PCSError(
642                status_code,
643                "Failed to authenticate or authorize the request.",
644            )),
645            StatusCode::NotFound => {
646                Err(Error::PCSError(status_code, "Root CA CRL cannot be found"))
647            }
648            StatusCode::InternalServerError => Err(Error::PCSError(
649                status_code,
650                "PCS suffered from an internal server error",
651            )),
652            StatusCode::ServiceUnavailable => Err(Error::PCSError(
653                status_code,
654                "PCS is temporarily unavailable",
655            )),
656            __ => Err(Error::PCSError(
657                status_code,
658                "Unexpected response from PCS server",
659            )),
660        }
661    }
662
663    fn parse_response(
664        &self,
665        response_body: String,
666        _response_headers: Vec<(String, String)>,
667        _api_version: PcsVersion,
668    ) -> Result<Self::Output, Error> {
669        RootCaCrl::new_from_pem(&response_body)
670            .map_err(|e| Error::ReadResponseError(Cow::Owned(e.to_string().into())))
671    }
672}
673
674#[cfg(all(test, feature = "reqwest"))]
675mod tests {
676    use assert_matches::assert_matches;
677    use std::convert::TryFrom;
678    use std::hash::Hash;
679    use std::hash::Hasher;
680    use std::path::PathBuf;
681    use std::time::Duration;
682
683    use pcs::platform;
684    use pcs::PlatformTypeForTcbInfo;
685    use pcs::{
686        DcapArtifactIssuer, EnclaveIdentity, Fmspc, PckID, RawTcbEvaluationDataNumbers,
687        WriteOptionsBuilder,
688    };
689
690    use crate::provisioning_client::{
691        test_helpers, IntelProvisioningClientBuilder, PcsVersion, ProvisioningClient,
692        ProvisioningClientFuncSelector,
693    };
694    use crate::{reqwest_client, Error, StatusCode};
695    use std::hash::DefaultHasher;
696
697    const PCKID_TEST_FILE: &str = "./tests/data/pckid_retrieval.csv";
698    const OUTPUT_TEST_DIR: &str = "./tests/data/";
699    const TIME_RETRY_TIMEOUT: Duration = Duration::from_secs(180);
700
701    #[test]
702    pub fn pcks() {
703        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
704            .set_retry_timeout(TIME_RETRY_TIMEOUT);
705
706        let client = intel_builder.build(reqwest_client());
707
708        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
709            .unwrap()
710            .iter()
711        {
712            let pcks = client
713                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
714                .unwrap();
715            assert_eq!(
716                test_helpers::get_cert_subject(pcks.ca_chain().last().unwrap()),
717                "Intel SGX Root CA"
718            );
719            pcks.fmspc().unwrap();
720            pcks.write_to_file(
721                OUTPUT_TEST_DIR,
722                pckid.qe_id.as_slice(),
723                WriteOptionsBuilder::new().build(),
724            )
725            .unwrap();
726        }
727    }
728
729    #[test]
730    pub fn pcks_cached() {
731        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
732            .set_retry_timeout(TIME_RETRY_TIMEOUT);
733
734        let client = intel_builder.build(reqwest_client());
735
736        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
737            .unwrap()
738            .iter()
739        {
740            let pcks = client
741                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
742                .unwrap();
743
744            // The cache should be populated after initial service call
745            {
746                let mut cache = client.pckcerts_service.cache.lock().unwrap();
747
748                assert!(cache.len() > 0);
749
750                let (cached_pcks, _) = {
751                    let mut hasher = DefaultHasher::new();
752                    let input = client
753                        .pckcerts_service
754                        .pcs_service()
755                        .build_input(&pckid.enc_ppid, pckid.pce_id.clone());
756                    input.hash(&mut hasher);
757
758                    cache
759                        .get_mut(&hasher.finish())
760                        .expect("Can't find key in cache")
761                        .to_owned()
762                };
763
764                assert_eq!(pcks.fmspc().unwrap(), cached_pcks.fmspc().unwrap());
765                assert_eq!(pcks, cached_pcks);
766            }
767
768            // Second service call should return value from cache
769            let pcks_from_service = client
770                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
771                .unwrap();
772
773            assert_eq!(pcks, pcks_from_service);
774            assert_eq!(pcks.fmspc().unwrap(), pcks_from_service.fmspc().unwrap());
775        }
776    }
777
778    #[test]
779    pub fn pck() {
780        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
781            .set_retry_timeout(TIME_RETRY_TIMEOUT);
782
783        let client = intel_builder.build(reqwest_client());
784        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
785            .unwrap()
786            .iter()
787        {
788            let pck = client
789                .pckcert(
790                    Some(&pckid.enc_ppid),
791                    &pckid.pce_id,
792                    &pckid.cpu_svn,
793                    pckid.pce_isvsvn,
794                    None,
795                )
796                .unwrap();
797            assert_eq!(
798                test_helpers::get_cert_subject(pck.ca_chain().last().unwrap()),
799                "Intel SGX Root CA"
800            );
801        }
802    }
803
804    #[test]
805    pub fn pck_cached() {
806        let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
807        let root_cas = [&root_ca[..]];
808        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
809            .set_retry_timeout(TIME_RETRY_TIMEOUT);
810
811        let client = intel_builder.build(reqwest_client());
812        let crl_processor = client
813            .pckcrl(DcapArtifactIssuer::PCKProcessorCA)
814            .unwrap()
815            .crl_as_pem()
816            .to_owned();
817        let crl_platform = client
818            .pckcrl(DcapArtifactIssuer::PCKPlatformCA)
819            .unwrap()
820            .crl_as_pem()
821            .to_owned();
822        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
823            .unwrap()
824            .iter()
825        {
826            let pck = client
827                .pckcert(
828                    Some(&pckid.enc_ppid),
829                    &pckid.pce_id,
830                    &pckid.cpu_svn,
831                    pckid.pce_isvsvn,
832                    None,
833                )
834                .unwrap();
835            let pck = pck
836                .clone()
837                .verify(&root_cas, Some(&crl_processor))
838                .or(pck.clone().verify(&root_cas, Some(&crl_platform)))
839                .unwrap();
840
841            // The cache should be populated after initial service call
842            {
843                let mut cache = client.pckcert_service.cache.lock().unwrap();
844
845                assert!(cache.len() > 0);
846
847                let (cached_pck, _) = {
848                    let mut hasher = DefaultHasher::new();
849                    let input = client.pckcert_service.pcs_service().build_input(
850                        Some(&pckid.enc_ppid),
851                        &pckid.pce_id,
852                        &pckid.cpu_svn,
853                        pckid.pce_isvsvn,
854                        None,
855                    );
856                    input.hash(&mut hasher);
857
858                    cache
859                        .get_mut(&hasher.finish())
860                        .expect("Can't find key in cache")
861                        .to_owned()
862                };
863
864                assert_eq!(
865                    pck.fmspc().unwrap(),
866                    cached_pck
867                        .clone()
868                        .verify(&root_cas, None)
869                        .unwrap()
870                        .fmspc()
871                        .unwrap()
872                );
873                assert_eq!(pck.ca_chain(), cached_pck.ca_chain());
874            }
875
876            // Second service call should return value from cache
877            let pck_from_service = client
878                .pckcert(
879                    Some(&pckid.enc_ppid),
880                    &pckid.pce_id,
881                    &pckid.cpu_svn,
882                    pckid.pce_isvsvn,
883                    None,
884                )
885                .unwrap();
886
887            assert_eq!(
888                pck.fmspc().unwrap(),
889                pck_from_service
890                    .clone()
891                    .verify(&root_cas, None)
892                    .unwrap()
893                    .fmspc()
894                    .unwrap()
895            );
896            assert_eq!(pck.ca_chain(), pck_from_service.ca_chain());
897        }
898    }
899
900    #[test]
901    pub fn tcb_info() {
902        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
903            .set_retry_timeout(TIME_RETRY_TIMEOUT);
904
905        let client = intel_builder.build(reqwest_client());
906        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
907            .unwrap()
908            .iter()
909        {
910            let pckcerts = client
911                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
912                .unwrap();
913            assert!(client
914                .sgx_tcbinfo(&pckcerts.fmspc().unwrap(), None)
915                .and_then(|tcb| {
916                    Ok(tcb
917                        .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
918                        .unwrap())
919                })
920                .is_ok());
921        }
922    }
923
924    #[test]
925    pub fn tcb_info_tdx() {
926        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
927            .set_retry_timeout(TIME_RETRY_TIMEOUT);
928        let client = intel_builder.build(reqwest_client());
929        let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
930        let root_cas = [&root_ca[..]];
931
932        // List of knowns FMSPCS that has valid TDX TCB
933        let fmspcs = [
934            Fmspc::try_from("00a06d080000").unwrap(),
935            Fmspc::try_from("70a06d070000").unwrap(),
936            Fmspc::try_from("00a06e050000").unwrap(),
937            Fmspc::try_from("50806f000000").unwrap(),
938            Fmspc::try_from("20a06e050000").unwrap(),
939            Fmspc::try_from("10a06f010000").unwrap(),
940            Fmspc::try_from("b0c06f000000").unwrap(),
941            Fmspc::try_from("20a06f000000").unwrap(),
942            Fmspc::try_from("60a06f000000").unwrap(),
943            Fmspc::try_from("c0806f000000").unwrap(),
944            Fmspc::try_from("20a06d080000").unwrap(),
945            Fmspc::try_from("10a06d000000").unwrap(),
946            Fmspc::try_from("00806f050000").unwrap(),
947            Fmspc::try_from("90c06f000000").unwrap(),
948        ];
949
950        for item in fmspcs.iter() {
951            let tdx_tcbinfo = client.tdx_tcbinfo(&item, None);
952            println!("FMSPC: {} => {}", item.to_string(), tdx_tcbinfo.is_ok());
953            assert!(tdx_tcbinfo.is_ok());
954
955            let _ = tdx_tcbinfo.unwrap().verify(&root_cas, 2).unwrap();
956        }
957    }
958
959    #[test]
960    pub fn tcb_info_with_evaluation_data_number() {
961        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
962            .set_retry_timeout(TIME_RETRY_TIMEOUT);
963        let client = intel_builder.build(reqwest_client());
964        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
965            .unwrap()
966            .iter()
967        {
968            let pckcerts = client
969                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
970                .unwrap();
971            let fmspc = pckcerts.fmspc().unwrap();
972
973            let evaluation_data_numbers = client
974                .sgx_tcb_evaluation_data_numbers()
975                .unwrap()
976                .evaluation_data_numbers()
977                .unwrap();
978
979            for number in evaluation_data_numbers.numbers() {
980                let tcb = match client.sgx_tcbinfo(&fmspc, Some(number.number())) {
981                    Ok(tcb) => tcb,
982                    // API query with update="standard" will return QE Identity with TCB Evaluation Data Number M.
983                    // A 410 Gone response is returned when the inputted TCB Evaluation Data Number is < M,
984                    // so we ignore these TCB Evaluation Data Numbers.
985                    Err(super::Error::PCSError(status_code, _))
986                        if status_code == super::StatusCode::Gone =>
987                    {
988                        continue
989                    }
990                    res @ Err(_) => res.unwrap(),
991                };
992                tcb.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
993                    .unwrap();
994            }
995        }
996    }
997
998    #[test]
999    pub fn tcb_info_cached() {
1000        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1001            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1002
1003        let client = intel_builder.build(reqwest_client());
1004        for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
1005            .unwrap()
1006            .iter()
1007        {
1008            let pckcerts = client
1009                .pckcerts(&pckid.enc_ppid, pckid.pce_id.clone())
1010                .unwrap();
1011            let fmspc = pckcerts.fmspc().unwrap();
1012            let tcb_info = client.sgx_tcbinfo(&fmspc, None).unwrap();
1013
1014            // The cache should be populated after initial service call
1015            {
1016                let mut cache = client.sgx_tcbinfo_service.cache.lock().unwrap();
1017
1018                assert!(cache.len() > 0);
1019
1020                let (cached_tcb_info, _) = {
1021                    let mut hasher = DefaultHasher::new();
1022                    let input = client
1023                        .sgx_tcbinfo_service
1024                        .pcs_service()
1025                        .build_input(&fmspc, None);
1026                    input.hash(&mut hasher);
1027
1028                    cache
1029                        .get_mut(&hasher.finish())
1030                        .expect("Can't find key in cache")
1031                        .to_owned()
1032                };
1033
1034                assert_eq!(tcb_info, cached_tcb_info);
1035            }
1036
1037            // Second service call should return value from cache
1038            let tcb_info_from_service = client.sgx_tcbinfo(&fmspc, None).unwrap();
1039
1040            assert_eq!(tcb_info, tcb_info_from_service);
1041        }
1042    }
1043
1044    #[test]
1045    pub fn pckcrl() {
1046        for ca in [
1047            DcapArtifactIssuer::PCKProcessorCA,
1048            DcapArtifactIssuer::PCKPlatformCA,
1049        ] {
1050            let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1051                .set_retry_timeout(TIME_RETRY_TIMEOUT);
1052
1053            let client = intel_builder.build(reqwest_client());
1054            assert!(client
1055                .pckcrl(ca)
1056                .and_then(|crl| {
1057                    Ok(crl
1058                        .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
1059                        .unwrap())
1060                })
1061                .is_ok());
1062        }
1063    }
1064
1065    #[test]
1066    pub fn pckcrl_cached() {
1067        for ca in [
1068            DcapArtifactIssuer::PCKProcessorCA,
1069            DcapArtifactIssuer::PCKPlatformCA,
1070        ] {
1071            let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1072                .set_retry_timeout(TIME_RETRY_TIMEOUT);
1073
1074            let client = intel_builder.build(reqwest_client());
1075            let pckcrl = client.pckcrl(ca).unwrap();
1076
1077            // The cache should be populated after initial service call
1078            {
1079                let mut cache = client.pckcrl_service.cache.lock().unwrap();
1080
1081                assert!(cache.len() > 0);
1082
1083                let (cached_pckcrl, _) = {
1084                    let mut hasher = DefaultHasher::new();
1085                    let input = client.pckcrl_service.pcs_service().build_input(ca);
1086                    input.hash(&mut hasher);
1087
1088                    cache
1089                        .get_mut(&hasher.finish())
1090                        .expect("Can't find key in cache")
1091                        .to_owned()
1092                };
1093
1094                assert_eq!(pckcrl, cached_pckcrl);
1095            }
1096
1097            // Second service call should return value from cache
1098            let pckcrl_from_service = client.pckcrl(ca).unwrap();
1099
1100            assert_eq!(pckcrl, pckcrl_from_service);
1101        }
1102    }
1103
1104    #[test]
1105    pub fn qe_identity() {
1106        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1107            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1108
1109        let client = intel_builder.build(reqwest_client());
1110        let qe_id = client.qe_identity(None).unwrap();
1111        assert!(qe_id
1112            .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
1113            .is_ok());
1114    }
1115
1116    #[test]
1117    pub fn qe_identity_cached() {
1118        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1119            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1120
1121        let client = intel_builder.build(reqwest_client());
1122        let qe_id = client.qe_identity(None).unwrap();
1123
1124        // The cache should be populated after initial service call
1125        {
1126            let mut cache = client.qeid_service.cache.lock().unwrap();
1127
1128            assert!(cache.len() > 0);
1129
1130            let (cached_qeid, _) = {
1131                let mut hasher = DefaultHasher::new();
1132                let input = client.qeid_service.pcs_service().build_input(None);
1133                input.hash(&mut hasher);
1134
1135                cache
1136                    .get_mut(&hasher.finish())
1137                    .expect("Can't find key in cache")
1138                    .to_owned()
1139            };
1140
1141            assert_eq!(qe_id, cached_qeid);
1142        }
1143
1144        // Second service call should return value from cache
1145        let qeid_from_service = client.qe_identity(None).unwrap();
1146
1147        assert_eq!(qe_id, qeid_from_service);
1148    }
1149
1150    #[test]
1151    pub fn gone_artifacts() {
1152        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1153            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1154        let client = intel_builder.build(reqwest_client());
1155        let fmspc = Fmspc::try_from("90806f000000").unwrap();
1156        assert_matches!(
1157            client.qe_identity(Some(15)),
1158            Err(Error::PCSError(StatusCode::Gone, _))
1159        );
1160        assert_matches!(
1161            client.sgx_tcbinfo(&fmspc, Some(15)),
1162            Err(Error::PCSError(StatusCode::Gone, _))
1163        );
1164    }
1165
1166    fn tcb_evaluation_data_numbers_test_base<T: PartialEq>()
1167    where
1168        T: PlatformTypeForTcbInfo + ProvisioningClientFuncSelector + std::fmt::Debug,
1169    {
1170        let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
1171        let root_cas = [&root_ca[..]];
1172        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1173            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1174        let client = intel_builder.build(reqwest_client());
1175        let eval_numbers = T::get_tcb_evaluation_data_numbers(&client).unwrap();
1176
1177        let eval_numbers2 = serde_json::ser::to_vec(&eval_numbers)
1178            .and_then(|v| serde_json::from_slice::<RawTcbEvaluationDataNumbers<T>>(&v))
1179            .unwrap();
1180        assert_eq!(eval_numbers, eval_numbers2);
1181
1182        let fmspc = Fmspc::try_from("50806f000000").unwrap();
1183        let eval_numbers = eval_numbers.verify(&root_cas).unwrap();
1184        for number in eval_numbers.numbers().map(|n| n.number()) {
1185            let qe_identity = match client.qe_identity(Some(number)) {
1186                Ok(id) => id,
1187                // API query with update="standard" will return QE Identity with TCB Evaluation Data Number M.
1188                // A 410 Gone response is returned when the inputted TCB Evaluation Data Number is < M,
1189                // so we ignore these TCB Evaluation Data Numbers.
1190                Err(super::Error::PCSError(status_code, _))
1191                    if status_code == super::StatusCode::Gone =>
1192                {
1193                    continue
1194                }
1195                res @ Err(_) => res.unwrap(),
1196            };
1197            let verified_qe_id = qe_identity.verify(&root_cas, EnclaveIdentity::QE).unwrap();
1198            assert_eq!(
1199                verified_qe_id.tcb_evaluation_data_number(),
1200                u64::from(number)
1201            );
1202
1203            let tcb_info = T::get_tcbinfo(&client, &fmspc, Some(number))
1204                .unwrap()
1205                .verify(&root_cas, 2)
1206                .unwrap();
1207            assert_eq!(tcb_info.tcb_evaluation_data_number(), u64::from(number));
1208        }
1209    }
1210
1211    #[test]
1212    pub fn sgx_tcb_evaluation_data_numbers() {
1213        tcb_evaluation_data_numbers_test_base::<platform::SGX>()
1214    }
1215
1216    #[test]
1217    pub fn tdx_tcb_evaluation_data_numbers() {
1218        tcb_evaluation_data_numbers_test_base::<platform::TDX>()
1219    }
1220
1221    #[test]
1222    pub fn root_ca_crl() {
1223        let intel_builder = IntelProvisioningClientBuilder::new(PcsVersion::V4)
1224            .set_retry_timeout(TIME_RETRY_TIMEOUT);
1225
1226        let client = intel_builder.build(reqwest_client());
1227        let root_ca_crl = client.root_ca_crl().unwrap();
1228
1229        let root_ca = include_bytes!("../../../pcs/tests/data/root_SGX_CA_der.cert");
1230        let root_cas = [&root_ca[..]];
1231        root_ca_crl.verify(&root_cas).unwrap();
1232    }
1233}