structured-pkix 0.4.1

Borrowed X.509 certificates and provider-neutral certification path validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Actual signer binding and response signature authentication.

use super::{BasicResponse, Digest, ResponderMatch};
use crate::error::CallbackError;
use crate::path::{Verified, Verify, WorkingKey};
use crate::{Certificate, Error};
use core::fmt;
use structured_asn1::memory::{MemoryError, Work};

/// Failure to execute authentication, retaining the originating capability.
#[derive(Debug)]
pub enum SignatureError<V, D> {
    /// Located shared processing/resource failure.
    Processing(Error),
    /// Signature provider failure, including its resource or policy error.
    Verification(V),
    /// Digest provider failure, including its resource or policy error.
    Digest(D),
}

impl<V, D> From<Error> for SignatureError<V, D> {
    fn from(error: Error) -> Self {
        Self::Processing(error)
    }
}

impl<V: fmt::Display, D: fmt::Display> fmt::Display for SignatureError<V, D> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Processing(error) => error.fmt(formatter),
            Self::Verification(error) => write!(formatter, "signature verifier: {error}"),
            Self::Digest(error) => write!(formatter, "digest provider: {error}"),
        }
    }
}

#[cfg(feature = "std")]
impl<V: std::error::Error + 'static, D: std::error::Error + 'static> std::error::Error
    for SignatureError<V, D>
{
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Processing(error) => Some(error),
            Self::Verification(error) => Some(error),
            Self::Digest(error) => Some(error),
        }
    }
}

/// Completed negative binding/signature result, not an execution failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignatureFailure {
    /// Effective key does not belong to the supplied signer's original SPKI.
    KeyBinding,
    /// `ResponderID` does not identify the actual supplied signer.
    ResponderIdentity,
    /// Provider resolved protocol-imposed SHA-1 with a contradicting width.
    DigestWidth,
    /// The completed signature verification rejected the signature.
    Signature,
}

/// Original response authenticated by its actual signer. This proves neither
/// signer authorization for a target issuer nor freshness or request binding.
#[derive(Debug, Clone, Copy)]
pub struct SignedResponse<'r, 'a> {
    response: &'r BasicResponse<'a>,
    signer: &'r Certificate<'a>,
    key: WorkingKey<'a>,
}

impl<'r, 'a> SignedResponse<'r, 'a> {
    /// Original signed response, retaining every assertion and extension.
    #[must_use]
    pub fn response(self) -> &'r BasicResponse<'a> {
        self.response
    }
    /// Actual certificate whose subject/key matched `ResponderID`.
    #[must_use]
    pub fn signer(self) -> &'r Certificate<'a> {
        self.signer
    }
    /// Effective key bound to that certificate's original SPKI.
    #[must_use]
    pub fn key(self) -> WorkingKey<'a> {
        self.key
    }
}

/// Signature authentication outcome with unsupported capabilities separate.
#[derive(Debug)]
pub enum SignatureAuthentication<'r, 'a> {
    /// Signer identity and signature established; authorization remains separate.
    Signed(SignedResponse<'r, 'a>),
    /// Completed semantic rejection.
    Rejected(SignatureFailure),
    /// Protocol-imposed SHA-1 cannot be supplied by this provider/policy.
    UnsupportedDigest,
    /// Signature algorithm/effective key is unsupported by this verifier.
    UnsupportedSignature,
}

impl<'a> BasicResponse<'a> {
    /// Authenticate exact `ResponseData` with the actual signer's bound key.
    /// Included certificates are candidates only. RFC6960 §§4.2.2.2–4.2.2.3
    /// require authorization and status validity beyond this signature fact.
    /// <https://www.rfc-editor.org/rfc/rfc6960#section-4.2.2.2>
    pub fn authenticate_signature<'r, V: Verify<E>, D: Digest<E>, E: Work>(
        &'r self,
        signer: &'r Certificate<'a>,
        key: WorkingKey<'a>,
        verifier: &V,
        digest: &D,
        execution: &E,
    ) -> core::result::Result<SignatureAuthentication<'r, 'a>, SignatureError<V::Error, D::Error>>
    {
        const FIELD: &str = "ocspResponse.signature";
        let charge = |work| {
            execution
                .charge_work(work)
                .map_err(|reason| Error::resource(reason, FIELD, self.span.start))
        };
        let encoded = key.key().as_bytes();
        let actual = signer.tbs().public_key().as_bytes();
        let work = u64::try_from(encoded.len().max(actual.len()))
            .ok()
            .and_then(|n| n.checked_mul(2))
            .and_then(|n| n.checked_add(1))
            .ok_or_else(|| Error::resource(MemoryError::WorkExceeded, FIELD, self.span.start))?;
        charge(work)?;
        if encoded != actual {
            return Ok(SignatureAuthentication::Rejected(
                SignatureFailure::KeyBinding,
            ));
        }
        let identity = self
            .responder
            .matches_certificate(signer, digest, execution, FIELD, self.span.start)
            .map_err(|cause| match cause {
                CallbackError::Processing(cause) => SignatureError::Processing(cause),
                CallbackError::Callback(cause) => SignatureError::Digest(cause),
            })?;
        match identity {
            ResponderMatch::Matches => {}
            ResponderMatch::Differs => {
                return Ok(SignatureAuthentication::Rejected(
                    SignatureFailure::ResponderIdentity,
                ));
            }
            ResponderMatch::MalformedHashWidth => {
                return Ok(SignatureAuthentication::Rejected(
                    SignatureFailure::DigestWidth,
                ));
            }
            ResponderMatch::UnsupportedHash => {
                return Ok(SignatureAuthentication::UnsupportedDigest);
            }
        }
        charge(1)?;
        match verifier
            .verify(&self.algorithm, key, self.signed, self.signature, execution)
            .map_err(SignatureError::Verification)?
        {
            Verified::Yes => Ok(SignatureAuthentication::Signed(SignedResponse {
                response: self,
                signer,
                key,
            })),
            Verified::No => Ok(SignatureAuthentication::Rejected(
                SignatureFailure::Signature,
            )),
            Verified::Unsupported => Ok(SignatureAuthentication::UnsupportedSignature),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::DigestAlgorithm;
    use super::*;
    use crate::fixtures::{CertificateParts, bits, context, extension, octets, seq, tlv};
    use core::{cell::Cell, num::NonZeroUsize};
    use structured_asn1::memory::Memory;
    use structured_asn1::{BitString, Parser};

    struct Provider<'a> {
        key: &'a [u8],
        signed: &'a [u8],
        hashes: Cell<usize>,
        signatures: Cell<usize>,
        width: usize,
        digest_answer: Option<bool>,
        signature_answer: Verified,
        failure: bool,
    }
    impl Digest for Provider<'_> {
        type Handle = ();
        type Error = &'static str;
        fn resolve(
            &self,
            algorithm: DigestAlgorithm<'_>,
            _: &Memory,
        ) -> Result<Option<super::super::ResolvedDigest<()>>, Self::Error> {
            assert!(matches!(algorithm, DigestAlgorithm::Sha1));
            if self.failure {
                return Err("digest refusal");
            }
            Ok(self.digest_answer.map(|_| super::super::ResolvedDigest {
                handle: (),
                width: NonZeroUsize::new(self.width).unwrap(),
            }))
        }
        fn matches(
            &self,
            (): (),
            input: &[u8],
            expected: &[u8],
            _: &Memory,
        ) -> Result<bool, Self::Error> {
            self.hashes.set(self.hashes.get() + 1);
            assert_eq!(input.as_ptr(), self.key.as_ptr());
            assert_eq!(input, self.key);
            assert_eq!(expected, &[0x33; 20]);
            Ok(self.digest_answer.unwrap())
        }
    }
    impl Verify for Provider<'_> {
        type Error = &'static str;
        fn verify(
            &self,
            _: &crate::AlgorithmIdentifier<'_>,
            _: WorkingKey<'_>,
            signed: &[u8],
            _: BitString<'_>,
            _: &Memory,
        ) -> Result<Verified, Self::Error> {
            self.signatures.set(self.signatures.get() + 1);
            assert_eq!(signed.as_ptr(), self.signed.as_ptr());
            assert_eq!(signed, self.signed);
            Ok(self.signature_answer)
        }
    }

    #[test]
    fn responder_identity_query_reuses_original_key_bits_without_signature_or_output_copy() {
        // XAdES byKey identifiers need the same RFC6960 identity check outside
        // signature authentication. A malformed width cannot call the provider,
        // and current query refusal remains located processing failure.
        use crate::error::CallbackError;
        use crate::ocsp::{ResponderId, ResponderMatch};
        let bytes = CertificateParts::default().build();
        let memory = crate::fixtures::memory();
        let parser = Parser::der(memory.clone());
        let certificate = Certificate::read(&parser, &bytes, 100).unwrap();
        let mut provider = Provider {
            key: certificate.tbs().public_key().key().as_bytes(),
            signed: &[],
            hashes: Cell::new(0),
            signatures: Cell::new(0),
            width: 20,
            digest_answer: Some(true),
            signature_answer: Verified::Yes,
            failure: false,
        };
        let selector = ResponderId::KeyHash(&[0x33; 20]);
        let held = memory.used();
        assert_eq!(
            selector
                .matches_certificate(&certificate, &provider, &memory, "original.byKey", 900)
                .unwrap(),
            ResponderMatch::Matches
        );
        assert_eq!((provider.hashes.get(), provider.signatures.get()), (1, 0));
        assert_eq!(memory.used(), held);
        provider.failure = true;
        assert_eq!(
            ResponderId::KeyHash(&[0x33; 19])
                .matches_certificate(&certificate, &provider, &memory, "original.byKey", 900)
                .unwrap(),
            ResponderMatch::MalformedHashWidth
        );
        assert!(matches!(
            selector.matches_certificate(&certificate, &provider, &memory, "original.byKey", 900),
            Err(CallbackError::Callback("digest refusal"))
        ));
        let stopped = Memory::new(alloc::sync::Arc::new(
            structured_asn1::memory::MemoryAccount::new(0, 0),
        ));
        assert!(
            matches!(selector.matches_certificate(&certificate,&provider,&stopped,"original.byKey",900),Err(CallbackError::Processing(error)) if error.is_resource() && error.offset()==900)
        );
        assert_eq!((provider.hashes.get(), provider.signatures.get()), (1, 0));
        assert_eq!(memory.used(), held);
    }

    #[test]
    fn issuer_binding_enforces_object_signing_key_usage() {
        // RFC5280 4.2.1.3: certificate/CRL signing bits cannot authorize an
        // OCSP object signature; either object-signing bit is sufficient.
        for (usage, permitted) in [
            (None, true),
            (Some([7, 0x80]), true),
            (Some([6, 0x40]), true),
            (Some([1, 0x06]), false),
            (Some([5, 0x20]), false),
        ] {
            let certificate_bytes = CertificateParts {
                extensions: usage
                    .map(|value| seq(&[extension(crate::oid::KEY_USAGE, true, &tlv(3, &value))])),
                ..CertificateParts::default()
            }
            .build();
            let execution = crate::fixtures::memory();
            let parser = Parser::der(execution.clone());
            let issuer = Certificate::read(&parser, &certificate_bytes, 100).unwrap();
            let algorithm = issuer.signature_algorithm().as_bytes();
            let timestamp = tlv(24, b"20261012120000Z");
            let id = seq(&[
                algorithm.to_vec(),
                octets(&[0x11; 20]),
                octets(&[0x22; 20]),
                tlv(2, &[1]),
            ]);
            let single = seq(&[id, tlv(0x80, &[]), timestamp.clone()]);
            let data = seq(&[
                context(2, &[octets(&[0x33; 20])]),
                timestamp,
                seq(&[single]),
            ]);
            let bytes = seq(&[data, algorithm.to_vec(), bits(&[0xab])]);
            let mut reader = parser.read(&bytes, 700).unwrap();
            let root = reader.next_element().unwrap().unwrap();
            let response = super::super::read_basic(&reader, &root).unwrap();
            let key = WorkingKey::standing(issuer.tbs().public_key());
            let provider = Provider {
                key: issuer.tbs().public_key().key().as_bytes(),
                signed: response.signed_bytes(),
                hashes: Cell::new(0),
                signatures: Cell::new(0),
                width: 20,
                digest_answer: Some(true),
                signature_answer: Verified::Yes,
                failure: false,
            };
            let SignatureAuthentication::Signed(signed) = response
                .authenticate_signature(&issuer, key, &provider, &provider, &execution)
                .unwrap()
            else {
                panic!("signature fixture rejected");
            };
            let result = signed.bind_issuer(&issuer, key, &execution).unwrap();
            assert_eq!(
                matches!(result, super::super::AuthorityBinding::Bound(_)),
                permitted
            );
            if !permitted {
                assert!(matches!(
                    result,
                    super::super::AuthorityBinding::Rejected(
                        super::super::AuthorityFailure::KeyUsage
                    )
                ));
            }
            assert_eq!(provider.signatures.get(), 1);
        }
    }

    #[test]
    fn actual_signer_precedes_hash_and_original_response_data_verification() {
        // This observes dispatch/provenance only, not cryptographic correctness.
        // Wrong SPKI, responder identity or SHA1 width must stop before verify.
        let certificate_bytes = CertificateParts::default().build();
        let execution = crate::fixtures::memory();
        let parser = Parser::der(execution.clone());
        let signer = Certificate::read(&parser, &certificate_bytes, 100).unwrap();
        let algorithm = signer.signature_algorithm().as_bytes();
        let timestamp = tlv(24, b"20261012120000Z");
        let id = seq(&[
            algorithm.to_vec(),
            octets(&[0x11; 20]),
            octets(&[0x22; 20]),
            tlv(2, &[1]),
        ]);
        let single = seq(&[id, tlv(0x80, &[]), timestamp.clone()]);
        let data = seq(&[
            context(2, &[octets(&[0x33; 20])]),
            timestamp,
            seq(&[single]),
        ]);
        let bytes = seq(&[data, algorithm.to_vec(), bits(&[0xab])]);
        let mut reader = parser.read(&bytes, 700).unwrap();
        let element = reader.next_element().unwrap().unwrap();
        let response = super::super::read_basic(&reader, &element).unwrap();
        let key = WorkingKey::standing(signer.tbs().public_key());
        let mut provider = Provider {
            key: signer.tbs().public_key().key().as_bytes(),
            signed: response.signed_bytes(),
            hashes: Cell::new(0),
            signatures: Cell::new(0),
            width: 20,
            digest_answer: Some(true),
            signature_answer: Verified::Yes,
            failure: false,
        };
        let retained = execution.used();
        let SignatureAuthentication::Signed(proof) = response
            .authenticate_signature(&signer, key, &provider, &provider, &execution)
            .unwrap()
        else {
            panic!("signature not authenticated");
        };
        assert!(core::ptr::eq(proof.response(), &raw const response));
        assert!(core::ptr::eq(proof.signer(), &raw const signer));
        assert_eq!(provider.signatures.get(), 1);
        assert_eq!(execution.used(), retained);
        provider.signatures.set(0);
        provider.width = 19;
        assert!(matches!(
            response
                .authenticate_signature(&signer, key, &provider, &provider, &execution)
                .unwrap(),
            SignatureAuthentication::Rejected(SignatureFailure::DigestWidth)
        ));
        assert_eq!(provider.signatures.get(), 0);
        provider.width = 20;
        provider.digest_answer = Some(false);
        assert!(matches!(
            response
                .authenticate_signature(&signer, key, &provider, &provider, &execution)
                .unwrap(),
            SignatureAuthentication::Rejected(SignatureFailure::ResponderIdentity)
        ));
        assert_eq!(provider.signatures.get(), 0);
        provider.digest_answer = None;
        assert!(matches!(
            response
                .authenticate_signature(&signer, key, &provider, &provider, &execution)
                .unwrap(),
            SignatureAuthentication::UnsupportedDigest
        ));
        provider.failure = true;
        assert!(matches!(
            response.authenticate_signature(&signer, key, &provider, &provider, &execution),
            Err(SignatureError::Digest("digest refusal"))
        ));
        let unfunded = Memory::new(alloc::sync::Arc::new(
            structured_asn1::memory::MemoryAccount::new(0, 0),
        ));
        assert!(
            matches!(response.authenticate_signature(&signer, key, &provider, &provider, &unfunded), Err(SignatureError::Processing(error)) if error.is_resource() && error.offset() == 700)
        );
    }
}