spdm-attest 0.1.0

Hardware-rooted PCIe SPDM 1.2/1.3 attestation quote and measurement validator for Confidential GPU computing.
Documentation
//! Attestation verification engine orchestrating protocol, crypto, and baseline validation.

use crate::crypto::verify_certificate_chain;
use crate::measurement::{compare_measurements, GoldenManifest, MeasurementComparison};
use crate::protocol::{MeasurementsResponse, ProtocolError};
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum AttestationError {
    #[error("SPDM protocol decoding error: {0}")]
    Protocol(#[from] ProtocolError),

    #[error("Cryptographic verification error: {0}")]
    Crypto(#[from] crate::crypto::CryptoError),

    #[error("Quote contains no signature")]
    MissingSignature,

    #[error("Replay detected: nonce in quote does not match expected challenge nonce")]
    NonceMismatch,

    #[error("Hardware measurement integrity violation: {0} component(s) mismatched or missing")]
    MeasurementIntegrityFailure(usize),
}

/// Options controlling attestation verification.
#[derive(Debug, Clone, Default)]
pub struct AttestationOptions {
    /// Nonce generated by initiator in CHALLENGE / GET_MEASUREMENTS for replay protection.
    pub expected_nonce: Option<[u8; 32]>,
    /// Optional golden manifest containing known-good firmware and hardware digests.
    pub golden_manifest: Option<GoldenManifest>,
}

/// Detailed structured attestation report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationReport {
    pub success: bool,
    pub spdm_version: String,
    pub responder_algo: String,
    pub total_blocks: usize,
    pub nonce_verified: bool,
    pub signature_verified: bool,
    pub cert_chain_verified: bool,
    pub comparisons: Vec<MeasurementComparison>,
    pub failure_reason: Option<String>,
}

/// Verifies an SPDM attestation quote against a certificate chain, root CA, and optional golden manifest.
pub fn verify_attestation(
    quote_bytes: &[u8],
    cert_chain_bytes: &[u8],
    root_ca_bytes: &[u8],
    options: &AttestationOptions,
) -> Result<AttestationReport, AttestationError> {
    // 1. Validate Certificate Chain and extract device public key
    let public_key = verify_certificate_chain(cert_chain_bytes, root_ca_bytes)?;
    let asym_algo = public_key.asym_algo();

    // 2. Parse SPDM Measurements Response using the negotiated algorithm
    let response = MeasurementsResponse::parse(quote_bytes, asym_algo)?;

    if response.signature.is_empty() {
        return Err(AttestationError::MissingSignature);
    }

    // 3. Replay Protection: verify nonce if challenge nonce was supplied
    let mut nonce_verified = false;
    if let Some(expected_nonce) = options.expected_nonce {
        if let Some(quote_nonce) = response.nonce {
            if quote_nonce != expected_nonce {
                return Err(AttestationError::NonceMismatch);
            }
            nonce_verified = true;
        } else {
            return Err(AttestationError::NonceMismatch);
        }
    } else if response.nonce.is_some() {
        nonce_verified = true;
    }

    // 4. Verify Quote Signature over the signed transcript
    let transcript = response.signed_transcript();
    public_key.verify_signature(&transcript, &response.signature)?;

    // 5. Compare Measurements against Golden Baseline (if provided)
    let comparisons = if let Some(ref golden) = options.golden_manifest {
        let comps = compare_measurements(&response.blocks, golden);
        let mismatches = comps
            .iter()
            .filter(|c| {
                c.status == crate::measurement::ComparisonStatus::Mismatch
                    || c.status == crate::measurement::ComparisonStatus::Missing
            })
            .count();

        if mismatches > 0 {
            return Ok(AttestationReport {
                success: false,
                spdm_version: format!("{:#04x}", response.header.version),
                responder_algo: public_key.algo_name().to_string(),
                total_blocks: response.blocks.len(),
                nonce_verified,
                signature_verified: true,
                cert_chain_verified: true,
                comparisons: comps,
                failure_reason: Some(format!(
                    "Measurement baseline check failed: {} component(s) mismatched or missing",
                    mismatches
                )),
            });
        }
        comps
    } else {
        // Return informative comparisons without golden expectations
        response
            .blocks
            .iter()
            .map(|b| MeasurementComparison {
                index: b.index,
                component: b.type_name().to_string(),
                actual_hash: hex::encode(&b.value),
                expected_hash: None,
                status: crate::measurement::ComparisonStatus::Unexpected,
            })
            .collect()
    };

    Ok(AttestationReport {
        success: true,
        spdm_version: format!("{:#04x}", response.header.version),
        responder_algo: public_key.algo_name().to_string(),
        total_blocks: response.blocks.len(),
        nonce_verified,
        signature_verified: true,
        cert_chain_verified: true,
        comparisons,
        failure_reason: None,
    })
}