Skip to main content

maple_sdk/
attestation.rs

1use crate::cbor::{self, Value as CborValue};
2use crate::error::{Error, Result};
3use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
4use ring::signature;
5use serde::{Deserialize, Serialize};
6use x509_parser::prelude::*;
7
8// AWS Nitro Root Certificate (production)
9const AWS_NITRO_ROOT_CERT: &[u8] = include_bytes!("../assets/aws_nitro_root.der");
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct AttestationDocument {
13    pub module_id: String,
14    pub timestamp: u64,
15    pub digest: String,
16    pub pcrs: std::collections::HashMap<usize, Vec<u8>>,
17    pub certificate: Vec<u8>,
18    pub cabundle: Vec<Vec<u8>>,
19    pub public_key: Option<Vec<u8>>,
20    pub user_data: Option<Vec<u8>>,
21    pub nonce: Option<Vec<u8>>,
22}
23
24/// Low-level AWS Nitro document verifier.
25///
26/// This verifies the certificate chain, document signature, and nonce. Nitro
27/// authenticity alone does not identify an OpenSecret deployment. Production
28/// callers should use `OpenSecretClient`, which additionally enforces its
29/// configured `Pcr0TrustPolicy` before key exchange.
30#[derive(Default)]
31pub struct AttestationVerifier {
32    expected_pcrs: Option<std::collections::HashMap<usize, Vec<u8>>>,
33}
34
35impl AttestationVerifier {
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    pub fn with_expected_pcrs(mut self, pcrs: std::collections::HashMap<usize, Vec<u8>>) -> Self {
41        self.expected_pcrs = Some(pcrs);
42        self
43    }
44
45    pub fn verify_attestation_document(
46        &self,
47        document_b64: &str,
48        expected_nonce: &str,
49    ) -> Result<AttestationDocument> {
50        self.verify_attestation_document_with(document_b64, |nonce_bytes| {
51            let nonce_str = String::from_utf8(nonce_bytes.to_vec()).map_err(|e| {
52                Error::AttestationVerificationFailed(format!("Invalid nonce encoding: {}", e))
53            })?;
54
55            if nonce_str != expected_nonce {
56                return Err(Error::AttestationVerificationFailed(
57                    "Nonce mismatch".to_string(),
58                ));
59            }
60            Ok(())
61        })
62    }
63
64    /// Verify a Nitro document against an exact binary nonce.
65    ///
66    /// Transport v2 uses a uniformly random 32-byte challenge. Keeping this
67    /// entry point beside the established verifier ensures certificate and
68    /// COSE validation remain identical without forcing binary freshness
69    /// material through UTF-8. The caller still applies its PCR policy, and
70    /// the public string API above is unchanged.
71    pub(crate) fn verify_attestation_document_bytes(
72        &self,
73        document_b64: &str,
74        expected_nonce: &[u8],
75    ) -> Result<AttestationDocument> {
76        self.verify_attestation_document_with(document_b64, |nonce_bytes| {
77            if nonce_bytes != expected_nonce {
78                return Err(Error::AttestationVerificationFailed(
79                    "Nonce mismatch".to_string(),
80                ));
81            }
82            Ok(())
83        })
84    }
85
86    fn verify_attestation_document_with(
87        &self,
88        document_b64: &str,
89        verify_nonce: impl FnOnce(&[u8]) -> Result<()>,
90    ) -> Result<AttestationDocument> {
91        self.verify_attestation_document_at(document_b64, verify_nonce, current_time_ms())
92    }
93
94    /// Verifies a document with an explicit device clock reading (milliseconds
95    /// since the UNIX epoch). See [`ATTESTATION_NOT_BEFORE_LEEWAY_MS`].
96    fn verify_attestation_document_at(
97        &self,
98        document_b64: &str,
99        verify_nonce: impl FnOnce(&[u8]) -> Result<()>,
100        device_now_ms: u64,
101    ) -> Result<AttestationDocument> {
102        let document_bytes = BASE64.decode(document_b64)?;
103
104        // Parse COSE_Sign1 structure
105        let cbor_value: CborValue = cbor::from_slice(&document_bytes)?;
106
107        let cose_sign1 = match &cbor_value {
108            CborValue::Array(arr) => arr,
109            _ => {
110                return Err(Error::AttestationVerificationFailed(
111                    "Invalid COSE_Sign1 structure".to_string(),
112                ))
113            }
114        };
115
116        if cose_sign1.len() != 4 {
117            return Err(Error::AttestationVerificationFailed(
118                "COSE_Sign1 must have 4 elements".to_string(),
119            ));
120        }
121
122        // Extract components
123        let protected = match &cose_sign1[0] {
124            CborValue::Bytes(b) => b,
125            _ => {
126                return Err(Error::AttestationVerificationFailed(
127                    "Invalid protected header".to_string(),
128                ))
129            }
130        };
131
132        let payload = match &cose_sign1[2] {
133            CborValue::Bytes(b) => b,
134            _ => {
135                return Err(Error::AttestationVerificationFailed(
136                    "Invalid payload".to_string(),
137                ))
138            }
139        };
140
141        let signature = match &cose_sign1[3] {
142            CborValue::Bytes(b) => b,
143            _ => {
144                return Err(Error::AttestationVerificationFailed(
145                    "Invalid signature".to_string(),
146                ))
147            }
148        };
149
150        // Parse attestation document from payload
151        let doc_cbor: CborValue = cbor::from_slice(payload)?;
152
153        let doc = self.parse_attestation_document(&doc_cbor)?;
154
155        // Verify freshness before accepting any attested key material.
156        let nonce_bytes = doc.nonce.as_deref().ok_or_else(|| {
157            Error::AttestationVerificationFailed(
158                "Missing nonce in attestation document".to_string(),
159            )
160        })?;
161        verify_nonce(nonce_bytes)?;
162
163        // Verify certificate chain signatures up to the pinned AWS root
164        self.verify_certificate_chain(&doc)?;
165
166        // Verify the document signature; after this the payload, including
167        // its `timestamp`, is authenticated by the Nitro PKI.
168        self.verify_signature(protected, payload, signature, &doc)?;
169
170        // Verify every certificate's validity window against the device clock,
171        // as AWS specifies. This runs after the signature check so the signed
172        // `timestamp` can explain a failure in terms of the device clock.
173        self.verify_certificate_validity(&doc, device_now_ms)?;
174
175        // Verify PCRs if expected
176        if let Some(expected_pcrs) = &self.expected_pcrs {
177            self.verify_pcrs(&doc, expected_pcrs)?;
178        }
179
180        Ok(doc)
181    }
182
183    fn parse_attestation_document(&self, cbor: &CborValue) -> Result<AttestationDocument> {
184        let map = match cbor {
185            CborValue::Map(m) => m,
186            _ => {
187                return Err(Error::AttestationVerificationFailed(
188                    "Invalid attestation document format".to_string(),
189                ))
190            }
191        };
192
193        let mut doc = AttestationDocument {
194            module_id: String::new(),
195            timestamp: 0,
196            digest: String::new(),
197            pcrs: std::collections::HashMap::new(),
198            certificate: Vec::new(),
199            cabundle: Vec::new(),
200            public_key: None,
201            user_data: None,
202            nonce: None,
203        };
204
205        for (key, value) in map {
206            let key_str = match key {
207                CborValue::Text(s) => s.as_str(),
208                _ => {
209                    return Err(Error::AttestationVerificationFailed(
210                        "Invalid key in attestation document".to_string(),
211                    ))
212                }
213            };
214
215            match key_str {
216                "module_id" => {
217                    doc.module_id = match value {
218                        CborValue::Text(s) => s.clone(),
219                        _ => {
220                            return Err(Error::AttestationVerificationFailed(
221                                "Invalid module_id".to_string(),
222                            ))
223                        }
224                    };
225                }
226                "timestamp" => {
227                    doc.timestamp = match value {
228                        CborValue::Integer(i) => cbor_integer_to_u64(*i, "timestamp")?,
229                        _ => {
230                            return Err(Error::AttestationVerificationFailed(
231                                "Invalid timestamp: not an integer".to_string(),
232                            ))
233                        }
234                    };
235                }
236                "digest" => {
237                    doc.digest = match value {
238                        CborValue::Text(s) => s.clone(),
239                        _ => {
240                            return Err(Error::AttestationVerificationFailed(
241                                "Invalid digest".to_string(),
242                            ))
243                        }
244                    };
245                }
246                "pcrs" => {
247                    let pcrs_map = match value {
248                        CborValue::Map(m) => m,
249                        _ => {
250                            return Err(Error::AttestationVerificationFailed(
251                                "Invalid PCRs format".to_string(),
252                            ))
253                        }
254                    };
255
256                    for (pcr_key, pcr_value) in pcrs_map {
257                        let index = match pcr_key {
258                            CborValue::Integer(i) => cbor_integer_to_usize(*i, "PCR index")?,
259                            _ => {
260                                return Err(Error::AttestationVerificationFailed(
261                                    "Invalid PCR index: not an integer".to_string(),
262                                ))
263                            }
264                        };
265
266                        let pcr_bytes = match pcr_value {
267                            CborValue::Bytes(b) => b.clone(),
268                            _ => {
269                                return Err(Error::AttestationVerificationFailed(
270                                    "Invalid PCR value".to_string(),
271                                ))
272                            }
273                        };
274
275                        doc.pcrs.insert(index, pcr_bytes);
276                    }
277                }
278                "certificate" => {
279                    doc.certificate = match value {
280                        CborValue::Bytes(b) => b.clone(),
281                        _ => {
282                            return Err(Error::AttestationVerificationFailed(
283                                "Invalid certificate".to_string(),
284                            ))
285                        }
286                    };
287                }
288                "cabundle" => {
289                    let bundle = match value {
290                        CborValue::Array(a) => a,
291                        _ => {
292                            return Err(Error::AttestationVerificationFailed(
293                                "Invalid cabundle".to_string(),
294                            ))
295                        }
296                    };
297
298                    for cert in bundle {
299                        let cert_bytes = match cert {
300                            CborValue::Bytes(b) => b.clone(),
301                            _ => {
302                                return Err(Error::AttestationVerificationFailed(
303                                    "Invalid certificate in bundle".to_string(),
304                                ))
305                            }
306                        };
307                        doc.cabundle.push(cert_bytes);
308                    }
309                }
310                "public_key" => {
311                    doc.public_key = match value {
312                        CborValue::Bytes(b) => Some(b.clone()),
313                        _ => None,
314                    };
315                }
316                "user_data" => {
317                    doc.user_data = match value {
318                        CborValue::Bytes(b) => Some(b.clone()),
319                        _ => None,
320                    };
321                }
322                "nonce" => {
323                    doc.nonce = match value {
324                        CborValue::Bytes(b) => Some(b.clone()),
325                        _ => None,
326                    };
327                }
328                _ => {} // Ignore unknown fields
329            }
330        }
331
332        Ok(doc)
333    }
334
335    fn verify_certificate_chain(&self, doc: &AttestationDocument) -> Result<()> {
336        // Step 1: Verify the first cert in cabundle matches AWS Nitro root
337        if doc.cabundle.is_empty() {
338            return Err(Error::AttestationVerificationFailed(
339                "Certificate bundle is empty".to_string(),
340            ));
341        }
342
343        if doc.cabundle[0] != AWS_NITRO_ROOT_CERT {
344            return Err(Error::AttestationVerificationFailed(
345                "First certificate does not match AWS Nitro root certificate".to_string(),
346            ));
347        }
348
349        // Step 2: Parse all certificates and check validity
350        let mut certs = Vec::new();
351        for (i, cert_der) in doc.cabundle.iter().enumerate() {
352            let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| {
353                Error::AttestationVerificationFailed(format!(
354                    "Failed to parse certificate {}: {:?}",
355                    i, e
356                ))
357            })?;
358
359            // Validity periods are checked against the device clock in
360            // `verify_certificate_validity` once the signature is verified.
361            certs.push(cert);
362        }
363
364        // Parse the leaf certificate
365        let (_, leaf_cert) = X509Certificate::from_der(&doc.certificate).map_err(|e| {
366            Error::AttestationVerificationFailed(format!(
367                "Failed to parse leaf certificate: {:?}",
368                e
369            ))
370        })?;
371
372        // Step 3: Verify the certificate chain signatures
373        // AWS Nitro chain: root -> regional -> zonal -> instance -> leaf
374        // Each cert must be signed by the PREVIOUS cert in the hierarchical chain
375
376        // Verify each cert (except root) is signed by the previous cert
377        for i in 1..certs.len() {
378            let cert = &certs[i];
379            let cert_der = &doc.cabundle[i];
380            let issuer = &certs[i - 1]; // The issuer should be the previous cert in the chain
381
382            // Verify the issuer/subject relationship
383            if cert.issuer() != issuer.subject() {
384                return Err(Error::AttestationVerificationFailed(format!(
385                    "Certificate {} issuer doesn't match certificate {} subject - chain is broken",
386                    i,
387                    i - 1
388                )));
389            }
390
391            // Verify the signature
392            if !self.verify_cert_signature(cert_der, issuer)? {
393                return Err(Error::AttestationVerificationFailed(format!(
394                    "Certificate {} signature verification failed (not signed by certificate {})",
395                    i,
396                    i - 1
397                )));
398            }
399        }
400
401        // Verify the leaf certificate is signed by the last cert in the chain
402        if !certs.is_empty() {
403            let last_cert = &certs[certs.len() - 1];
404
405            // Verify the issuer/subject relationship
406            if leaf_cert.issuer() != last_cert.subject() {
407                return Err(Error::AttestationVerificationFailed(
408                    "Leaf certificate issuer doesn't match last certificate in chain".to_string(),
409                ));
410            }
411
412            // Verify the signature
413            if !self.verify_cert_signature(&doc.certificate, last_cert)? {
414                return Err(Error::AttestationVerificationFailed(
415                    "Leaf certificate signature verification failed".to_string(),
416                ));
417            }
418        }
419
420        Ok(())
421    }
422
423    /// Checks every certificate's validity window against the device clock,
424    /// with [`ATTESTATION_NOT_BEFORE_LEEWAY_MS`] applied to `notBefore`.
425    ///
426    /// The enclave leaf certificate is issued without backdating and re-issued
427    /// roughly every 2 h 45 m, so a device clock a few seconds slow used to
428    /// fail right after each re-issue. `notAfter` stays strict, which bounds a
429    /// fast device clock by the leaf's remaining validity. A failure is
430    /// explained by comparing the device clock with the signed `timestamp`.
431    fn verify_certificate_validity(
432        &self,
433        doc: &AttestationDocument,
434        device_now_ms: u64,
435    ) -> Result<()> {
436        let device_now_s = i64::try_from(device_now_ms / 1000).map_err(|_| {
437            Error::AttestationVerificationFailed("Device clock is out of range".to_string())
438        })?;
439        let leeway_s = (ATTESTATION_NOT_BEFORE_LEEWAY_MS / 1000) as i64;
440        let chain = doc
441            .cabundle
442            .iter()
443            .chain(std::iter::once(&doc.certificate))
444            .enumerate();
445        for (i, cert_der) in chain {
446            let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| {
447                Error::AttestationVerificationFailed(format!(
448                    "Failed to parse certificate {}: {:?}",
449                    i, e
450                ))
451            })?;
452            let validity = cert.validity();
453            let not_before_s = validity.not_before.timestamp();
454            let not_after_s = validity.not_after.timestamp();
455            let not_yet_valid = device_now_s + leeway_s < not_before_s;
456            let expired = device_now_s > not_after_s;
457            if not_yet_valid || expired {
458                return Err(Error::AttestationVerificationFailed(
459                    describe_validity_failure(
460                        i,
461                        if expired { "expired" } else { "not yet valid" },
462                        validity.not_before.timestamp() * 1000,
463                        validity.not_after.timestamp() * 1000,
464                        device_now_ms,
465                        doc.timestamp,
466                    ),
467                ));
468            }
469        }
470        Ok(())
471    }
472
473    fn verify_cert_signature(&self, cert_der: &[u8], issuer: &X509Certificate) -> Result<bool> {
474        // Parse the certificate to get its TBS (to-be-signed) portion and signature
475        let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| {
476            Error::AttestationVerificationFailed(format!(
477                "Failed to parse certificate for signature verification: {:?}",
478                e
479            ))
480        })?;
481
482        // The signature algorithm should match what AWS Nitro uses
483        let sig_algo = &cert.signature_algorithm;
484        let sig_oid = sig_algo.algorithm.to_id_string();
485
486        // AWS Nitro uses ECDSA with P-384 and SHA-384 (OID: 1.2.840.10045.4.3.3)
487        if sig_oid != "1.2.840.10045.4.3.3" {
488            // Also support P-256 with SHA-256 (OID: 1.2.840.10045.4.3.2) for compatibility
489            if sig_oid != "1.2.840.10045.4.3.2" {
490                return Ok(false); // Unsupported algorithm
491            }
492        }
493
494        // Extract the issuer's public key
495        let issuer_pubkey = issuer.public_key();
496
497        // The public key is in SubjectPublicKeyInfo format
498        // For EC keys, we need to extract the actual EC point
499        let pubkey_bytes = issuer_pubkey.raw;
500
501        // Find the EC point in the public key data
502        // EC points start with 0x04 (uncompressed) and are 97 bytes for P-384, 65 for P-256
503        let ec_point = if sig_oid == "1.2.840.10045.4.3.3" {
504            // P-384: 97 bytes (0x04 + 48 bytes X + 48 bytes Y)
505            extract_ec_point(pubkey_bytes, 97)
506        } else {
507            // P-256: 65 bytes (0x04 + 32 bytes X + 32 bytes Y)
508            extract_ec_point(pubkey_bytes, 65)
509        }?;
510
511        // Get the TBS certificate data and signature
512        let tbs_cert = cert.tbs_certificate.as_ref();
513        let signature = cert.signature_value.as_ref();
514
515        // Verify the signature using ring
516        let verification_alg = if sig_oid == "1.2.840.10045.4.3.3" {
517            &signature::ECDSA_P384_SHA384_ASN1
518        } else {
519            &signature::ECDSA_P256_SHA256_ASN1
520        };
521
522        let public_key = signature::UnparsedPublicKey::new(verification_alg, ec_point);
523
524        public_key
525            .verify(tbs_cert, signature)
526            .map(|_| true)
527            .map_err(|_| {
528                Error::AttestationVerificationFailed(
529                    "Certificate signature verification failed".to_string(),
530                )
531            })
532    }
533
534    fn verify_signature(
535        &self,
536        protected: &[u8],
537        payload: &[u8],
538        signature_bytes: &[u8],
539        doc: &AttestationDocument,
540    ) -> Result<()> {
541        // Parse the leaf certificate
542        let (_, cert) = X509Certificate::from_der(&doc.certificate).map_err(|e| {
543            Error::AttestationVerificationFailed(format!(
544                "Failed to parse leaf certificate: {:?}",
545                e
546            ))
547        })?;
548
549        // Extract the public key bytes from the certificate
550        let public_key_info = cert.public_key();
551
552        // AWS Nitro uses P-384, extract the EC point properly
553        // P-384: 97 bytes (0x04 + 48 bytes X + 48 bytes Y)
554        let public_key_bytes = extract_ec_point(public_key_info.raw, 97)?;
555
556        // Create the COSE_Sign1 signature structure
557        // This follows the COSE specification for the data to be signed
558        let sig_structure = create_sig_structure(protected, payload)?;
559
560        // For ECDSA P-384 with SHA-384 (which is what AWS Nitro uses)
561        // AWS Nitro uses raw signatures (r||s), not ASN.1 encoded
562        let public_key = signature::UnparsedPublicKey::new(
563            &signature::ECDSA_P384_SHA384_FIXED,
564            public_key_bytes,
565        );
566
567        // Verify the signature
568        public_key
569            .verify(&sig_structure, signature_bytes)
570            .map_err(|_| {
571                Error::AttestationVerificationFailed("Signature verification failed".to_string())
572            })?;
573
574        Ok(())
575    }
576
577    fn verify_pcrs(
578        &self,
579        doc: &AttestationDocument,
580        expected: &std::collections::HashMap<usize, Vec<u8>>,
581    ) -> Result<()> {
582        for (index, expected_value) in expected {
583            match doc.pcrs.get(index) {
584                Some(actual_value) => {
585                    if actual_value != expected_value {
586                        return Err(Error::AttestationVerificationFailed(format!(
587                            "PCR{} mismatch",
588                            index
589                        )));
590                    }
591                }
592                None => {
593                    return Err(Error::AttestationVerificationFailed(format!(
594                        "PCR{} missing",
595                        index
596                    )));
597                }
598            }
599        }
600        Ok(())
601    }
602}
603
604fn extract_ec_point(pubkey_bytes: &[u8], expected_size: usize) -> Result<&[u8]> {
605    // The public key is in SubjectPublicKeyInfo format (ASN.1 DER encoded)
606    // We need to extract the actual EC point from the BIT STRING
607
608    // The structure is:
609    // SEQUENCE {
610    //   algorithm AlgorithmIdentifier,
611    //   subjectPublicKey BIT STRING
612    // }
613
614    // For EC keys, x509-parser gives us the raw bytes which includes the full
615    // SubjectPublicKeyInfo structure. The EC point is at the end after the
616    // algorithm identifier and is preceded by a BIT STRING tag.
617
618    // Look for BIT STRING tag (0x03) followed by length and unused bits (0x00)
619    // The EC point follows immediately after
620    for i in 0..pubkey_bytes.len() {
621        if pubkey_bytes[i] == 0x03 {
622            // BIT STRING tag
623            if i + 2 < pubkey_bytes.len() {
624                // Next byte is length (for EC keys, usually 0x42 for P-256 or 0x62 for P-384)
625                // Then 0x00 for no unused bits
626                // Then 0x04 for uncompressed point
627                if i + 3 < pubkey_bytes.len()
628                    && pubkey_bytes[i + 2] == 0x00
629                    && pubkey_bytes[i + 3] == 0x04
630                {
631                    let ec_point_start = i + 3;
632                    let remaining = &pubkey_bytes[ec_point_start..];
633                    if remaining.len() == expected_size {
634                        return Ok(remaining);
635                    }
636                }
637            }
638        }
639    }
640
641    // Fallback: The x509-parser might have already extracted just the key material
642    // In this case, look for the uncompressed point marker (0x04) at the expected position
643    if pubkey_bytes.len() >= expected_size {
644        // Try from the end (most common case with x509-parser)
645        let from_end = &pubkey_bytes[pubkey_bytes.len() - expected_size..];
646        if from_end[0] == 0x04 {
647            return Ok(from_end);
648        }
649
650        // Try from a typical offset (after algorithm OID and parameters)
651        // For EC keys, this is often around offset 23-27
652        for offset in [23, 24, 25, 26, 27].iter() {
653            if *offset + expected_size <= pubkey_bytes.len() {
654                let candidate = &pubkey_bytes[*offset..*offset + expected_size];
655                if candidate[0] == 0x04 {
656                    return Ok(candidate);
657                }
658            }
659        }
660    }
661
662    Err(Error::AttestationVerificationFailed(format!(
663        "Failed to extract EC public key point (expected {} bytes, pubkey is {} bytes)",
664        expected_size,
665        pubkey_bytes.len()
666    )))
667}
668
669fn cbor_integer_to_u64(value: ciborium::value::Integer, field_name: &str) -> Result<u64> {
670    u64::try_from(value).map_err(|_| {
671        Error::AttestationVerificationFailed(format!(
672            "Invalid {}: negative or out of range value",
673            field_name
674        ))
675    })
676}
677
678fn cbor_integer_to_usize(value: ciborium::value::Integer, field_name: &str) -> Result<usize> {
679    usize::try_from(value).map_err(|_| {
680        Error::AttestationVerificationFailed(format!(
681            "Invalid {}: negative or out of range value",
682            field_name
683        ))
684    })
685}
686
687fn create_sig_structure(protected: &[u8], payload: &[u8]) -> Result<Vec<u8>> {
688    // Create the COSE_Sign1 signature structure as a CBOR array
689    // ["Signature1", protected, external_aad, payload]
690    let sig_structure = CborValue::Array(vec![
691        CborValue::Text("Signature1".to_string()),
692        CborValue::Bytes(protected.to_vec()),
693        CborValue::Bytes(vec![]), // empty external AAD
694        CborValue::Bytes(payload.to_vec()),
695    ]);
696
697    // Encode to CBOR bytes
698    cbor::to_vec(&sig_structure)
699}
700
701/// Leeway applied to certificate `notBefore` so a device clock that runs
702/// slightly slow does not reject a freshly issued enclave leaf certificate.
703/// `notAfter` gets no leeway. The TypeScript SDK applies the same values.
704pub const ATTESTATION_NOT_BEFORE_LEEWAY_MS: u64 = 5 * 60 * 1000;
705
706/// Device/enclave difference above which a validity failure is reported as a
707/// device clock problem rather than a transient certificate problem.
708pub const NOTICEABLE_CLOCK_SKEW_MS: u64 = 60 * 1000;
709
710/// Prefix of every attestation failure message that blames the device clock.
711/// [`crate::Error::is_device_clock_problem`] recognizes it so clients can show
712/// their own clock guidance without surfacing SDK internals.
713const DEVICE_CLOCK_MESSAGE_PREFIX: &str = "This device's clock is about";
714
715impl crate::Error {
716    /// True when this is an attestation failure caused by the device clock
717    /// disagreeing with the enclave's signed timestamp (wrong date, time or
718    /// time zone on the device), as opposed to an untrusted or invalid
719    /// document.
720    pub fn is_device_clock_problem(&self) -> bool {
721        matches!(
722            self,
723            crate::Error::AttestationVerificationFailed(message)
724                if message.starts_with(DEVICE_CLOCK_MESSAGE_PREFIX)
725        )
726    }
727}
728
729fn current_time_ms() -> u64 {
730    std::time::SystemTime::now()
731        .duration_since(std::time::UNIX_EPOCH)
732        .map(|d| d.as_millis() as u64)
733        .unwrap_or(0)
734}
735
736fn format_time_ms(ms: i64) -> String {
737    chrono::DateTime::<chrono::Utc>::from_timestamp_millis(ms)
738        .map(|t| t.to_rfc3339_opts(chrono::SecondsFormat::Millis, true))
739        .unwrap_or_else(|| format!("{ms} ms since epoch"))
740}
741
742fn describe_duration_ms(ms: u64) -> String {
743    const MINUTE: u64 = 60 * 1000;
744    const HOUR: u64 = 60 * MINUTE;
745    const DAY: u64 = 24 * HOUR;
746    for (name, size) in [("day", DAY), ("hour", HOUR), ("minute", MINUTE)] {
747        if ms >= size {
748            let count = (ms as f64 / size as f64).round() as u64;
749            let plural = if count == 1 { "" } else { "s" };
750            return format!("{count} {name}{plural}");
751        }
752    }
753    format!("{} seconds", (ms as f64 / 1000.0).round() as u64)
754}
755
756/// Builds the user-facing message for a certificate outside its validity
757/// window, blaming the device clock when it disagrees with the enclave's
758/// signed timestamp by a noticeable amount.
759fn describe_validity_failure(
760    index: usize,
761    state: &str,
762    not_before_ms: i64,
763    not_after_ms: i64,
764    device_now_ms: u64,
765    enclave_now_ms: u64,
766) -> String {
767    let (skew, direction) = if device_now_ms >= enclave_now_ms {
768        (device_now_ms - enclave_now_ms, "ahead of")
769    } else {
770        (enclave_now_ms - device_now_ms, "behind")
771    };
772    let device = format_time_ms(i64::try_from(device_now_ms).unwrap_or(i64::MAX));
773    if skew >= NOTICEABLE_CLOCK_SKEW_MS {
774        format!(
775            "{DEVICE_CLOCK_MESSAGE_PREFIX} {} {} the secure enclave (device: {}, enclave: {}), so the enclave's certificate looks {}. Check the device's date, time and time zone settings, then try again.",
776            describe_duration_ms(skew),
777            direction,
778            device,
779            format_time_ms(i64::try_from(enclave_now_ms).unwrap_or(i64::MAX)),
780            state
781        )
782    } else {
783        format!(
784            "The secure enclave's certificate {} is {} on this device's clock (valid {} to {}, device: {}). Try again in a moment; if it keeps happening, check the device's date, time and time zone settings.",
785            index,
786            state,
787            format_time_ms(not_before_ms),
788            format_time_ms(not_after_ms),
789            device
790        )
791    }
792}
793
794#[cfg(feature = "mock-attestation")]
795pub fn create_mock_attestation_document(nonce: &str) -> Result<String> {
796    use std::collections::HashMap;
797
798    let mut pcrs = HashMap::new();
799    pcrs.insert(0, vec![0u8; 48]); // Mock PCR0
800
801    let doc = AttestationDocument {
802        module_id: "mock-module".to_string(),
803        timestamp: chrono::Utc::now().timestamp() as u64,
804        digest: "SHA384".to_string(),
805        pcrs,
806        certificate: vec![0u8; 256],    // Mock certificate
807        cabundle: vec![vec![0u8; 256]], // Mock CA bundle
808        public_key: None,
809        user_data: None,
810        nonce: Some(nonce.as_bytes().to_vec()),
811    };
812
813    // Create a mock COSE_Sign1 structure
814    let payload = cbor::to_vec(&doc)?;
815    let protected = vec![0u8; 32]; // Mock protected header
816    let signature = vec![0u8; 64]; // Mock signature
817
818    let cose_sign1 = vec![
819        CborValue::Bytes(protected),
820        CborValue::Map(Vec::new()), // Empty unprotected headers
821        CborValue::Bytes(payload),
822        CborValue::Bytes(signature),
823    ];
824
825    let cose_bytes = cbor::to_vec(&CborValue::Array(cose_sign1))?;
826    Ok(BASE64.encode(cose_bytes))
827}
828
829#[cfg(all(test, feature = "mock-attestation"))]
830mod tests {
831    use super::*;
832
833    #[test]
834    fn default_verifier_never_accepts_feature_gated_mock_documents() {
835        let nonce = "test-nonce";
836        let document = create_mock_attestation_document(nonce).unwrap();
837
838        let error = AttestationVerifier::new()
839            .verify_attestation_document(&document, nonce)
840            .unwrap_err();
841
842        assert!(matches!(error, Error::AttestationVerificationFailed(_)));
843    }
844}
845
846#[cfg(test)]
847mod clock_policy_tests {
848    use super::*;
849
850    /// A real production document from 2024-10-28. Its leaf certificate became
851    /// valid 361 s before the document was signed and expired three hours later.
852    const FIXTURE: &str = include_str!("test_fixtures/nitro_attestation_document_2024-10-28.b64");
853    const NONCE: &str = "cc6b95ef-a0d7-477d-90f2-36cc088d2449";
854    const SIGNED_AT_MS: u64 = 1_730_141_656_206;
855    const LEAF_NOT_BEFORE_MS: u64 = SIGNED_AT_MS - 361 * 1000 - 206;
856    const LEAF_NOT_AFTER_MS: u64 = LEAF_NOT_BEFORE_MS + 3 * 60 * 60 * 1000 + 3 * 1000;
857    const SECOND_MS: u64 = 1000;
858    const DAY_MS: u64 = 24 * 60 * 60 * SECOND_MS;
859
860    fn verify_at(device_now_ms: u64) -> Result<AttestationDocument> {
861        AttestationVerifier::new().verify_attestation_document_at(
862            FIXTURE.trim(),
863            |nonce| {
864                assert_eq!(nonce, NONCE.as_bytes());
865                Ok(())
866            },
867            device_now_ms,
868        )
869    }
870
871    fn failure_at(device_now_ms: u64) -> String {
872        verify_at(device_now_ms).unwrap_err().to_string()
873    }
874
875    #[test]
876    fn fixture_leaf_validity_matches_the_certificate() {
877        let doc = verify_at(SIGNED_AT_MS).unwrap();
878        let (_, leaf) = X509Certificate::from_der(&doc.certificate).unwrap();
879        assert_eq!(
880            leaf.validity().not_before.timestamp() as u64 * 1000,
881            LEAF_NOT_BEFORE_MS
882        );
883        assert_eq!(
884            leaf.validity().not_after.timestamp() as u64 * 1000,
885            LEAF_NOT_AFTER_MS
886        );
887    }
888
889    #[test]
890    fn real_document_verifies_when_the_device_clock_matches_the_enclave() {
891        let doc = verify_at(SIGNED_AT_MS).unwrap();
892        assert_eq!(doc.module_id, "i-06c79bf817127030a-enc0192d3d4945e0432");
893        assert_eq!(doc.timestamp, SIGNED_AT_MS);
894    }
895
896    #[test]
897    fn device_clock_slightly_behind_a_fresh_leaf_verifies_within_the_leeway() {
898        for device_now_ms in [
899            LEAF_NOT_BEFORE_MS - SECOND_MS,
900            LEAF_NOT_BEFORE_MS - 60 * SECOND_MS,
901            LEAF_NOT_BEFORE_MS - ATTESTATION_NOT_BEFORE_LEEWAY_MS,
902        ] {
903            verify_at(device_now_ms).unwrap();
904        }
905    }
906
907    #[test]
908    fn device_clock_behind_by_more_than_the_leeway_is_a_clock_error() {
909        let message = failure_at(LEAF_NOT_BEFORE_MS - ATTESTATION_NOT_BEFORE_LEEWAY_MS - SECOND_MS);
910        assert!(
911            message.contains("about 11 minutes behind the secure enclave"),
912            "{message}"
913        );
914        assert!(message.contains("looks not yet valid"), "{message}");
915        assert!(
916            message.contains("date, time and time zone settings"),
917            "{message}"
918        );
919    }
920
921    #[test]
922    fn fast_device_clock_is_accepted_only_while_the_leaf_is_valid() {
923        verify_at(LEAF_NOT_AFTER_MS - SECOND_MS).unwrap();
924        let message = failure_at(LEAF_NOT_AFTER_MS + SECOND_MS);
925        assert!(
926            message.contains("about 3 hours ahead of the secure enclave"),
927            "{message}"
928        );
929        assert!(message.contains("looks expired"), "{message}");
930    }
931
932    #[test]
933    fn device_clock_days_off_names_the_difference() {
934        let ahead = failure_at(SIGNED_AT_MS + 3 * DAY_MS);
935        assert!(
936            ahead.contains("about 3 days ahead of the secure enclave"),
937            "{ahead}"
938        );
939        let behind = failure_at(SIGNED_AT_MS - 3 * DAY_MS);
940        assert!(
941            behind.contains("about 3 days behind the secure enclave"),
942            "{behind}"
943        );
944    }
945
946    #[test]
947    fn clock_problems_are_distinguishable_from_other_attestation_failures() {
948        let clock_error = verify_at(SIGNED_AT_MS + 3 * DAY_MS).unwrap_err();
949        assert!(clock_error.is_device_clock_problem());
950
951        let other = Error::AttestationVerificationFailed("PCR0 mismatch".to_string());
952        assert!(!other.is_device_clock_problem());
953        assert!(!Error::Session("expired".to_string()).is_device_clock_problem());
954    }
955
956    #[test]
957    fn todays_clock_rejects_the_2024_document() {
958        let message = failure_at(current_time_ms());
959        assert!(message.contains("ahead of the secure enclave"), "{message}");
960    }
961
962    #[test]
963    fn tampered_timestamp_fails_signature_verification_first() {
964        let raw = BASE64.decode(FIXTURE.trim()).unwrap();
965        let mut cose = match cbor::from_slice::<CborValue>(&raw).unwrap() {
966            CborValue::Array(items) => items,
967            other => panic!("unexpected COSE structure: {other:?}"),
968        };
969        let payload = match &cose[2] {
970            CborValue::Bytes(bytes) => bytes.clone(),
971            other => panic!("unexpected payload: {other:?}"),
972        };
973        let mut fields = match cbor::from_slice::<CborValue>(&payload).unwrap() {
974            CborValue::Map(fields) => fields,
975            other => panic!("unexpected payload map: {other:?}"),
976        };
977        for (key, value) in fields.iter_mut() {
978            if matches!(key, CborValue::Text(name) if name == "timestamp") {
979                *value = CborValue::Integer(current_time_ms().into());
980            }
981        }
982        cose[2] = CborValue::Bytes(cbor::to_vec(&CborValue::Map(fields)).unwrap());
983        let forged = BASE64.encode(cbor::to_vec(&CborValue::Array(cose)).unwrap());
984
985        let error = AttestationVerifier::new()
986            .verify_attestation_document_at(&forged, |_| Ok(()), SIGNED_AT_MS)
987            .unwrap_err();
988        assert!(
989            error.to_string().contains("Signature verification failed"),
990            "{error}"
991        );
992    }
993}