1use std::convert::{TryFrom, TryInto};
9use std::fmt::{self, Display, Formatter};
10use std::path::PathBuf;
11
12use chrono::{DateTime, Utc};
13use serde::{de, Deserialize, Deserializer, Serialize};
14use serde_json::value::RawValue;
15use sgx_isa::{Attributes, Miscselect};
16#[cfg(feature = "verify")]
17use {
18 std::ops::Deref,
19 crate::RootCaCrl,
20};
21
22use crate::io::{self};
23use crate::{Error, TcbStatus, Unverified, VerificationType, Verified, WriteOptions};
24
25#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
26pub enum EnclaveIdentity {
27 QE,
28 QVE,
29 QAE,
30 TDQE,
31}
32
33mod enclave_identity {
34 use serde::{Deserialize, Deserializer};
35 use serde::de;
36 use super::EnclaveIdentity;
37
38 pub fn serialize<S>(id: &EnclaveIdentity, serializer: S) -> Result<S::Ok, S::Error>
39 where
40 S: ::serde::Serializer,
41 {
42 let s = match id {
43 EnclaveIdentity::QE => "QE",
44 EnclaveIdentity::QVE => "QVE",
45 EnclaveIdentity::QAE => "QAE",
46 EnclaveIdentity::TDQE => "TD_QE",
47 };
48 serializer.serialize_str(&s)
49 }
50
51 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<EnclaveIdentity, D::Error> {
52 let id = String::deserialize(deserializer)?;
53 match id.as_str() {
54 "QE" => Ok(EnclaveIdentity::QE),
55 "QVE" => Ok(EnclaveIdentity::QVE),
56 "QAE" => Ok(EnclaveIdentity::QAE),
57 "TD_QE" => Ok(EnclaveIdentity::TDQE),
58 _ => Err(de::Error::custom("Unknown Enclave Identity variant"))
59 }
60 }
61}
62
63impl Display for EnclaveIdentity {
64 fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
65 match self {
66 EnclaveIdentity::QE => write!(f, "QE"),
67 EnclaveIdentity::QVE => write!(f, "QVE"),
68 EnclaveIdentity::QAE => write!(f, "QAE"),
69 EnclaveIdentity::TDQE => write!(f, "TD_QE"),
70 }
71 }
72}
73
74#[derive(Clone, Serialize, Deserialize, Debug)]
75pub(crate) struct Tcb {
76 pub(crate) isvsvn: u16,
77}
78
79#[derive(Clone, Serialize, Deserialize, Debug)]
80#[serde(rename_all = "camelCase")]
81pub struct TcbLevel {
82 pub(crate) tcb: Tcb,
83 tcb_date: String,
84 pub(crate) tcb_status: TcbStatus,
85 #[serde(default, rename = "advisoryIDs", skip_serializing_if = "Vec::is_empty")]
86 advisory_ids: Vec<String>,
87}
88
89impl TcbLevel {
90 pub fn tcb_status(&self) -> &TcbStatus {
91 &self.tcb_status
92 }
93}
94
95#[derive(Clone, Serialize, Deserialize, Debug)]
96#[serde(rename_all = "camelCase")]
97pub struct QeIdentity<V: VerificationType = Verified> {
98 version: u16,
99 #[serde(with = "enclave_identity")]
100 id: EnclaveIdentity,
101 #[serde(with = "crate::iso8601")]
102 issue_date: DateTime<Utc>,
103 #[serde(with = "crate::iso8601")]
104 next_update: DateTime<Utc>,
105 tcb_evaluation_data_number: u64,
106 #[serde(deserialize_with = "miscselect_deserializer", serialize_with = "miscselect_serializer")]
107 miscselect: Miscselect,
108 #[serde(
109 deserialize_with = "miscselect_mask_deserializer",
110 serialize_with = "miscselect_mask_serializer"
111 )]
112 miscselect_mask: u32,
113 #[serde(deserialize_with = "attributes_deserializer", serialize_with = "attributes_serializer")]
114 attributes: Attributes,
115 #[serde(deserialize_with = "attributes_deserializer", serialize_with = "attributes_serializer")]
116 attributes_mask: Attributes,
117 #[serde(deserialize_with = "mrsigner_deserializer", serialize_with = "mrsigner_serializer")]
118 mrsigner: [u8; 32],
119 isvprodid: u16,
120 tcb_levels: Vec<TcbLevel>,
121 #[serde(skip_serializing)]
122 _type: V,
123}
124
125impl QeIdentity {
126 pub fn find_tcb_level<'a>(&'a self, isvsvn: u16) -> Option<&'a TcbLevel> {
128 for tcb in self.tcb_levels.iter() {
130 if tcb.tcb.isvsvn <= isvsvn {
131 return Some(tcb);
132 }
133 }
134 None
135 }
136
137 pub fn mrsigner(&self) -> &[u8; 32] {
138 &self.mrsigner
139 }
140
141 pub fn isvprodid(&self) -> u16 {
142 self.isvprodid
143 }
144
145 pub fn attributes<'a>(&'a self) -> &'a Attributes {
146 &self.attributes
147 }
148
149 pub fn attributes_mask<'a>(&'a self) -> &'a Attributes {
150 &self.attributes_mask
151 }
152
153 pub fn miscselect<'a>(&'a self) -> &'a Miscselect {
154 &self.miscselect
155 }
156
157 pub fn miscselect_mask(&self) -> Miscselect {
158 Miscselect::from_bits_truncate(self.miscselect_mask)
159 }
160
161 pub fn issue_date(&self) -> &DateTime<Utc> {
162 &self.issue_date
163 }
164
165 pub fn next_update(&self) -> &DateTime<Utc> {
166 &self.next_update
167 }
168}
169
170impl<V: VerificationType> QeIdentity<V> {
171 pub fn tcb_evaluation_data_number(&self) -> u64 {
172 self.tcb_evaluation_data_number
173 }
174
175 pub(crate) fn tcb_levels(&self) -> &[TcbLevel] {
176 &self.tcb_levels
177 }
178}
179
180impl TryFrom<&QeIdentitySigned> for QeIdentity<Unverified> {
181 type Error = Error;
182
183 fn try_from(id: &QeIdentitySigned) -> Result<Self, Self::Error> {
184 serde_json::from_str(&id.raw_enclave_identity).map_err(|e| Error::ParseError(e))
185 }
186}
187
188fn mrsigner_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
189 let mrsigner = String::deserialize(deserializer)?;
190 let mrsigner = base16::decode(&mrsigner).map_err(de::Error::custom)?;
191 mrsigner.as_slice().try_into().map_err(de::Error::custom)
192}
193
194fn mrsigner_serializer<S>(mrsigner: &[u8; 32], serializer: S) -> ::std::result::Result<S::Ok, S::Error>
195where
196 S: ::serde::Serializer,
197{
198 let mrsigner = base16::encode_upper(mrsigner);
199 serializer.serialize_str(&mrsigner)
200}
201
202fn attributes_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Attributes, D::Error> {
203 let attributes = String::deserialize(deserializer)?;
204 let attributes = base16::decode(&attributes).map_err(de::Error::custom)?;
205 Attributes::try_copy_from(&attributes).ok_or_else(|| de::Error::custom("Could not parse attribtes"))
206}
207
208fn attributes_serializer<S>(attributes: &Attributes, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
209where
210 S: ::serde::Serializer,
211{
212 let attributes: &[u8] = attributes.as_ref();
213 let attributes = base16::encode_upper(&attributes);
214 serializer.serialize_str(&attributes)
215}
216
217fn miscselect_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Miscselect, D::Error> {
218 let miscselect = String::deserialize(deserializer)?;
219 let miscselect = u32::from_str_radix(&miscselect, 16).map_err(de::Error::custom)?;
220 Miscselect::from_bits(miscselect).ok_or_else(|| de::Error::custom("Could not parse miscselect"))
221}
222
223fn miscselect_serializer<S>(miscselect: &Miscselect, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
224where
225 S: ::serde::Serializer,
226{
227 let miscselect = miscselect.bits();
228 let miscselect = base16::encode_upper(&miscselect.to_be_bytes());
229 serializer.serialize_str(&miscselect)
230}
231
232fn miscselect_mask_deserializer<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u32, D::Error> {
233 let miscselect = String::deserialize(deserializer)?;
234 u32::from_str_radix(&miscselect, 16).map_err(de::Error::custom)
235}
236
237fn miscselect_mask_serializer<S>(miscselect: &u32, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
238where
239 S: ::serde::Serializer,
240{
241 let miscselect = base16::encode_upper(&miscselect.to_be_bytes());
242 serializer.serialize_str(&miscselect)
243}
244
245#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
246pub struct QeIdentitySigned {
247 raw_enclave_identity: String,
248 signature: Vec<u8>,
249 ca_chain: Vec<String>,
250}
251
252impl QeIdentitySigned {
253 const FILENAME_PREFIX: &'static str = "qe3_identity";
254 const FILENAME_EXTENSION: &'static str = ".id";
255
256 pub fn parse(body: &String, ca_chain: Vec<String>) -> Result<Self, Error> {
257 #[derive(Deserialize)]
258 #[serde(rename_all = "camelCase")]
259 struct IntelQeIdentitySigned<'a> {
260 #[serde(borrow)]
261 enclave_identity: &'a RawValue,
262 #[serde(deserialize_with = "crate::intel_signature_deserializer")]
263 signature: Vec<u8>,
264 }
265 let IntelQeIdentitySigned {
266 enclave_identity,
267 signature,
268 } = serde_json::from_str(&body)?;
269 Ok(QeIdentitySigned::new(enclave_identity.to_string(), signature, ca_chain))
270 }
271
272 pub fn new(raw_enclave_identity: String, signature: Vec<u8>, ca_chain: Vec<String>) -> Self {
273 QeIdentitySigned {
274 raw_enclave_identity,
275 signature,
276 ca_chain,
277 }
278 }
279
280 pub fn create_filename(evaluation_data_number: Option<u64>) -> String {
281 io::compose_filename(Self::FILENAME_PREFIX, Self::FILENAME_EXTENSION, evaluation_data_number)
282 }
283
284 pub fn write_to_file(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
285 let id = QeIdentity::<Unverified>::try_from(self)?;
286 let filename = Self::create_filename(Some(id.tcb_evaluation_data_number));
287 io::write_to_file(&self, output_dir, &filename, option)
288 }
289
290 pub fn read_from_file(input_dir: &str, evaluation_data_number: Option<u64>) -> Result<Self, Error> {
291 let filename = Self::create_filename(evaluation_data_number);
292 let identity: Self = io::read_from_file(input_dir, &filename)?;
293 Ok(identity)
294 }
295
296 pub fn read_all<'a>(input_dir: &'a str) -> impl Iterator<Item = Result<Self, Error>> + 'a {
297 io::all_files(input_dir, Self::FILENAME_PREFIX, Self::FILENAME_EXTENSION)
298 .map(move |i| i.and_then(|entry| io::read_from_file(input_dir, entry.file_name())) )
299 }
300
301 pub fn raw_qe_identity(&self) -> &String {
302 &self.raw_enclave_identity
303 }
304
305 pub fn signature(&self) -> &Vec<u8> {
306 &self.signature
307 }
308
309 pub fn certificate_chain(&self) -> &Vec<String> {
310 &self.ca_chain
311 }
312 #[cfg(feature = "verify")]
313 pub fn verify<B: Deref<Target = [u8]>>(&self, trusted_root_certs: &[B], enclave_identity: EnclaveIdentity) -> Result<QeIdentity, Error> {
314 self.verify_with_rootcacrl(trusted_root_certs, &[], enclave_identity)
315 }
316
317 #[cfg(feature = "verify")]
318 pub fn verify_with_rootcacrl<B: Deref<Target = [u8]>>(&self, trusted_root_certs: &[B], root_ca_crls: &[RootCaCrl], enclave_identity: EnclaveIdentity) -> Result<QeIdentity, Error> {
319 let (chain, root) = crate::build_and_verify_cert_chain(&self.ca_chain, trusted_root_certs, root_ca_crls)?;
321 let mut leaf = chain.first().unwrap_or(&root).clone();
322
323 let mut hash = [0u8; 32];
325 mbedtls::hash::Md::hash(mbedtls::hash::Type::Sha256, self.raw_enclave_identity.as_bytes(), &mut hash).unwrap();
326 leaf.public_key_mut()
327 .verify(mbedtls::hash::Type::Sha256, &hash, &self.signature)
328 .map_err(|e| Error::InvalidQe3Id(e))?;
329
330 let QeIdentity::<Unverified> {
331 version,
332 id,
333 issue_date,
334 next_update,
335 tcb_evaluation_data_number,
336 miscselect,
337 miscselect_mask,
338 attributes,
339 attributes_mask,
340 mrsigner,
341 isvprodid,
342 tcb_levels,
343 _type: _
344 } = serde_json::from_str(&self.raw_enclave_identity).map_err(|e| Error::ParseError(e))?;
345
346 if version != 2 {
347 return Err(Error::UnknownQeIdentityVersion(version));
348 }
349
350 if id != enclave_identity {
351 return Err(Error::Qe3NotValid(format!("QE identity {enclave_identity} expected, got {id}")))
352 }
353
354 let now = Utc::now();
355 if now < issue_date {
356 return Err(Error::Qe3NotValid(format!("QE3 only valid from {}", issue_date)))
357 }
358
359 if next_update < now {
360 return Err(Error::Qe3NotValid(format!("QE3 expired on {}", next_update)))
361 }
362
363 Ok(QeIdentity::<Verified> {
364 version,
365 id,
366 issue_date,
367 next_update,
368 tcb_evaluation_data_number,
369 miscselect,
370 miscselect_mask,
371 attributes,
372 attributes_mask,
373 mrsigner,
374 isvprodid,
375 tcb_levels,
376 _type: Verified,
377 })
378 }
379}
380
381#[cfg(feature = "verify")]
382#[cfg(test)]
383mod tests {
384 #[cfg(not(target_env = "sgx"))]
385 use {
386 crate::qe_identity::{QeIdentitySigned, EnclaveIdentity},
387 crate::Error,
388 };
389
390 #[test]
391 #[cfg(not(target_env = "sgx"))]
392 fn read_qe3_identity() {
393 let qe_id = QeIdentitySigned::read_from_file("./tests/data/", None).expect("validated");
394
395 let root_cert = include_bytes!("../tests/data/root_SGX_CA_der.cert");
396 let root_certs = [&root_cert[..]];
397 match qe_id.verify(&root_certs, EnclaveIdentity::QE) {
398 Err(Error::Qe3NotValid(msg)) => assert_eq!(msg, "QE3 expired on 2020-06-17 17:49:21 UTC"),
399 e => assert!(false, "wrong result: {:?}", e),
400 }
401
402 match qe_id.verify(&root_certs, EnclaveIdentity::TDQE) {
403 Err(Error::Qe3NotValid(msg)) => assert_eq!(msg, "QE identity TD_QE expected, got QE"),
404 e => assert!(false, "wrong result: {:?}", e),
405 }
406 }
407
408 #[test]
409 #[cfg(not(target_env = "sgx"))]
410 fn read_corrupted_qe3_identity() {
411 let qeid = QeIdentitySigned::read_from_file("./tests/data/corrupted/", None).unwrap();
412
413 let root_cert = include_bytes!("../tests/data/root_SGX_CA_der.cert");
414 let root_certs = [&root_cert[..]];
415 assert!(qeid.verify(&root_certs, EnclaveIdentity::QE).is_err());
416 }
417}