Skip to main content

sui_types/
nitro_attestation.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::de::{Error, MapAccess, Visitor};
5use serde::{Deserialize, Deserializer};
6use std::collections::BTreeMap;
7use std::fmt;
8use x509_parser::public_key::PublicKey;
9use x509_parser::time::ASN1Time;
10use x509_parser::x509::SubjectPublicKeyInfo;
11
12use crate::error::{SuiError, SuiErrorKind, SuiResult};
13
14use ciborium::value::{Integer, Value};
15use once_cell::sync::Lazy;
16use p384::ecdsa::signature::Verifier;
17use p384::ecdsa::{Signature, VerifyingKey};
18use rustls_pki_types::{CertificateDer, pem::PemObject};
19use x509_parser::{certificate::X509Certificate, prelude::FromDer};
20
21#[cfg(test)]
22#[path = "unit_tests/nitro_attestation_tests.rs"]
23mod nitro_attestation_tests;
24
25/// Maximum length of the certificate chain. This is to limit the absolute upper bound on execution.
26const MAX_CERT_CHAIN_LENGTH: usize = 10;
27/// Max user data length from aws nitro spec.
28const MAX_USER_DATA_LENGTH: usize = 512;
29/// Max pk length from aws nitro spec.
30const MAX_PK_LENGTH: usize = 1024;
31/// Max pcrs length from aws nitro spec.
32const MAX_PCRS_LENGTH: usize = 32;
33/// Max certificate length from aws nitro spec.
34const MAX_CERT_LENGTH: usize = 1024;
35
36/// Root certificate for AWS Nitro Attestation.
37static ROOT_CERTIFICATE: Lazy<Vec<u8>> = Lazy::new(|| {
38    let pem_bytes = include_bytes!("./nitro_root_certificate.pem");
39    let cert = CertificateDer::pem_slice_iter(pem_bytes)
40        .next()
41        .expect("should have root cert")
42        .expect("root cert should be valid");
43    cert.to_vec()
44});
45
46/// Error type for Nitro attestation verification.
47#[derive(Debug, PartialEq, Eq)]
48pub enum NitroAttestationVerifyError {
49    /// Invalid COSE_Sign1: {0}
50    InvalidCoseSign1(String),
51    /// Invalid signature
52    InvalidSignature,
53    /// Invalid public key
54    InvalidPublicKey,
55    /// Siganture failed to verify
56    SignatureFailedToVerify,
57    /// Invalid attestation document
58    InvalidAttestationDoc(String),
59    /// Invalid user data.
60    InvalidUserData,
61    /// Invalid certificate: {0}
62    InvalidCertificate(String),
63    /// Invalid PCRs
64    InvalidPcrs,
65}
66
67impl fmt::Display for NitroAttestationVerifyError {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        match self {
70            NitroAttestationVerifyError::InvalidCoseSign1(msg) => {
71                write!(f, "InvalidCoseSign1: {}", msg)
72            }
73            NitroAttestationVerifyError::InvalidSignature => write!(f, "InvalidSignature"),
74            NitroAttestationVerifyError::InvalidPublicKey => write!(f, "InvalidPublicKey"),
75            NitroAttestationVerifyError::SignatureFailedToVerify => {
76                write!(f, "SignatureFailedToVerify")
77            }
78            NitroAttestationVerifyError::InvalidAttestationDoc(msg) => {
79                write!(f, "InvalidAttestationDoc: {}", msg)
80            }
81            NitroAttestationVerifyError::InvalidCertificate(msg) => {
82                write!(f, "InvalidCertificate: {}", msg)
83            }
84            NitroAttestationVerifyError::InvalidPcrs => write!(f, "InvalidPcrs"),
85            NitroAttestationVerifyError::InvalidUserData => write!(f, "InvalidUserData"),
86        }
87    }
88}
89
90impl From<NitroAttestationVerifyError> for SuiError {
91    fn from(err: NitroAttestationVerifyError) -> Self {
92        SuiErrorKind::NitroAttestationFailedToVerify(err.to_string()).into()
93    }
94}
95
96fn decode_cbor(bytes: &[u8], strict: bool) -> Result<Value, String> {
97    let mut remaining = bytes;
98    let value = ciborium::de::from_reader(&mut remaining).map_err(|e| e.to_string())?;
99    if !strict {
100        return Ok(value);
101    }
102    if !remaining.is_empty() {
103        return Err("trailing bytes after CBOR value".to_string());
104    }
105
106    // Ciborium combines segmented byte strings, so inspect the original encoding.
107    // Decoding above has already established CBOR structural validity.
108    let mut remaining = bytes;
109    while !remaining.is_empty() {
110        let header = ciborium_ll::Decoder::from(&mut remaining)
111            .pull()
112            .map_err(|e| format!("invalid CBOR header: {e:?}"))?;
113        match header {
114            ciborium_ll::Header::Bytes(None) => {
115                return Err("indefinite-length byte strings are not allowed".to_string());
116            }
117            ciborium_ll::Header::Bytes(Some(len)) | ciborium_ll::Header::Text(Some(len)) => {
118                remaining = remaining
119                    .get(len..)
120                    .ok_or_else(|| "truncated CBOR string".to_string())?;
121            }
122            _ => {}
123        }
124    }
125    Ok(value)
126}
127
128/// Given an attestation in bytes, parse it into signature, signed message and a parsed payload.
129pub fn parse_nitro_attestation(
130    attestation_bytes: &[u8],
131    is_upgraded_parsing: bool,
132    include_all_nonzero_pcrs: bool,
133    always_include_required_pcrs: bool,
134    simplify_nitro_header_validation: bool,
135) -> SuiResult<(Vec<u8>, Vec<u8>, AttestationDocument)> {
136    let cose_sign1 =
137        CoseSign1::parse_and_validate(attestation_bytes, simplify_nitro_header_validation)?;
138    let doc = AttestationDocument::parse_payload(
139        &cose_sign1.payload,
140        is_upgraded_parsing,
141        include_all_nonzero_pcrs,
142        always_include_required_pcrs,
143        simplify_nitro_header_validation,
144    )?;
145    let msg = cose_sign1.to_signed_message()?;
146    let signature = cose_sign1.signature;
147    Ok((signature, msg, doc))
148}
149
150/// Given the signature bytes, signed message and parsed payload, verify everything according to
151/// <https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html> and
152/// <https://github.com/aws/aws-nitro-enclaves-nsm-api/blob/main/docs/attestation_process.md>.
153pub fn verify_nitro_attestation(
154    signature: &[u8],
155    signed_message: &[u8],
156    payload: &AttestationDocument,
157    timestamp: u64,
158) -> SuiResult<()> {
159    // Extract public key from cert and signature as P384.
160    let signature = Signature::from_slice(signature)
161        .map_err(|_| NitroAttestationVerifyError::InvalidSignature)?;
162    let (_, cert) = X509Certificate::from_der(payload.certificate.as_slice())
163        .map_err(|e| NitroAttestationVerifyError::InvalidCertificate(e.to_string()))?;
164    let pk_bytes = SubjectPublicKeyInfo::parsed(cert.public_key())
165        .map_err(|err| NitroAttestationVerifyError::InvalidCertificate(err.to_string()))?;
166
167    // Verify the signature against the public key and the message.
168    match pk_bytes {
169        PublicKey::EC(ec) => {
170            let verifying_key = VerifyingKey::from_sec1_bytes(ec.data())
171                .map_err(|_| NitroAttestationVerifyError::InvalidPublicKey)?;
172            verifying_key
173                .verify(signed_message, &signature)
174                .map_err(|_| NitroAttestationVerifyError::SignatureFailedToVerify)?;
175        }
176        _ => {
177            return Err(NitroAttestationVerifyError::InvalidPublicKey.into());
178        }
179    }
180
181    payload.verify_cert(cert, timestamp)?;
182    Ok(())
183}
184
185///  Implementation of the COSE_Sign1 structure as defined in [RFC8152](https://tools.ietf.org/html/rfc8152).
186///  protected_header: See Section 3 (Note: AWS Nitro does not have unprotected header.)
187///  payload: See Section 4.2.
188///  signature: See Section 4.2.
189///  Class and trait impl adapted from <https://github.com/awslabs/aws-nitro-enclaves-cose/blob/main/src/sign.rs>
190#[derive(Debug, Clone)]
191pub struct CoseSign1 {
192    /// protected: empty_or_serialized_map,
193    protected: Vec<u8>,
194    /// unprotected: HeaderMap
195    #[allow(dead_code)]
196    unprotected: HeaderMap,
197    /// payload: bstr
198    /// The spec allows payload to be nil and transported separately, but it's not useful at the
199    /// moment, so this is just a Bytes for simplicity.
200    payload: Vec<u8>,
201    /// signature: bstr
202    signature: Vec<u8>,
203}
204
205/// Empty map wrapper for COSE headers.
206#[derive(Clone, Debug, Default)]
207pub struct HeaderMap;
208
209impl<'de> Deserialize<'de> for HeaderMap {
210    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
211    where
212        D: Deserializer<'de>,
213    {
214        struct MapVisitor;
215
216        impl<'de> Visitor<'de> for MapVisitor {
217            type Value = HeaderMap;
218
219            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220                formatter.write_str("a map")
221            }
222
223            fn visit_map<A>(self, mut access: A) -> Result<Self::Value, A::Error>
224            where
225                A: MapAccess<'de>,
226            {
227                let mut seen_keys = Vec::new();
228
229                // Check for duplicate keys while consuming entries
230                while let Some((key, _value)) = access.next_entry::<Value, Value>()? {
231                    if seen_keys.contains(&key) {
232                        return Err(Error::custom("duplicate key found in CBOR map"));
233                    }
234                    seen_keys.push(key);
235                }
236                Ok(HeaderMap)
237            }
238        }
239
240        deserializer.deserialize_map(MapVisitor)
241    }
242}
243
244impl<'de> Deserialize<'de> for CoseSign1 {
245    fn deserialize<D>(deserializer: D) -> Result<CoseSign1, D::Error>
246    where
247        D: Deserializer<'de>,
248    {
249        use serde::de::{Error, SeqAccess, Visitor};
250        use std::fmt;
251
252        struct CoseSign1Visitor;
253
254        impl<'de> Visitor<'de> for CoseSign1Visitor {
255            type Value = CoseSign1;
256
257            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258                f.write_str("a possibly tagged CoseSign1 structure")
259            }
260
261            fn visit_seq<A>(self, mut seq: A) -> Result<CoseSign1, A::Error>
262            where
263                A: SeqAccess<'de>,
264            {
265                fn extract_bytes(value: Value) -> Option<Vec<u8>> {
266                    match value {
267                        Value::Bytes(bytes) => Some(bytes),
268                        _ => None,
269                    }
270                }
271
272                // Get protected header bytes
273                let protected = match seq.next_element::<Value>()? {
274                    Some(v) => extract_bytes(v)
275                        .ok_or_else(|| A::Error::custom("protected header must be bytes"))?,
276                    None => return Err(A::Error::missing_field("protected")),
277                };
278
279                let unprotected = match seq.next_element()? {
280                    Some(v) => v,
281                    None => return Err(A::Error::missing_field("unprotected")),
282                };
283                // Get payload bytes
284                let payload = match seq.next_element::<Value>()? {
285                    Some(v) => {
286                        extract_bytes(v).ok_or_else(|| A::Error::custom("payload must be bytes"))?
287                    }
288                    None => return Err(A::Error::missing_field("payload")),
289                };
290
291                // Get signature bytes
292                let signature = match seq.next_element::<Value>()? {
293                    Some(v) => extract_bytes(v)
294                        .ok_or_else(|| A::Error::custom("signature must be bytes"))?,
295                    None => return Err(A::Error::missing_field("signature")),
296                };
297
298                Ok(CoseSign1 {
299                    protected,
300                    unprotected,
301                    payload,
302                    signature,
303                })
304            }
305
306            fn visit_newtype_struct<D>(self, deserializer: D) -> Result<CoseSign1, D::Error>
307            where
308                D: Deserializer<'de>,
309            {
310                // This is the tagged version: we ignore the tag part, and just go into it
311                deserializer.deserialize_seq(CoseSign1Visitor)
312            }
313        }
314
315        deserializer.deserialize_any(CoseSign1Visitor)
316    }
317}
318
319impl CoseSign1 {
320    /// Parse CBOR bytes into struct. Adapted from <https://github.com/awslabs/aws-nitro-enclaves-cose/blob/main/src/sign.rs>
321    pub fn parse_and_validate(
322        bytes: &[u8],
323        simplify_nitro_header_validation: bool,
324    ) -> Result<Self, NitroAttestationVerifyError> {
325        let tagged_value = decode_cbor(bytes, simplify_nitro_header_validation)
326            .map_err(NitroAttestationVerifyError::InvalidCoseSign1)?;
327
328        let (tag, value) = match tagged_value {
329            ciborium::value::Value::Tag(tag, box_value) => (Some(tag), *box_value),
330            other => (None, other),
331        };
332
333        // Validate tag (18 is the COSE_Sign1 tag)
334        match tag {
335            None | Some(18) => (),
336            Some(_) => {
337                return Err(NitroAttestationVerifyError::InvalidCoseSign1(
338                    "invalid tag".to_string(),
339                ));
340            }
341        }
342
343        let cosesign1 = if simplify_nitro_header_validation {
344            // When enabled, validate the decoded fields directly:
345            // 1. Require an empty unprotected map.
346            // 2. Require the protected header to contain exactly {1: -35}.
347            let Value::Array(fields) = value else {
348                return Err(NitroAttestationVerifyError::InvalidCoseSign1(
349                    "expected a COSE_Sign1 array".to_string(),
350                ));
351            };
352            let fields: [Value; 4] = fields.try_into().map_err(|_| {
353                NitroAttestationVerifyError::InvalidCoseSign1(
354                    "expected four COSE_Sign1 fields".to_string(),
355                )
356            })?;
357            let [
358                Value::Bytes(protected),
359                Value::Map(unprotected),
360                Value::Bytes(payload),
361                Value::Bytes(signature),
362            ] = fields
363            else {
364                return Err(NitroAttestationVerifyError::InvalidCoseSign1(
365                    "invalid COSE_Sign1 field types".to_string(),
366                ));
367            };
368            if !unprotected.is_empty() {
369                return Err(NitroAttestationVerifyError::InvalidCoseSign1(
370                    "unprotected header must be an empty map".to_string(),
371                ));
372            }
373            Self {
374                protected,
375                unprotected: HeaderMap,
376                payload,
377                signature,
378            }
379        } else {
380            // The legacy path deserializes headers and checks for duplicate keys.
381            // Create a buffer for serialization
382            let mut buf = Vec::new();
383
384            // Serialize the value into the buffer
385            ciborium::ser::into_writer(&value, &mut buf)
386                .map_err(|e| NitroAttestationVerifyError::InvalidCoseSign1(e.to_string()))?;
387
388            // Deserialize the COSE_Sign1 structure from the buffer
389            let cosesign1: Self = ciborium::de::from_reader(&buf[..])
390                .map_err(|e| NitroAttestationVerifyError::InvalidCoseSign1(e.to_string()))?;
391
392            let _: HeaderMap = ciborium::de::from_reader(cosesign1.protected.as_slice())
393                .map_err(|e| NitroAttestationVerifyError::InvalidCoseSign1(e.to_string()))?;
394
395            cosesign1
396        };
397
398        cosesign1.validate_header(simplify_nitro_header_validation)?;
399        Ok(cosesign1)
400    }
401
402    /// Validate protected header, payload and signature length.
403    pub fn validate_header(&self, strict: bool) -> Result<(), NitroAttestationVerifyError> {
404        if !(Self::is_valid_protected_header(self.protected.as_slice(), strict)
405            && (1..16384).contains(&self.payload.len())
406            && self.signature.len() == 96)
407        {
408            return Err(NitroAttestationVerifyError::InvalidCoseSign1(
409                "invalid cbor header".to_string(),
410            ));
411        }
412        Ok(())
413    }
414
415    // Check protected header: https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html#COSE-CBOR
416    // 18(/* COSE_Sign1 CBOR tag is 18 */
417    //     {1: -35}, /* This is equivalent with {algorithm: ECDS 384} */
418    //     {}, /* We have nothing in unprotected */
419    //     $ATTESTATION_DOCUMENT_CONTENT /* Attestation Document */,
420    //     signature /* This is the signature */
421    // )
422    fn is_valid_protected_header(bytes: &[u8], strict: bool) -> bool {
423        let expected_key: Integer = Integer::from(1);
424        let expected_val: Integer = Integer::from(-35);
425        let mut remaining = bytes;
426        let value: Value = match ciborium::de::from_reader(&mut remaining) {
427            Ok(v) => v,
428            Err(_) => return false,
429        };
430        if strict && !remaining.is_empty() {
431            return false;
432        }
433        match value {
434            Value::Map(vec) => match &vec[..] {
435                [(Value::Integer(key), Value::Integer(val))] => {
436                    key == &expected_key && val == &expected_val
437                }
438                _ => false,
439            },
440            _ => false,
441        }
442    }
443
444    /// This is the content that the signature is committed over.
445    fn to_signed_message(&self) -> SuiResult<Vec<u8>> {
446        let value = Value::Array(vec![
447            Value::Text("Signature1".to_string()),
448            Value::Bytes(self.protected.as_slice().to_vec()),
449            Value::Bytes(vec![]),
450            Value::Bytes(self.payload.as_slice().to_vec()),
451        ]);
452        // 17 for extra metadata bytes
453        let mut bytes = Vec::with_capacity(self.protected.len() + self.payload.len() + 17);
454        ciborium::ser::into_writer(&value, &mut bytes).map_err(|_| {
455            SuiErrorKind::NitroAttestationFailedToVerify("cannot parse message".to_string())
456        })?;
457        Ok(bytes)
458    }
459}
460
461/// The AWS Nitro Attestation Document, see <https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html#doc-def>
462#[allow(dead_code)]
463#[derive(Debug, Clone)]
464pub struct AttestationDocument {
465    pub module_id: String,
466    pub timestamp: u64,
467    pub digest: String,
468    pub pcr_vec: Vec<Vec<u8>>,
469    pub pcr_map: BTreeMap<u8, Vec<u8>>,
470    certificate: Vec<u8>,
471    cabundle: Vec<Vec<u8>>,
472    pub public_key: Option<Vec<u8>>,
473    pub user_data: Option<Vec<u8>>,
474    pub nonce: Option<Vec<u8>>,
475}
476
477impl AttestationDocument {
478    /// Validate and parse the payload of the attestation document.
479    /// Adapted from <https://github.com/EternisAI/remote-attestation-verifier/blob/main/src/lib.rs>
480    pub fn parse_payload(
481        payload: &[u8],
482        is_upgraded_parsing: bool,
483        include_all_nonzero_pcrs: bool,
484        always_include_required_pcrs: bool,
485        strict: bool,
486    ) -> Result<AttestationDocument, NitroAttestationVerifyError> {
487        let document_map = Self::to_map(payload, is_upgraded_parsing, strict)?;
488        Self::validate_document_map(
489            &document_map,
490            is_upgraded_parsing,
491            include_all_nonzero_pcrs,
492            always_include_required_pcrs,
493        )
494    }
495
496    fn to_map(
497        payload: &[u8],
498        is_upgraded_parsing: bool,
499        strict: bool,
500    ) -> Result<BTreeMap<String, Value>, NitroAttestationVerifyError> {
501        let document_data = decode_cbor(payload, strict).map_err(|err| {
502            NitroAttestationVerifyError::InvalidAttestationDoc(format!(
503                "cannot parse payload CBOR: {}",
504                err
505            ))
506        })?;
507
508        let document_map: BTreeMap<String, Value> = match document_data {
509            ciborium::value::Value::Map(map) => {
510                let map_size = map.len();
511                let result = map
512                    .into_iter()
513                    .map(|(k, v)| {
514                        let k = k.as_text().ok_or(
515                            NitroAttestationVerifyError::InvalidAttestationDoc(format!(
516                                "invalid key type: {:?}",
517                                k
518                            )),
519                        )?;
520                        Ok((k.to_string(), v))
521                    })
522                    .collect::<Result<BTreeMap<String, Value>, NitroAttestationVerifyError>>()?;
523
524                if is_upgraded_parsing && result.len() != map_size {
525                    return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
526                        "duplicate keys found in attestation document".to_string(),
527                    ));
528                }
529                result
530            }
531            _ => {
532                return Err(NitroAttestationVerifyError::InvalidAttestationDoc(format!(
533                    "expected map, got {:?}",
534                    document_data
535                )));
536            }
537        };
538        Ok(document_map)
539    }
540
541    fn validate_document_map(
542        document_map: &BTreeMap<String, Value>,
543        is_upgraded_parsing: bool,
544        include_all_nonzero_pcrs: bool,
545        always_include_required_pcrs: bool,
546    ) -> Result<AttestationDocument, NitroAttestationVerifyError> {
547        let module_id = document_map
548            .get("module_id")
549            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
550                "module id not found".to_string(),
551            ))?
552            .as_text()
553            .filter(|s| !s.is_empty())
554            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
555                "invalid module id".to_string(),
556            ))?
557            .to_string();
558
559        let digest = document_map
560            .get("digest")
561            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
562                "digest not found".to_string(),
563            ))?
564            .as_text()
565            .filter(|s| s == &"SHA384")
566            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
567                "invalid digest".to_string(),
568            ))?
569            .to_string();
570
571        let certificate = document_map
572            .get("certificate")
573            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
574                "certificate not found".to_string(),
575            ))?
576            .as_bytes()
577            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
578                "invalid certificate".to_string(),
579            ))?
580            .to_vec();
581
582        if certificate.is_empty() || certificate.len() > MAX_CERT_LENGTH {
583            return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
584                "invalid certificate".to_string(),
585            ));
586        }
587
588        let timestamp = document_map
589            .get("timestamp")
590            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
591                "timestamp not found".to_string(),
592            ))?
593            .as_integer()
594            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
595                "timestamp is not an integer".to_string(),
596            ))
597            .and_then(|integer| {
598                u64::try_from(integer).map_err(|_| {
599                    NitroAttestationVerifyError::InvalidAttestationDoc(
600                        "timestamp not u64".to_string(),
601                    )
602                })
603            })?;
604
605        let public_key = document_map
606            .get("public_key")
607            .and_then(|v| v.as_bytes())
608            .map(|bytes| bytes.to_vec());
609
610        if let Some(data) = &public_key {
611            if is_upgraded_parsing {
612                if data.len() > MAX_PK_LENGTH {
613                    return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
614                        "invalid public key".to_string(),
615                    ));
616                }
617            } else if data.is_empty() || data.len() > MAX_PK_LENGTH {
618                return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
619                    "invalid public key".to_string(),
620                ));
621            }
622        }
623
624        let user_data = document_map
625            .get("user_data")
626            .and_then(|v| v.as_bytes())
627            .map(|bytes| bytes.to_vec());
628
629        if let Some(data) = &user_data
630            && data.len() > MAX_USER_DATA_LENGTH
631        {
632            return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
633                "invalid user data".to_string(),
634            ));
635        }
636
637        let nonce = document_map
638            .get("nonce")
639            .and_then(|v| v.as_bytes())
640            .map(|bytes| bytes.to_vec());
641
642        if let Some(data) = &nonce
643            && data.len() > MAX_USER_DATA_LENGTH
644        {
645            return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
646                "invalid nonce".to_string(),
647            ));
648        }
649
650        let (pcr_vec, pcr_map) = document_map
651            .get("pcrs")
652            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
653                "pcrs not found".to_string(),
654            ))?
655            .as_map()
656            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
657                "invalid pcrs format".to_string(),
658            ))
659            .and_then(|pairs| {
660                if pairs.len() > MAX_PCRS_LENGTH {
661                    return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
662                        "invalid PCRs length".to_string(),
663                    ));
664                }
665                let mut pcr_vec = Vec::with_capacity(pairs.len());
666                let mut pcr_map = BTreeMap::new();
667                for (k, v) in pairs.iter() {
668                    let key = k.as_integer().ok_or(
669                        NitroAttestationVerifyError::InvalidAttestationDoc(
670                            "invalid PCR key format".to_string(),
671                        ),
672                    )?;
673                    let value =
674                        v.as_bytes()
675                            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
676                                "invalid PCR value format".to_string(),
677                            ))?;
678
679                    if value.len() != 32 && value.len() != 48 && value.len() != 64 {
680                        return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
681                            "invalid PCR value length".to_string(),
682                        ));
683                    }
684
685                    // legacy parsing that populates a vector.
686                    let key_u64 = u64::try_from(key).map_err(|_| {
687                        NitroAttestationVerifyError::InvalidAttestationDoc(
688                            "invalid PCR index".to_string(),
689                        )
690                    })?;
691                    for i in [0, 1, 2, 3, 4, 8] {
692                        if key_u64 == i {
693                            pcr_vec.push(value.to_vec());
694                        }
695                    }
696
697                    // when upgraded parsing is enabled, use btreemap to avoid dup.
698                    if is_upgraded_parsing {
699                        // valid key is 0..31, can parse with u8.
700                        let key_u8 = u8::try_from(key).map_err(|_| {
701                            NitroAttestationVerifyError::InvalidAttestationDoc(
702                                "invalid PCR index".to_string(),
703                            )
704                        })?;
705
706                        if pcr_map.contains_key(&key_u8) {
707                            return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
708                                format!("duplicate PCR index {}", key_u8),
709                            ));
710                        }
711
712                        if include_all_nonzero_pcrs {
713                            // If include_all_nonzero_pcrs = true, parse all 0..31 PCRs, but
714                            // only include nonzero values.
715                            // See: <https://github.com/aws/aws-nitro-enclaves-nsm-api/issues/18#issuecomment-970172662>
716                            // Also: <https://github.com/aws/aws-nitro-enclaves-nsm-api/blob/main/nsm-test/src/bin/nsm-check.rs#L193-L199>
717                            let is_required_pcr = matches!(key_u8, 0 | 1 | 2 | 3 | 4 | 8);
718                            let is_nonzero = !value.iter().all(|&b| b == 0);
719
720                            // If always_include_required_pcrs = true, always include required PCRs,
721                            // regardless if they are zero or not.
722                            if key_u8 <= 31
723                                && (is_nonzero || (is_required_pcr && always_include_required_pcrs))
724                            {
725                                pcr_map.insert(key_u8, value.to_vec());
726                            }
727                        } else {
728                            // Legacy mode (include_all_nonzero_pcrs=false): Parse only
729                            // required PCRs (0, 1, 2, 3, 4, 8), regardless if they are zero or not.
730                            // See: <https://docs.aws.amazon.com/enclaves/latest/user/set-up-attestation.html#where>
731                            if matches!(key_u8, 0 | 1 | 2 | 3 | 4 | 8) {
732                                pcr_map.insert(key_u8, value.to_vec());
733                            }
734                        }
735                    }
736                }
737                Ok((pcr_vec, pcr_map))
738            })?;
739
740        let cabundle = document_map
741            .get("cabundle")
742            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
743                "cabundle not found".to_string(),
744            ))?
745            .as_array()
746            .map(|arr| {
747                if arr.is_empty() || arr.len() > MAX_CERT_CHAIN_LENGTH {
748                    return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
749                        "invalid ca chain length".to_string(),
750                    ));
751                }
752                let mut certs = Vec::with_capacity(arr.len());
753                for cert in arr.iter() {
754                    let cert_bytes = cert.as_bytes().ok_or(
755                        NitroAttestationVerifyError::InvalidAttestationDoc(
756                            "invalid certificate bytes".to_string(),
757                        ),
758                    )?;
759                    if cert_bytes.is_empty() || cert_bytes.len() > MAX_CERT_LENGTH {
760                        return Err(NitroAttestationVerifyError::InvalidAttestationDoc(
761                            "invalid ca length".to_string(),
762                        ));
763                    }
764                    certs.push(cert_bytes.to_vec());
765                }
766                Ok(certs)
767            })
768            .ok_or(NitroAttestationVerifyError::InvalidAttestationDoc(
769                "invalid cabundle".to_string(),
770            ))??;
771
772        let doc = AttestationDocument {
773            module_id,
774            timestamp,
775            digest,
776            pcr_vec,
777            pcr_map,
778            certificate,
779            cabundle,
780            public_key,
781            user_data,
782            nonce,
783        };
784        Ok(doc)
785    }
786
787    /// Verify the certificate against AWS Nitro root of trust and checks expiry.
788    /// Assume the cabundle is in order.
789    fn verify_cert<'a>(
790        &'a self,
791        leaf: X509Certificate<'a>,
792        now: u64,
793    ) -> Result<(), NitroAttestationVerifyError> {
794        // Create chain starting with leaf cert all the way to root.
795        let mut chain = Vec::with_capacity(1 + self.cabundle.len());
796        chain.push(self.certificate.as_slice());
797        chain.extend(self.cabundle.iter().rev().map(|cert| cert.as_slice()));
798        verify_cert_chain(&chain, leaf, now)
799    }
800
801    /// Get the length of the certificate chain.
802    pub fn get_cert_chain_length(&self) -> usize {
803        self.cabundle.len()
804    }
805}
806/// Verify the certificate chain against the root of trust.
807fn verify_cert_chain<'a>(
808    cert_chain: &[&'a [u8]],
809    mut cert: X509Certificate<'a>,
810    now_ms: u64,
811) -> Result<(), NitroAttestationVerifyError> {
812    let root_cert = X509Certificate::from_der(ROOT_CERTIFICATE.as_slice())
813        .map_err(|e| NitroAttestationVerifyError::InvalidCertificate(e.to_string()))?
814        .1;
815
816    let now_secs =
817        ASN1Time::from_timestamp((now_ms as i64).checked_div(1000).ok_or_else(|| {
818            NitroAttestationVerifyError::InvalidAttestationDoc("timestamp overflow".to_string())
819        })?)
820        .map_err(|e| NitroAttestationVerifyError::InvalidCertificate(e.to_string()))?;
821
822    // Validate the chain starting from the leaf
823    for i in 0..cert_chain.len() {
824        // Check key usage for all certificates
825        if let Ok(Some(key_usage)) = cert.key_usage() {
826            if i == 0 {
827                // Target certificate must have digitalSignature
828                if !key_usage.value.digital_signature() {
829                    return Err(NitroAttestationVerifyError::InvalidCertificate(
830                        "Target certificate missing digitalSignature key usage".to_string(),
831                    ));
832                }
833            } else {
834                // CA certificates must have keyCertSign
835                if !key_usage.value.key_cert_sign() {
836                    return Err(NitroAttestationVerifyError::InvalidCertificate(
837                        "CA certificate missing keyCertSign key usage".to_string(),
838                    ));
839                }
840            }
841        } else {
842            return Err(NitroAttestationVerifyError::InvalidCertificate(
843                "Missing key usage extension".to_string(),
844            ));
845        }
846
847        if i != 0 {
848            // all ca certs must have basic contraint, must be critical, ca flag must be true,
849            // pathLenConstraint is optional but if present must be checked.
850            if let Ok(Some(bc)) = cert.basic_constraints() {
851                if !bc.critical || !bc.value.ca {
852                    return Err(NitroAttestationVerifyError::InvalidCertificate(
853                        "CA certificate invalid".to_string(),
854                    ));
855                }
856                if let Some(path_len) = bc.value.path_len_constraint {
857                    // path_len_constraint is the maximum number of CA certificates
858                    // that may follow this certificate. A value of zero indicates
859                    // that only an end-entity certificate may follow in the path.
860                    if i - 1 > path_len as usize {
861                        return Err(NitroAttestationVerifyError::InvalidCertificate(
862                            "Cert chain exceeds pathLenConstraint".to_string(),
863                        ));
864                    }
865                }
866            } else {
867                return Err(NitroAttestationVerifyError::InvalidCertificate(
868                    "missing basic constraint".to_string(),
869                ));
870            }
871        } else if let Ok(Some(bc)) = cert.basic_constraints() {
872            // end entity can have basic constraint optionally, if present, ca must be false and
873            // pathLenConstraint is undefined.
874            if bc.value.path_len_constraint.is_some() || bc.value.ca {
875                return Err(NitroAttestationVerifyError::InvalidCertificate(
876                    "Cert chain exceeds pathLenConstraint".to_string(),
877                ));
878            }
879        }
880
881        // Check timestamp validity
882        if !cert.validity().is_valid_at(now_secs) {
883            return Err(NitroAttestationVerifyError::InvalidCertificate(
884                "Certificate timestamp not valid".to_string(),
885            ));
886        }
887
888        // Get issuer cert from either next in chain or root
889        let issuer_cert = if i < cert_chain.len() - 1 {
890            X509Certificate::from_der(cert_chain[i + 1])
891                .map_err(|e| NitroAttestationVerifyError::InvalidCertificate(e.to_string()))?
892                .1
893        } else {
894            root_cert.clone()
895        };
896
897        // Verify issuer/subject chaining
898        if cert.issuer() != issuer_cert.subject() {
899            return Err(NitroAttestationVerifyError::InvalidCertificate(
900                "certificate chain issuer mismatch".to_string(),
901            ));
902        }
903
904        // Verify signature
905        cert.verify_signature(Some(issuer_cert.public_key()))
906            .map_err(|_| {
907                NitroAttestationVerifyError::InvalidCertificate(
908                    "certificate fails to verify".to_string(),
909                )
910            })?;
911        cert = issuer_cert;
912    }
913
914    Ok(())
915}