Skip to main content

spdm_attest/
verifier.rs

1//! Attestation verification engine orchestrating protocol, crypto, and baseline validation.
2
3use crate::crypto::verify_certificate_chain;
4use crate::measurement::{compare_measurements, GoldenManifest, MeasurementComparison};
5use crate::protocol::{MeasurementsResponse, ProtocolError};
6use serde::{Deserialize, Serialize};
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10pub enum AttestationError {
11    #[error("SPDM protocol decoding error: {0}")]
12    Protocol(#[from] ProtocolError),
13
14    #[error("Cryptographic verification error: {0}")]
15    Crypto(#[from] crate::crypto::CryptoError),
16
17    #[error("Quote contains no signature")]
18    MissingSignature,
19
20    #[error("Replay detected: nonce in quote does not match expected challenge nonce")]
21    NonceMismatch,
22
23    #[error("Hardware measurement integrity violation: {0} component(s) mismatched or missing")]
24    MeasurementIntegrityFailure(usize),
25}
26
27/// Options controlling attestation verification.
28#[derive(Debug, Clone, Default)]
29pub struct AttestationOptions {
30    /// Nonce generated by initiator in CHALLENGE / GET_MEASUREMENTS for replay protection.
31    pub expected_nonce: Option<[u8; 32]>,
32    /// Optional golden manifest containing known-good firmware and hardware digests.
33    pub golden_manifest: Option<GoldenManifest>,
34}
35
36/// Detailed structured attestation report.
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct AttestationReport {
39    pub success: bool,
40    pub spdm_version: String,
41    pub responder_algo: String,
42    pub total_blocks: usize,
43    pub nonce_verified: bool,
44    pub signature_verified: bool,
45    pub cert_chain_verified: bool,
46    pub comparisons: Vec<MeasurementComparison>,
47    pub failure_reason: Option<String>,
48}
49
50/// Verifies an SPDM attestation quote against a certificate chain, root CA, and optional golden manifest.
51pub fn verify_attestation(
52    quote_bytes: &[u8],
53    cert_chain_bytes: &[u8],
54    root_ca_bytes: &[u8],
55    options: &AttestationOptions,
56) -> Result<AttestationReport, AttestationError> {
57    // 1. Validate Certificate Chain and extract device public key
58    let public_key = verify_certificate_chain(cert_chain_bytes, root_ca_bytes)?;
59    let asym_algo = public_key.asym_algo();
60
61    // 2. Parse SPDM Measurements Response using the negotiated algorithm
62    let response = MeasurementsResponse::parse(quote_bytes, asym_algo)?;
63
64    if response.signature.is_empty() {
65        return Err(AttestationError::MissingSignature);
66    }
67
68    // 3. Replay Protection: verify nonce if challenge nonce was supplied
69    let mut nonce_verified = false;
70    if let Some(expected_nonce) = options.expected_nonce {
71        if let Some(quote_nonce) = response.nonce {
72            if quote_nonce != expected_nonce {
73                return Err(AttestationError::NonceMismatch);
74            }
75            nonce_verified = true;
76        } else {
77            return Err(AttestationError::NonceMismatch);
78        }
79    } else if response.nonce.is_some() {
80        nonce_verified = true;
81    }
82
83    // 4. Verify Quote Signature over the signed transcript
84    let transcript = response.signed_transcript();
85    public_key.verify_signature(&transcript, &response.signature)?;
86
87    // 5. Compare Measurements against Golden Baseline (if provided)
88    let comparisons = if let Some(ref golden) = options.golden_manifest {
89        let comps = compare_measurements(&response.blocks, golden);
90        let mismatches = comps
91            .iter()
92            .filter(|c| {
93                c.status == crate::measurement::ComparisonStatus::Mismatch
94                    || c.status == crate::measurement::ComparisonStatus::Missing
95            })
96            .count();
97
98        if mismatches > 0 {
99            return Ok(AttestationReport {
100                success: false,
101                spdm_version: format!("{:#04x}", response.header.version),
102                responder_algo: public_key.algo_name().to_string(),
103                total_blocks: response.blocks.len(),
104                nonce_verified,
105                signature_verified: true,
106                cert_chain_verified: true,
107                comparisons: comps,
108                failure_reason: Some(format!(
109                    "Measurement baseline check failed: {} component(s) mismatched or missing",
110                    mismatches
111                )),
112            });
113        }
114        comps
115    } else {
116        // Return informative comparisons without golden expectations
117        response
118            .blocks
119            .iter()
120            .map(|b| MeasurementComparison {
121                index: b.index,
122                component: b.type_name().to_string(),
123                actual_hash: hex::encode(&b.value),
124                expected_hash: None,
125                status: crate::measurement::ComparisonStatus::Unexpected,
126            })
127            .collect()
128    };
129
130    Ok(AttestationReport {
131        success: true,
132        spdm_version: format!("{:#04x}", response.header.version),
133        responder_algo: public_key.algo_name().to_string(),
134        total_blocks: response.blocks.len(),
135        nonce_verified,
136        signature_verified: true,
137        cert_chain_verified: true,
138        comparisons,
139        failure_reason: None,
140    })
141}