Skip to main content

xml_sec/xmldsig/
trust.rs

1//! Key discovery and authorization are distinct from signature validation.
2
3use std::{ops::Deref, time::SystemTime};
4
5use super::{DsigError, SignatureAlgorithm, VerifyingKey};
6use crate::policy::{KeyTrustPolicy, PolicyViolation, VerificationPolicy};
7
8/// Evidence of key authorization, independent of the signature's validity.
9#[derive(Debug, Clone, PartialEq, Eq)]
10// The fixed path bound avoids a heap allocation for every verification result.
11#[expect(
12    clippy::large_enum_variant,
13    reason = "bounded inline path evidence avoids heap allocation"
14)]
15pub enum KeyTrustEvidence {
16    /// Verification stopped before key authorization.
17    NotEvaluated,
18    /// Only mathematical signature verification was requested.
19    NotEstablished,
20    /// The application explicitly supplied or authorized this key.
21    CallerTrusted,
22    /// A certificate path was validated to a caller-provided anchor.
23    ValidatedX509(X509TrustEvidence),
24}
25
26/// Immutable identity of the exact path that established key authorization.
27/// Fields cannot be constructed or changed by a certificate parser or caller.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct X509TrustEvidence {
30    fingerprints: [[u8; 32]; crate::hard_limits::X509_CHAIN_DEPTH_CEILING],
31    path_len: usize,
32    verification_time: SystemTime,
33    revocation_checked: bool,
34}
35
36impl X509TrustEvidence {
37    pub(crate) fn new(
38        certificates: impl ExactSizeIterator<Item = impl AsRef<[u8]>>,
39        verification_time: SystemTime,
40        revocation_checked: bool,
41    ) -> Result<Self, DsigError> {
42        use sha2::{Digest, Sha256};
43        let path_len = certificates.len();
44        if path_len == 0 || path_len > crate::hard_limits::X509_CHAIN_DEPTH_CEILING {
45            return Err(PolicyViolation::KeyTrust {
46                reason: "invalid validated certificate path",
47            }
48            .into());
49        }
50        // Path identity is bounded by the same hard depth ceiling as validation.
51        // Fixed storage avoids an unmetered post-validation allocation.
52        let mut fingerprints = [[0; 32]; crate::hard_limits::X509_CHAIN_DEPTH_CEILING];
53        for (fingerprint, certificate) in fingerprints.iter_mut().zip(certificates) {
54            *fingerprint = Sha256::digest(certificate.as_ref()).into();
55        }
56        Ok(Self {
57            fingerprints,
58            path_len,
59            verification_time,
60            revocation_checked,
61        })
62    }
63
64    /// SHA-256 identities in leaf-to-anchor order, including the trust anchor.
65    pub fn certificate_fingerprints(&self) -> &[[u8; 32]] {
66        &self.fingerprints[..self.path_len]
67    }
68
69    /// SHA-256 identity of the caller-supplied anchor that terminated the path.
70    pub fn anchor_fingerprint(&self) -> &[u8; 32] {
71        &self.fingerprints[self.path_len - 1]
72    }
73
74    /// The single time captured for all candidate-path validation in the operation.
75    pub fn verification_time(&self) -> SystemTime {
76        self.verification_time
77    }
78
79    /// Whether the policy requested and validation enforced CRL processing.
80    pub fn revocation_checked(&self) -> bool {
81        self.revocation_checked
82    }
83}
84
85/// A public key authorized by certificate path validation, not just DER parsing.
86/// Only the validating resolver can create it; callers may inspect evidence.
87pub struct TrustedPublicKey {
88    key: Box<dyn VerifyingKey>,
89    trust: KeyTrustPolicy,
90    evidence: X509TrustEvidence,
91}
92
93impl TrustedPublicKey {
94    pub(crate) fn new(
95        key: Box<dyn VerifyingKey>,
96        mut trust: KeyTrustPolicy,
97        evidence: X509TrustEvidence,
98    ) -> Self {
99        // RFC 5280 §6.1.1: a proof is tied to an actual validation time, never
100        // to a reusable "choose now later" placeholder.
101        // https://www.rfc-editor.org/rfc/rfc5280#section-6.1.1
102        trust.verification_time = Some(evidence.verification_time);
103        Self {
104            key,
105            trust,
106            evidence,
107        }
108    }
109
110    /// Validated certificate identities and the operation's validation time.
111    pub fn evidence(&self) -> &X509TrustEvidence {
112        &self.evidence
113    }
114}
115
116impl VerifyingKey for TrustedPublicKey {
117    fn verification_spki(&self, algorithm: SignatureAlgorithm) -> Result<Option<&[u8]>, DsigError> {
118        self.key.verification_spki(algorithm)
119    }
120
121    fn ecdsa_encoding(&self) -> crate::policy::EcdsaSignatureValueEncoding {
122        self.key.ecdsa_encoding()
123    }
124
125    fn verify_candidate_keys(
126        &self,
127        verify: &mut dyn FnMut(&dyn VerifyingKey) -> Result<bool, DsigError>,
128    ) -> Result<Option<bool>, DsigError> {
129        self.key.verify_candidate_keys(verify)
130    }
131    fn verify_with_context(
132        &self,
133        algorithm: SignatureAlgorithm,
134        context: &super::SignatureContext,
135        data: &[u8],
136        signature: &[u8],
137    ) -> Result<bool, DsigError> {
138        self.key
139            .verify_with_context(algorithm, context, data, signature)
140    }
141    fn validate_policy(&self, policy: &VerificationPolicy) -> Result<(), DsigError> {
142        if self.trust != policy.key_trust {
143            return Err(PolicyViolation::KeyTrust {
144                reason: "validated key belongs to a different trust policy",
145            }
146            .into());
147        }
148        self.key.validate_policy(policy)
149    }
150
151    fn validate_signature_value(
152        &self,
153        algorithm: SignatureAlgorithm,
154        signature: &[u8],
155    ) -> Result<bool, DsigError> {
156        self.key.validate_signature_value(algorithm, signature)
157    }
158
159    fn validate_signature_value_with_policy(
160        &self,
161        policy: &VerificationPolicy,
162        algorithm: SignatureAlgorithm,
163        signature: &[u8],
164    ) -> Result<bool, DsigError> {
165        self.validate_policy(policy)?;
166        self.key
167            .validate_signature_value_with_policy(policy, algorithm, signature)
168    }
169
170    fn verify(
171        &self,
172        algorithm: SignatureAlgorithm,
173        data: &[u8],
174        signature: &[u8],
175    ) -> Result<bool, DsigError> {
176        self.key.verify(algorithm, data, signature)
177    }
178
179    fn verify_with_policy(
180        &self,
181        policy: &VerificationPolicy,
182        algorithm: SignatureAlgorithm,
183        data: &[u8],
184        signature: &[u8],
185    ) -> Result<bool, DsigError> {
186        self.validate_policy(policy)?;
187        self.key
188            .verify_with_policy(policy, algorithm, data, signature)
189    }
190}
191
192/// Resolver output: finding a key does not implicitly authorize its signer.
193#[expect(
194    clippy::large_enum_variant,
195    reason = "one bounded resolver result per operation needs no extra box"
196)]
197pub enum ResolvedVerificationKey<'a> {
198    /// Document-supplied or otherwise unauthenticated key material.
199    Candidate(Box<dyn VerifyingKey + 'a>),
200    /// An explicit trust declaration made by application-owned resolver code.
201    CallerTrusted(Box<dyn VerifyingKey + 'a>),
202    /// An unforgeable result of the built-in certificate validation boundary.
203    Validated(TrustedPublicKey),
204}
205
206impl<'a> ResolvedVerificationKey<'a> {
207    /// Extract the mathematical verifier without establishing signer trust.
208    pub fn into_key(self) -> Box<dyn VerifyingKey + 'a> {
209        match self {
210            Self::Candidate(key) | Self::CallerTrusted(key) => key,
211            Self::Validated(key) => Box::new(key),
212        }
213    }
214
215    pub(crate) fn authorize(
216        &self,
217        policy: &VerificationPolicy,
218    ) -> Result<KeyTrustEvidence, DsigError> {
219        use crate::policy::VerificationTrustMode;
220        // XMLDSig 1.1 §4.5 leaves key trust to the application:
221        // https://www.w3.org/TR/2013/REC-xmldsig-core1-20130411/#sec-KeyInfo
222        // This explicit mode is application policy, not a conformance requirement.
223        if policy.key_trust.mode == VerificationTrustMode::CryptographicOnly {
224            return Ok(KeyTrustEvidence::NotEstablished);
225        }
226        match self {
227            Self::Candidate(_) => Err(PolicyViolation::KeyTrust {
228                reason: "verification requires an authorized key",
229            }
230            .into()),
231            Self::CallerTrusted(_) => Ok(KeyTrustEvidence::CallerTrusted),
232            Self::Validated(key) => {
233                key.validate_policy(policy)?;
234                Ok(KeyTrustEvidence::ValidatedX509(key.evidence.clone()))
235            }
236        }
237    }
238}
239
240impl<'a> AsRef<dyn VerifyingKey + 'a> for ResolvedVerificationKey<'a> {
241    fn as_ref(&self) -> &(dyn VerifyingKey + 'a) {
242        match self {
243            Self::Candidate(key) | Self::CallerTrusted(key) => key.as_ref(),
244            Self::Validated(key) => key,
245        }
246    }
247}
248
249impl<'a> Deref for ResolvedVerificationKey<'a> {
250    type Target = dyn VerifyingKey + 'a;
251    fn deref(&self) -> &Self::Target {
252        self.as_ref()
253    }
254}
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    struct NeverExecuted;
261    impl VerifyingKey for NeverExecuted {
262        fn verify(&self, _: SignatureAlgorithm, _: &[u8], _: &[u8]) -> Result<bool, DsigError> {
263            panic!("stale authorization must fail before mathematical work");
264        }
265    }
266
267    #[test]
268    fn validated_key_is_bound_to_time_purpose_and_policy() {
269        // A validated key must not be reusable under another time or purpose,
270        // or through a caller policy whose implicit clock has not been captured.
271        let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000);
272        let evidence =
273            X509TrustEvidence::new([b"bounded certificate identity"].into_iter(), time, false)
274                .expect("a one-certificate proof fits the hard path bound");
275        let mut policy = VerificationPolicy::default();
276        policy.key_trust.verify_x509_chains = true;
277        let key =
278            TrustedPublicKey::new(Box::new(NeverExecuted), policy.key_trust.clone(), evidence);
279        assert!(key.validate_policy(&policy).is_err());
280        policy.key_trust.verification_time = Some(time);
281        key.validate_policy(&policy)
282            .expect("the exact captured snapshot must match");
283        let mut changed = policy.clone();
284        changed.key_trust.verification_time = Some(time + std::time::Duration::from_secs(1));
285        assert!(
286            key.verify_with_policy(
287                &changed,
288                SignatureAlgorithm::RsaSha256,
289                b"data",
290                b"signature"
291            )
292            .is_err()
293        );
294        changed = policy.clone();
295        changed
296            .key_trust
297            .allowed_extended_key_usages
298            .insert(crate::policy::ExtendedKeyPurpose::CodeSigning);
299        assert!(key.validate_policy(&changed).is_err());
300        changed = policy;
301        changed.key_trust.check_crls = true;
302        assert!(key.validate_policy(&changed).is_err());
303    }
304}