1use std::borrow::Cow;
14use std::marker::PhantomData;
15use std::num::ParseIntError;
16use std::time::Duration;
17
18use pcs::{
19 platform, CpuSvn, DcapArtifactIssuer, EncPpid, Fmspc, PceId, PceIsvsvn, PckCert, PckCrl,
20 PlatformType, PlatformTypeForTcbInfo, QeId, QeIdentitySigned, RootCaCrl, TcbInfo, Unverified,
21};
22use rustc_serialize::hex::{FromHex, ToHex};
23
24use super::intel::TcbEvaluationDataNumbersApi;
25use super::{common::*, RootCaCrlIn, RootCaCrlService};
26use super::{
27 Client, ClientBuilder, Fetcher, PckCertIn, PckCertService, PckCrlIn, PckCrlService, PcsVersion,
28 ProvisioningServiceApi, QeIdIn, QeIdService, StatusCode, TcbInfoIn, TcbInfoService,
29};
30use crate::{provisioning_client::PlatformApiTag, Error};
31
32pub struct PccsProvisioningClientBuilder {
33 base_url: Cow<'static, str>,
34 api_version: PcsVersion,
35 client_builder: ClientBuilder,
36}
37
38impl PccsProvisioningClientBuilder {
39 pub fn new<T: Into<Cow<'static, str>>>(api_version: PcsVersion, base_url: T) -> Self {
40 Self {
41 base_url: base_url.into(),
42 api_version,
43 client_builder: ClientBuilder::new(),
44 }
45 }
46
47 pub fn set_retry_timeout(mut self, retry_timeout: Duration) -> Self {
48 self.client_builder = self.client_builder.set_retry_timeout(retry_timeout);
49 self
50 }
51
52 pub fn build<F: for<'a> Fetcher<'a>>(self, fetcher: F) -> Client<F> {
53 let pck_certs = PckCertsApiNotSupported;
54 let pck_cert = PckCertApi::new(self.base_url.clone(), self.api_version);
55 let pck_crl = PckCrlApi::new(self.base_url.clone(), self.api_version);
56 let qeid = QeIdApi::new(self.base_url.clone(), self.api_version.clone());
57 let sgx_tcbinfo = TcbInfoApi::<platform::SGX>::new(self.base_url.clone(), self.api_version);
58 let tdx_tcbinfo = TcbInfoApi::<platform::TDX>::new(self.base_url.clone(), self.api_version);
59 let sgx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(self.base_url.clone());
60 let tdx_evaluation_data_numbers = TcbEvaluationDataNumbersApi::new(self.base_url.clone());
61 let root_ca_crl = RootCaCrlApi::new(self.base_url.clone());
62
63 self.client_builder.build(
64 pck_certs,
65 pck_cert,
66 pck_crl,
67 qeid,
68 sgx_tcbinfo,
69 tdx_tcbinfo,
70 sgx_evaluation_data_numbers,
71 tdx_evaluation_data_numbers,
72 root_ca_crl,
73 fetcher,
74 )
75 }
76}
77
78pub struct PckCertApi {
79 base_url: Cow<'static, str>,
80 api_version: PcsVersion,
81}
82
83impl PckCertApi {
84 pub(crate) fn new(base_url: Cow<'static, str>, api_version: PcsVersion) -> PckCertApi {
85 PckCertApi {
86 base_url,
87 api_version,
88 }
89 }
90}
91
92impl<'inp> PckCertService<'inp> for PckCertApi {
93 fn build_input(
94 &'inp self,
95 encrypted_ppid: Option<&'inp EncPpid>,
96 pce_id: &'inp PceId,
97 cpu_svn: &'inp CpuSvn,
98 pce_isvsvn: PceIsvsvn,
99 qe_id: Option<&'inp QeId>,
100 ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
101 PckCertIn {
102 encrypted_ppid,
103 pce_id,
104 cpu_svn,
105 pce_isvsvn,
106 qe_id,
107 api_key: &None,
108 api_version: self.api_version,
109 }
110 }
111}
112
113impl<'inp> ProvisioningServiceApi<'inp> for PckCertApi {
117 type Input = PckCertIn<'inp>;
118 type Output = PckCert<Unverified>;
119
120 fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
121 let api_version = input.api_version as u8;
122 let encrypted_ppid = input
123 .encrypted_ppid
124 .ok_or(Error::NoEncPPID)
125 .map(|e_ppid| e_ppid.to_hex())?;
126
127 let cpu_svn = input.cpu_svn.to_hex();
128 let pce_isvsvn = input.pce_isvsvn.to_le_bytes().to_hex();
129 let pce_id = input.pce_id.to_le_bytes().to_hex();
130 let qe_id = input
131 .qe_id
132 .ok_or(Error::NoQeID)
133 .map(|qe_id| qe_id.to_hex())?;
134
135 let url = format!(
136 "{}/sgx/certification/v{}/pckcert?encrypted_ppid={}&cpusvn={}&pcesvn={}&pceid={}&qeid={}",
137 self.base_url, api_version, encrypted_ppid, cpu_svn, pce_isvsvn, pce_id, qe_id,
138 );
139 let headers = Vec::new();
140 Ok((url, headers))
141 }
142
143 fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
144 match status_code {
145 StatusCode::Ok => Ok(()),
146 StatusCode::BadRequest => {
147 Err(Error::PCSError(status_code, "Invalid request parameters"))
148 }
149 StatusCode::NotFound => Err(Error::PCSError(
150 status_code,
151 "No cache data for this platform",
152 )),
153 StatusCode::NonStandard461 => Err(Error::PCSError(
154 status_code,
155 "The platform was not found in the cache",
156 )),
157 StatusCode::NonStandard462 => Err(Error::PCSError(
158 status_code,
159 "Certificates are not available for certain TCBs",
160 )),
161 StatusCode::InternalServerError => Err(Error::PCSError(
162 status_code,
163 "PCCS suffered from an internal server error",
164 )),
165 StatusCode::BadGateway => Err(Error::PCSError(
166 status_code,
167 "Unable to retrieve the collateral from the Intel SGX PCS",
168 )),
169 _ => Err(Error::PCSError(
170 status_code,
171 "Unexpected response from PCCS server",
172 )),
173 }
174 }
175
176 fn parse_response(
177 &self,
178 response_body: String,
179 response_headers: Vec<(String, String)>,
180 _api_version: PcsVersion,
181 ) -> Result<Self::Output, Error> {
182 let ca_chain = parse_issuer_header(&response_headers, PCK_CERTIFICATE_ISSUER_CHAIN_HEADER)?;
183 Ok(PckCert::new(response_body, ca_chain))
184 }
185}
186
187pub struct PckCrlApi {
188 base_url: Cow<'static, str>,
189 api_version: PcsVersion,
190}
191
192impl PckCrlApi {
193 pub fn new(base_url: Cow<'static, str>, api_version: PcsVersion) -> Self {
194 PckCrlApi {
195 base_url,
196 api_version,
197 }
198 }
199}
200
201impl<'inp> PckCrlService<'inp> for PckCrlApi {
202 fn build_input(
203 &'inp self,
204 ca: DcapArtifactIssuer,
205 ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
206 PckCrlIn {
207 api_version: self.api_version,
208 ca,
209 }
210 }
211}
212
213impl<'inp> ProvisioningServiceApi<'inp> for PckCrlApi {
217 type Input = PckCrlIn;
218 type Output = PckCrl<Unverified>;
219
220 fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
221 let ca = match input.ca {
222 DcapArtifactIssuer::PCKProcessorCA => "processor",
223 DcapArtifactIssuer::PCKPlatformCA => "platform",
224 DcapArtifactIssuer::SGXRootCA => {
225 return Err(Error::PCSError(
226 StatusCode::BadRequest,
227 "Invalid ca parameter",
228 ));
229 }
230 };
231 let url = format!(
232 "{}/sgx/certification/v{}/pckcrl?ca={}",
233 self.base_url, input.api_version as u8, ca
234 );
235 Ok((url, Vec::new()))
236 }
237
238 fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
239 match &status_code {
240 StatusCode::Ok => Ok(()),
241 StatusCode::BadRequest => {
242 Err(Error::PCSError(status_code, "Invalid request parameters"))
243 }
244 StatusCode::NotFound => Err(Error::PCSError(status_code, "PCK CRL cannot be found")),
245 StatusCode::InternalServerError => Err(Error::PCSError(
246 status_code,
247 "PCCS suffered from an internal server error",
248 )),
249 StatusCode::BadGateway => Err(Error::PCSError(
250 status_code,
251 "Unable to retrieve the collateral from the Intel SGX PCS",
252 )),
253 _ => Err(Error::PCSError(
254 status_code,
255 "Unexpected response from PCCS server",
256 )),
257 }
258 }
259
260 fn parse_response(
261 &self,
262 response_body: String,
263 response_headers: Vec<(String, String)>,
264 _api_version: PcsVersion,
265 ) -> Result<Self::Output, Error> {
266 let ca_chain = parse_issuer_header(&response_headers, PCK_CRL_ISSUER_CHAIN_HEADER)?;
267 let pem_crl = pkix::pem::der_to_pem(
268 &response_body.from_hex().map_err(|e| {
269 Error::ReadResponseError(
270 format!("failed to parse response body as hex-encoded DER: {}", e).into(),
271 )
272 })?,
273 pkix::pem::PEM_CRL,
274 );
275 Ok(PckCrl::new(pem_crl, ca_chain)?)
276 }
277}
278
279pub struct TcbInfoApi<T> {
280 base_url: Cow<'static, str>,
281 api_version: PcsVersion,
282 type_: PhantomData<T>,
283}
284
285impl<T: PlatformType> TcbInfoApi<T> {
286 pub fn new(base_url: Cow<'static, str>, api_version: PcsVersion) -> Self {
287 TcbInfoApi {
288 base_url,
289 api_version,
290 type_: PhantomData,
291 }
292 }
293}
294
295impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> TcbInfoService<'inp, T> for TcbInfoApi<T> {
296 fn build_input(
297 &'inp self,
298 fmspc: &'inp Fmspc,
299 tcb_evaluation_data_number: Option<u16>,
300 ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
301 TcbInfoIn {
302 api_version: self.api_version,
303 fmspc,
304 tcb_evaluation_data_number,
305 }
306 }
307}
308
309impl<'inp, T: PlatformTypeForTcbInfo + PlatformApiTag> ProvisioningServiceApi<'inp>
313 for TcbInfoApi<T>
314{
315 type Input = TcbInfoIn<'inp>;
316 type Output = TcbInfo<T>;
317
318 fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
319 let api_version = input.api_version as u8;
320 let fmspc = input.fmspc.as_bytes().to_hex();
321 let url = if let Some(evaluation_data_number) = input.tcb_evaluation_data_number {
322 format!(
323 "{}/{}/certification/v{}/tcb?fmspc={}&tcbEvaluationDataNumber={}",
324 self.base_url,
325 T::tag(),
326 api_version,
327 fmspc,
328 evaluation_data_number
329 )
330 } else {
331 format!(
332 "{}/{}/certification/v{}/tcb?fmspc={}&update=early",
333 self.base_url,
334 T::tag(),
335 api_version,
336 fmspc,
337 )
338 };
339 Ok((url, Vec::new()))
340 }
341
342 fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
343 match &status_code {
344 StatusCode::Ok => Ok(()),
345 StatusCode::BadRequest => {
346 Err(Error::PCSError(status_code, "Invalid request parameters"))
347 }
348 StatusCode::NotFound => Err(Error::PCSError(
349 status_code,
350 "TCB information for provided FMSPC cannot be found",
351 )),
352 StatusCode::InternalServerError => Err(Error::PCSError(
353 status_code,
354 "PCCS suffered from an internal server error",
355 )),
356 StatusCode::BadGateway => Err(Error::PCSError(
357 status_code,
358 "Unable to retrieve the collateral from the Intel SGX PCS",
359 )),
360 _ => Err(Error::PCSError(
361 status_code,
362 "Unexpected response from PCCS server",
363 )),
364 }
365 }
366
367 #[allow(deprecated)]
368 fn parse_response(
369 &self,
370 response_body: String,
371 response_headers: Vec<(String, String)>,
372 api_version: PcsVersion,
373 ) -> Result<Self::Output, Error> {
374 let key = match api_version {
375 PcsVersion::V3 => TCB_INFO_ISSUER_CHAIN_HEADER_V3,
376 PcsVersion::V4 => TCB_INFO_ISSUER_CHAIN_HEADER_V4,
377 };
378 let ca_chain = parse_issuer_header(&response_headers, key)?;
379 Ok(TcbInfo::parse(&response_body, ca_chain)?)
380 }
381}
382
383pub struct QeIdApi {
384 base_url: Cow<'static, str>,
385 api_version: PcsVersion,
386}
387
388impl QeIdApi {
389 pub fn new(base_url: Cow<'static, str>, api_version: PcsVersion) -> Self {
390 QeIdApi {
391 base_url,
392 api_version,
393 }
394 }
395}
396
397impl<'inp> QeIdService<'inp> for QeIdApi {
398 fn build_input(
399 &'inp self,
400 tcb_evaluation_data_number: Option<u16>,
401 ) -> <Self as ProvisioningServiceApi<'inp>>::Input {
402 QeIdIn {
403 api_version: self.api_version,
404 tcb_evaluation_data_number,
405 }
406 }
407}
408
409impl<'inp> ProvisioningServiceApi<'inp> for QeIdApi {
413 type Input = QeIdIn;
414 type Output = QeIdentitySigned;
415
416 fn build_request(&self, input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
417 let api_version = input.api_version as u8;
418 let url = if let Some(tcb_evaluation_data_number) = input.tcb_evaluation_data_number {
419 format!(
420 "{}/sgx/certification/v{}/qe/identity?tcbEvaluationDataNumber={}",
421 self.base_url, api_version, tcb_evaluation_data_number
422 )
423 } else {
424 format!(
425 "{}/sgx/certification/v{}/qe/identity?update=early",
426 self.base_url, api_version,
427 )
428 };
429 Ok((url, Vec::new()))
430 }
431
432 fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
433 match &status_code {
434 StatusCode::Ok => Ok(()),
435 StatusCode::NotFound => Err(Error::PCSError(
436 status_code,
437 "QE identity information cannot be found",
438 )),
439 StatusCode::InternalServerError => Err(Error::PCSError(
440 status_code,
441 "PCCS suffered from an internal server error",
442 )),
443 StatusCode::BadGateway => Err(Error::PCSError(
444 status_code,
445 "Unable to retrieve the collateral from the Intel SGX PCS",
446 )),
447 _ => Err(Error::PCSError(
448 status_code,
449 "Unexpected response from PCCS server",
450 )),
451 }
452 }
453
454 fn parse_response(
455 &self,
456 response_body: String,
457 response_headers: Vec<(String, String)>,
458 _api_version: PcsVersion,
459 ) -> Result<Self::Output, Error> {
460 let ca_chain = parse_issuer_header(&response_headers, ENCLAVE_ID_ISSUER_CHAIN_HEADER)?;
461 let id = QeIdentitySigned::parse(&response_body, ca_chain)?;
462 Ok(id)
463 }
464}
465
466pub struct RootCaCrlApi {
467 base_url: Cow<'static, str>,
468}
469
470impl RootCaCrlApi {
471 pub fn new(base_url: Cow<'static, str>) -> Self {
472 RootCaCrlApi { base_url }
473 }
474}
475
476impl<'inp> RootCaCrlService<'inp> for RootCaCrlApi {
477 fn build_input(&'inp self) -> <Self as ProvisioningServiceApi<'inp>>::Input {
478 RootCaCrlIn
479 }
480}
481
482impl<'inp> ProvisioningServiceApi<'inp> for RootCaCrlApi {
483 type Input = RootCaCrlIn;
484 type Output = RootCaCrl<Unverified>;
485
486 fn build_request(&self, _input: &Self::Input) -> Result<(String, Vec<(String, String)>), Error> {
487 let url = format!("{}/sgx/certification/v4/rootcacrl", self.base_url);
488 Ok((url, Vec::new()))
489 }
490
491 fn validate_response(&self, status_code: StatusCode) -> Result<(), Error> {
492 match &status_code {
493 StatusCode::Ok => Ok(()),
494 StatusCode::BadRequest => Err(Error::PCSError(status_code, "Invalid parameter")),
495 StatusCode::Unauthorized => Err(Error::PCSError(
496 status_code,
497 "Failed to authenticate or authorize the request.",
498 )),
499 StatusCode::NotFound => {
500 Err(Error::PCSError(status_code, "Root CA CRL cannot be found"))
501 }
502 StatusCode::InternalServerError => Err(Error::PCSError(
503 status_code,
504 "PCS suffered from an internal server error",
505 )),
506 StatusCode::ServiceUnavailable => Err(Error::PCSError(
507 status_code,
508 "PCS is temporarily unavailable",
509 )),
510 __ => Err(Error::PCSError(
511 status_code,
512 "Unexpected response from PCS server",
513 )),
514 }
515 }
516
517 fn parse_response(
518 &self,
519 response_body: String,
520 _response_headers: Vec<(String, String)>,
521 _api_version: PcsVersion,
522 ) -> Result<Self::Output, Error> {
523 pub fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> {
524 (0..s.len())
525 .step_by(2)
526 .map(|i| u8::from_str_radix(&s[i..i + 2], 16))
527 .collect()
528 }
529
530 let der = decode_hex(&response_body)
531 .map_err(|_| Error::ReadResponseError(Cow::Borrowed("Cannot parse CRL repsonse")))?;
532 RootCaCrl::new(&der).map_err(|e| Error::ReadResponseError(Cow::Owned(e.to_string().into())))
533 }
534}
535
536#[cfg(all(test, feature = "reqwest"))]
537mod tests {
538 use assert_matches::assert_matches;
539 use std::convert::TryFrom;
540 use std::hash::{DefaultHasher, Hash, Hasher};
541 use std::path::PathBuf;
542 use std::sync::OnceLock;
543 use std::time::Duration;
544
545 use pcs::{
546 platform, EnclaveIdentity, Fmspc, PckID, RawTcbEvaluationDataNumbers,
547 TcbEvaluationDataNumbers, WriteOptionsBuilder,
548 };
549
550 use super::Client;
551 use crate::provisioning_client::{
552 test_helpers, DcapArtifactIssuer, Error, PccsProvisioningClientBuilder, PcsVersion,
553 ProvisioningClient, StatusCode,
554 };
555 use crate::{reqwest_client_insecure_tls, ReqwestClient};
556
557 const PCKID_TEST_FILE: &str = "./tests/data/pckid_retrieval.csv";
558 const OUTPUT_TEST_DIR: &str = "./tests/data/";
559 const TIME_RETRY_TIMEOUT: Duration = Duration::from_secs(180);
560
561 static PCCS_URL: OnceLock<String> = OnceLock::new();
562
563 fn pccs_url_from_env() -> String {
564 let url = std::env::var("PCCS_URL").unwrap_or(String::from("https://pccs.fortanix.com"));
565 assert!(
566 !url.is_empty(),
567 "Empty string in environment variable: PCCS_URL"
568 );
569 url
570 }
571
572 fn make_client() -> Client<ReqwestClient> {
573 let url = &*PCCS_URL.get_or_init(pccs_url_from_env);
574 PccsProvisioningClientBuilder::new(PcsVersion::V4, url)
575 .set_retry_timeout(TIME_RETRY_TIMEOUT)
576 .build(reqwest_client_insecure_tls())
577 }
578
579 #[test]
580 pub fn pck() {
581 let client = make_client();
582
583 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
584 .unwrap()
585 .iter()
586 {
587 let pck = client
588 .pckcert(
589 Some(&pckid.enc_ppid),
590 &pckid.pce_id,
591 &pckid.cpu_svn,
592 pckid.pce_isvsvn,
593 Some(&pckid.qe_id),
594 )
595 .unwrap();
596
597 assert_eq!(
598 test_helpers::get_cert_subject(pck.ca_chain().last().unwrap()),
599 "Intel SGX Root CA"
600 );
601 }
602 }
603
604 #[test]
605 pub fn pck_cached() {
606 let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
607 let root_cas = [&root_ca[..]];
608 let client = make_client();
609
610 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
611 .unwrap()
612 .iter()
613 {
614 let pck = client
615 .pckcert(
616 Some(&pckid.enc_ppid),
617 &pckid.pce_id,
618 &pckid.cpu_svn,
619 pckid.pce_isvsvn,
620 Some(&pckid.qe_id),
621 )
622 .unwrap();
623
624 let pck = pck.verify(&root_cas, None).unwrap();
625
626 {
628 let mut cache = client.pckcert_service.cache.lock().unwrap();
629
630 assert!(cache.len() > 0);
631
632 let (cached_pck, _) = {
633 let mut hasher = DefaultHasher::new();
634 let input = client.pckcert_service.pcs_service().build_input(
635 Some(&pckid.enc_ppid),
636 &pckid.pce_id,
637 &pckid.cpu_svn,
638 pckid.pce_isvsvn,
639 Some(&pckid.qe_id),
640 );
641 input.hash(&mut hasher);
642
643 cache
644 .get_mut(&hasher.finish())
645 .expect("Can't find key in cache")
646 .to_owned()
647 };
648
649 assert_eq!(
650 pck.fmspc().unwrap(),
651 cached_pck
652 .clone()
653 .verify(&root_cas, None)
654 .unwrap()
655 .fmspc()
656 .unwrap()
657 );
658 assert_eq!(pck.ca_chain(), cached_pck.ca_chain());
659 }
660
661 let pck_from_service = client
663 .pckcert(
664 Some(&pckid.enc_ppid),
665 &pckid.pce_id,
666 &pckid.cpu_svn,
667 pckid.pce_isvsvn,
668 Some(&pckid.qe_id),
669 )
670 .unwrap();
671
672 assert_eq!(
673 pck.fmspc().unwrap(),
674 pck_from_service
675 .clone()
676 .verify(&root_cas, None)
677 .unwrap()
678 .fmspc()
679 .unwrap()
680 );
681 assert_eq!(pck.ca_chain(), pck_from_service.ca_chain());
682 }
683 }
684
685 #[test]
686 pub fn test_pckcerts_with_fallback() {
687 let client = make_client();
688
689 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
690 .unwrap()
691 .iter()
692 {
693 let pckcerts = client.pckcerts_with_fallback(&pckid).unwrap();
694 println!("Found {} PCK certs.", pckcerts.as_pck_certs().len());
695
696 let tcb_info = client
697 .sgx_tcbinfo(&pckcerts.fmspc().unwrap(), None)
698 .unwrap();
699 let tcb_data = tcb_info.data().unwrap();
700
701 let selected = pckcerts
702 .select_pck(&tcb_data, &pckid.cpu_svn, pckid.pce_isvsvn, pckid.pce_id)
703 .unwrap();
704
705 let pck = client
706 .pckcert(
707 Some(&pckid.enc_ppid),
708 &pckid.pce_id,
709 &pckid.cpu_svn,
710 pckid.pce_isvsvn,
711 Some(&pckid.qe_id),
712 )
713 .unwrap();
714
715 assert_eq!(
716 format!("{:?}", selected.sgx_extension().unwrap()),
717 format!("{:?}", pck.sgx_extension().unwrap())
718 );
719 }
720 }
721
722 #[test]
723 pub fn tcb_info() {
724 let client = make_client();
725
726 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
727 .unwrap()
728 .iter()
729 {
730 let pckcerts = client.pckcerts_with_fallback(&pckid).unwrap();
731
732 assert!(client
733 .sgx_tcbinfo(&pckcerts.fmspc().unwrap(), None)
734 .and_then(|tcb| {
735 Ok(tcb
736 .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
737 .unwrap())
738 })
739 .is_ok());
740 }
741 }
742
743 #[test]
744 pub fn tcb_info_tdx() {
745 let client = make_client();
746 let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
747 let root_cas = [&root_ca[..]];
748
749 let fmspcs = [
751 Fmspc::try_from("00a06d080000").unwrap(),
752 Fmspc::try_from("70a06d070000").unwrap(),
753 Fmspc::try_from("00a06e050000").unwrap(),
754 Fmspc::try_from("50806f000000").unwrap(),
755 Fmspc::try_from("20a06e050000").unwrap(),
756 Fmspc::try_from("10a06f010000").unwrap(),
757 Fmspc::try_from("b0c06f000000").unwrap(),
758 Fmspc::try_from("20a06f000000").unwrap(),
759 Fmspc::try_from("60a06f000000").unwrap(),
760 Fmspc::try_from("c0806f000000").unwrap(),
761 Fmspc::try_from("20a06d080000").unwrap(),
762 Fmspc::try_from("10a06d000000").unwrap(),
763 Fmspc::try_from("00806f050000").unwrap(),
764 Fmspc::try_from("90c06f000000").unwrap(),
765 ];
766
767 for item in fmspcs.iter() {
768 let tdx_tcbinfo = client.tdx_tcbinfo(&item, None);
769 println!("FMSPC: {} => {}", item.to_string(), tdx_tcbinfo.is_ok());
770 assert!(tdx_tcbinfo.is_ok());
771
772 let _ = tdx_tcbinfo.unwrap().verify(&root_cas, 2).unwrap();
773 }
774 }
775
776 #[test]
777 pub fn tcb_info_with_evaluation_data_number() {
778 let client = make_client();
779 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
780 .unwrap()
781 .iter()
782 {
783 let pckcerts = client.pckcerts_with_fallback(&pckid).unwrap();
784
785 let fmspc = pckcerts.fmspc().unwrap();
786
787 let evaluation_data_numbers = client
788 .sgx_tcb_evaluation_data_numbers()
789 .unwrap()
790 .evaluation_data_numbers()
791 .unwrap();
792
793 for number in evaluation_data_numbers.numbers() {
794 if number.number() < 18 {
801 continue;
802 }
803 let tcb = match client.sgx_tcbinfo(&fmspc, Some(number.number())) {
804 Ok(tcb) => tcb,
805 Err(super::Error::PCSError(status_code, _))
809 if status_code == super::StatusCode::Gone =>
810 {
811 continue
812 }
813 res @ Err(_) => res.unwrap(),
814 };
815 tcb.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
816 .unwrap();
817 }
818 }
819 }
820
821 #[test]
822 pub fn tcb_info_cached() {
823 let client = make_client();
824
825 for pckid in PckID::parse_file(&PathBuf::from(PCKID_TEST_FILE).as_path())
826 .unwrap()
827 .iter()
828 {
829 let pckcerts = client.pckcerts_with_fallback(&pckid).unwrap();
830 let fmspc = pckcerts.fmspc().unwrap();
831 let tcb_info = client.sgx_tcbinfo(&fmspc, None).unwrap();
832
833 {
835 let mut cache = client.sgx_tcbinfo_service.cache.lock().unwrap();
836
837 assert!(cache.len() > 0);
838
839 let (cached_tcb_info, _) = {
840 let mut hasher = DefaultHasher::new();
841 let input = client
842 .sgx_tcbinfo_service
843 .pcs_service()
844 .build_input(&fmspc, None);
845 input.hash(&mut hasher);
846
847 cache
848 .get_mut(&hasher.finish())
849 .expect("Can't find key in cache")
850 .to_owned()
851 };
852
853 assert_eq!(tcb_info, cached_tcb_info);
854 }
855
856 let tcb_info_from_service = client.sgx_tcbinfo(&fmspc, None).unwrap();
858
859 assert_eq!(tcb_info, tcb_info_from_service);
860 }
861 }
862
863 #[test]
864 pub fn pckcrl() {
865 let client = make_client();
866 assert!(client
867 .pckcrl(DcapArtifactIssuer::PCKProcessorCA)
868 .and_then(|crl| Ok(crl
869 .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
870 .unwrap()))
871 .is_ok());
872 assert!(client
873 .pckcrl(DcapArtifactIssuer::PCKPlatformCA)
874 .and_then(|crl| Ok(crl
875 .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
876 .unwrap()))
877 .is_ok());
878 }
879
880 #[test]
881 pub fn pckcrl_cached() {
882 for ca in [
883 DcapArtifactIssuer::PCKProcessorCA,
884 DcapArtifactIssuer::PCKPlatformCA,
885 ] {
886 let client = make_client();
887 let pckcrl = client.pckcrl(ca).unwrap();
888
889 {
891 let mut cache = client.pckcrl_service.cache.lock().unwrap();
892
893 assert!(cache.len() > 0);
894
895 let (cached_pckcrl, _) = {
896 let mut hasher = DefaultHasher::new();
897 let input = client.pckcrl_service.pcs_service().build_input(ca);
898 input.hash(&mut hasher);
899
900 cache
901 .get_mut(&hasher.finish())
902 .expect("Can't find key in cache")
903 .to_owned()
904 };
905
906 assert_eq!(pckcrl, cached_pckcrl);
907 }
908
909 let pckcrl_from_service = client.pckcrl(ca).unwrap();
911
912 assert_eq!(pckcrl, pckcrl_from_service);
913 }
914 }
915
916 #[test]
917 pub fn qe_identity() {
918 let client = make_client();
919 let qe_id = client.qe_identity(None);
920 assert!(qe_id.is_ok());
921 assert!(qe_id
922 .unwrap()
923 .write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build())
924 .is_ok());
925 }
926
927 #[test]
928 pub fn qe_identity_cached() {
929 let client = make_client();
930 let qe_id = client.qe_identity(None).unwrap();
931
932 {
934 let mut cache = client.qeid_service.cache.lock().unwrap();
935
936 assert!(cache.len() > 0);
937
938 let (cached_qeid, _) = {
939 let mut hasher = DefaultHasher::new();
940 let input = client.qeid_service.pcs_service().build_input(None);
941 input.hash(&mut hasher);
942
943 cache
944 .get_mut(&hasher.finish())
945 .expect("Can't find key in cache")
946 .to_owned()
947 };
948
949 assert_eq!(qe_id, cached_qeid);
950 }
951
952 let qeid_from_service = client.qe_identity(None).unwrap();
954
955 assert_eq!(qe_id, qeid_from_service);
956 }
957
958 #[test]
959 pub fn gone_artifacts() {
960 let client = make_client();
961 let fmspc = Fmspc::try_from("90806f000000").unwrap();
962 assert_matches!(
963 client.qe_identity(Some(15)),
964 Err(Error::PCSError(StatusCode::Gone, _))
965 );
966 assert_matches!(
967 client.sgx_tcbinfo(&fmspc, Some(15)),
968 Err(Error::PCSError(StatusCode::Gone, _))
969 );
970 }
971
972 #[test]
973 pub fn tcb_evaluation_data_numbers() {
974 let root_ca = include_bytes!("../../tests/data/root_SGX_CA_der.cert");
975 let root_cas = [&root_ca[..]];
976 let client = make_client();
977 let eval_numbers = client.sgx_tcb_evaluation_data_numbers().unwrap();
978
979 let eval_numbers2 = serde_json::ser::to_vec(&eval_numbers)
980 .and_then(|v| serde_json::from_slice::<RawTcbEvaluationDataNumbers<platform::SGX>>(&v))
981 .unwrap();
982 assert_eq!(eval_numbers, eval_numbers2);
983
984 let fmspc = Fmspc::try_from("90806f000000").unwrap();
985 let eval_numbers: TcbEvaluationDataNumbers<platform::SGX> =
986 eval_numbers.verify(&root_cas).unwrap();
987 for number in eval_numbers.numbers().map(|n| n.number()) {
988 if number < 18 {
995 continue;
996 }
997 let qe_identity = match client.qe_identity(Some(number)) {
998 Ok(id) => id,
999 Err(super::Error::PCSError(status_code, _))
1003 if status_code == super::StatusCode::Gone =>
1004 {
1005 continue
1006 }
1007 res @ Err(_) => res.unwrap(),
1008 };
1009 let verified_qe_id = qe_identity.verify(&root_cas, EnclaveIdentity::QE).unwrap();
1010 assert_eq!(
1011 verified_qe_id.tcb_evaluation_data_number(),
1012 u64::from(number)
1013 );
1014
1015 let tcb_info = client
1016 .sgx_tcbinfo(&fmspc, Some(number))
1017 .unwrap()
1018 .verify(&root_cas, 2)
1019 .unwrap();
1020 assert_eq!(tcb_info.tcb_evaluation_data_number(), u64::from(number));
1021 }
1022 }
1023
1024 #[test]
1025 pub fn root_ca_crl() {
1026 let client = make_client();
1027 let root_ca_crl = client.root_ca_crl().unwrap();
1028
1029 let root_ca = include_bytes!("../../../pcs/tests/data/root_SGX_CA_der.cert");
1030 let root_cas = [&root_ca[..]];
1031 root_ca_crl.verify(&root_cas).unwrap();
1032 }
1033}