1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
/* Copyright (c) Fortanix, Inc.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use byteorder::{BigEndian, ReadBytesExt};
use serde::{Serialize, Deserialize};
use sgx_isa::{Attributes, Miscselect, Report};
use std::str;
use std::fmt;
use std::marker::PhantomData;

#[cfg(feature = "client")]
use {
    super::verifier::{self, Crypto, Error, ErrorKind},
    pkix::types::DerSequence,
};

#[derive(Debug, Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum IasVersion {
    V2 = 2,
    V3,
    V4
}

pub const LATEST_IAS_VERSION: IasVersion = IasVersion::V4;

/// Adapts `serde_bytes` for `Option<T: AsRef<[u8]>>` and `Option<T: From<Vec<u8>>>`
mod serde_option_bytes {
    use serde_bytes;
    use serde::de::{Deserializer, Visitor};
    use serde::ser::Serializer;
    use std::marker::PhantomData;

    pub fn serialize<T, S>(value: &Option<T>, serializer: S) -> ::std::result::Result<S::Ok, S::Error>
        where T: serde_bytes::Serialize,
              S: Serializer
    {
        match *value {
            Some(ref bytes) => serde_bytes::serialize(bytes, serializer),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, T, D>(deserializer: D) -> ::std::result::Result<Option<T>, D::Error>
        where D: Deserializer<'de>,
              T: serde_bytes::Deserialize<'de>
    {
        struct VisitorImpl<'de, T: serde_bytes::Deserialize<'de>>(PhantomData<&'de ()>, PhantomData<T>);
        impl<'de, T> Visitor<'de> for VisitorImpl<'de, T>
            where T: serde_bytes::Deserialize<'de>
        {
            type Value = Option<T>;

            fn expecting(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(formatter, "an optional byte array")
            }

            fn visit_none<E>(self) -> Result<Self::Value, E> {
                Ok(None)
            }

            fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
                Ok(Some(serde_bytes::deserialize(deserializer)?))
            }
        }
        deserializer.deserialize_option(VisitorImpl(PhantomData, PhantomData))
    }
}

/// A request body for the IAS "verify attestation evidence" endpoint.  Refer to
/// the IAS API Specification.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VerifyAttestationEvidenceRequest {
    #[serde(with = "serde_bytes")]
    pub isv_enclave_quote: Vec<u8>,

    #[serde(skip_serializing_if = "Option::is_none", with = "self::serde_option_bytes")]
    pub pse_manifest: Option<Vec<u8>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>, // IAS spec: max length 32 characters
}

/// The ISV enclave quote body as returned in VerifyAttestationEvidenceResponse.
/// Compared to sgx_isa::Report, this has some QE metadata at the front, and
/// omits keyid and mac at the end. Everything else is the same.
/// Refer to the IAS API Specification.
#[repr(C)]
pub struct EnclaveQuoteBody {
    // "BODY" in the IAS API spec
    pub version:    u16,
    pub signature_type: u16,
    pub gid:        [u8; 4],
    pub isvsvn_qe:  u16,
    pub isvsvn_pce: u16,
    pub _reserved0: [u8;  4],
    pub basename:   [u8; 32],

    // "REPORTDATA" in the IAS API spec
    pub cpusvn:     [u8; 16],
    pub miscselect: Miscselect,
    pub _reserved1: [u8; 28],
    pub attributes: Attributes,
    pub mrenclave:  [u8; 32],
    pub _reserved2: [u8; 32],
    pub mrsigner:   [u8; 32],
    pub _reserved3: [u8; 96],
    pub isvprodid:  u16,
    pub isvsvn:     u16,
    pub _reserved4: [u8; 60],
    pub reportdata: [u8; 64],
}

pub const ENCLAVE_QUOTE_BODY_LEN: usize = 432;

impl EnclaveQuoteBody {
    /// If `src` has the correct length, returns `Some<EnclaveQuoteBody>`
    /// copied from `src`, else returns `None`.
    pub fn try_copy_from(src: &[u8]) -> Option<Self> {
        if src.len() == ENCLAVE_QUOTE_BODY_LEN {
            unsafe {
                Some(::std::ptr::read_unaligned(src.as_ptr() as *const EnclaveQuoteBody))
            }
        } else {
            None
        }
    }

    // Compile time check that the size argument is correct.
    // Not otherwise used.
    unsafe fn _check_size(b: Self) -> [u8; ENCLAVE_QUOTE_BODY_LEN] {
        ::std::mem::transmute(b)
    }

    // Report of the Enclave being attested.
    // key_id and mac are required parameter hence have to pass default value for them
    // as these values are not present in EnclaveQuoteBody
    pub fn get_report(self) -> Report {
        let EnclaveQuoteBody{cpusvn, miscselect, _reserved1, attributes, mrenclave, _reserved2, mrsigner, _reserved3, isvprodid, isvsvn, _reserved4, reportdata, ..} = self;
        Report {
            cpusvn,
            miscselect,
            _reserved1,
            attributes,
            mrenclave,
            _reserved2,
            mrsigner,
            _reserved3,
            isvprodid,
            isvsvn,
            _reserved4,
            reportdata,
            keyid: [0; 32],
            mac: [0; 16],
        }
    }
}

fn two() -> u64 {
    2
}

fn less_than_three(&v: &u64) -> bool {
    v < 3
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct IasAdvisoryId(String);

impl From<&str> for IasAdvisoryId {
    fn from(adv: &str) -> Self {
        IasAdvisoryId::new(adv)
    }
}

impl IasAdvisoryId {
    pub fn new(adv: &str) -> Self {
        IasAdvisoryId(adv.to_uppercase())
    }

    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

pub trait VerificationType {}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct VerifiedSig {}
impl VerificationType for VerifiedSig {}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) struct Unverified {}
impl VerificationType for Unverified {}

trait SafeToDeserializeInto {}
impl SafeToDeserializeInto for Unverified {}

/// A response body for the IAS "verify attestation evidence" endpoint.  Refer
/// to the IAS API Specification.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(bound(deserialize = "V: SafeToDeserializeInto"))]
#[serde(rename_all = "camelCase")]
pub struct VerifyAttestationEvidenceResponse<V: VerificationType = VerifiedSig> {
    id: String, // TODO: decimal big integer

    timestamp: String, // TODO: DateTime<UTC>, but DateTime serde doesn't
                           // like the IAS timestamp format.

    #[serde(default = "two", skip_serializing_if = "less_than_three")]
    version: u64,

    isv_enclave_quote_status: QuoteStatus,

    #[serde(with = "serde_bytes")]
    isv_enclave_quote_body: Vec<u8>,

    #[serde(skip_serializing_if = "Option::is_none")]
    revocation_reason: Option<u32>, // TODO: enum RFC5280 CRLReason

    #[serde(skip_serializing_if = "Option::is_none")]
    pse_manifest_status: Option<String>, // TODO: enum per IAS spec

    #[serde(skip_serializing_if = "Option::is_none")]
    pse_manifest_hash: Option<String>, // TODO: base16 blob

    #[serde(skip_serializing_if = "Option::is_none")]
    platform_info_blob: Option<String>, // TODO: base16 blob

    #[serde(skip_serializing_if = "Option::is_none")]
    nonce: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none", with = "self::serde_option_bytes")]
    epid_pseudonym: Option<Vec<u8>>,

    #[serde(skip_serializing_if = "Option::is_none", rename = "advisoryURL")]
    advisory_url: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none", rename = "advisoryIDs")]
    advisory_ids: Option<Vec<IasAdvisoryId>>,

    #[serde(skip)]
    type_: PhantomData<V>
}

#[cfg(feature = "client")]
impl VerifyAttestationEvidenceResponse<Unverified> {
    pub(crate) fn advisory_url(&self) -> &Option<String> {
        &self.advisory_url
    }

    pub(crate) fn advisory_ids(&self) -> &Option<Vec<IasAdvisoryId>> {
        &self.advisory_ids
    }
}

impl VerifyAttestationEvidenceResponse {
    #[cfg(feature = "client")]
    pub fn from_raw_report<C: Crypto>(raw_report: &[u8], report_sig: &[u8], cert_chain: &Vec<DerSequence>, ca_certificates: &[&[u8]]) -> Result<Self, Error> {
        // serde JSON deserialize, but binary data is Base64-encoded strings
        let mut deser = serde_json::Deserializer::from_slice(&raw_report);
        let deser = serde_bytes_repr::ByteFmtDeserializer::new_base64(&mut deser, base64::Config::new(base64::CharacterSet::Standard, true));
        let resp: VerifyAttestationEvidenceResponse<Unverified> = VerifyAttestationEvidenceResponse::deserialize(deser)
            .map_err(|e| Error { error_kind: ErrorKind::ReportJsonParse, cause: Some(Box::new(e)) })?;

        verifier::verify_raw_report::<C>(raw_report, report_sig, cert_chain, ca_certificates)?;

        let VerifyAttestationEvidenceResponse::<Unverified> {
            id,
            timestamp,
            version,
            isv_enclave_quote_status,
            isv_enclave_quote_body,
            revocation_reason,
            pse_manifest_status,
            pse_manifest_hash,
            platform_info_blob,
            nonce,
            epid_pseudonym,
            advisory_url,
            advisory_ids,
            type_: _,
        } = resp;

        Ok(VerifyAttestationEvidenceResponse{
            id,
            timestamp,
            version,
            isv_enclave_quote_status,
            isv_enclave_quote_body,
            revocation_reason,
            pse_manifest_status,
            pse_manifest_hash,
            platform_info_blob,
            nonce,
            epid_pseudonym,
            advisory_url,
            advisory_ids,
            type_: PhantomData,
        })
    }
}

impl VerifyAttestationEvidenceResponse {
    pub fn id(&self) -> &String {
        &self.id
    }

    pub fn version(&self) -> u64 {
        self.version
    }

    pub fn isv_enclave_quote_status(&self) -> QuoteStatus {
        self.isv_enclave_quote_status
    }

    pub fn isv_enclave_quote_body(&self) -> EnclaveQuoteBody {
        EnclaveQuoteBody::try_copy_from(&self.isv_enclave_quote_body)
            .expect("Validated at VerifyAttestationEvidenceResponse verification time")
    }

    pub fn revocation_reason(&self) -> Option<u32> {
        self.revocation_reason
    }

    pub fn pse_manifest_status(&self) -> &Option<String> {
        &self.pse_manifest_status
    }

    pub fn pse_manifest_hash(&self) -> &Option<String> {
        &self.pse_manifest_hash
    }

    pub fn platform_info_blob(&self) -> &Option<String> {
        &self.platform_info_blob
    }

    pub fn nonce(&self) -> &Option<String> {
        &self.nonce
    }

    pub fn epid_pseudonym(&self) -> &Option<Vec<u8>> {
        &self.epid_pseudonym
    }

    pub fn advisory_url(&self) -> &Option<String> {
        &self.advisory_url
    }

    pub fn advisory_ids(&self) -> &Option<Vec<IasAdvisoryId>> {
        &self.advisory_ids
    }
}


/// Attestation verification status enum. Refer to "Attestation Verification
/// Report" in the IAS API specification.
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum QuoteStatus {
    Ok,
    SignatureInvalid,
    GroupRevoked,
    SignatureRevoked,
    KeyRevoked,
    SigRlVersionMismatch,
    GroupOutOfDate,
    ConfigurationNeeded,
    SwHardeningNeeded,
    ConfigurationAndSwHardeningNeeded,
}

macro_rules! pif_v2_bitflags {
    ($($k:ident = $v:expr);* $(;)*) => (
        bitflags! {
            pub struct PlatformInfoFlagsV2: u64 {
                $(const $k = $v;)*
            }
        }

        static PIF_V2_NAMES: &'static [(PlatformInfoFlagsV2, &'static str)] = &[
            $((PlatformInfoFlagsV2::$k, stringify!($k)),)*
        ];
    )
}

pif_v2_bitflags! {
    // See Intel Linux SGX PSW, psw/ae/aesm_service/source/common/platform_info_blob.h
    /* Masks for sgx_epid_group_flags */
    QE_EPID_GROUP_REVOKED                           = 0x01_0000_0000;
    PERF_REKEY_FOR_QE_EPID_GROUP_AVAILABLE          = 0x02_0000_0000;
    QE_EPID_GROUP_OUT_OF_DATE                       = 0x04_0000_0000;

    /* Masks for sgx_tcb_evaluation_flags */
    QUOTE_CPUSVN_OUT_OF_DATE                        = 0x00_0001_0000;
    QUOTE_ISVSVN_QE_OUT_OF_DATE                     = 0x00_0002_0000;
    QUOTE_ISVSVN_PCE_OUT_OF_DATE                    = 0x00_0004_0000;
    PLATFORM_CONFIGURATION_NEEDED                   = 0x00_0008_0000;

    /* Masks for sgx_pse_evaluation_flags PS_SEC_PROP_DESC.PSE_ISVSVN is out of date */
    PSE_ISVSVN_OUT_OF_DATE                          = 0x00_0000_0001;
    EPID_GROUP_ID_BY_PS_HW_GID_REVOKED              = 0x00_0000_0002;
    SVN_FROM_PS_HW_SEC_INFO_OUT_OF_DATE             = 0x00_0000_0004;
    SIGRL_VER_FROM_PS_HW_SIG_RLVER_OUT_OF_DATE      = 0x00_0000_0008;
    PRIVRL_VER_FROM_PS_HW_PRV_KEY_RLVER_OUT_OF_DATE = 0x00_0000_0010;
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PlatformStatus {
    V2(PlatformInfoFlagsV2)
}

impl fmt::Display for PlatformStatus {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let &PlatformStatus::V2(mut flags) = self;
        for &(val, name) in PIF_V2_NAMES {
            if flags.contains(val) {
                flags.remove(val);
                write!(f, "{}", name)?;
                if !flags.is_empty() {
                    write!(f, ", ")?;
                }
            }
        }
        Ok(())
    }
}

impl str::FromStr for PlatformStatus {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, ()> {
        fn parse_hex(s: &str) -> Option<Vec<u8>> {
            if !s.is_ascii() || (s.len() % 2) == 1 {
                return None
            }
            s.as_bytes().chunks(2).map(|v| u8::from_str_radix(str::from_utf8(v).unwrap(/*is_ascii*/), 16).ok() ).collect()
        }

        const PLATFORM_INFO_BLOB_TYPE: u8 = 21;
        const PLATFORM_INFO_BLOB_VERSION: u8 = 2;
        const PLATFORM_INFO_BLOB_V2_LEN: u16 = 101;

        let pinfo = parse_hex(s).ok_or_else(|| warn!("Platform info blob is not properly hex encoded") )?;
        let pinfo = &mut &pinfo[..];

        let type_ = pinfo.read_u8().map_err(|_|())?;
        let version = pinfo.read_u8().map_err(|_|())?;
        let len = pinfo.read_u16::<BigEndian>().map_err(|_|())?;
        if (type_, version, len) != (PLATFORM_INFO_BLOB_TYPE, PLATFORM_INFO_BLOB_VERSION, PLATFORM_INFO_BLOB_V2_LEN) {
            warn!("Platform info blob TLV mismatch");
            return Err(())
        }

        let status = pinfo.read_uint::<BigEndian>(5).map_err(|_|())?;
        if let Some(bits) = PlatformInfoFlagsV2::from_bits(status) {
            Ok(PlatformStatus::V2(bits))
        } else {
            warn!("Platform info blob unexpected status bits set: {:010x}", status);
            Err(())
        }
    }
}

#[test]
fn parse_platform_info_blob() {
    let blob = "1502006504000100000707020401010000000000000000000005000004000000020000000000000AC888E762232B197B0114CFBFF28163B0D5EF1501399EFE6FF0A7F0CAD93E3A50AD744BA39C8A44FB91F17F5806687202BE0AE5459CD5613588A7B7539E003ABD48";
    assert_eq!(blob.parse::<PlatformStatus>().unwrap(), PlatformStatus::V2(PlatformInfoFlagsV2::QE_EPID_GROUP_OUT_OF_DATE | PlatformInfoFlagsV2::QUOTE_CPUSVN_OUT_OF_DATE));
}