1#![deny(warnings)]
9
10extern crate percent_encoding;
11extern crate yasna;
12#[macro_use]
13extern crate quick_error;
14
15use std::convert::TryFrom;
16use std::fmt::{self};
17
18use serde::de::{self};
19use serde::{Deserialize, Deserializer, Serialize};
20pub use yasna::ASN1Error;
21#[cfg(feature = "verify")]
22use {
23 mbedtls::alloc::{Box as MbedtlsBox, List as MbedtlsList},
24 mbedtls::x509::certificate::Certificate,
25 mbedtls::Error as MbedError,
26 mbedtls::x509::Crl,
27 std::ffi::CString,
28 std::ops::Deref,
29};
30
31pub use crate::io::{WriteOptions, WriteOptionsBuilder};
32pub use crate::pckcrl::PckCrl;
33pub use crate::pckcrt::{
34 PckCert, PckCerts, PlatformTCB, PlatformTypeForTcbComponent, SGXPCKCertificateExtension,
35 SGXType, TcbComponentType, TcbComponents, TcbComponentsOf
36};
37pub use crate::qe_identity::{EnclaveIdentity, QeIdentity, QeIdentitySigned};
38pub use crate::tcb_evaluation_data_numbers::{
39 RawTcbEvaluationDataNumbers, TcbEvalNumber, TcbEvaluationDataNumbers, TcbPolicy,
40};
41pub use crate::tcb_info::{
42 AdvisoryID, Fmspc, PlatformTypeForTcbInfo, TcbData, TcbInfo, TcbLevelOf, TcbLevel, TdxModule,
43 TdxModuleIdentity, TdxModuleTcbLevel, TdxModuleTcbLevelIsvSvn, TdxTcbLevel
44};
45pub use crate::root_ca_crl::RootCaCrl;
46
47mod io;
48mod iso8601;
49mod pckcrl;
50mod pckcrt;
51mod pckid;
52mod qe_identity;
53mod tcb_evaluation_data_numbers;
54mod tcb_info;
55mod root_ca_crl;
56
57pub type CpuSvn = [u8; 16];
58pub type EncPpid = Vec<u8>;
59pub type PceId = u16;
60pub type PceIsvsvn = u16;
61pub type QeId = [u8; 16];
62pub use crate::pckid::PckID;
63
64pub trait PlatformType : Clone + Default {
66 fn platform_id() -> &'static str;
67}
68
69pub fn deserialize_platform_id<'de, D: Deserializer<'de>, T: PlatformType>(deserializer: D) -> Result<T, D::Error> {
71 let platform_str = String::deserialize(deserializer)?;
72 if platform_str == T::platform_id() {
73 Ok(T::default())
74 } else {
75 Err(serde::de::Error::custom(format!("invalid platform id: {platform_str}, expected {}", T::platform_id())))
76 }
77}
78
79pub mod platform {
81 use serde::{Serialize, Deserialize};
82
83 #[derive(Serialize, Deserialize, Clone, Default, Eq, PartialEq, Debug)]
85 pub struct SGX;
86
87 impl super::PlatformType for SGX {
88 fn platform_id() -> &'static str {
89 "SGX"
90 }
91 }
92
93 #[derive(Serialize, Deserialize, Clone, Default, Eq, PartialEq, Debug)]
95 pub struct TDX;
96
97 impl super::PlatformType for TDX {
98 fn platform_id() -> &'static str {
99 "TDX"
100 }
101 }
102}
103
104quick_error! {
105 #[derive(Debug)]
106 pub enum Error {
107 MissingCaChain{
108 display("CA chain was unexpectedly empty")
109 }
110 IncorrectCA {
111 display("Invalid CA")
112 }
113 InvalidCaFormat {
114 display("CA certificate could not be parsed")
115 }
116 InvalidPckFormat(err: ASN1Error){
117 display("Invalid formatted PckCert: {}", err)
118 }
119 InvalidPck(err: String){
120 display("Invalid PCK: {}", err)
121 }
122 InvalidPcks(err: String){
123 display("Invalid PCKs: {}", err)
124 }
125 InvalidFormatQe3Quote{
126 display("Qe3 Quote could not be parsed")
127 }
128 NoPckForTcbFound{
129 display("No PCK matching the TCB was found")
130 }
131 #[cfg(feature = "verify")]
132 InvalidCrl(err: MbedError){
133 display("Invalid CRL: {}", err)
134 }
135 InvalidCrlFormat{
136 display("Invalid CRL format")
137 }
138 InvalidTcbInfo(err: String){
139 display("Invalid TCB info: {}", err)
140 }
141 InvalidTcbEvaluationDataNumbers(err: String){
142 display("Invalid TCB Evaluation Data Numbers: {}", err)
143 }
144 #[cfg(feature = "verify")]
145 UntrustworthyTcbEvaluationDataNumber(err: MbedError) {
146 display("TCB Evaluation Data Number not trustworthy: {}", err)
147 }
148 UnknownTcbType(tcb_type: u16){
149 display("Unknown TCB type: {}", tcb_type)
150 }
151 #[cfg(feature = "verify")]
152 InvalidQe3Id(err: MbedError){
153 display("Invalid QE3 ID: {}", err)
154 }
155 Qe3NotValid(err: String){
156 display("Invalid QE3: {}", err)
157 }
158 InvalidFormatQe3Identity{
159 display("Invalid QE3 Identity format")
160 }
161 IoError(err: std::io::Error){
162 display("I/O error: {}", err)
163 from()
164 }
165 ParseError(err: serde_json::error::Error){
166 from()
167 display("json error: {}", err)
168 }
169 NoPckCertData{
170 display("Empty PckCerts")
171 }
172 EncodingError(err: serde_json::error::Error){
173 display("json error: {}", err)
174 }
175 UnknownTcbInfoVersion(version: u16){
176 display("The TCB Info structure has unexpected version: {}", version)
177 }
178 UntrustedTcbInfoVersion(curr_version: u16, min_version: u16) {
179 display("The TCB Info structure has version {curr_version}, while at least {min_version} is required")
180 }
181 EnclaveTcbLevelNotFound {
182 display("TCB level not found for enclave")
183 }
184 UnknownQeIdentityVersion(version: u16){
185 display("The QEIdentity structure has unexpected version: {}", version)
186 }
187 InvalidDcapAttestationFormat{
188 display("The DCAP Attestation certificate has an unexpected format")
189 }
190 }
191}
192
193#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
194pub enum DcapArtifactIssuer {
195 PCKPlatformCA,
196 PCKProcessorCA,
197 SGXRootCA,
198}
199
200impl TryFrom<&str> for DcapArtifactIssuer {
201 type Error = Error;
202
203 fn try_from(value: &str) -> Result<Self, Self::Error> {
204 if value.contains("Intel SGX PCK Platform CA") {
205 return Ok(DcapArtifactIssuer::PCKPlatformCA);
206 }
207
208 if value.contains("Intel SGX PCK Processor CA") {
209 return Ok(DcapArtifactIssuer::PCKProcessorCA);
210 }
211
212 if value.contains("Intel SGX Root CA") {
213 return Ok(DcapArtifactIssuer::SGXRootCA);
214 }
215
216 Err(Error::InvalidCaFormat)
217 }
218}
219
220pub trait VerificationType { }
223
224#[derive(Clone, Debug, Eq, PartialEq)]
225pub struct Verified;
226
227impl VerificationType for Verified {}
228
229#[derive(Clone, Debug, Eq, PartialEq)]
230pub struct Unverified;
231
232impl VerificationType for Unverified {}
233
234impl<'de> Deserialize<'de> for Unverified {
238 fn deserialize<D>(_: D) -> Result<Self, D::Error>
239 where
240 D: Deserializer<'de> {
241 Ok(Self{})
242 }
243}
244
245fn get_ecdsa_sig_der(sig: &[u8]) -> Result<Vec<u8>, ()> {
248 if sig.len() % 2 != 0 {
249 return Err(());
250 }
251
252 let (r_bytes, s_bytes) = sig.split_at(sig.len() / 2);
253 let r = num::BigUint::from_bytes_be(r_bytes);
254 let s = num::BigUint::from_bytes_be(s_bytes);
255
256 let der = yasna::construct_der(|writer| {
257 writer.write_sequence(|writer| {
258 writer.next().write_biguint(&r);
259 writer.next().write_biguint(&s);
260 })
261 });
262
263 Ok(der)
264}
265
266fn intel_signature_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
267 let signature = String::deserialize(deserializer)?;
268 let signature = &base16::decode(signature.as_bytes()).map_err(de::Error::custom)?;
269 crate::get_ecdsa_sig_der(signature).map_err(|_| de::Error::custom("Failed ECDSA signature conversion"))
270}
271
272#[cfg(feature = "verify")]
273fn create_cert_chain(certs: &[String]) -> Result<(Vec<MbedtlsBox<Certificate>>, MbedtlsBox<Certificate>), Error> {
274 fn str_to_cert_box(ca: &String) -> Result<MbedtlsBox<Certificate>, Error> {
275 let ca = CString::new(ca.as_bytes()).map_err(|_| Error::InvalidCaFormat)?;
276 Certificate::from_pem(ca.as_bytes_with_nul()).map_err(|_| Error::InvalidCaFormat)
277 }
278 if let Some((last_cert, certs)) = certs.split_last() {
279 let chain = certs.iter().map(str_to_cert_box).collect::<Result<Vec<_>, _>>()?;
280 let last_cert = str_to_cert_box(last_cert)?;
281 Ok((chain, last_cert))
282 } else {
283 Err(Error::MissingCaChain)
284 }
285}
286
287#[cfg(feature = "verify")]
292fn build_and_verify_cert_chain<B: Deref<Target = [u8]>>(
293 ca_chain: &[String],
294 trusted_root_certs: &[B],
295 root_ca_crls: &[RootCaCrl]
296) -> Result<(Vec<MbedtlsBox<Certificate>>, MbedtlsBox<Certificate>), Error> {
297 use pkix::{oid, pem::PEM_CERTIFICATE, x509::GenericCertificate, FromBer};
298
299 let (chain, root) = crate::create_cert_chain(ca_chain)?;
300 let root_list = std::iter::once(root.clone()).collect();
301
302 crate::check_root_ca(trusted_root_certs, &root_list)?;
304
305 if 0 < chain.len() {
306 let trust_ca: MbedtlsList<Certificate> = chain.clone().into_iter().collect();
307
308 let mut root_crl = if !root_ca_crls.is_empty() {
311 let mut crls = Crl::new();
312 for crl in root_ca_crls {
313 crl.push_to_crl_list(&mut crls)?;
314 }
315 Some(crls)
316 } else {
317 None
318 };
319
320 let root_crl_ref = if let Some(crl) = &mut root_crl {
321 Some(crl)
322 } else {
323 None
324 };
325 Certificate::verify(&trust_ca, &root_list, root_crl_ref, None).map_err(|e| Error::InvalidQe3Id(e))?;
326 }
327
328 let leaf = ca_chain.first().ok_or(Error::MissingCaChain)?;
330 let tcb =
331 &pkix::pem::pem_to_der(&leaf, Some(PEM_CERTIFICATE)).ok_or(Error::InvalidCaFormat)?;
332 let tcb = GenericCertificate::from_ber(&tcb).map_err(|_| Error::InvalidCaFormat)?;
333 let name = tcb
334 .tbscert
335 .subject
336 .get(&*oid::commonName)
337 .ok_or(Error::InvalidCaFormat)?;
338 if String::from_utf8_lossy(&name.value()) != "Intel SGX TCB Signing" {
339 return Err(Error::IncorrectCA);
340 }
341
342 Ok((chain, root))
343}
344
345#[cfg(feature = "verify")]
359fn check_root_ca<B: Deref<Target = [u8]>>(trusted_root_certs: &[B], candidate: &MbedtlsList<Certificate>) -> Result<(), Error> {
360 if trusted_root_certs
361 .iter()
362 .filter_map(|trusted_der| Certificate::from_der(&**trusted_der).ok())
363 .any(|trusted| Certificate::verify(candidate, &std::iter::once(trusted).collect(), None, None).is_ok())
364 {
365 return Ok(());
366 } else {
367 return Err(Error::IncorrectCA);
368 }
369}
370
371#[cfg(test)]
372#[cfg(not(target_env = "sgx"))]
373fn get_cert_subject(cert: &str) -> String {
374 let der = &pkix::pem::pem_to_der(cert.trim(), Some(pkix::pem::PEM_CERTIFICATE))
375 .ok_or(ASN1Error::new(yasna::ASN1ErrorKind::Invalid))
376 .unwrap();
377 get_cert_subject_from_der(der)
378}
379
380#[cfg(test)]
381#[cfg(not(target_env = "sgx"))]
382fn get_cert_subject_from_der(cert: &Vec<u8>) -> String {
383 use pkix::FromBer;
384 let cert = pkix::x509::GenericCertificate::from_ber(&cert).unwrap();
385 let name = cert.tbscert.subject.get(&*pkix::oid::commonName).unwrap();
386 String::from_utf8_lossy(&name.value()).to_string()
387}
388
389#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug, Copy)]
390pub enum TcbStatus {
391 UpToDate,
392 SWHardeningNeeded,
393 ConfigurationNeeded,
394 ConfigurationAndSWHardeningNeeded,
395 OutOfDate,
396 OutOfDateConfigurationNeeded,
397 Revoked,
398}
399
400impl TcbStatus {
401 pub(crate) fn drop_sw_hardening_needed(self) -> Self {
402 match self {
403 Self::SWHardeningNeeded => Self::UpToDate,
404 Self::ConfigurationAndSWHardeningNeeded => Self::ConfigurationNeeded,
405 v => v,
406 }
407 }
408}
409
410impl fmt::Display for TcbStatus {
411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412 match self {
413 TcbStatus::UpToDate => write!(f, "Up to Date"),
414 TcbStatus::SWHardeningNeeded => write!(f, "Software Hardening Needed"),
415 TcbStatus::ConfigurationNeeded => write!(f, "Configuration Needed"),
416 TcbStatus::ConfigurationAndSWHardeningNeeded => write!(f, "Configuration And Software Hardening Needed"),
417 TcbStatus::OutOfDate => write!(f, "Out of Date"),
418 TcbStatus::OutOfDateConfigurationNeeded => write!(f, "Out of Date, Configuration Needed"),
419 TcbStatus::Revoked => write!(f, "Revoked"),
420 }
421 }
422}
423
424#[cfg(feature = "verify")]
425pub(crate) fn as_mbedtls_crl(crl_pem: &str) -> Result<Crl, Error> {
426 let c = CString::new(crl_pem.as_bytes()).map_err(|_| Error::InvalidCrlFormat)?;
427 let mut crl = Crl::new();
428 crl.push_from_pem(c.as_bytes_with_nul()).map_err(|_| Error::InvalidCrlFormat)?;
429 Ok(crl)
430}