Skip to main content

pcs/
pckcrt.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 std::borrow::Cow;
9use std::cmp::Ordering;
10use std::convert::{TryFrom, TryInto};
11use std::fmt::Debug;
12use std::mem;
13use std::path::PathBuf;
14
15use percent_encoding::percent_decode;
16use pkix::pem::{self, PEM_CERTIFICATE};
17use pkix::types::ObjectIdentifier;
18use pkix::x509::GenericCertificate;
19use pkix::FromBer;
20use serde::de::DeserializeOwned;
21use serde::{Deserialize, Deserializer, Serialize, Serializer};
22use sgx_pkix::oid::{self, SGX_EXTENSION};
23use yasna::{ASN1Error, ASN1ErrorKind, ASN1Result, BERDecodable, BERReader, BERReaderSeq};
24#[cfg(feature = "verify")]
25use {
26    super::{DcapArtifactIssuer, PckCrl, RootCaCrl},
27    mbedtls::alloc::{Box as MbedtlsBox, List as MbedtlsList},
28    mbedtls::ecp::EcPoint,
29    mbedtls::error::{codes, Error as ErrMbed},
30    mbedtls::x509::certificate::Certificate,
31    mbedtls::x509::Crl,
32    std::ffi::CString,
33    std::ops::Deref,
34};
35
36use crate::io::{self, WriteOptions};
37use crate::tcb_info::{Fmspc, TcbData, TcbLevel};
38use crate::{
39    CpuSvn, Error, PlatformTypeForTcbInfo, Unverified, VerificationType, Verified, platform
40};
41
42/// [`SGXType`] is a rust enum representing the IntelĀ® SGX Type.
43///
44/// Ref: <https://api.trustedservices.intel.com/documents/Intel_SGX_PCK_Certificate_CRL_Spec-1.5.pdf>
45#[derive(Debug, Serialize, Deserialize, Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
46#[serde(rename_all = "kebab-case")]
47pub enum SGXType {
48    Standard,
49    /// Type for machines only provide confidentiality protection for EPC memory, such as Azure DC v3 instance.
50    Scalable,
51    /// Type for machines provide integrity and confidentiality protection for EPC memory, such as our FX2200 series 3 instance.
52    ScalableWithIntegrity,
53}
54
55impl Default for SGXType {
56    fn default() -> SGXType {
57        SGXType::Standard
58    }
59}
60
61impl TryFrom<i64> for SGXType {
62    type Error = ();
63
64    fn try_from(v: i64) -> Result<Self, ()> {
65        match v {
66            0 => Ok(SGXType::Standard),
67            1 => Ok(SGXType::Scalable),
68            2 => Ok(SGXType::ScalableWithIntegrity),
69            _ => Err(()),
70        }
71    }
72}
73
74/// TCB component as specified in the Intel PCKCrt API v3 and v4
75#[derive(Serialize, Deserialize, Debug, Default)]
76pub struct TcbComponentsV3 {
77    sgxtcbcomp01svn: u8,
78    sgxtcbcomp02svn: u8,
79    sgxtcbcomp03svn: u8,
80    sgxtcbcomp04svn: u8,
81    sgxtcbcomp05svn: u8,
82    sgxtcbcomp06svn: u8,
83    sgxtcbcomp07svn: u8,
84    sgxtcbcomp08svn: u8,
85    sgxtcbcomp09svn: u8,
86    sgxtcbcomp10svn: u8,
87    sgxtcbcomp11svn: u8,
88    sgxtcbcomp12svn: u8,
89    sgxtcbcomp13svn: u8,
90    sgxtcbcomp14svn: u8,
91    sgxtcbcomp15svn: u8,
92    sgxtcbcomp16svn: u8,
93    pcesvn: u16,
94}
95
96/// TCB component as specified in TcbInfo (version 3) of the PCS version 4 API
97/// https://api.trustedservices.intel.com/documents/PCS_V3-V4_migration_guide.pdf
98#[derive(Serialize, Deserialize, Clone, Debug, Default, Eq)]
99pub struct TcbComponentEntry {
100    svn: u8,
101    #[serde(default)]
102    category: String,
103    #[serde(default, rename = "type")]
104    comp_type: String,
105}
106
107impl Ord for TcbComponentEntry {
108    fn cmp(&self, other: &Self) -> Ordering {
109        self.svn.cmp(&other.svn)
110    }
111}
112
113impl PartialOrd for TcbComponentEntry {
114    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
115        self.svn.partial_cmp(&other.svn)
116    }
117}
118
119impl PartialEq for TcbComponentEntry {
120    fn eq(&self, other: &Self) -> bool {
121        self.svn == other.svn
122    }
123}
124
125impl From<u8> for TcbComponentEntry {
126    fn from(svn: u8) -> TcbComponentEntry {
127        TcbComponentEntry {
128            svn,
129            category: String::new(),
130            comp_type: String::new(),
131        }
132    }
133}
134
135#[derive(Serialize, Deserialize, Clone, Debug, Default, Eq, PartialEq, PartialOrd)]
136pub struct SGXSpecificTcbComponentData {}
137
138#[derive(Serialize, Deserialize, Clone, Debug, Default, Eq)]
139pub struct TDXSpecificTcbComponentData {
140    pub(crate) tdxtcbcomponents: [TcbComponentEntry; 16],
141}
142
143impl TDXSpecificTcbComponentData {
144    /// According to PCS reference: https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
145    /// the second element of the `tdxTcbComponents` indicates the Module ID to be used to select TDX Module Identity on the
146    /// TCB info.
147    ///
148    /// > find a matching TDX Module Identity (in tdxModuleIdentities array of TCB Info) with its id set to
149    //    "TDX_<version>" where <version> matches the value of TEE TCB SVN at index 1.
150    pub fn tdx_module_id(&self) -> u8 {
151        self.tdxtcbcomponents[1].svn
152    }
153
154    /// According to PCS reference: https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
155    /// the first element of the `tdxTcbComponents` indicates the ISV SVN for the TDX Module of the machine.
156    ///
157    /// > [...] for the selected TDX Module Identity go over the sorted collection of TCB Levels starting
158    ///   from the first item on the list and compare its isvsvn value to the TEE TCB SVN at index 0.
159    pub fn tdx_module_svn(&self) -> u8 {
160        self.tdxtcbcomponents[0].svn
161    }
162}
163
164/// Function to compare sequences of pairs `(a, b)`, where `a` will be compared against `b` and
165/// produces an ordering in which all pairs must have equal or consistent ordering (i.e, if one
166/// pair orders to `Ordering::Greater`, every other pairs must also be either `Ordering::Greater`
167/// or `Ordering::Equal`). If the sequence has inconsistent ordering, it returns `None`.
168fn sequence_partial_cmp<T: Iterator, U: Ord>(mut iter: T) -> Option<Ordering>
169    where T: Iterator<Item = (U, U)>
170{
171    iter.try_fold(Ordering::Equal, |prev, (a, b)|
172        match (a.cmp(&b), prev) {
173            (x, Ordering::Equal) => Some(x),
174            (Ordering::Greater, Ordering::Less)
175            | (Ordering::Less, Ordering::Greater) => None,
176            _ => Some(prev),
177        }
178    )
179}
180
181impl PartialOrd for TDXSpecificTcbComponentData {
182    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
183        // Reference:
184        // https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
185        //
186        // Compare SVNs in TEE TCB SVN array retrieved from TD Report in Quote
187        // (from index 0 to 15 if TEE TCB SVN at index 1 is set to 0, or from index 2 to 15 otherwise) with
188        // the corresponding values of SVNs in tdxtcbcomponents array of TCB Level.
189        let skip_idx = if self.tdx_module_id() != 0 || other.tdx_module_id() != 0 {
190            2
191        } else {
192            0
193        };
194
195        sequence_partial_cmp(self.tdxtcbcomponents
196            .iter()
197            .zip(other.tdxtcbcomponents.iter())
198            .skip(skip_idx))
199    }
200}
201
202impl PartialEq for TDXSpecificTcbComponentData {
203    fn eq(&self, other: &Self) -> bool {
204        // Following the `PartialCmp` implementation, we ignore the first and second
205        // element if the second element is non-zero, as the second element indicates
206        // TdxModule identity that is evaluated separately
207        let skip_idx = if self.tdx_module_id() != 0 || other.tdx_module_id() != 0 {
208            2
209        } else {
210            0
211        };
212
213        self.tdxtcbcomponents.iter().skip(skip_idx).eq(other.tdxtcbcomponents.iter().skip(skip_idx))
214    }
215}
216
217impl TDXSpecificTcbComponentData {
218    pub fn from_raw(raw_tdxsvn: [u8; 16]) -> Self {
219        TDXSpecificTcbComponentData {
220            tdxtcbcomponents: raw_tdxsvn.map(|tdxsvn| tdxsvn.into()),
221        }
222    }
223}
224
225pub trait PlatformTypeForTcbComponent
226where
227    // This bound ensures that the type-checker understands that `TcbComponents` implements
228    // `TryFrom`, since a normal where-bound would not be propagated
229    Self: ImplyBound<ToBound = TcbComponents<Self::PlatformSpecificTcbComponentData>>,
230    Self: ImplyBound<ToBound: TryFrom<TcbComponentsV3, Error = Error>>,
231{
232    type PlatformSpecificTcbComponentData: Debug
233        + Clone
234        + Serialize
235        + DeserializeOwned;
236}
237
238impl PlatformTypeForTcbComponent for platform::SGX {
239    type PlatformSpecificTcbComponentData = SGXSpecificTcbComponentData;
240}
241
242impl PlatformTypeForTcbComponent for platform::TDX {
243    type PlatformSpecificTcbComponentData = TDXSpecificTcbComponentData;
244}
245
246/// Auxiliary trait to propagate bound on
247/// [PlatformTypeForTcbComponent::PlatformSpecificTcbComponentData]
248pub trait ImplyBound where Self: Sized {
249    type ToBound;
250}
251
252impl ImplyBound for platform::SGX {
253    type ToBound = TcbComponents<SGXSpecificTcbComponentData>;
254}
255
256impl ImplyBound for platform::TDX {
257    type ToBound = TcbComponents<TDXSpecificTcbComponentData>;
258}
259
260impl TryFrom<TcbComponentsV3> for TcbComponents<SGXSpecificTcbComponentData> {
261    type Error = Error;
262
263    fn try_from(value: TcbComponentsV3) -> Result<Self, Error> {
264        Ok(TcbComponents::<SGXSpecificTcbComponentData>(value.into()))
265    }
266}
267
268impl TryFrom<TcbComponentsV3> for TcbComponents<TDXSpecificTcbComponentData> {
269    type Error = Error;
270
271    fn try_from(_value: TcbComponentsV3) -> Result<Self, Error> {
272        Err(Error::InvalidTcbInfo("attempting to convert TcbComponentsV3 into TcbComponentsV4<TDX>".to_string()))
273    }
274}
275
276#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
277pub struct TcbComponentsV4<P> {
278    sgxtcbcomponents: [TcbComponentEntry; 16],
279    pcesvn: u16,
280    #[serde(flatten)]
281    platform_specific_data: P,
282}
283
284#[derive(Serialize, Deserialize, Debug)]
285#[serde(untagged)]
286enum TcbComponentsCompatibilitySelector<P> {
287    V3(TcbComponentsV3),
288    V4(TcbComponentsV4<P>),
289}
290
291#[derive(Serialize, Deserialize, Clone, Debug, Default, Eq)]
292#[serde(try_from = "TcbComponentsCompatibilitySelector<P>")]
293#[serde(bound(deserialize = "TcbComponents<P>: TryFrom<TcbComponentsV3, Error: std::fmt::Display>, P : Deserialize<'de>"))]
294pub struct TcbComponents<P>(TcbComponentsV4<P>);
295
296#[derive(PartialEq, Eq, Debug, Clone, Copy)]
297pub enum TcbComponentType {
298    EarlyMicrocodeUpdate,
299    LateMicrocodeUpdate,
300}
301
302impl TryFrom<&str> for TcbComponentType {
303    type Error = ();
304
305    fn try_from(s: &str) -> Result<Self, Self::Error> {
306        if s == "Early Microcode Update" {
307            Ok(TcbComponentType::EarlyMicrocodeUpdate)
308        } else if s == "SGX Late Microcode Update" {
309            Ok(TcbComponentType::LateMicrocodeUpdate)
310        } else {
311            Err(())
312        }
313    }
314}
315
316pub type TcbComponentsOf<T> = TcbComponents<<T as PlatformTypeForTcbComponent>::PlatformSpecificTcbComponentData>;
317
318impl TcbComponents<SGXSpecificTcbComponentData> {
319    pub fn from_raw(raw_cpusvn: [u8; 16], pcesvn: u16) -> Self {
320        TcbComponents(TcbComponentsV4 {
321            sgxtcbcomponents: raw_cpusvn.map(|svn| svn.into()),
322            pcesvn,
323            platform_specific_data: SGXSpecificTcbComponentData {},
324        })
325    }
326}
327
328impl TcbComponents<TDXSpecificTcbComponentData> {
329    pub fn from_raw(raw_cpusvn: [u8; 16], pcesvn: u16, raw_tdxsvn: [u8; 16]) -> Self {
330        TcbComponents(TcbComponentsV4 {
331            sgxtcbcomponents: raw_cpusvn.map(|svn| svn.into()),
332            pcesvn,
333            platform_specific_data: TDXSpecificTcbComponentData::from_raw(raw_tdxsvn),
334        })
335    }
336
337    pub fn tdx_tcb_components(&self) -> &TDXSpecificTcbComponentData {
338        &self.0.platform_specific_data
339    }
340}
341
342impl<P> TcbComponents<P> {
343    fn iter_components<'a>(&'a self) -> impl Iterator<Item = u16> + 'a {
344        self.0
345            .sgxtcbcomponents
346            .iter()
347            .map(|comp| comp.svn as u16)
348            .chain(std::iter::once(self.0.pcesvn))
349    }
350
351    pub fn pce_svn(&self) -> u16 {
352        self.0.pcesvn
353    }
354
355    pub fn cpu_svn(&self) -> CpuSvn {
356        // NOTE: to support older stable compilers (pre 1.77) we are avoiding
357        // the obvious implementation:
358        //
359        // self.0.sgxtcbcomponents.each_ref().map(|c| c.svn)
360        let mut out: CpuSvn = [0u8; 16];
361        for (i, c) in self.0.sgxtcbcomponents.iter().enumerate() {
362            out[i] = c.svn;
363        }
364        out
365    }
366
367    /// Returns the index of the TCB component
368    pub fn tcb_component_index(&self, comp: TcbComponentType) -> Option<usize> {
369        self.0.sgxtcbcomponents
370            .iter()
371            .position(|c| TcbComponentType::try_from(c.comp_type.as_str()) == Ok(comp))
372    }
373}
374
375impl<T, U> PartialOrd<TcbComponents<U>> for TcbComponents<T> {
376    /// Compare all 17 components. If all are equal, order as equal. If some
377    /// are less and others are greater, ordering is not defined. If some are
378    /// less, order as less. If some are greater, order as greater.
379    fn partial_cmp(&self, other: &TcbComponents<U>) -> Option<Ordering> {
380        // TODO: This likely violates PartialCmp/PartialEq semantics as it does not take
381        // platform specific data field into account. Likely to create separate
382        // wrapper type to perform this comparison instead of implementing it in
383        // the `TcbComponents` scope.
384        // The main issue is that currently Rust cannot allow defining generic specialization
385        // that intersects with existing generic bounds. Since this impl allows comparison
386        // with differing platform specific type (T vs. U), T.partial_cmp(U) is unspecified.
387        // But if T == U, T.partial_cmp(U) is well-defined.
388        sequence_partial_cmp(self.iter_components().zip(other.iter_components()))
389    }
390}
391
392impl<T, U> PartialEq<TcbComponents<U>> for TcbComponents<T> {
393    fn eq(&self, other: &TcbComponents<U>) -> bool {
394        self.iter_components().eq(other.iter_components())
395    }
396}
397
398impl std::convert::From<TcbComponentsV3> for TcbComponentsV4<SGXSpecificTcbComponentData> {
399    fn from(c: TcbComponentsV3) -> Self {
400        TcbComponentsV4 {
401            sgxtcbcomponents: [
402                c.sgxtcbcomp01svn.into(),
403                c.sgxtcbcomp02svn.into(),
404                c.sgxtcbcomp03svn.into(),
405                c.sgxtcbcomp04svn.into(),
406                c.sgxtcbcomp05svn.into(),
407                c.sgxtcbcomp06svn.into(),
408                c.sgxtcbcomp07svn.into(),
409                c.sgxtcbcomp08svn.into(),
410                c.sgxtcbcomp09svn.into(),
411                c.sgxtcbcomp10svn.into(),
412                c.sgxtcbcomp11svn.into(),
413                c.sgxtcbcomp12svn.into(),
414                c.sgxtcbcomp13svn.into(),
415                c.sgxtcbcomp14svn.into(),
416                c.sgxtcbcomp15svn.into(),
417                c.sgxtcbcomp16svn.into(),
418            ],
419            pcesvn: c.pcesvn,
420            platform_specific_data: SGXSpecificTcbComponentData {}
421        }
422    }
423}
424
425impl<P> TryFrom<TcbComponentsCompatibilitySelector<P>> for TcbComponents<P>
426where
427    TcbComponents<P>: TryFrom<TcbComponentsV3>,
428{
429    type Error = <TcbComponents<P> as TryFrom<TcbComponentsV3>>::Error;
430
431    fn try_from(c: TcbComponentsCompatibilitySelector<P>) -> Result<Self, Self::Error> {
432        match c {
433            TcbComponentsCompatibilitySelector::V3(c) => c.try_into(),
434            TcbComponentsCompatibilitySelector::V4(c) => Ok(TcbComponents(c)),
435        }
436    }
437}
438
439impl<T> std::convert::From<TcbComponentsV4<T>> for TcbComponents<T> {
440    fn from(tcb_components: TcbComponentsV4<T>) -> Self {
441        TcbComponents::<T>(tcb_components)
442    }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq)]
446enum PckCertValue {
447    Cert(Vec<u8>),
448    Missing(String),
449}
450
451impl<'de> Deserialize<'de> for PckCertValue {
452    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
453    where
454        D: Deserializer<'de>,
455    {
456        let s = String::deserialize(deserializer)?;
457        let der = percent_decode(s.as_bytes())
458            .decode_utf8()
459            .map_err(|_| Error::InvalidPcks("utf8 decode error".into()))
460            .map(|c| pem::pem_to_der(c.trim(), Some(PEM_CERTIFICATE)));
461
462        if let Ok(Some(der)) = der {
463            Ok(PckCertValue::Cert(der))
464        } else {
465            Ok(PckCertValue::Missing(s.to_string()))
466        }
467    }
468}
469
470impl Serialize for PckCertValue {
471    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
472    where
473        S: Serializer,
474    {
475        match self {
476            PckCertValue::Cert(der) => serializer.serialize_str(&pem::der_to_pem(der, PEM_CERTIFICATE)),
477            PckCertValue::Missing(s) => serializer.serialize_str(s),
478        }
479    }
480}
481
482#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
483pub struct PckCertBodyItem {
484    tcb: TcbComponents<SGXSpecificTcbComponentData>,
485    tcbm: String,
486    cert: PckCertValue,
487}
488
489#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
490pub struct PckCerts {
491    pck_data: Vec<PckCertBodyItem>,
492    ca_chain: Vec<String>,
493}
494
495impl PckCerts {
496    pub fn new(pck_data: Vec<PckCertBodyItem>, ca_chain: Vec<String>) -> Self {
497        Self { pck_data, ca_chain }
498    }
499
500    pub fn parse(body: &str, ca_chain: Vec<String>) -> Result<PckCerts, Error> {
501        let data: Vec<PckCertBodyItem> = serde_json::from_str(body)?;
502
503        let pcks = PckCerts {
504            pck_data: data,
505            ca_chain,
506        };
507        Ok(pcks)
508    }
509
510    pub fn filename(qe_id: &[u8]) -> String {
511        format!("{}.certs", base16::encode_lower(qe_id))
512    }
513
514    pub fn write_to_file(&self, output_dir: &str, qe_id: &[u8], option: WriteOptions) -> Result<Option<PathBuf>, Error> {
515        let filename = PckCerts::filename(qe_id);
516        io::write_to_file(&self, output_dir, &filename, option)
517    }
518
519    pub fn read_from_file(input_dir: &str, qe_id: &[u8]) -> Result<Self, Error> {
520        let filename = PckCerts::filename(qe_id);
521        let pcks: PckCerts = io::read_from_file(input_dir, &filename)?;
522        Ok(pcks)
523    }
524
525    pub fn fmspc(&self) -> Result<Fmspc, Error> {
526        let pck = self.iter().nth(0).ok_or(Error::NoPckCertData)?;
527        let sgx_extension = SGXPCKCertificateExtension::try_from(pck).map_err(|e| Error::InvalidPckFormat(e))?;
528        Ok(sgx_extension.fmspc)
529    }
530
531    pub fn ca_chain(&self) -> &[String] {
532        &self.ca_chain
533    }
534
535    /// Returns an iterator over the pck certificates (in der format) in this structure.
536    /// WARNING: Missing, or malformed certificates are hidden from the iterator
537    pub fn iter(&self) -> impl Iterator<Item = &Vec<u8>> {
538        self.pck_data.iter().filter_map(|pck_body_item| {
539            if let PckCertValue::Cert(der) = &pck_body_item.cert {
540                Some(der)
541            } else {
542                None
543            }
544        })
545    }
546
547    /// Returns a `Vec` of `PckCert` in this structure.
548    /// WARNING: Missing, or malformed certificates are hidden from the iterator
549    pub fn as_pck_certs(&self) -> Vec<PckCert<Unverified>> {
550        self.iter()
551            .map(|pckcert| PckCert::new(pem::der_to_pem(pckcert, PEM_CERTIFICATE), self.ca_chain.clone()))
552            .collect()
553    }
554
555    /// Order all PCKs according to the tcb info
556    /// TCB Info is carefully ordered by Intel
557    fn order_pcks<T: PlatformTypeForTcbInfo, V: VerificationType>(&self, tcb_info: &TcbData<T, V>) -> Vec<PckCert<Unverified>> {
558        let mut pck_certs = self.as_pck_certs();
559
560        // Sort PCK certs by applicable TCB level. If two certs are in the same TCB
561        // level, maintain existing ordering (stable sort). PCK certs without a TCB
562        // level are sorted last.
563        pck_certs.sort_by_cached_key(|cert| cert.find_sgx_tcb_level_idx(tcb_info).unwrap_or(usize::MAX));
564        pck_certs
565    }
566
567    /// Given the cpusvn, pcesvn and qe_id, searches for the best PCK certificate
568    /// Code re-implements <https://github.com/intel/SGXDataCenterAttestationPrimitives/blob/ab8d31d72f842adb4b8a49eb3639f2e9a789d13b/tools/PCKCertSelection/PCKCertSelectionLib/pck_sorter.cpp#L441>
569    pub fn select_pck<T: PlatformTypeForTcbInfo, V: VerificationType>(
570        &self,
571        tcb_info: &TcbData<T, V>,
572        cpusvn: &[u8; 16],
573        pcesvn: u16,
574        pceid: u16,
575    ) -> Result<PckCert<Unverified>, Error> {
576        // 1. Order PCK certs according to TCB levels
577        let pcks = self.order_pcks(&tcb_info);
578
579        // 2. Find first PCK cert in ordered list that matches current platform
580        let tcb_components = tcb_info.decompose_raw_cpusvn(cpusvn, pcesvn)?;
581        let pck = pcks
582            .iter()
583            .find(|pck| pck.valid_for_tcb(&tcb_components, pceid).is_ok())
584            .ok_or(Error::NoPckForTcbFound)?;
585        Ok(pck.to_owned())
586    }
587
588    #[cfg(feature = "verify")]
589    pub fn issuer(&self) -> Option<DcapArtifactIssuer> {
590        self.iter()
591            .find_map(|pckcert| {
592                let pck = PckCert::new(pem::der_to_pem(pckcert, PEM_CERTIFICATE), self.ca_chain.clone());
593                pck.issuer().ok()
594            })
595    }
596}
597
598#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
599pub struct PckCert<V: VerificationType = Verified> {
600    cert: String,
601    ca_chain: Vec<String>,
602    #[serde(skip_serializing)]
603    _type: V,
604}
605
606impl PckCert<Unverified> {
607    pub fn from_pck_chain(certs: Vec<Cow<'_, str>>) -> Result<PckCert<Unverified>, Error> {
608        if certs.is_empty() {
609            return Err(Error::InvalidPck("Missing CA chain".into()));
610        }
611        if let Some((first, rest)) = certs.split_first() {
612            Ok(PckCert::new(first.to_string(), rest.iter().map(|c| c.to_string()).collect()))
613        } else {
614            Err(Error::InvalidPck("Expected two certificates in CA chain".into()))
615        }
616    }
617
618    /// Creates a new PckCert from the PCK certificate and CA chain. The root certificate must be
619    /// the last certificate in the chain
620    pub fn new(cert: String, ca_chain: Vec<String>) -> PckCert<Unverified> {
621        let ca_chain = ca_chain.iter().map(|cert| cert.trim().to_string()).collect();
622        PckCert {
623            cert,
624            ca_chain,
625            _type: Unverified
626        }
627    }
628
629    #[cfg(feature = "verify")]
630    pub fn verify<B: Deref<Target = [u8]>>(self, trusted_root_certs: &[B], pckcrl: Option<&str>) -> Result<PckCert, Error> {
631        self.verify_with_rootcacrl(trusted_root_certs, &[], pckcrl)
632    }
633
634    #[cfg(feature = "verify")]
635    pub fn verify_with_rootcacrl<B: Deref<Target = [u8]>>(self, trusted_root_certs: &[B], root_ca_crls: &[RootCaCrl], pckcrl: Option<&str>) -> Result<PckCert, Error> {
636        let crl = if let Some(pckcrl) = pckcrl {
637            let pckcrl = PckCrl::new(pckcrl.to_string(), self.ca_chain.clone())?;
638            let pckcrl = pckcrl.verify(trusted_root_certs)?;
639
640            Some(crate::as_mbedtls_crl(&pckcrl.crl)?)
641        } else {
642            None
643        };
644
645        // Attempt to append Root CA CRL to the PCK CRL if available
646        let mut crl = if root_ca_crls.is_empty() {
647            crl
648        } else {
649            let mut base_crl = if let Some(pckcrl) = crl {
650                pckcrl
651            } else {
652                Crl::new()
653            };
654            for crl in root_ca_crls {
655                crl.push_to_crl_list(&mut base_crl)?;
656            }
657            Some(base_crl)
658        };
659
660        let pck = CString::new(self.cert.as_bytes()).map_err(|_| Error::InvalidPck("Conversion into CString failed".into()))?;
661        let pck = Certificate::from_pem(pck.as_bytes_with_nul())
662            .map_err(|_| Error::InvalidPck("Cannot decode PCKCert as pem".into()))?;
663
664        let (mut chain, root) = crate::create_cert_chain(&self.ca_chain)?;
665        chain.insert(0, pck);
666        let trust_ca: MbedtlsList<Certificate> = chain.into_iter().collect();
667        let root_list = std::iter::once(root).collect();
668        let mut err = String::default();
669        Certificate::verify(&trust_ca, &root_list, crl.as_mut(), Some(&mut err))
670            .map_err(|_| Error::InvalidPck(format!("Failed to verify PckCert: {}", err)))?;
671
672        crate::check_root_ca(trusted_root_certs, &root_list)?;
673
674        Ok(PckCert {
675            cert: self.cert,
676            ca_chain: self.ca_chain,
677            _type: Verified,
678        })
679    }
680
681    #[cfg(feature = "verify")]
682    pub fn issuer(&self) -> Result<DcapArtifactIssuer, Error> {
683        let pck = CString::new(self.cert.as_bytes()).map_err(|e| Error::InvalidPck(e.to_string()))?;
684        let pck = Certificate::from_pem(pck.as_bytes_with_nul()).map_err(|e| Error::InvalidPck(e.to_string()))?;
685        let issuer = pck.issuer().map_err(|e| Error::InvalidPck(e.to_string()))?;
686
687        DcapArtifactIssuer::try_from(issuer.as_str())
688    }
689
690    pub fn read_from_file(input_dir: &str, filename: &str) -> Result<Self, Error> {
691        io::read_from_file(input_dir, filename)
692    }
693}
694
695impl PckCert<Verified> {
696    /// Selects the highest matching TCB level
697    /// see <https://api.portal.trustedservices.intel.com/documentation#pcs-tcb-info-v2>
698    pub fn find_tcb_state<V: VerificationType, T: PlatformTypeForTcbInfo>(
699        &self,
700        tcb_data: &TcbData<T, V>,
701    ) -> Option<TcbLevel<T::PlatformSpecificTcbComponentData>> {
702        let idx = self.find_sgx_tcb_level_idx(tcb_data)?;
703        Some(tcb_data.tcb_levels()[idx].clone())
704    }
705
706    #[cfg(feature = "verify")]
707    pub fn pck(&self) -> Result<MbedtlsBox<Certificate>, ErrMbed> {
708        let cert = CString::new(self.cert.as_bytes()).map_err(|_| ErrMbed::HighLevel(codes::X509InvalidFormat))?;
709        Certificate::from_pem(cert.as_bytes_with_nul()).map_err(|_| ErrMbed::HighLevel(codes::X509InvalidFormat))
710    }
711
712    #[cfg(feature = "verify")]
713    pub fn public_key(&self) -> Result<EcPoint, ErrMbed> {
714        let cert = self.pck()?;
715        let pk = cert.public_key();
716        pk.ec_public()
717    }
718
719    pub fn ppid(&self) -> Result<Vec<u8>, ASN1Error> {
720        let extension = self.sgx_extension()?;
721        Ok(extension.ppid)
722    }
723
724    pub fn fmspc(&self) -> Result<Fmspc, ASN1Error> {
725        let extension = self.sgx_extension()?;
726        Ok(extension.fmspc)
727    }
728}
729
730impl<V: VerificationType> PckCert<V> {
731    /// Returns the the CA chain in the order [leaf .. root]
732    pub fn ca_chain(&self) -> &[String] {
733        return &self.ca_chain;
734    }
735
736    pub fn pck_pem<'a>(&'a self) -> &'a String {
737        &self.cert
738    }
739
740    pub fn write_to_file(&self, output_dir: &str, filename: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
741        io::write_to_file(&self, output_dir, &filename, option)
742    }
743
744    pub fn sgx_extension(&self) -> Result<SGXPCKCertificateExtension, ASN1Error> {
745        let der = &pem::pem_to_der(&self.cert, Some(PEM_CERTIFICATE)).ok_or(ASN1Error::new(ASN1ErrorKind::Invalid))?;
746        let cert = GenericCertificate::from_ber(&der)?;
747        let extension = cert
748            .tbscert
749            .get_extension(&SGX_EXTENSION)
750            .ok_or(ASN1Error::new(ASN1ErrorKind::Eof))?;
751        SGXPCKCertificateExtension::parse_extension(&extension.value)
752    }
753
754    pub fn platform_tcb(&self) -> Result<PlatformTCB, ASN1Error> {
755        let extension = self.sgx_extension()?;
756        Ok(extension.tcb)
757    }
758
759    fn as_pck_cert_body_item(&self) -> Result<PckCertBodyItem, ASN1Error> {
760        let ext = self.sgx_extension()?;
761        let cpusvn = ext.tcb.cpusvn;
762        let pce_svn = ext.tcb.tcb_components.0.pcesvn;
763        let mut tcbm = Vec::from(cpusvn);
764        tcbm.extend_from_slice(&pce_svn.to_le_bytes());
765        let cert = pem::pem_to_der(&self.cert, Some(PEM_CERTIFICATE)).ok_or(ASN1Error::new(ASN1ErrorKind::Invalid))?;
766        Ok(PckCertBodyItem {
767            tcb: ext.tcb.tcb_components,
768            tcbm: base16::encode_upper(&tcbm),
769            cert: PckCertValue::Cert(cert),
770        })
771    }
772
773    pub fn sgx_type(&self) -> Result<SGXType, ASN1Error> {
774        let extension = self.sgx_extension()?;
775        Ok(extension.sgx_type)
776    }
777
778    /// Find the index of the highest matching TCB level
779    fn find_sgx_tcb_level_idx<V2: VerificationType, T: PlatformTypeForTcbInfo>(&self, tcb_info: &TcbData<T, V2>) -> Option<usize> {
780        let pck_tcb_level = self.platform_tcb().ok()?;
781        tcb_info.find_sgx_tcb_level_idx(&pck_tcb_level.tcb_components)
782    }
783
784    fn valid_for_tcb(&self, comps: &TcbComponents<SGXSpecificTcbComponentData>, pceid: u16) -> Result<(), Error> {
785        let sgx_extension = self
786            .sgx_extension()
787            .map_err(|_| Error::InvalidPck("Failed to parse SGX extension".into()))?;
788        let tcb = sgx_extension.tcb;
789        if sgx_extension.pceid == pceid && tcb.tcb_components <= *comps {
790            Ok(())
791        } else {
792            Err(Error::InvalidPck("PckCert isn't valid for provided TCB".into()))
793        }
794    }
795}
796
797#[derive(Default, Debug)]
798pub struct PlatformTCB {
799    pub tcb_components: TcbComponents<SGXSpecificTcbComponentData>,
800    pub cpusvn: CpuSvn,
801}
802
803fn decode_tcb_sequence<'a, 'b>(reader: &mut BERReaderSeq<'a, 'b>) -> ASN1Result<PlatformTCB> {
804    let mut platform_tcb = PlatformTCB::default();
805    for i in 1..=18 {
806        platform_tcb = reader.next().read_sequence(|reader| {
807            let oid = reader.next().read_oid()?;
808            if let Some((last, rest)) = oid.components().split_last() {
809                if rest != oid::SGX_EXTENSION_TCB.components().as_slice() || i != *last {
810                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
811                }
812                match last {
813                    i @ 1..=16 => {
814                        platform_tcb.tcb_components.0.sgxtcbcomponents[(i - 1) as usize].svn = reader.next().read_u8()?
815                    }
816                    17 => platform_tcb.tcb_components.0.pcesvn = reader.next().read_u16()?,
817                    18 => {
818                        platform_tcb.cpusvn = reader
819                            .next()
820                            .read_bytes()?
821                            .as_slice()
822                            .try_into()
823                            .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?
824                    }
825                    _ => return Err(ASN1Error::new(ASN1ErrorKind::Invalid)),
826                }
827                Ok(platform_tcb)
828            } else {
829                return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
830            }
831        })?;
832    }
833    Ok(platform_tcb)
834}
835
836fn decode_ber_sgx_type(reader: BERReader) -> ASN1Result<SGXType> {
837    reader
838        .read_enum()?
839        .try_into()
840        .map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))
841}
842
843#[derive(Default, Debug)]
844pub struct SGXPlatformConfiguration {
845    pub dynamic: bool,
846    pub cached_keys: bool,
847    pub smt_enabled: bool,
848}
849
850fn read_tagged<'a, 'b, F, T>(reader: BERReader<'a, 'b>, oid: &ObjectIdentifier, callback: F) -> ASN1Result<T>
851where
852    F: for<'c> FnOnce(BERReader<'a, 'c>) -> ASN1Result<T>,
853{
854    reader.read_sequence(|reader| {
855        if reader.next().read_oid()? != *oid {
856            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
857        }
858        callback(reader.next())
859    })
860}
861
862impl BERDecodable for SGXPlatformConfiguration {
863    fn decode_ber(reader: BERReader) -> ASN1Result<Self> {
864        reader.read_sequence(|reader| {
865            let dynamic = read_tagged(reader.next(), &*oid::SGX_EXTENSION_CONF_DYNAMIC_PLATFORM, |r| r.read_bool())?;
866            let cached_keys = read_tagged(reader.next(), &*oid::SGX_EXTENSION_CONF_CACHED_KEYS, |r| r.read_bool())?;
867            let smt_enabled = read_tagged(reader.next(), &*oid::SGX_EXTENSION_CONF_SMT_ENABLED, |r| r.read_bool())?;
868
869            Ok(SGXPlatformConfiguration {
870                dynamic,
871                cached_keys,
872                smt_enabled,
873            })
874        })
875    }
876}
877
878#[derive(Debug)]
879pub struct SGXPCKCertificateExtension {
880    pub ppid: Vec<u8>,
881    pub tcb: PlatformTCB,
882    pub pceid: u16,
883    pub fmspc: Fmspc,
884    pub sgx_type: SGXType,
885    pub platform_instance_id: Option<Vec<u8>>,
886    pub configuration: Option<SGXPlatformConfiguration>,
887}
888
889impl SGXPCKCertificateExtension {
890    /// Parses an SGX PCK Certificate extension as define in Section 3.5
891    /// <https://download.01.org/intel-sgx/latest/dcap-latest/linux/docs/SGX_PCK_Certificate_CRL_Spec-1.4.pdf>
892    pub fn parse_extension(extension: &[u8]) -> ASN1Result<Self> {
893        yasna::parse_der(extension, |reader| {
894            reader.read_sequence(|reader| {
895                struct SGXPCKCertificateExtensionReader<'r, 'a, 'c> {
896                    reader: &'r mut yasna::BERReaderSeq<'a, 'c>,
897                    current: u64,
898                }
899
900                impl<'r, 'a, 'c> SGXPCKCertificateExtensionReader<'r, 'a, 'c> {
901                    fn next<F, R>(&mut self, with_next: F) -> ASN1Result<R>
902                    where
903                        F: FnOnce(yasna::BERReader) -> ASN1Result<R>,
904                    {
905                        let current = &mut self.current;
906                        self.reader.next().read_sequence(|reader| {
907                            if let Some((last, comp)) = reader.next().read_oid()?.components().split_last() {
908                                if *comp == *oid::SGX_EXTENSION.components().as_slice() && *current == *last {
909                                    *current += 1;
910                                    return with_next(reader.next());
911                                }
912                            }
913                            return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
914                        })
915                    }
916                }
917
918                let mut reader = SGXPCKCertificateExtensionReader { reader, current: 1 };
919
920                let ppid = reader.next(|reader| reader.read_bytes())?;
921                let tcb = reader.next(|reader| reader.read_sequence(|reader| decode_tcb_sequence(reader)))?;
922                let pceid = reader.next(|reader| reader.read_bytes())?;
923                let fmspc = reader.next(|reader| reader.read_bytes())?;
924                let sgx_type = reader.next(|reader| decode_ber_sgx_type(reader))?;
925
926                let mut platform_instance_id = None;
927                let mut configuration = None;
928                if sgx_type == SGXType::Scalable || sgx_type == SGXType::ScalableWithIntegrity {
929                    platform_instance_id = Some(reader.next(|reader| reader.read_bytes())?);
930                    configuration = Some(reader.next(|reader| SGXPlatformConfiguration::decode_ber(reader))?);
931                }
932
933                let fmspc = Fmspc::try_from(&fmspc).map_err(|_| ASN1Error::new(ASN1ErrorKind::Invalid))?;
934                if ppid.len() != 16 || pceid.len() != 2 || platform_instance_id.as_ref().map_or(false, |id| id.len() != 16) {
935                    return Err(ASN1Error::new(ASN1ErrorKind::Invalid));
936                }
937
938                let extension = SGXPCKCertificateExtension {
939                    ppid,
940                    tcb,
941                    pceid: u16::from_be_bytes(pceid.as_slice().try_into().expect("validated len = 2")),
942                    fmspc,
943                    sgx_type,
944                    configuration,
945                    platform_instance_id,
946                };
947
948                Ok(extension)
949            })
950        })
951    }
952}
953
954impl TryFrom<&str> for SGXPCKCertificateExtension {
955    type Error = ASN1Error;
956
957    fn try_from(cert: &str) -> Result<Self, ASN1Error> {
958        let cert = &pem::pem_to_der(cert, Some(PEM_CERTIFICATE)).ok_or(ASN1Error::new(ASN1ErrorKind::Invalid))?;
959        SGXPCKCertificateExtension::try_from(cert)
960    }
961}
962
963impl TryFrom<&Vec<u8>> for SGXPCKCertificateExtension {
964    type Error = ASN1Error;
965
966    fn try_from(cert: &Vec<u8>) -> Result<Self, ASN1Error> {
967        let cert = GenericCertificate::from_ber(&cert)?;
968        let extension = cert
969            .tbscert
970            .get_extension(&SGX_EXTENSION)
971            .ok_or(ASN1Error::new(ASN1ErrorKind::Eof))?;
972        SGXPCKCertificateExtension::parse_extension(&extension.value)
973    }
974}
975
976impl<V> TryFrom<PckCert<V>> for PckCerts
977where
978    V: VerificationType,
979{
980    type Error = ASN1Error;
981
982    fn try_from(pck: PckCert<V>) -> Result<PckCerts, ASN1Error> {
983        let cert_body_item = pck.as_pck_cert_body_item()?;
984
985        Ok(PckCerts {
986            pck_data: vec![cert_body_item],
987            ca_chain: pck.ca_chain,
988        })
989    }
990}
991
992/// NOTE: This conversion is only correct if all PCK certs in the vec have the
993/// same CA chain.
994impl<V> TryFrom<Vec<PckCert<V>>> for PckCerts
995where
996    V: VerificationType,
997{
998    type Error = ASN1Error;
999
1000    fn try_from(mut pcks: Vec<PckCert<V>>) -> Result<PckCerts, ASN1Error> {
1001        let pck_data = pcks.iter().map(|pck| pck.as_pck_cert_body_item()).collect::<Result<Vec<_>, ASN1Error>>()?;
1002        // NOTE: assuming that all PCK certs in the vec have the same CA chain,
1003        // so we pick the ca_chain from the first one:
1004        let ca_chain = match pcks.first_mut() {
1005            Some(first) => mem::take(&mut first.ca_chain),
1006            None => return Err(ASN1Error::new(ASN1ErrorKind::Eof)),
1007        };
1008        Ok(PckCerts { pck_data, ca_chain })
1009    }
1010}
1011
1012#[cfg(test)]
1013mod tests {
1014    use dcap_ql::quote::{Qe3CertDataPckCertChain, Quote, Quote3SignatureEcdsaP256};
1015    use hex::FromHex;
1016    use pkix::derives::ObjectIdentifier;
1017    use sgx_pkix::oid::{SGX_EXTENSION_PPID, SGX_EXTENSION_TCB, SGX_EXTENSION_TCB_COMP01_SVN};
1018    use yasna;
1019    use test_case::test_case;
1020
1021    use super::*;
1022    #[cfg(not(target_env = "sgx"))]
1023    use crate::{get_cert_subject, get_cert_subject_from_der};
1024
1025    fn decode_tcb_item<'a, 'b>(reader: &mut BERReaderSeq<'a, 'b>) -> ASN1Result<(ObjectIdentifier, u8)> {
1026        let oid = reader.next().read_oid()?;
1027        let value = reader.next().read_u8()?;
1028        Ok((oid, value))
1029    }
1030
1031    #[test]
1032    fn sgx_extension_oid() {
1033        let oid_enc = vec![0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x01];
1034
1035        let oid = yasna::parse_der(&oid_enc, |reader| {
1036            let oid = reader.read_oid()?;
1037            Ok(oid)
1038        })
1039        .unwrap();
1040        assert_eq!(oid, *SGX_EXTENSION_PPID);
1041    }
1042
1043    #[test]
1044    fn sgx_extension_ppid() {
1045        let ppid_enc = vec![
1046            0x04, 0x10, 0x88, 0x58, 0x9d, 0xd5, 0x8b, 0xd4, 0xe8, 0x0c, 0x2b, 0x12, 0x49, 0x86, 0x22, 0xa3, 0x48, 0x77,
1047        ];
1048
1049        let ppid = yasna::parse_der(&ppid_enc, |reader| {
1050            let ppid = reader.read_bytes()?;
1051            Ok(ppid)
1052        })
1053        .unwrap();
1054        assert_eq!(
1055            ppid,
1056            vec![136, 88, 157, 213, 139, 212, 232, 12, 43, 18, 73, 134, 34, 163, 72, 119]
1057        );
1058    }
1059
1060    #[test]
1061    fn sgx_extension_ppid_seq() {
1062        let ppid_seq = vec![
1063            0x30, 0x1e, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x01, 0x04, 0x10, 0x88, 0x58, 0x9d,
1064            0xd5, 0x8b, 0xd4, 0xe8, 0x0c, 0x2b, 0x12, 0x49, 0x86, 0x22, 0xa3, 0x48, 0x77,
1065        ];
1066        let (oid, ppid) = yasna::parse_der(&ppid_seq, |reader| {
1067            reader.read_sequence(|reader| {
1068                let oid = reader.next().read_oid()?;
1069                let ppid = reader.next().read_bytes()?;
1070                Ok((oid, ppid))
1071            })
1072        })
1073        .unwrap();
1074        assert_eq!(oid, *SGX_EXTENSION_PPID);
1075        assert_eq!(
1076            ppid,
1077            vec![136, 88, 157, 213, 139, 212, 232, 12, 43, 18, 73, 134, 34, 163, 72, 119]
1078        );
1079    }
1080
1081    #[test]
1082    fn sgx_extension_tcb_comp() {
1083        let tcb_comp_seq = vec![
1084            0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x0d,
1085        ];
1086
1087        let (oid, tcb_comp) = yasna::parse_der(&tcb_comp_seq, |reader| {
1088            reader.read_sequence(|reader| {
1089                let oid = reader.next().read_oid()?;
1090                let tcb_comp = reader.next().read_u8()?;
1091                Ok((oid, tcb_comp))
1092            })
1093        })
1094        .unwrap();
1095        assert_eq!(oid, *SGX_EXTENSION_TCB_COMP01_SVN);
1096        assert_eq!(tcb_comp, 13);
1097    }
1098
1099    #[test]
1100    fn sgx_extension_tcb_comp2() {
1101        let tcb_comp_seq = vec![
1102            0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x0d,
1103        ];
1104
1105        let (oid, tcb_comp) = yasna::parse_der(&tcb_comp_seq, |reader| reader.read_sequence(decode_tcb_item)).unwrap();
1106        assert_eq!(oid, *SGX_EXTENSION_TCB_COMP01_SVN);
1107        assert_eq!(tcb_comp, 13);
1108    }
1109
1110    #[test]
1111    fn sgx_extension_tcb() {
1112        let tcb_enc = vec![
1113            0x30, 0x82, 0x01, 0x64, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x30, 0x82, 0x01,
1114            0x54, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x0d,
1115            0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x02, 0x02, 0x01, 0x0d, 0x30,
1116            0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x03, 0x02, 0x01, 0x02, 0x30, 0x10,
1117            0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x04, 0x02, 0x01, 0x04, 0x30, 0x10, 0x06,
1118            0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x05, 0x02, 0x01, 0x01, 0x30, 0x11, 0x06, 0x0b,
1119            0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x06, 0x02, 0x02, 0x00, 0x80, 0x30, 0x10, 0x06, 0x0b,
1120            0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x30, 0x10, 0x06, 0x0b, 0x2a,
1121            0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x08, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86,
1122            0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x09, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48,
1123            0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x0a, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86,
1124            0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x0b, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8,
1125            0x4d, 0x01, 0x0d, 0x01, 0x02, 0x0c, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d,
1126            0x01, 0x0d, 0x01, 0x02, 0x0d, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01,
1127            0x0d, 0x01, 0x02, 0x0e, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d,
1128            0x01, 0x02, 0x0f, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01,
1129            0x02, 0x10, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02,
1130            0x11, 0x02, 0x01, 0x09, 0x30, 0x1f, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x12,
1131            0x04, 0x10, 0x0d, 0x0d, 0x02, 0x04, 0x01, 0x80, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1132        ];
1133
1134        let (oid, tcb) = yasna::parse_der(&tcb_enc, |reader| {
1135            reader.read_sequence(|reader| {
1136                let oid = reader.next().read_oid()?;
1137                let tcb = reader.next().read_sequence(decode_tcb_sequence)?;
1138                Ok((oid, tcb))
1139            })
1140        })
1141        .unwrap();
1142        assert_eq!(oid, *SGX_EXTENSION_TCB);
1143        assert_eq!(
1144            tcb.tcb_components.0.sgxtcbcomponents.map(|c| c.svn),
1145            [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1146        );
1147        assert_eq!(tcb.cpusvn, [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1148        assert_eq!(tcb.tcb_components.0.pcesvn, 9);
1149    }
1150
1151    #[test]
1152    fn sgx_extension() {
1153        let extension = vec![
1154            0x30, 0x82, 0x01, 0xc1, 0x30, 0x1e, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x01, 0x04,
1155            0x10, 0xa9, 0xf2, 0x39, 0xa8, 0x05, 0xb7, 0xd9, 0x38, 0xf5, 0xb0, 0xea, 0x87, 0x3b, 0x69, 0xdb, 0xa7, 0x30, 0x82,
1156            0x01, 0x64, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x30, 0x82, 0x01, 0x54, 0x30,
1157            0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x01, 0x02, 0x01, 0x0d, 0x30, 0x10,
1158            0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x02, 0x02, 0x01, 0x0d, 0x30, 0x10, 0x06,
1159            0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x03, 0x02, 0x01, 0x02, 0x30, 0x10, 0x06, 0x0b,
1160            0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x04, 0x02, 0x01, 0x04, 0x30, 0x10, 0x06, 0x0b, 0x2a,
1161            0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x05, 0x02, 0x01, 0x01, 0x30, 0x11, 0x06, 0x0b, 0x2a, 0x86,
1162            0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x06, 0x02, 0x02, 0x00, 0x80, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86,
1163            0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x07, 0x02, 0x01, 0x03, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48,
1164            0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x08, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86,
1165            0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x09, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8,
1166            0x4d, 0x01, 0x0d, 0x01, 0x02, 0x0a, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d,
1167            0x01, 0x0d, 0x01, 0x02, 0x0b, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01,
1168            0x0d, 0x01, 0x02, 0x0c, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d,
1169            0x01, 0x02, 0x0d, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01,
1170            0x02, 0x0e, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02,
1171            0x0f, 0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x10,
1172            0x02, 0x01, 0x00, 0x30, 0x10, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x11, 0x02,
1173            0x01, 0x09, 0x30, 0x1f, 0x06, 0x0b, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x02, 0x12, 0x04, 0x10,
1174            0x0d, 0x0d, 0x02, 0x04, 0x01, 0x80, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x10, 0x06,
1175            0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x03, 0x04, 0x02, 0x00, 0x00, 0x30, 0x14, 0x06, 0x0a,
1176            0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x04, 0x04, 0x06, 0x00, 0x90, 0x6e, 0xa1, 0x00, 0x00, 0x30,
1177            0x0f, 0x06, 0x0a, 0x2a, 0x86, 0x48, 0x86, 0xf8, 0x4d, 0x01, 0x0d, 0x01, 0x05, 0x0a, 0x01, 0x00,
1178        ];
1179        let sgx_extension = SGXPCKCertificateExtension::parse_extension(&extension);
1180        assert!(sgx_extension.is_ok());
1181        let sgx_extension = sgx_extension.unwrap();
1182        assert_eq!(
1183            sgx_extension.ppid,
1184            [169, 242, 57, 168, 5, 183, 217, 56, 245, 176, 234, 135, 59, 105, 219, 167]
1185        );
1186        assert_eq!(
1187            sgx_extension.tcb.tcb_components.0.sgxtcbcomponents.map(|c| c.svn),
1188            [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1189        );
1190        assert_eq!(sgx_extension.tcb.tcb_components.0.pcesvn, 9);
1191        assert_eq!(sgx_extension.tcb.cpusvn, [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1192        assert_eq!(sgx_extension.pceid, 0);
1193        assert_eq!(sgx_extension.fmspc, Fmspc::new([0, 144, 110, 161, 0, 0]));
1194        assert_eq!(sgx_extension.sgx_type, SGXType::Standard);
1195        assert!(sgx_extension.platform_instance_id.is_none());
1196        assert!(sgx_extension.configuration.is_none());
1197    }
1198
1199    #[test]
1200    fn sgx_extension_platform_cert() {
1201        let extension = Vec::<u8>::from_hex(
1202            "30820226301e060a2a864886f84d010d010104103f545fc38af1107f31ed41547783bcd730820163060a2a864886f84d010d0102\
1203             308201533010060b2a864886f84d010d0102010201033010060b2a864886f84d010d0102020201033010060b2a864886f84d010d\
1204             0102030201003010060b2a864886f84d010d0102040201003010060b2a864886f84d010d0102050201003010060b2a864886f84d\
1205             010d0102060201003010060b2a864886f84d010d0102070201003010060b2a864886f84d010d0102080201003010060b2a864886\
1206             f84d010d0102090201003010060b2a864886f84d010d01020a0201003010060b2a864886f84d010d01020b0201003010060b2a86\
1207             4886f84d010d01020c0201003010060b2a864886f84d010d01020d0201003010060b2a864886f84d010d01020e0201003010060b\
1208             2a864886f84d010d01020f0201003010060b2a864886f84d010d0102100201003010060b2a864886f84d010d01021102010a301f\
1209             060b2a864886f84d010d0102120410030300000000000000000000000000003010060a2a864886f84d010d010304020000301406\
1210             0a2a864886f84d010d0104040610606a000000300f060a2a864886f84d010d01050a0101301e060a2a864886f84d010d01060410\
1211             5e5a84633cb1ddad3d79b9bea40300923044060a2a864886f84d010d010730363010060b2a864886f84d010d0107010101ff3010\
1212             060b2a864886f84d010d0107020101ff3010060b2a864886f84d010d0107030101ff",
1213        )
1214        .unwrap();
1215        let sgx_extension = SGXPCKCertificateExtension::parse_extension(&extension);
1216        assert!(sgx_extension.is_ok());
1217        let sgx_extension = sgx_extension.unwrap();
1218        assert_eq!(
1219            sgx_extension.ppid,
1220            [0x3F, 0x54, 0x5F, 0xC3, 0x8A, 0xF1, 0x10, 0x7F, 0x31, 0xED, 0x41, 0x54, 0x77, 0x83, 0xBC, 0xD7]
1221        );
1222        assert_eq!(
1223            sgx_extension.tcb.tcb_components.0.sgxtcbcomponents.map(|c| c.svn),
1224            [3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1225        );
1226        assert_eq!(sgx_extension.tcb.tcb_components.0.pcesvn, 10);
1227        assert_eq!(sgx_extension.tcb.cpusvn, [3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1228        assert_eq!(sgx_extension.pceid, 0);
1229        assert_eq!(sgx_extension.fmspc, Fmspc::new([16, 96, 106, 0, 0, 0]));
1230        assert_eq!(sgx_extension.sgx_type, SGXType::Scalable);
1231        assert_eq!(
1232            sgx_extension.platform_instance_id.unwrap(),
1233            [0x5E, 0x5A, 0x84, 0x63, 0x3C, 0xB1, 0xDD, 0xAD, 0x3D, 0x79, 0xB9, 0xBE, 0xA4, 0x03, 0x00, 0x92]
1234        );
1235        let configuration = sgx_extension.configuration.unwrap();
1236        assert!(configuration.dynamic);
1237        assert!(configuration.cached_keys);
1238        assert!(configuration.smt_enabled);
1239    }
1240
1241    #[test]
1242    #[cfg(not(target_env = "sgx"))]
1243    fn read_pckcrt() {
1244        let pck = PckCert::read_from_file(
1245            "./tests/data/",
1246            "5d39f104e642e51c91507932..71b719-0f0f0205ff8007000000000000000000-0900-0000.pckcert",
1247        )
1248        .expect("validated");
1249
1250        assert_eq!(get_cert_subject(&pck.ca_chain.last().unwrap()), "Intel SGX Root CA");
1251        assert_eq!(get_cert_subject(&pck.cert), "Intel SGX PCK Certificate");
1252        #[cfg(feature = "verify")]
1253        {
1254            let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
1255            let root_cas = [&root_ca[..]];
1256            let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
1257            let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_cas).unwrap()];
1258
1259            let platform_crl = reqwest::blocking::get("https://api.trustedservices.intel.com/sgx/certification/v4/pckcrl?ca=platform&encoding=pem")
1260                .unwrap()
1261                .text()
1262                .unwrap();
1263            match pck.clone().verify_with_rootcacrl(&root_cas, &root_ca_crls, Some(&platform_crl)) {
1264                Err(Error::InvalidCrl(ErrMbed::HighLevel(codes::EcpVerifyFailed))) => (),
1265                e => panic!("Unexpected error: {:?}", e),
1266            }
1267            let processor_crl = reqwest::blocking::get("https://api.trustedservices.intel.com/sgx/certification/v4/pckcrl?ca=processor&encoding=pem")
1268                .unwrap()
1269                .text()
1270                .unwrap();
1271
1272            let pck = pck.verify_with_rootcacrl(&root_cas, &root_ca_crls, Some(&processor_crl)).unwrap();
1273
1274            let sgx_extension = pck.sgx_extension().expect("validated");
1275            assert_eq!(
1276                sgx_extension.ppid,
1277                [138, 37, 248, 76, 1, 238, 38, 35, 157, 25, 11, 226, 233, 16, 18, 144]
1278            );
1279            assert_eq!(
1280                sgx_extension.tcb.tcb_components.0.sgxtcbcomponents.map(|c| c.svn),
1281                [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1282            );
1283            assert_eq!(sgx_extension.tcb.tcb_components.0.pcesvn, 9);
1284            assert_eq!(sgx_extension.tcb.cpusvn, [13, 13, 2, 4, 1, 128, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1285            assert_eq!(sgx_extension.pceid, 0);
1286            assert_eq!(sgx_extension.fmspc, Fmspc::new([0, 144, 110, 161, 0, 0]));
1287        }
1288    }
1289
1290    #[test]
1291    fn pckcrt_from_quote() {
1292        let quote = include_bytes!("../tests/data/quote.bin");
1293        let quote = Quote::parse(Cow::from(&quote[..])).unwrap();
1294        let sig = quote.signature::<Quote3SignatureEcdsaP256>().unwrap();
1295        let pck_chain: Qe3CertDataPckCertChain = sig.certification_data().unwrap();
1296        let pck = PckCert::from_pck_chain(pck_chain.certs.into()).unwrap();
1297        let sgx_extension = pck.sgx_extension().unwrap();
1298        assert_eq!(sgx_extension.fmspc, Fmspc::new([0, 144, 110, 161, 0, 0]));
1299    }
1300
1301    #[test]
1302    #[cfg(not(target_env = "sgx"))]
1303    fn read_pckcrts() {
1304        let pcks = PckCerts::read_from_file(
1305            "./tests/data/",
1306            &base16::decode("16a5b41ebb076d263a1e39e64e7175e7".as_bytes()).unwrap(),
1307        )
1308        .expect("validated");
1309        assert_eq!(pcks.iter().count(), 12);
1310        for cert in pcks.iter() {
1311            SGXPCKCertificateExtension::try_from(cert).expect("validated");
1312            assert_eq!(get_cert_subject_from_der(&cert), "Intel SGX PCK Certificate");
1313        }
1314        assert_eq!(get_cert_subject(&pcks.ca_chain.last().unwrap()), "Intel SGX Root CA");
1315
1316        let cert = pcks.iter().next().expect("validated");
1317        let sgx_extension = SGXPCKCertificateExtension::try_from(cert).expect("validated");
1318        assert_eq!(
1319            sgx_extension.ppid,
1320            [138, 37, 248, 76, 1, 238, 38, 35, 157, 25, 11, 226, 233, 16, 18, 144]
1321        );
1322        assert_eq!(
1323            sgx_extension.tcb.tcb_components.0.sgxtcbcomponents.map(|c| c.svn),
1324            [14, 14, 2, 4, 1, 128, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1325        );
1326        assert_eq!(sgx_extension.tcb.tcb_components.0.pcesvn, 10);
1327        assert_eq!(sgx_extension.tcb.cpusvn, [14, 14, 2, 4, 1, 128, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
1328        assert_eq!(sgx_extension.pceid, 0);
1329        assert_eq!(sgx_extension.fmspc, Fmspc::new([0, 144, 110, 161, 0, 0]));
1330    }
1331
1332    #[test]
1333    #[cfg(not(target_env = "sgx"))]
1334    fn read_pckcrts_with_missing_certs() {
1335        let pcks = PckCerts::read_from_file(
1336            "./tests/data/",
1337            &base16::decode("00000000000000000000000000000000".as_bytes()).unwrap(),
1338        )
1339        .expect("validated");
1340        let cert = pem::pem_to_der(
1341            &concat!(
1342                "-----BEGIN CERTIFICATE-----\n",
1343                "MIIE8jCCBJmgAwIBAgIVAIK77m63vG5A1vcRhx5fHPY75FnQMAoGCCqGSM49BAMC\n",
1344                "MHAxIjAgBgNVBAMMGUludGVsIFNHWCBQQ0sgUGxhdGZvcm0gQ0ExGjAYBgNVBAoM\n",
1345                "EUludGVsIENvcnBvcmF0aW9uMRQwEgYDVQQHDAtTYW50YSBDbGFyYTELMAkGA1UE\n",
1346                "CAwCQ0ExCzAJBgNVBAYTAlVTMB4XDTIyMTIxNjEwMTk0OVoXDTI5MTIxNjEwMTk0\n",
1347                "OVowcDEiMCAGA1UEAwwZSW50ZWwgU0dYIFBDSyBDZXJ0aWZpY2F0ZTEaMBgGA1UE\n",
1348                "CgwRSW50ZWwgQ29ycG9yYXRpb24xFDASBgNVBAcMC1NhbnRhIENsYXJhMQswCQYD\n",
1349                "VQQIDAJDQTELMAkGA1UEBhMCVVMwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATq\n",
1350                "R+sFzV6WAsyc8Ka4rul7Hz7l16ToABtGYRzZd5h22Y1eljsI0Vt6GnITfHuiXyS6\n",
1351                "HXsyRZqE4u8nRRTsFKU3o4IDDjCCAwowHwYDVR0jBBgwFoAUlW9dzb0b4elAScnU\n",
1352                "9DPOAVcL3lQwawYDVR0fBGQwYjBgoF6gXIZaaHR0cHM6Ly9hcGkudHJ1c3RlZHNl\n",
1353                "cnZpY2VzLmludGVsLmNvbS9zZ3gvY2VydGlmaWNhdGlvbi92My9wY2tjcmw/Y2E9\n",
1354                "cGxhdGZvcm0mZW5jb2Rpbmc9ZGVyMB0GA1UdDgQWBBR20OYrtxnHDel8lcKFwmhx\n",
1355                "/UEckzAOBgNVHQ8BAf8EBAMCBsAwDAYDVR0TAQH/BAIwADCCAjsGCSqGSIb4TQEN\n",
1356                "AQSCAiwwggIoMB4GCiqGSIb4TQENAQEEEPBi9+kxf7O+L8OZgujiZOswggFlBgoq\n",
1357                "hkiG+E0BDQECMIIBVTAQBgsqhkiG+E0BDQECAQIBBDAQBgsqhkiG+E0BDQECAgIB\n",
1358                "BDAQBgsqhkiG+E0BDQECAwIBAzAQBgsqhkiG+E0BDQECBAIBAzARBgsqhkiG+E0B\n",
1359                "DQECBQICAP8wEQYLKoZIhvhNAQ0BAgYCAgD/MBAGCyqGSIb4TQENAQIHAgEAMBAG\n",
1360                "CyqGSIb4TQENAQIIAgEAMBAGCyqGSIb4TQENAQIJAgEAMBAGCyqGSIb4TQENAQIK\n",
1361                "AgEAMBAGCyqGSIb4TQENAQILAgEAMBAGCyqGSIb4TQENAQIMAgEAMBAGCyqGSIb4\n",
1362                "TQENAQINAgEAMBAGCyqGSIb4TQENAQIOAgEAMBAGCyqGSIb4TQENAQIPAgEAMBAG\n",
1363                "CyqGSIb4TQENAQIQAgEAMBAGCyqGSIb4TQENAQIRAgELMB8GCyqGSIb4TQENAQIS\n",
1364                "BBAEBAMD//8AAAAAAAAAAAAAMBAGCiqGSIb4TQENAQMEAgAAMBQGCiqGSIb4TQEN\n",
1365                "AQQEBgBgagAAADAPBgoqhkiG+E0BDQEFCgEBMB4GCiqGSIb4TQENAQYEEIEDHYFl\n",
1366                "SvQX3oyiTA8B0/MwRAYKKoZIhvhNAQ0BBzA2MBAGCyqGSIb4TQENAQcBAQH/MBAG\n",
1367                "CyqGSIb4TQENAQcCAQH/MBAGCyqGSIb4TQENAQcDAQH/MAoGCCqGSM49BAMCA0cA\n",
1368                "MEQCIA6R9ZOhoLbanU/mPY1hKn3Mk4Wxo0GXb7sEtLzNYWSMAiBnbSyR4iL3qEQt\n",
1369                "GkDTeneBR0bJi4lCLTwIwxg6tuWjdQ==\n",
1370                "-----END CERTIFICATE-----\n"
1371            ),
1372            Some(PEM_CERTIFICATE),
1373        )
1374        .unwrap();
1375        assert_eq!(pcks.pck_data.len(), 5);
1376        assert_eq!(pcks.pck_data[0].cert, PckCertValue::Missing(String::from("Not available")));
1377        assert_eq!(pcks.pck_data[1].cert, PckCertValue::Missing(String::from("Not available")));
1378        assert_eq!(pcks.pck_data[2].cert, PckCertValue::Cert(cert));
1379        assert_eq!(pcks.iter().count(), 3);
1380    }
1381
1382    #[test]
1383    fn pck_cert_value() {
1384        let originals = vec![
1385            PckCertValue::Missing(String::from("Not available")),
1386            PckCertValue::Missing(String::from("bla")),
1387            PckCertValue::Cert(vec![0, 0, 0, 0, 0, 0, 0, 0]),
1388        ];
1389
1390        for original in originals {
1391            let ser = serde_json::to_string(&original).unwrap();
1392            let deser = serde_json::from_str(&ser).unwrap();
1393            assert_eq!(original, deser);
1394        }
1395    }
1396
1397    #[test]
1398    #[cfg(not(target_env = "sgx"))]
1399    fn pckcrts_conversion() {
1400        let pcks = PckCerts::read_from_file(
1401            "./tests/data/",
1402            &base16::decode("16a5b41ebb076d263a1e39e64e7175e7".as_bytes()).unwrap(),
1403        )
1404        .unwrap();
1405
1406        for i in 0..pcks.pck_data.len() {
1407            let pck: PckCert<Unverified> = pcks.as_pck_certs()[i].clone();
1408            let cert = pem::pem_to_der(&pck.cert, Some(PEM_CERTIFICATE)).unwrap();
1409            assert_eq!(pcks.pck_data[i].cert, PckCertValue::Cert(cert));
1410            assert_eq!(pcks.ca_chain.iter().map(|c| c.trim()).collect::<Vec<&str>>(), pck.ca_chain);
1411
1412            let pck: PckCerts = pck.try_into().unwrap();
1413            assert_eq!(
1414                pcks.pck_data[i].tcb.0.sgxtcbcomponents,
1415                pck.pck_data[0].tcb.0.sgxtcbcomponents
1416            );
1417            assert_eq!(pcks.pck_data[i].tcb.0.pcesvn, pck.pck_data[0].tcb.0.pcesvn);
1418            assert_eq!(pcks.pck_data[i].tcbm, pck.pck_data[0].tcbm);
1419            assert_eq!(pcks.pck_data[i].cert, pck.pck_data[0].cert);
1420        }
1421    }
1422
1423    #[test]
1424    fn tcb_level_partial_cmp() {
1425        let base_tcb = [10, 20, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1426        let base = TcbComponents::<SGXSpecificTcbComponentData>::from_raw(base_tcb, 40);
1427        let base = &base;
1428        let mut other = base.clone();
1429        assert_eq!(base.partial_cmp(&other), Some(Ordering::Equal));
1430
1431        other = base.clone();
1432        other.0.sgxtcbcomponents = [10, 20, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].map(|c| c.into());
1433        assert_eq!(base.partial_cmp(&other), Some(Ordering::Less));
1434
1435        other = base.clone();
1436        other.0.sgxtcbcomponents = [20, 20, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].map(|c| c.into());
1437        assert_eq!(base.partial_cmp(&other), Some(Ordering::Less));
1438
1439        other = base.clone();
1440        other.0.sgxtcbcomponents = [0, 20, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].map(|c| c.into());
1441        assert_eq!(base.partial_cmp(&other), Some(Ordering::Greater));
1442
1443        other = base.clone();
1444        other.0.sgxtcbcomponents = [10, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].map(|c| c.into());
1445        assert_eq!(base.partial_cmp(&other), Some(Ordering::Greater));
1446
1447        other = base.clone();
1448        other.0.sgxtcbcomponents = [0, 20, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].map(|c| c.into());
1449        assert_eq!(base.partial_cmp(&other), None);
1450
1451        other = base.clone();
1452        other.0.pcesvn = 50;
1453        assert_eq!(base.partial_cmp(&other), Some(Ordering::Less));
1454
1455        other = base.clone();
1456        other.0.pcesvn = 30;
1457        assert_eq!(base.partial_cmp(&other), Some(Ordering::Greater));
1458    }
1459
1460    // Case 1: TeeTcbSvn[1] == 0
1461    #[test_case([10, 0, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Equal))]
1462    #[test_case([10, 0, 20, 40, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Less))]
1463    #[test_case([20, 0, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Less))]
1464    #[test_case([0, 0, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Greater))]
1465    #[test_case([10, 0, 20, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Greater))]
1466    #[test_case([0, 0, 20, 30, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], None)]
1467    // Case 2: TeeTcbSvn[1] != 0
1468    #[test_case([5, 1, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Equal))]
1469    #[test_case([5, 1, 30, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Less))]
1470    #[test_case([5, 1, 20, 40, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Less))]
1471    #[test_case([30, 1, 10, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Greater))]
1472    #[test_case([30, 1, 20, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], Some(Ordering::Greater))]
1473    #[test_case([30, 1, 10, 30, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], None)]
1474    fn tdx_tcb_level_partial_cmp(other_arr: [u8; 16], expected_comparison: Option<Ordering>) {
1475        let base_tcb = [10, 0, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
1476        let base = TDXSpecificTcbComponentData::from_raw(base_tcb);
1477        let other = TDXSpecificTcbComponentData::from_raw(other_arr);
1478        assert_eq!(base.partial_cmp(&other), expected_comparison);
1479    }
1480
1481    #[test]
1482    fn tcb_components_cpu_svn() {
1483        let raw_cpu_svn = [
1484            10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
1485        ];
1486        let comp = TcbComponentsOf::<platform::SGX>::from_raw(raw_cpu_svn, 42);
1487        assert_eq!(comp.cpu_svn(), raw_cpu_svn);
1488    }
1489
1490    #[test]
1491    #[cfg(feature = "verify")]
1492    fn pck_for_tcb() {
1493        use crate::platform;
1494
1495        let root_ca = include_bytes!("../tests/data/root_SGX_CA_der.cert");
1496        let root_cas = [&root_ca[..]];
1497        let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
1498        let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_cas).unwrap()];
1499
1500        let pck_certs = PckCerts::read_from_file(
1501            "./tests/data/",
1502            &base16::decode("881c3086c0eef78f60f5702a7e379efe".as_bytes()).unwrap())
1503            .unwrap();
1504        let tcb_info = crate::TcbInfo::<platform::SGX>::read_from_file("./tests/data/", &Fmspc::try_from("90806F000000").unwrap(), Some(19))
1505            .unwrap();
1506        // This TCB matches exactly with the first PCK cert in the list. This PCK cert must be
1507        // selected
1508        let cpusvn = [8, 8, 2, 2, 4, 1, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0];
1509        let pcesvn = 11;
1510        let pceid = 0;
1511
1512        let pck_cert = pck_certs.select_pck(&tcb_info.data().unwrap(), &cpusvn, pcesvn, pceid)
1513            .unwrap()
1514            .verify_with_rootcacrl(&root_cas, &root_ca_crls, None)
1515            .unwrap();
1516        let ext = pck_cert.sgx_extension().unwrap();
1517        assert_eq!(ext.tcb.tcb_components, TcbComponents::<SGXSpecificTcbComponentData>::from_raw(cpusvn, pcesvn));
1518        assert_eq!(ext.tcb.cpusvn, cpusvn);
1519        assert_eq!(ext.pceid, pceid);
1520    }
1521}