Skip to main content

spdm_attest/
crypto.rs

1//! Cryptographic verification engine for SPDM signatures and X.509 certificate chains.
2
3use crate::protocol::{ASYM_ALG_ECDSA_P256, ASYM_ALG_ECDSA_P384, ASYM_ALG_ED25519};
4use ed25519_dalek::{Signature as Ed25519Signature, Verifier as Ed25519Verifier, VerifyingKey};
5use p256::ecdsa::{
6    signature::Verifier as P256Verifier, Signature as P256Signature,
7    VerifyingKey as P256VerifyingKey,
8};
9use p384::ecdsa::{
10    signature::Verifier as P384Verifier, Signature as P384Signature,
11    VerifyingKey as P384VerifyingKey,
12};
13use sha2::{Digest, Sha256, Sha384, Sha512};
14use std::fmt;
15use thiserror::Error;
16use x509_parser::prelude::*;
17
18#[derive(Debug, Error)]
19pub enum CryptoError {
20    #[error("Failed to parse X.509 certificate: {0}")]
21    CertificateParseError(String),
22
23    #[error("Empty certificate chain")]
24    EmptyCertificateChain,
25
26    #[error("Certificate chain verification failed: {0}")]
27    ChainVerificationFailed(String),
28
29    #[error("Unsupported public key algorithm in certificate")]
30    UnsupportedPublicKeyAlgorithm,
31
32    #[error("Signature verification failed: {0}")]
33    SignatureVerificationFailed(String),
34
35    #[error("Invalid signature format: {0}")]
36    InvalidSignatureFormat(String),
37
38    #[error("Root CA mismatch or untrusted root")]
39    UntrustedRootCa,
40
41    #[error("IO or PEM decoding error: {0}")]
42    PemError(String),
43}
44
45#[derive(Clone)]
46pub enum DevicePublicKey {
47    P384(P384VerifyingKey),
48    P256(P256VerifyingKey),
49    Ed25519(VerifyingKey),
50}
51
52impl fmt::Debug for DevicePublicKey {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            Self::P384(_) => write!(f, "DevicePublicKey::P384"),
56            Self::P256(_) => write!(f, "DevicePublicKey::P256"),
57            Self::Ed25519(_) => write!(f, "DevicePublicKey::Ed25519"),
58        }
59    }
60}
61
62impl DevicePublicKey {
63    pub fn asym_algo(&self) -> u32 {
64        match self {
65            Self::P256(_) => ASYM_ALG_ECDSA_P256,
66            Self::P384(_) => ASYM_ALG_ECDSA_P384,
67            Self::Ed25519(_) => ASYM_ALG_ED25519,
68        }
69    }
70
71    pub fn algo_name(&self) -> &'static str {
72        match self {
73            Self::P256(_) => "ECDSA-NIST-P256",
74            Self::P384(_) => "ECDSA-NIST-P384",
75            Self::Ed25519(_) => "Ed25519",
76        }
77    }
78
79    /// Verifies a signature over `message` using this public key.
80    /// Supports SPDM raw concatenated (r || s) format as well as DER format.
81    pub fn verify_signature(&self, message: &[u8], sig_bytes: &[u8]) -> Result<(), CryptoError> {
82        match self {
83            Self::P384(vk) => {
84                let sig = if sig_bytes.len() == 96 {
85                    // SPDM standard: r (48 bytes) || s (48 bytes)
86                    P384Signature::from_slice(sig_bytes)
87                        .map_err(|e| CryptoError::InvalidSignatureFormat(e.to_string()))?
88                } else {
89                    P384Signature::from_der(sig_bytes)
90                        .map_err(|e| CryptoError::InvalidSignatureFormat(e.to_string()))?
91                };
92
93                P384Verifier::verify(vk, message, &sig)
94                    .map_err(|e| CryptoError::SignatureVerificationFailed(e.to_string()))
95            }
96            Self::P256(vk) => {
97                let sig = if sig_bytes.len() == 64 {
98                    // SPDM standard: r (32 bytes) || s (32 bytes)
99                    P256Signature::from_slice(sig_bytes)
100                        .map_err(|e| CryptoError::InvalidSignatureFormat(e.to_string()))?
101                } else {
102                    P256Signature::from_der(sig_bytes)
103                        .map_err(|e| CryptoError::InvalidSignatureFormat(e.to_string()))?
104                };
105
106                P256Verifier::verify(vk, message, &sig)
107                    .map_err(|e| CryptoError::SignatureVerificationFailed(e.to_string()))
108            }
109            Self::Ed25519(vk) => {
110                if sig_bytes.len() != 64 {
111                    return Err(CryptoError::InvalidSignatureFormat(format!(
112                        "Expected 64 bytes for Ed25519 signature, got {}",
113                        sig_bytes.len()
114                    )));
115                }
116                let sig = Ed25519Signature::from_slice(sig_bytes)
117                    .map_err(|e| CryptoError::InvalidSignatureFormat(e.to_string()))?;
118
119                Ed25519Verifier::verify(vk, message, &sig)
120                    .map_err(|e| CryptoError::SignatureVerificationFailed(e.to_string()))
121            }
122        }
123    }
124}
125
126/// Parses a certificate chain from PEM or DER data and verifies its validity up to the Root CA.
127/// Returns the responder (leaf) public key.
128pub fn verify_certificate_chain(
129    chain_pem_or_der: &[u8],
130    root_ca_pem_or_der: &[u8],
131) -> Result<DevicePublicKey, CryptoError> {
132    let chain_certs = parse_certificates(chain_pem_or_der)?;
133    if chain_certs.is_empty() {
134        return Err(CryptoError::EmptyCertificateChain);
135    }
136
137    let root_certs = parse_certificates(root_ca_pem_or_der)?;
138    if root_certs.is_empty() {
139        return Err(CryptoError::CertificateParseError(
140            "No Root CA found".to_string(),
141        ));
142    }
143    let trusted_root = &root_certs[0];
144
145    // Verify chain integrity: Each cert must be signed by the next, and top cert signed by Root CA
146    let mut current_subject = &chain_certs[0];
147
148    for (i, issuer_cert) in chain_certs.iter().skip(1).enumerate() {
149        let current_parsed = current_subject
150            .parse()
151            .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
152        let issuer_parsed = issuer_cert
153            .parse()
154            .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
155
156        current_parsed
157            .verify_signature(Some(issuer_parsed.public_key()))
158            .map_err(|e| {
159                CryptoError::ChainVerificationFailed(format!(
160                    "Certificate {} verification failed against issuer: {:?}",
161                    i, e
162                ))
163            })?;
164
165        current_subject = issuer_cert;
166    }
167
168    // Verify top certificate in chain against the trusted Root CA
169    let top_parsed = current_subject
170        .parse()
171        .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
172    let root_parsed = trusted_root
173        .parse()
174        .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
175
176    top_parsed
177        .verify_signature(Some(root_parsed.public_key()))
178        .map_err(|_e| CryptoError::UntrustedRootCa)?;
179
180    // Extract public key from leaf certificate (first certificate in chain)
181    let leaf_parsed = chain_certs[0]
182        .parse()
183        .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
184
185    extract_public_key(&leaf_parsed.tbs_certificate.subject_pki)
186}
187
188/// Internal certificate container supporting both DER slices and parsed representations.
189pub struct RawCert(pub Vec<u8>);
190
191impl RawCert {
192    pub fn parse(
193        &self,
194    ) -> Result<X509Certificate<'_>, x509_parser::nom::Err<x509_parser::error::X509Error>> {
195        parse_x509_certificate(&self.0).map(|(_, cert)| cert)
196    }
197}
198
199pub fn parse_certificates(data: &[u8]) -> Result<Vec<RawCert>, CryptoError> {
200    let mut certs = Vec::new();
201    let text = String::from_utf8_lossy(data);
202
203    if text.contains("-----BEGIN CERTIFICATE-----") {
204        for cert in x509_parser::pem::Pem::iter_from_buffer(data) {
205            let pem = cert.map_err(|e| CryptoError::PemError(e.to_string()))?;
206            if pem.label == "CERTIFICATE" {
207                certs.push(RawCert(pem.contents));
208            }
209        }
210    } else {
211        // Treat as raw DER
212        certs.push(RawCert(data.to_vec()));
213    }
214
215    Ok(certs)
216}
217
218fn extract_public_key(spki: &SubjectPublicKeyInfo<'_>) -> Result<DevicePublicKey, CryptoError> {
219    let alg_oid = spki.algorithm.algorithm.to_id_string();
220    let raw_bytes = spki.subject_public_key.data.as_ref();
221
222    // id-ecPublicKey = 1.2.840.10045.2.1
223    if alg_oid == "1.2.840.10045.2.1" {
224        if let Some(params) = &spki.algorithm.parameters {
225            if let Ok(curve_oid) = params.as_oid() {
226                let curve_str = curve_oid.to_id_string();
227                // secp384r1 = 1.3.132.0.34
228                if curve_str == "1.3.132.0.34" {
229                    let vk = P384VerifyingKey::from_sec1_bytes(raw_bytes)
230                        .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
231                    return Ok(DevicePublicKey::P384(vk));
232                }
233                // prime256v1 / secp256r1 = 1.2.840.10045.3.1.7
234                if curve_str == "1.2.840.10045.3.1.7" {
235                    let vk = P256VerifyingKey::from_sec1_bytes(raw_bytes)
236                        .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
237                    return Ok(DevicePublicKey::P256(vk));
238                }
239            }
240        }
241    }
242
243    // Ed25519 = 1.3.101.112
244    if alg_oid == "1.3.101.112" {
245        let key_bytes: [u8; 32] = raw_bytes.try_into().map_err(|_| {
246            CryptoError::CertificateParseError("Invalid Ed25519 key length".to_string())
247        })?;
248        let vk = VerifyingKey::from_bytes(&key_bytes)
249            .map_err(|e| CryptoError::CertificateParseError(e.to_string()))?;
250        return Ok(DevicePublicKey::Ed25519(vk));
251    }
252
253    Err(CryptoError::UnsupportedPublicKeyAlgorithm)
254}
255
256pub fn sha256_digest(data: &[u8]) -> Vec<u8> {
257    let mut hasher = Sha256::new();
258    hasher.update(data);
259    hasher.finalize().to_vec()
260}
261
262pub fn sha384_digest(data: &[u8]) -> Vec<u8> {
263    let mut hasher = Sha384::new();
264    hasher.update(data);
265    hasher.finalize().to_vec()
266}
267
268pub fn sha512_digest(data: &[u8]) -> Vec<u8> {
269    let mut hasher = Sha512::new();
270    hasher.update(data);
271    hasher.finalize().to_vec()
272}