Skip to main content

pcs/
tcb_info.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::convert::TryFrom;
9use std::convert::TryInto;
10use std::marker::PhantomData;
11use std::path::PathBuf;
12
13use chrono::{DateTime, Utc};
14use serde::{de, de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer};
15use serde_json::value::RawValue;
16#[cfg(feature = "verify")]
17use {
18    std::ops::Deref, crate::RootCaCrl
19};
20
21use crate::io::WriteOptions;
22use crate::pckcrt::{PlatformTypeForTcbComponent, TcbComponentsV3};
23use crate::{io, CpuSvn, Error, PceIsvsvn, TcbStatus, Unverified, VerificationType, Verified};
24use crate::{
25    pckcrt::{TcbComponentType, TcbComponents},
26    platform, PlatformType,
27};
28
29#[derive(Debug, Clone, Hash, PartialEq, Eq)]
30pub struct Fmspc([u8; 6]);
31
32#[derive(Debug)]
33pub enum FmspcDecodeError {
34    InvalidHex,
35    InvalidFmspcLength,
36}
37
38impl From<base16::DecodeError> for FmspcDecodeError {
39    fn from(_value: base16::DecodeError) -> FmspcDecodeError {
40        FmspcDecodeError::InvalidHex
41    }
42}
43
44impl Fmspc {
45    pub const fn new(value: [u8; 6]) -> Self {
46        Fmspc(value)
47    }
48
49    pub fn as_bytes(&self) -> &[u8; 6] {
50        &self.0
51    }
52}
53
54impl From<[u8; 6]> for Fmspc {
55    fn from(value: [u8; 6]) -> Fmspc {
56        Fmspc::new(value)
57    }
58}
59
60impl TryFrom<&[u8]> for Fmspc {
61    type Error = FmspcDecodeError;
62
63    fn try_from(value: &[u8]) -> Result<Fmspc, FmspcDecodeError> {
64        let value = <[u8; 6]>::try_from(value).map_err(|_| FmspcDecodeError::InvalidFmspcLength)?;
65        Ok(Fmspc::new(value))
66    }
67}
68
69impl TryFrom<&Vec<u8>> for Fmspc {
70    type Error = FmspcDecodeError;
71
72    fn try_from(value: &Vec<u8>) -> Result<Fmspc, FmspcDecodeError> {
73        Fmspc::try_from(value.as_slice())
74    }
75}
76
77impl TryFrom<&str> for Fmspc {
78    type Error = FmspcDecodeError;
79
80    fn try_from(value: &str) -> Result<Fmspc, FmspcDecodeError> {
81        let value = base16::decode(value)?;
82        Fmspc::try_from(value.as_slice())
83    }
84}
85
86impl TryFrom<&String> for Fmspc {
87    type Error = FmspcDecodeError;
88
89    fn try_from(value: &String) -> Result<Fmspc, FmspcDecodeError> {
90        Fmspc::try_from(value.as_str())
91    }
92}
93
94impl ToString for Fmspc {
95    fn to_string(&self) -> String {
96        base16::encode_lower(&self.0)
97    }
98}
99
100impl Serialize for Fmspc {
101    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
102    where
103        S: Serializer,
104    {
105        self.to_string().serialize(serializer)
106    }
107}
108
109impl<'de> Deserialize<'de> for Fmspc {
110    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
111    where
112        D: Deserializer<'de>,
113    {
114        let fmspc = <&str>::deserialize(deserializer)?;
115        Fmspc::try_from(fmspc).map_err(|_| de::Error::custom("Bad fmspc format"))
116    }
117}
118
119#[derive(Serialize, Deserialize, Clone, Debug)]
120#[serde(rename_all = "camelCase")]
121pub struct TcbLevel<P> {
122    #[serde(bound(deserialize = "TcbComponents<P>: TryFrom<TcbComponentsV3, Error: std::fmt::Display>, P : Deserialize<'de>"))]
123    pub(crate) tcb: TcbComponents<P>,
124    #[serde(with = "crate::iso8601")]
125    tcb_date: DateTime<Utc>,
126    pub(crate) tcb_status: TcbStatus,
127    #[serde(default, rename = "advisoryIDs", skip_serializing_if = "Vec::is_empty")]
128    advisory_ids: Vec<AdvisoryID>,
129}
130
131pub type TcbLevelOf<T> = TcbLevel<<T as PlatformTypeForTcbComponent>::PlatformSpecificTcbComponentData>;
132
133impl<P> TcbLevel<P> {
134    pub fn components(&self) -> &TcbComponents<P> {
135        &self.tcb
136    }
137
138    pub fn tcb_status(&self) -> TcbStatus {
139        self.tcb_status
140    }
141
142    pub fn advisory_ids(&self) -> &Vec<AdvisoryID> {
143        &self.advisory_ids
144    }
145
146    pub fn tcb_date(&self) -> &DateTime<Utc> {
147        &self.tcb_date
148    }
149}
150
151#[derive(Clone, Debug, PartialEq, Eq)]
152pub enum AdvisoryID {
153    /// Security Advisory ID - "INTEL-SA-XXXXX" (where XXXXX is a placeholder for a 5-digit
154    /// number) - representing Security Advisories that can be searched on IntelĀ® Product
155    /// Security Center Advisories page
156    /// (<https://www.intel.com/content/www/us/en/security-center/default.html>)
157    Security(u32),
158    /// Document Advisory ID - "INTEL-DOC-XXXXX" (where XXXXX is a placeholder for a 5-digit
159    /// number) - representing articles containing additional information about the attested
160    /// platform. The articles can be found under the following URL:
161    /// <https://api.trustedservices.intel.com/documents/{docID}>
162    Documentation(u32)
163}
164
165impl ToString for AdvisoryID {
166    fn to_string(&self) -> String {
167        match self {
168            AdvisoryID::Security(v) => format!("INTEL-SA-{:05}", v),
169            AdvisoryID::Documentation(v) => format!("INTEL-DOC-{:05}", v),
170        }
171    }
172}
173
174impl TryFrom<&str> for AdvisoryID {
175    type Error = &'static str;
176
177    fn try_from(s: &str) -> Result<AdvisoryID, &'static str> {
178        fn tokenize(s: &str) -> Result<(String, String, u32), &'static str> {
179            let mut chunks = s.trim().split('-');
180
181            let intel = chunks.next().ok_or("Couldn't parse INTEL part of advisory ID number")?;
182            let typ = chunks.next().ok_or("Couldn't parse type of advisory ID number")?;
183            let value = chunks.next().ok_or("Couldn't parse value of advisory ID number")?;
184            let value = u32::from_str_radix(value, 10).map_err(|_| "Couldn't parse advisory ID number")?;
185
186            if chunks.next().is_some() {
187                return Err("Failed to parse Advisory ID");
188            }
189
190            Ok((intel.to_string(), typ.to_string(), value))
191        }
192
193        let (intel, typ, value) = tokenize(s)?;
194        if intel.to_uppercase() != "INTEL" {
195            return Err("Advisory IDs must start with INTEL");
196        }
197
198        match typ.to_uppercase().as_str() {
199            "SA" => Ok(AdvisoryID::Security(value)),
200            "DOC" => Ok(AdvisoryID::Documentation(value)),
201            _ => Err("Not a security nor document advisory ID"),
202        }
203    }
204}
205
206impl Serialize for AdvisoryID {
207    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
208    where
209        S: Serializer,
210    {
211        self.to_string().serialize(serializer)
212    }
213}
214
215impl<'de> Deserialize<'de> for AdvisoryID {
216    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
217    where
218        D: Deserializer<'de>,
219    {
220        let advisory = <&str>::deserialize(deserializer)?;
221        AdvisoryID::try_from(advisory).map_err(|e| de::Error::custom(format!("Bad AdvisoryID format: {e}")))
222    }
223}
224
225#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
226#[serde(rename_all = "camelCase")]
227pub struct TdxModule {
228    #[serde(deserialize_with = "tdx_mrsigner_deserializer", serialize_with = "tdx_mrsigner_serializer")]
229    pub mrsigner: [u8; 48],
230    #[serde(deserialize_with = "tdx_attribute_deserializer", serialize_with = "tdx_attribute_serializer")]
231    pub attributes: u64,
232    #[serde(deserialize_with = "tdx_attribute_deserializer", serialize_with = "tdx_attribute_serializer")]
233    pub attributes_mask: u64
234}
235
236impl Default for TdxModule {
237    fn default() -> Self {
238        Self { mrsigner: [0; 48], attributes: Default::default(), attributes_mask: Default::default() }
239    }
240}
241
242#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
243#[serde(rename_all = "camelCase")]
244pub struct TdxModuleIdentity {
245    #[serde(
246        deserialize_with = "tdx_id_deserializer",
247        serialize_with = "tdx_id_serializer"
248    )]
249    id: u8,
250    #[serde(flatten)]
251    tdx_module: TdxModule,
252    tcb_levels: Vec<TdxModuleTcbLevel>,
253}
254
255impl TdxModuleIdentity {
256    pub fn mrsigner(&self) -> &[u8; 48] {
257        &self.tdx_module.mrsigner
258    }
259
260    pub fn attributes(&self) -> u64 {
261        self.tdx_module.attributes
262    }
263
264    pub fn attributes_mask(&self) -> u64 {
265        self.tdx_module.attributes_mask
266    }
267
268    pub fn tcb_levels_iter(&self) -> impl Iterator<Item = &TdxModuleTcbLevel> + '_ {
269        self.tcb_levels.iter()
270    }
271
272    #[deprecated(since="0.8.3", note = "use `find_tcb_level` instead")]
273    pub fn find_best_tcb_level(&self, level: u64) -> Option<&TdxModuleTcbLevel> {
274        self.find_tcb_level(level)
275    }
276
277    /// Function to find best TDX TCB level for this TDX Module
278    pub(crate) fn find_tcb_level(&self, level: u64) -> Option<&TdxModuleTcbLevel> {
279        // Continuing reference:
280        // https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
281        //
282        // 5. [...] for the selected TDX Module Identity go over the sorted collection of TCB Levels
283        //    starting from the first item on the list and compare its isvsvn value to the TEE TCB SVN at
284        //    index 0. If TEE TCB SVN at index 0 is greater or equal to its value, read tcbStatus assigned
285        //    to this TCB level, otherwise move to the next item on TCB levels list.
286        self.tcb_levels.iter().find(|tcb| tcb.tcb() <= level)
287    }
288}
289
290#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
291#[serde(rename_all = "camelCase")]
292pub struct TdxModuleTcbLevelIsvSvn {
293    isvsvn: u64,
294}
295
296#[derive(Clone, Debug, Deserialize, Eq, PartialEq)]
297#[serde(rename_all = "camelCase")]
298pub struct TdxModuleTcbLevel {
299    tcb: TdxModuleTcbLevelIsvSvn,
300    #[serde(with = "crate::iso8601")]
301    tcb_date: DateTime<Utc>,
302    tcb_status: TcbStatus,
303    #[serde(default, rename = "advisoryIDs", skip_serializing_if = "Vec::is_empty")]
304    advisory_ids: Vec<AdvisoryID>,
305}
306
307impl TdxModuleTcbLevel {
308    pub fn tcb(&self) -> u64 {
309        self.tcb.isvsvn
310    }
311
312    pub fn tcb_date(&self) -> DateTime<Utc> {
313        self.tcb_date
314    }
315
316    pub fn tcb_status(&self) -> TcbStatus {
317        self.tcb_status
318    }
319
320    pub fn advisory_ids_iter(&self) -> impl Iterator<Item = &AdvisoryID> + '_ {
321        self.advisory_ids.iter()
322    }
323}
324
325/// Deserializer function for TDX ID as it appears in the TDX Module entry of the TDX TCB Info.
326/// TDX ID is always in the format of "TDX_xx" in which xx is a number of the TDX Module ID.
327/// It is confirmed from Intel that xx is in base 16 radix.
328///
329/// Reference: https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
330/// step no. 5
331fn tdx_id_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u8, D::Error> {
332    let id_str = String::deserialize(deserializer)?;
333    let split = id_str
334        .strip_prefix("TDX_")
335        .ok_or(serde::de::Error::custom(format!(
336            "Failed to parse TDX ID. Found: {id_str}"
337        )))?;
338
339    u8::from_str_radix(split, 16)
340        .map_err(|_| serde::de::Error::custom(format!("Failed to parse TDX ID. Found: {id_str}")))
341}
342
343
344#[allow(unused)]
345fn tdx_id_serializer<S>(id: &u8, serializer: S) -> Result<S::Ok, S::Error>
346where
347    S: ::serde::Serializer,
348{
349    serializer.serialize_str(format!("TDX_{id:02X}").as_str())
350}
351
352fn tdx_mrsigner_deserializer<'de, D: Deserializer<'de>>(
353    deserializer: D,
354) -> Result<[u8; 48], D::Error> {
355    let mrsigner = String::deserialize(deserializer)?;
356    let mrsigner = base16::decode(&mrsigner).map_err(de::Error::custom)?;
357    mrsigner.as_slice().try_into().map_err(de::Error::custom)
358}
359
360#[allow(unused)]
361fn tdx_mrsigner_serializer<S>(
362    mrsigner: &[u8; 48],
363    serializer: S,
364) -> Result<S::Ok, S::Error>
365where
366    S: ::serde::Serializer,
367{
368    let mrsigner = base16::encode_upper(mrsigner);
369    serializer.serialize_str(&mrsigner)
370}
371
372fn tdx_attribute_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
373    let attribute = String::deserialize(deserializer)?;
374    u64::from_str_radix(&attribute, 16).map_err(de::Error::custom)
375}
376
377#[allow(unused)]
378fn tdx_attribute_serializer<S>(attribute: u64, serializer: S) -> Result<S::Ok, S::Error>
379where
380    S: ::serde::Serializer,
381{
382    let attribute = format!("{attribute:16x}");
383    serializer.serialize_str(&attribute)
384}
385
386pub trait PlatformTypeForTcbInfo : PlatformType + PlatformTypeForTcbComponent {
387    type PlatformSpecificTcbData: DeserializeOwned + Default;
388    fn extra_extension() -> &'static str;
389}
390
391#[derive(Deserialize, Default, Clone, Debug, Eq, PartialEq)]
392pub struct SGXSpecificTcbData {}
393
394#[derive(Deserialize, Default, Clone, Debug, Eq, PartialEq)]
395#[serde(rename_all = "camelCase")]
396pub struct TDXSpecificTcbData {
397    pub(crate) tdx_module: TdxModule,
398    pub(crate) tdx_module_identities: Vec<TdxModuleIdentity>,
399}
400
401impl PlatformTypeForTcbInfo for platform::SGX {
402    type PlatformSpecificTcbData = SGXSpecificTcbData;
403
404    fn extra_extension() -> &'static str {
405        ""
406    }
407}
408
409#[allow(dead_code)]
410#[allow(unused)]
411impl PlatformTypeForTcbInfo for platform::TDX  {
412    type PlatformSpecificTcbData = TDXSpecificTcbData;
413
414    fn extra_extension() -> &'static str {
415        ".tdx"
416    }
417}
418
419#[allow(dead_code)]
420#[derive(Clone, Debug, Deserialize)]
421#[serde(rename_all = "camelCase")]
422pub struct TcbData<T: PlatformTypeForTcbInfo, V: VerificationType = Verified> {
423    #[serde(default)]
424    #[serde(deserialize_with = "crate::deserialize_platform_id")]
425    id: T,
426    version: u16,
427    #[serde(with = "crate::iso8601")]
428    issue_date: DateTime<Utc>,
429    #[serde(with = "crate::iso8601")]
430    next_update: DateTime<Utc>,
431    fmspc: Fmspc,
432    pce_id: String,
433    tcb_type: u16,
434    tcb_evaluation_data_number: u64,
435    #[serde(rename = "tcbLevels")]
436    tcb_levels: Vec<TcbLevel<T::PlatformSpecificTcbComponentData>>,
437    #[serde(flatten)]
438    platform_specific_data: T::PlatformSpecificTcbData,
439    type_: V,
440}
441
442impl<T: PlatformTypeForTcbInfo> TcbData<T, Verified> {
443    pub fn version(&self) -> u16 {
444        self.version
445    }
446
447    pub fn fmspc(&self) -> &Fmspc {
448        &self.fmspc
449    }
450
451    pub fn issue_date(&self) -> &DateTime<Utc> {
452        &self.issue_date
453    }
454
455    pub fn next_update(&self) -> &DateTime<Utc> {
456        &self.next_update
457    }
458
459    /// Function to find matching TCB level, but disregarding the platform-specific
460    /// TCB components, and only compares the SGX TCB components.
461    pub fn find_sgx_tcb_level<TT>(
462        &self,
463        tcb_level: &TcbComponents<TT>,
464    ) -> Option<&TcbLevel<T::PlatformSpecificTcbComponentData>> {
465        let idx = self.find_sgx_tcb_level_idx(tcb_level)?;
466        Some(&self.tcb_levels[idx])
467    }
468}
469
470impl<'de, T: PlatformTypeForTcbInfo> TcbData<T, Unverified> {
471    pub(crate) fn parse(raw_tcb_data: &String) -> Result<TcbData<T, Unverified>, Error> {
472        let data: TcbData<T, Unverified> = serde_json::from_str(&raw_tcb_data).map_err(|e| Error::ParseError(e))?;
473        if data.version != 2 && data.version != 3 {
474            return Err(Error::UnknownTcbInfoVersion(data.version));
475        }
476
477        // Only tcb_type 0 is known at the moment, verify that it has that expected value
478        if data.tcb_type != 0 {
479            return Err(Error::UnknownTcbType(data.tcb_type));
480        }
481        Ok(data)
482    }
483
484    /// Returns the index of the TCB component
485    pub fn tcb_component_index(&self, comp: TcbComponentType) -> Option<usize> {
486        if let Some(c) = self.tcb_levels.first() {
487            c.components().tcb_component_index(comp)
488        } else {
489            None
490        }
491    }
492}
493
494impl<T: PlatformTypeForTcbInfo, V: VerificationType> TcbData<T, V> {
495    pub fn tcb_evaluation_data_number(&self) -> u64 {
496        self.tcb_evaluation_data_number
497    }
498
499    // NOTE: don't make this publicly available. We want to prevent people from
500    // accessing the TCB levels without checking whether the TcbInfo is valid.
501    pub(crate) fn tcb_levels(&self) -> &Vec<TcbLevel<T::PlatformSpecificTcbComponentData>> {
502        &self.tcb_levels
503    }
504
505    pub(crate) fn decompose_raw_cpusvn(
506        &self,
507        raw_cpusvn: &[u8; 16],
508        pce_svn: u16,
509    ) -> Result<TcbComponents<crate::pckcrt::SGXSpecificTcbComponentData>, Error> {
510        if self.tcb_type != 0 {
511            return Err(Error::UnknownTcbType(self.tcb_type));
512        }
513
514        // TCB Type 0 simply copies cpu svn
515        Ok(TcbComponents::<crate::pckcrt::SGXSpecificTcbComponentData>::from_raw(*raw_cpusvn, pce_svn))
516    }
517
518    pub fn iter_tcb_components(&self) -> impl Iterator<Item = (CpuSvn, PceIsvsvn)> + '_ {
519        self.tcb_levels
520            .iter()
521            .map(|tcb_level| (tcb_level.tcb.cpu_svn(), tcb_level.tcb.pce_svn()))
522    }
523
524    pub(crate) fn find_sgx_tcb_level_idx<TT>(&self, tcb_level: &TcbComponents<TT>) -> Option<usize> {
525        // Reference:
526        // https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-v4
527        //
528        // 3. Go over the sorted collection of TCB Levels retrieved from TCB Info starting from the first item on the list:
529        //   a. Compare all of the SGX TCB Comp SVNs retrieved from the SGX PCK Certificate (from 01 to 16) with the corresponding
530        //      values in the TCB Level. If all SGX TCB Comp SVNs in the certificate are greater or equal to the corresponding values
531        //      in TCB Level, go to 3.b, otherwise move to the next item on TCB Levels list.
532        //   b. Compare PCESVN value retrieved from the SGX PCK certificate with the corresponding value in the TCB Level. If it is
533        //      greater or equal to the value in TCB Level, read status assigned to this TCB level. Otherwise, move to the next item
534        //      on TCB Levels list.
535        // 4. If no TCB level matches your SGX PCK Certificate, your TCB Level is not supported.
536        self.tcb_levels()
537            .iter()
538            .position(|tcb| *tcb.components() <= *tcb_level)
539    }
540}
541
542#[derive(Debug)]
543pub enum TdxTcbLevel<'a> {
544    TcbLevel(&'a TcbLevelOf<platform::TDX>),
545    TcbLevelWithModule(&'a TcbLevelOf<platform::TDX>, &'a TdxModuleTcbLevel),
546}
547
548impl TcbData<platform::TDX, Verified> {
549    pub fn tdx_module(&self) -> &TdxModule {
550        &self.platform_specific_data.tdx_module
551    }
552
553    pub fn iter_tdx_module_identities(&self) -> impl Iterator<Item = &TdxModuleIdentity> + '_ {
554        self.platform_specific_data.tdx_module_identities.iter()
555    }
556
557    pub fn find_tdx_module_identity(&self, id: u8) -> Option<&TdxModuleIdentity> {
558        self.platform_specific_data
559            .tdx_module_identities
560            .iter()
561            .find(|x| x.id == id)
562    }
563
564    /// Function to find matching TCB level with TDX TCB comparison function
565    pub fn find_tdx_tcb_level<'a>(
566        &'a self,
567        tcb_level: &TcbComponents<
568            <platform::TDX as PlatformTypeForTcbComponent>::PlatformSpecificTcbComponentData,
569        >,
570    ) -> Option<TdxTcbLevel<'a>> {
571        // Continuing reference from:
572        // https://api.portal.trustedservices.intel.com/content/documentation.html#pcs-tcb-info-tdx-v4
573        //
574        // 4. If no TCB level matches your SGX PCK Certificate and TD Report, your TCB level is not supported.
575        let matching_tcb_level = self.tcb_levels().iter().find(|tcb| {
576            *tcb.components() <= *tcb_level
577                && *tcb.components().tdx_tcb_components() <= *tcb_level.tdx_tcb_components()
578        })?;
579
580        // 5. Perform additional TCB status evaluation for TDX module in case TEE TCB SVN at index 1 is greater or
581        //    equal to 1, otherwise finish the comparison logic. In order to determine TCB status of TDX module,
582        //    find a matching TDX Module Identity (in tdxModuleIdentities array of TCB Info) with its id set to
583        //    "TDX_<version>" where <version> matches the value of TEE TCB SVN at index 1. If a matching TDX Module
584        //    Identity cannot be found, go to step 6, otherwise, for the selected TDX Module Identity go over the
585        //    sorted collection of TCB Levels starting from the first item on the list and compare its isvsvn value
586        //    to the TEE TCB SVN at index 0. If TEE TCB SVN at index 0 is greater or equal to its value,
587        //    read tcbStatus assigned to this TCB level, otherwise move to the next item on TCB levels list.
588        // 6. If no TCB level matches, the TCB level of TDX Module is not supported.
589        if tcb_level.tdx_tcb_components().tdx_module_id() == 0 {
590            Some(TdxTcbLevel::TcbLevel(matching_tcb_level))
591        } else {
592            // If tdxtcbcomponent[1] != 0, we have to iterate TDX modules
593            let tdx_module =
594                self.find_tdx_module_identity(tcb_level.tdx_tcb_components().tdx_module_id())?;
595            let tdx_module_tcb_level = tdx_module
596                .find_tcb_level(tcb_level.tdx_tcb_components().tdx_module_svn().into())?;
597            Some(TdxTcbLevel::TcbLevelWithModule(
598                matching_tcb_level,
599                tdx_module_tcb_level,
600            ))
601        }
602    }
603}
604
605#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
606pub struct TcbInfo<T> {
607    raw_tcb_info: String,
608    signature: Vec<u8>,
609    ca_chain: Vec<String>,
610    #[serde(skip)]
611    _type: PhantomData<T>
612}
613
614impl<T> TcbInfo<T> {
615    const FILENAME_EXTENSION: &'static str = ".tcb";
616
617    pub fn new(raw_tcb_info: String, signature: Vec<u8>, ca_chain: Vec<String>) -> Self {
618        TcbInfo {
619            raw_tcb_info,
620            signature,
621            ca_chain,
622            _type: PhantomData
623        }
624    }
625
626    pub fn parse(body: &String, ca_chain: Vec<String>) -> Result<Self, Error> {
627        #[derive(Deserialize)]
628        #[serde(rename_all = "camelCase")]
629        struct IntelTcbInfoSigned<'a> {
630            #[serde(borrow, rename = "tcbInfo")]
631            raw_tcb_info: &'a RawValue,
632            #[serde(deserialize_with = "crate::intel_signature_deserializer")]
633            signature: Vec<u8>,
634        }
635        let IntelTcbInfoSigned { raw_tcb_info, signature } = serde_json::from_str(&body)?;
636
637        Ok(TcbInfo::new(raw_tcb_info.to_string(), signature, ca_chain))
638    }
639
640    pub fn raw_tcb_info(&self) -> &String {
641        &self.raw_tcb_info
642    }
643
644    pub fn signature(&self) -> &Vec<u8> {
645        &self.signature
646    }
647
648    pub fn certificate_chain(&self) -> &Vec<String> {
649        &self.ca_chain
650    }
651}
652
653impl<T: PlatformTypeForTcbInfo> TcbInfo<T> {
654    pub fn create_filename(fmspc: &str, evaluation_data_number: Option<u64>) -> String {
655        let file_extension = format!("{}{}", T::extra_extension(), Self::FILENAME_EXTENSION);
656        io::compose_filename(fmspc, file_extension.as_str(), evaluation_data_number)
657    }
658
659    pub fn write_to_file(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
660        let data = TcbData::<T, Unverified>::parse(&self.raw_tcb_info)?;
661        let filename = Self::create_filename(&data.fmspc.to_string(), Some(data.tcb_evaluation_data_number));
662        io::write_to_file(&self, output_dir, &filename, option)
663    }
664
665    pub fn read_from_file(input_dir: &str, fmspc: &Fmspc, evaluation_data_number: Option<u64>) -> Result<Self, Error> {
666        let filename = Self::create_filename(&fmspc.to_string(), evaluation_data_number);
667        let info = io::read_from_file(input_dir, &filename)?;
668        Ok(info)
669    }
670
671    pub fn read_all<'a>(input_dir: &'a str, fmspc: &'a Fmspc) -> impl Iterator<Item = Result<Self, Error>> + 'a {
672        io::all_files(input_dir, fmspc.to_string(), Self::FILENAME_EXTENSION)
673            .map(move |i| i.and_then(|entry| io::read_from_file(input_dir, entry.file_name())) )
674    }
675
676    #[cfg(feature = "verify")]
677    pub fn verify<B: Deref<Target = [u8]>>(&self, trusted_root_certs: &[B], min_version: u16) -> Result<TcbData<T, Verified>, Error> {
678        let now = Utc::now();
679        self.verify_ex(trusted_root_certs, &[], min_version, &now)
680    }
681
682    #[cfg(feature = "verify")]
683    pub fn verify_with_rootcacrl<B: Deref<Target = [u8]>>(&self, trusted_root_certs: &[B], root_ca_crls: &[RootCaCrl], min_version: u16) -> Result<TcbData<T, Verified>, Error> {
684        let now = Utc::now();
685        self.verify_ex(trusted_root_certs, root_ca_crls, min_version, &now)
686    }
687
688    #[cfg(feature = "verify")]
689    fn verify_ex<B: Deref<Target = [u8]>>(&self, trusted_root_certs: &[B], root_ca_crls: &[RootCaCrl], min_version: u16, now: &DateTime<Utc>) -> Result<TcbData<T, Verified>, Error> {
690        // Check cert chain
691        let (chain, root) = crate::build_and_verify_cert_chain(&self.ca_chain, trusted_root_certs, root_ca_crls)?;
692        let mut leaf = chain.first().unwrap_or(&root).clone();
693
694        // Check signature on data
695        let mut hash = [0u8; 32];
696        mbedtls::hash::Md::hash(mbedtls::hash::Type::Sha256, self.raw_tcb_info.as_bytes(), &mut hash).unwrap();
697        leaf.public_key_mut()
698            .verify(mbedtls::hash::Type::Sha256, &hash, self.signature())
699            .map_err(|_| Error::InvalidTcbInfo("Signature verification failed".into()))?;
700
701        let TcbData {
702            id,
703            version,
704            issue_date,
705            next_update,
706            fmspc,
707            pce_id,
708            tcb_type,
709            tcb_evaluation_data_number,
710            platform_specific_data,
711            tcb_levels,
712            ..
713        } = TcbData::<T, Unverified>::parse(&self.raw_tcb_info)?;
714
715        if min_version > version {
716            return Err(Error::UntrustedTcbInfoVersion(version, min_version))
717        }
718
719        if *now < issue_date {
720            return Err(Error::InvalidTcbInfo(format!("TCB Info only valid from {}", issue_date)))
721        }
722        if next_update < *now {
723            return Err(Error::InvalidTcbInfo(format!("TCB Info expired on {}", next_update)))
724        }
725
726        Ok(TcbData::<T, Verified> {
727            id,
728            version,
729            issue_date,
730            next_update,
731            fmspc,
732            pce_id,
733            tcb_type,
734            tcb_evaluation_data_number,
735            platform_specific_data,
736            tcb_levels,
737            type_: Verified,
738        })
739    }
740
741    pub fn data(&self) -> Result<TcbData<T, Unverified>, Error> {
742        TcbData::<T, Unverified>::parse(&self.raw_tcb_info)
743    }
744}
745
746#[cfg(feature = "verify")]
747#[cfg(test)]
748mod tests {
749    #[cfg(not(target_env = "sgx"))]
750    use {
751        chrono::{Utc, TimeZone},
752        crate::Error,
753        crate::tcb_info::{Fmspc, TcbInfo},
754        crate::platform,
755        crate::RootCaCrl,
756        tempdir::TempDir,
757    };
758    use {crate::{PlatformTypeForTcbInfo, TcbComponentsOf, TcbData, TcbStatus, Unverified, tcb_info::TdxTcbLevel}, serde::{Deserialize, Serialize}, std::convert::TryFrom};
759    use super::AdvisoryID;
760    use test_case::test_case;
761    use crate::tcb_info::{tdx_id_deserializer, tdx_id_serializer};
762
763    #[test]
764    #[cfg(not(target_env = "sgx"))]
765    fn read_tcb_info() {
766        use crate::WriteOptionsBuilder;
767
768        let info =
769            TcbInfo::<platform::SGX>::read_from_file("./tests/data/", &Fmspc::try_from("00906ea10000").expect("static fmspc"), None).expect("validated");
770        let root_certificate = include_bytes!("../tests/data/root_SGX_CA_der.cert");
771        let root_certificates = [&root_certificate[..]];
772        match info.verify(&root_certificates, 2) {
773            Err(Error::InvalidTcbInfo(msg)) => assert_eq!(msg, String::from("TCB Info expired on 2020-06-17 17:49:24 UTC")),
774            e => assert!(false, "wrong result: {:?}", e),
775        }
776        let juni_5_2020 = Utc.with_ymd_and_hms(2020, 6, 5, 12, 0, 0).unwrap();
777
778        let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
779        let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_certificates).unwrap()];
780
781        assert!(info.verify_ex(&root_certificates, &root_ca_crls, 2, &juni_5_2020).is_ok());
782
783        // Test serialization/deserialization
784        let temp_dir = TempDir::new("tempdir").unwrap();
785        let path = temp_dir.path().as_os_str().to_str().unwrap();
786        info.write_to_file(&path, WriteOptionsBuilder::new().build()).unwrap();
787        let info2 = TcbInfo::read_from_file(&path, &Fmspc::try_from("00906ea10000").expect("static fmspc"), Some(8)).unwrap();
788        assert_eq!(info, info2);
789    }
790
791    #[test]
792    #[cfg(not(target_env = "sgx"))]
793    fn read_corrupt_tcb_info() {
794        let tcb_info = TcbInfo::<platform::SGX>::read_from_file("./tests/data/corrupted", &Fmspc::try_from("00906ea10000").unwrap(), None).unwrap();
795        let root_certificate = include_bytes!("../tests/data/root_SGX_CA_der.cert");
796        let root_certificates = [&root_certificate[..]];
797        assert!(tcb_info.verify(&root_certificates, 2).is_err());
798    }
799
800    #[test]
801    #[cfg(not(target_env = "sgx"))]
802    fn read_tcb_info_v3() {
803        let tcb_info = TcbInfo::<platform::SGX>::read_from_file("./tests/data/", &Fmspc::try_from("00906ed50000").unwrap(), Some(19)).unwrap();
804        let root_certificate = include_bytes!("../tests/data/root_SGX_CA_der.cert");
805        let root_certificates = [&root_certificate[..]];
806        let june_5_2025 = Utc.with_ymd_and_hms(2025, 6, 5, 12, 0, 0).unwrap();
807
808        let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
809        let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_certificates).unwrap()];
810
811        assert!(tcb_info.verify_ex(&root_certificates, &root_ca_crls, 3, &june_5_2025).is_ok());
812        assert!(tcb_info.verify_ex(&root_certificates, &root_ca_crls, 4, &june_5_2025).is_err());
813    }
814
815    #[test]
816    fn parse_advisory_ids() {
817        assert_eq!(AdvisoryID::try_from("INTEL-SA-00123"), Ok(AdvisoryID::Security(123)));
818        assert_eq!(AdvisoryID::try_from("INTEL-SA-10123"), Ok(AdvisoryID::Security(10123)));
819        assert_eq!(AdvisoryID::try_from("INTEL-SA-00001"), Ok(AdvisoryID::Security(1)));
820        assert_eq!(AdvisoryID::try_from("INTEL-DOC-00123"), Ok(AdvisoryID::Documentation(123)));
821        assert_eq!(AdvisoryID::try_from("INTEL-DOC-10123"), Ok(AdvisoryID::Documentation(10123)));
822        assert_eq!(AdvisoryID::try_from("INTEL-DOC-00001"), Ok(AdvisoryID::Documentation(1)));
823    }
824
825    #[test]
826    fn advisory_ids_to_string() {
827        assert_eq!(AdvisoryID::Security(123).to_string(), "INTEL-SA-00123");
828        assert_eq!(AdvisoryID::Security(1).to_string(), "INTEL-SA-00001");
829        assert_eq!(AdvisoryID::Security(99999).to_string(), "INTEL-SA-99999");
830        assert_eq!(AdvisoryID::Documentation(123).to_string(), "INTEL-DOC-00123");
831        assert_eq!(AdvisoryID::Documentation(1).to_string(), "INTEL-DOC-00001");
832        assert_eq!(AdvisoryID::Documentation(99999).to_string(), "INTEL-DOC-99999");
833    }
834
835    #[test]
836    fn parse_tcbinfo_json() {
837        // Note to anyone who needs it:
838        // This cert chain is attached from the HTTP response of TCB info API from PCS
839        // Will be highly unlikely to change unless Intel revokes their own certificate.
840        let ca_chain = vec![
841            include_str!("../tests/data/cert-chain/cert-chain-1.cert").to_string(),
842            include_str!("../tests/data/cert-chain/cert-chain-2.cert").to_string()
843        ];
844
845        let root_certificate = include_bytes!("../tests/data/root_SGX_CA_der.cert");
846        let root_certificates = [&root_certificate[..]];
847
848        let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
849        let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_certificates).unwrap()];
850
851        let march_1_2026 = Utc.with_ymd_and_hms(2026, 3, 1, 12, 0, 0).unwrap();
852
853        // Parse and verify TDX TCB Info
854        let tdx_tcbinfo = TcbInfo::<platform::TDX>::parse(&include_str!("../tests/data/tcb-json/tcb-tdx.json").to_string(), ca_chain.clone()).unwrap();
855        TcbData::<platform::TDX, Unverified>::parse(tdx_tcbinfo.raw_tcb_info()).unwrap();
856        tdx_tcbinfo.verify_ex(&root_certificates, &root_ca_crls, 0, &march_1_2026).unwrap();
857
858        // Passing SGX TCB Info JSON to the TDX type must throw error
859        let sgx_tcbinfo_in_tdx_type = TcbInfo::<platform::TDX>::parse(&include_str!("../tests/data/tcb-json/tcb-sgx.json").to_string(), vec![]).unwrap();
860        assert!(TcbData::<platform::TDX, Unverified>::parse(sgx_tcbinfo_in_tdx_type.raw_tcb_info()).is_err());
861
862        // Parse and verify SGX TCB Info
863        let sgx_tcbinfo = TcbInfo::<platform::SGX>::parse(&include_str!("../tests/data/tcb-json/tcb-sgx.json").to_string(), ca_chain.clone()).unwrap();
864        assert!(TcbData::<platform::SGX, Unverified>::parse(sgx_tcbinfo.raw_tcb_info()).is_ok());
865        sgx_tcbinfo.verify_ex(&root_certificates, &root_ca_crls, 0, &march_1_2026).unwrap();
866
867        // Passing TDX TCB Info JSON to the SGX type must throw error
868        let tgx_tcbinfo_in_sdx_type = TcbInfo::<platform::SGX>::parse(&include_str!("../tests/data/tcb-json/tcb-tdx.json").to_string(), vec![]).unwrap();
869        assert!(TcbData::<platform::SGX, Unverified>::parse(tgx_tcbinfo_in_sdx_type.raw_tcb_info()).is_err());
870    }
871
872    fn load_tcb_info<T: PlatformTypeForTcbInfo>(json_file: &str) -> TcbData<T> {
873        use std::io::Read;
874        fn read_to_string(file: &str) -> String {
875            let mut ret = String::new();
876            let _ = std::fs::File::open(file).unwrap().read_to_string(&mut ret).unwrap();
877            ret
878        }
879
880        let ca_chain = vec![
881            include_str!("../tests/data/cert-chain/cert-chain-1.cert").to_string(),
882            include_str!("../tests/data/cert-chain/cert-chain-2.cert").to_string()
883        ];
884
885        let root_certificate = include_bytes!("../tests/data/root_SGX_CA_der.cert");
886        let root_certificates = [&root_certificate[..]];
887
888        let root_ca_crl_der = include_bytes!("../tests/data/IntelSGXRootCA.der");
889        let root_ca_crls = [RootCaCrl::new(root_ca_crl_der).unwrap().verify(&root_certificates).unwrap()];
890
891        let march_1_2026 = Utc.with_ymd_and_hms(2026, 3, 10, 12, 0, 0).unwrap();
892
893        // Parse and verify TDX TCB Info
894        let tcbinfo = TcbInfo::<T>::parse(&read_to_string(json_file), ca_chain.clone()).unwrap();
895        tcbinfo.verify_ex(&root_certificates, &root_ca_crls, 0, &march_1_2026).unwrap()
896    }
897
898    #[test]
899    fn find_tcb_level() {
900        let sgx_tcb_info: TcbData<platform::SGX> = load_tcb_info("./tests/data/tcb-json/tcb-sgx.json");
901        let tdx_tcb_info: TcbData<platform::TDX> = load_tcb_info("./tests/data/tcb-json/tcb-tdx.json");
902
903        // This should retrieve the UpToDate level
904        let tcb_level = TcbComponentsOf::<platform::SGX>::from_raw([6, 6, 10, 10, 5, 255, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0], 14);
905        let matching_level = sgx_tcb_info.find_sgx_tcb_level(&tcb_level).unwrap();
906        assert_eq!(matching_level.tcb_status(), TcbStatus::UpToDate);
907
908        let matching_level = tdx_tcb_info.find_sgx_tcb_level(&tcb_level).unwrap();
909        assert_eq!(matching_level.tcb_status(), TcbStatus::UpToDate);
910    }
911
912    #[derive(Debug)]
913    enum ExpectTcbLevel {
914        None,
915        TcbOnly(TcbStatus),
916        WithModule(TcbStatus, TcbStatus),
917    }
918
919    impl<'a> PartialEq<TdxTcbLevel<'a>> for ExpectTcbLevel {
920        fn eq(&self, other: &TdxTcbLevel<'a>) -> bool {
921            match (self, other) {
922                (ExpectTcbLevel::TcbOnly(s), TdxTcbLevel::TcbLevel(tcb)) => s == &tcb.tcb_status(),
923                (
924                    ExpectTcbLevel::WithModule(s, m),
925                    TdxTcbLevel::TcbLevelWithModule(tcb, module),
926                ) => s == &tcb.tcb_status() && m == &module.tcb_status(),
927                _ => false,
928            }
929        }
930    }
931
932    #[test_case("tcb-tdx.json", [6, 6, 10, 10, 5, 255, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0], 14, [5, 3, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::WithModule(TcbStatus::UpToDate, TcbStatus::UpToDate); "Up To Date - Own machine")]
933    #[test_case("tcb-tdx-2.json", [3, 3, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [5, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::TcbOnly(TcbStatus::UpToDate); "Up to Date TCB")]
934    #[test_case("tcb-tdx-2.json", [2, 2, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [5, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::TcbOnly(TcbStatus::OutOfDate); "Out of Date SGX SVN")]
935    #[test_case("tcb-tdx-2.json", [3, 3, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [5, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::TcbOnly(TcbStatus::OutOfDate); "Out of Date TDX SVN")]
936    #[test_case("tcb-tdx-2.json", [3, 3, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [6, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::WithModule(TcbStatus::UpToDate, TcbStatus::UpToDate); "Up to Date TCB and Module")]
937    #[test_case("tcb-tdx-2.json", [3, 3, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [5, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::WithModule(TcbStatus::UpToDate, TcbStatus::OutOfDate); "Up to Date TCB and Out of Date Module")]
938    #[test_case("tcb-tdx-2.json", [3, 3, 2, 2, 4, 1, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0], 11, [6, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::WithModule(TcbStatus::OutOfDate, TcbStatus::UpToDate); "Out of Date TDX SVN and Up to Date Module")]
939    #[test_case("tcb-tdx-2.json", [1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], 1,  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ExpectTcbLevel::None; "Cannot determine TCB level")]
940    fn evaluate_tdx_module_tcb(
941        tcb_info_json: &str,
942        cpusvn: [u8; 16],
943        pcesvn: u16,
944        tdxsvn: [u8; 16],
945        expected: ExpectTcbLevel,
946    ) {
947        // This test case is retrieved from an actual testing machine that we own
948        let tdx_tcb_info: TcbData<platform::TDX> =
949            load_tcb_info(("./tests/data/tcb-json/".to_owned() + tcb_info_json).as_str());
950        let tcb_level = TcbComponentsOf::<platform::TDX>::from_raw(cpusvn, pcesvn, tdxsvn);
951        if let Some(matching_level) = tdx_tcb_info.find_tdx_tcb_level(&tcb_level) {
952            if let ExpectTcbLevel::None = expected {
953                panic!("expecting None but receiving TCB level");
954            } else if expected != matching_level {
955                panic!("invalid TDX TCB Level");
956            }
957        } else {
958            assert!(matches!(expected, ExpectTcbLevel::None));
959        }
960    }
961
962    #[test]
963    fn test_tdx_id_parser() {
964        #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
965        #[serde(rename_all = "camelCase")]
966        pub struct TdxIdTest {
967            #[serde(
968                deserialize_with = "tdx_id_deserializer",
969                serialize_with = "tdx_id_serializer"
970            )]
971            id: u8,
972        }
973
974        let test_val = TdxIdTest {
975            id: 10,
976        };
977
978        let serialized = serde_json::ser::to_string(&test_val).unwrap();
979
980        println!("{serialized}");
981
982        assert!(serialized.contains("TDX_0A"));
983
984        let deserialized: TdxIdTest = serde_json::de::from_str(&serialized).unwrap();
985
986        assert_eq!(test_val.id, deserialized.id);
987    }
988
989}