wintrust 0.3.0

Portable Rust catalog trust with Windows API name aliases
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Signed, explicitly supplied offline CRL/OCSP evidence. Missing evidence is unknown.
use super::crypto;
use crate::{
    CertificateStore,
    error::{Context, Error, Result, ensure},
};
#[cfg(feature = "online")]
use alloc::vec;
use alloc::{
    borrow::ToOwned,
    collections::BTreeSet,
    format,
    string::{String, ToString},
    vec::Vec,
};
use der::{Decode, Encode};
use serde::{Deserialize, Serialize};
use x509_cert::{
    Certificate,
    ext::pkix::{ExtendedKeyUsage, KeyUsage},
};
use x509_ocsp::{BasicOcspResponse, CertStatus, OcspResponse, OcspResponseStatus, ResponderId};

mod crl;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RevocationStatus {
    Good,
    Revoked,
    Unknown,
}
#[derive(Debug, Clone, Serialize)]
pub struct CertificateStatus {
    pub certificate_sha256: String,
    pub status: RevocationStatus,
    pub evidence_sha256: Vec<String>,
    pub diagnostics: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RevocationReport {
    pub status: RevocationStatus,
    pub certificates: Vec<CertificateStatus>,
    pub current_unix_time: u64,
    pub signature_verification_time: u64,
    /// Origin of the pinned and acquired evidence this report was computed from.
    pub provenance: Vec<ArtifactProvenance>,
}
#[derive(Debug, Clone, Copy)]
pub struct RevocationLimits {
    pub max_artifacts: usize,
    pub max_artifact_bytes: usize,
    pub max_chain_certificates: usize,
    pub max_entries: usize,
    /// NextUpdate alone may permit excessively old replay: also bound age.
    pub max_age_seconds: u64,
    pub allow_sha1: bool,
}
impl Default for RevocationLimits {
    fn default() -> Self {
        Self {
            max_artifacts: 256,
            max_artifact_bytes: 16 * 1024 * 1024,
            max_chain_certificates: 16,
            max_entries: 100_000,
            max_age_seconds: 7 * 24 * 3600,
            allow_sha1: false,
        }
    }
}
fn hash(bytes: &[u8]) -> Result<String> {
    Ok(hex::encode(crypto::digest(
        ("2.16.840.1.101.3.4.2.1")
            .parse()
            .map_err(Error::malformed)?,
        bytes,
        &crypto::CryptoOptions::default(),
    )?))
}
fn verify_signature(
    cert: &Certificate,
    algorithm_der: &[u8],
    message: &[u8],
    signature: &[u8],
    allow_sha1: bool,
) -> Result<()> {
    crypto::verify_algorithm(
        &cert
            .tbs_certificate
            .subject_public_key_info
            .to_der()
            .map_err(Error::malformed)?,
        algorithm_der,
        message,
        signature,
        &crypto::SignatureOptions {
            digest_oid: None,
            crypto: crypto::CryptoOptions { allow_sha1 },
        },
    )
}
fn fresh(this: u64, next: Option<u64>, now: u64, limits: RevocationLimits) -> Result<()> {
    let next = next.ok_or_else(|| Error::policy("revocation evidence lacks nextUpdate"))?;
    ensure!(
        this <= now && now <= next && this < next,
        "stale or future revocation evidence"
    );
    ensure!(
        now - this <= limits.max_age_seconds,
        "revocation evidence age exceeds policy"
    );
    Ok(())
}
fn extensions_supported(
    exts: Option<&[x509_cert::ext::Extension]>,
    allowed: &[&str],
) -> Result<()> {
    let mut seen = BTreeSet::new();
    for e in exts.unwrap_or_default() {
        let oid = e.extn_id.to_string();
        ensure!(
            seen.insert(oid.clone()),
            Error::malformed("duplicate revocation extension")
        );
        ensure!(
            !e.critical || allowed.contains(&oid.as_str()),
            Error::unsupported(format!("unsupported critical revocation extension {oid}"))
        );
    }
    Ok(())
}
/// Verify a CRL for `certificate` issued by `issuer` (RFC 5280 section 6.3).
///
/// Status is `Good` only when this single CRL is fresh, authenticated, in scope
/// and covers every revocation reason; a listing is `Revoked`. A delta CRL, a
/// partial-scope CRL or stale evidence cannot prove absence here and is an
/// error; use [`verify_chain_revocation`] to combine several CRLs.
pub fn verify_crl(
    bytes: &[u8],
    certificate: &Certificate,
    issuer: &Certificate,
    now: u64,
    limits: RevocationLimits,
) -> Result<RevocationStatus> {
    let outcome = crl::evaluate(
        &[bytes],
        certificate,
        core::slice::from_ref(issuer),
        &[],
        now,
        limits,
    )?;
    ensure!(
        outcome.status != RevocationStatus::Unknown,
        "CRL does not establish certificate status: {}",
        if outcome.diagnostics.is_empty() {
            "no fresh in-scope evidence".to_owned()
        } else {
            outcome.diagnostics.join("; ")
        }
    );
    Ok(outcome.status)
}
fn responder_matches(id: &ResponderId, certificate: &Certificate) -> Result<bool> {
    Ok(match id {
        ResponderId::ByName(name) => *name == certificate.tbs_certificate.subject,
        ResponderId::ByKey(key) => {
            key.as_bytes()
                == crypto::digest(
                    ("1.3.14.3.2.26").parse().map_err(Error::malformed)?,
                    certificate
                        .tbs_certificate
                        .subject_public_key_info
                        .subject_public_key
                        .as_bytes()
                        .context("unaligned responder public key")?,
                    &crypto::CryptoOptions { allow_sha1: true },
                )?
        }
    })
}
/// Verify issuer-signed or directly delegated OCSP. Delegation requires an
/// issuer signature and OCSP EKU, never merely a matching responder name.
pub fn verify_ocsp(
    bytes: &[u8],
    certificate: &Certificate,
    issuer: &Certificate,
    now: u64,
    limits: RevocationLimits,
) -> Result<RevocationStatus> {
    ensure!(
        bytes.len() <= limits.max_artifact_bytes,
        Error::resource_limit("OCSP byte limit")
    );
    let response = OcspResponse::from_der(bytes).map_err(Error::malformed)?;
    ensure!(
        response.response_status == OcspResponseStatus::Successful,
        "OCSP unsuccessful response"
    );
    let response = response
        .response_bytes
        .context("missing OCSP responseBytes")?;
    ensure!(
        response.response_type.to_string() == "1.3.6.1.5.5.7.48.1.1",
        Error::unsupported("unsupported OCSP response type")
    );
    let basic =
        BasicOcspResponse::from_der(response.response.as_bytes()).map_err(Error::malformed)?;
    let tbs = &basic.tbs_response_data;
    ensure!(
        certificate.tbs_certificate.issuer == issuer.tbs_certificate.subject,
        Error::malformed("OCSP certificate issuer mismatch")
    );
    ensure!(
        tbs.responses.len() <= limits.max_entries,
        Error::resource_limit("OCSP response limit")
    );
    extensions_supported(tbs.response_extensions.as_deref(), &[])?;
    let produced = tbs.produced_at.0.to_unix_duration().as_secs();
    ensure!(produced <= now, "future OCSP producedAt");
    let responder = if responder_matches(&tbs.responder_id, issuer)? {
        issuer
    } else {
        let certs = basic
            .certs
            .as_deref()
            .ok_or_else(|| Error::policy("OCSP responder certificate absent"))?;
        ensure!(
            certs.len() <= limits.max_chain_certificates,
            Error::resource_limit("OCSP certificate limit")
        );
        let mut candidate = None;
        for cert in certs {
            if responder_matches(&tbs.responder_id, cert)? {
                ensure!(
                    candidate.is_none(),
                    Error::malformed("ambiguous OCSP responder")
                );
                candidate = Some(cert);
            }
        }
        let cert = candidate.ok_or_else(|| Error::policy("ambiguous OCSP responder"))?;
        extensions_supported(
            cert.tbs_certificate.extensions.as_deref(),
            &[
                "2.5.29.19",
                "2.5.29.15",
                "2.5.29.37",
                "2.5.29.14",
                "2.5.29.35",
            ],
        )?;
        if let Some((_, constraints)) = cert
            .tbs_certificate
            .get::<x509_cert::ext::pkix::BasicConstraints>()
            .map_err(Error::malformed)?
        {
            ensure!(!constraints.ca, "OCSP delegate must be an end entity");
        }

        ensure!(
            cert.tbs_certificate.issuer == issuer.tbs_certificate.subject,
            "OCSP responder not delegated by issuer"
        );
        ensure!(
            cert.signature_algorithm == cert.tbs_certificate.signature,
            Error::malformed("OCSP responder signature algorithm mismatch")
        );
        verify_signature(
            issuer,
            &cert
                .signature_algorithm
                .to_der()
                .map_err(Error::malformed)?,
            &cert.tbs_certificate.to_der().map_err(Error::malformed)?,
            cert.signature
                .as_bytes()
                .context("unaligned responder signature")?,
            limits.allow_sha1,
        )?;
        let eku = cert
            .tbs_certificate
            .get::<ExtendedKeyUsage>()
            .map_err(Error::malformed)?
            .ok_or_else(|| Error::policy("OCSP responder EKU absent"))?;
        ensure!(
            eku.1.0.iter().any(|o| o.to_string() == "1.3.6.1.5.5.7.3.9"),
            "OCSP responder EKU missing"
        );
        let usage = cert
            .tbs_certificate
            .get::<KeyUsage>()
            .map_err(Error::malformed)?
            .ok_or_else(|| Error::policy("OCSP responder keyUsage absent"))?;
        ensure!(
            usage.1.digital_signature(),
            "OCSP responder lacks digitalSignature"
        );
        ensure!(
            cert.tbs_certificate
                .validity
                .not_before
                .to_unix_duration()
                .as_secs()
                <= produced
                && produced
                    <= cert
                        .tbs_certificate
                        .validity
                        .not_after
                        .to_unix_duration()
                        .as_secs(),
            "OCSP responder expired at producedAt"
        );
        // Delegated responder revocation is checked using issuer-signed CRLs by
        // the outer policy; until evidence is supplied, require no-check rather
        // than silently ignoring responder revocation.
        ensure!(
            cert.tbs_certificate
                .extensions
                .as_deref()
                .unwrap_or_default()
                .iter()
                .any(|e| e.extn_id.to_string() == "1.3.6.1.5.5.7.48.1.5"
                    && der::asn1::Null::from_der(e.extn_value.as_bytes()).is_ok()),
            "delegated OCSP responder requires signed nocheck"
        );
        cert
    };
    verify_signature(
        responder,
        &basic
            .signature_algorithm
            .to_der()
            .map_err(Error::malformed)?,
        &tbs.to_der().map_err(Error::malformed)?,
        basic
            .signature
            .as_bytes()
            .context("unaligned OCSP signature")?,
        limits.allow_sha1,
    )?;
    let mut matched_status = None;
    let mut matching_responses = 0usize;
    for single in &tbs.responses {
        let id = &single.cert_id;
        let oid = id.hash_algorithm.oid.to_string();
        if let Some(parameters) = &id.hash_algorithm.parameters {
            ensure!(
                parameters.is_null(),
                Error::unsupported("unsupported OCSP CertID hash parameters")
            );
        }
        if id.serial_number != certificate.tbs_certificate.serial_number {
            continue;
        }
        if id.issuer_name_hash.as_bytes()
            != crypto::digest(
                oid.parse().map_err(Error::malformed)?,
                &issuer
                    .tbs_certificate
                    .subject
                    .to_der()
                    .map_err(Error::malformed)?,
                &crypto::CryptoOptions { allow_sha1: true },
            )?
            || id.issuer_key_hash.as_bytes()
                != crypto::digest(
                    oid.parse().map_err(Error::malformed)?,
                    issuer
                        .tbs_certificate
                        .subject_public_key_info
                        .subject_public_key
                        .as_bytes()
                        .context("unaligned issuer public key")?,
                    &crypto::CryptoOptions { allow_sha1: true },
                )?
        {
            continue;
        }
        extensions_supported(single.single_extensions.as_deref(), &[])?;
        if let CertStatus::Revoked(info) = single.cert_status {
            ensure!(
                info.revocation_time.0.to_unix_duration().as_secs() <= now,
                "OCSP revocationTime in future"
            );
            return Ok(RevocationStatus::Revoked);
        }
        ensure!(
            now - produced <= limits.max_age_seconds,
            "stale OCSP producedAt"
        );
        fresh(
            single.this_update.0.to_unix_duration().as_secs(),
            single.next_update.map(|t| t.0.to_unix_duration().as_secs()),
            now,
            limits,
        )?;
        ensure!(
            single.this_update.0.to_unix_duration().as_secs() <= produced,
            "OCSP producedAt precedes thisUpdate"
        );
        matching_responses += 1;
        matched_status = Some(match single.cert_status {
            CertStatus::Good(_) => RevocationStatus::Good,
            _ => RevocationStatus::Unknown,
        });
    }
    ensure!(
        matching_responses == 1,
        Error::malformed("OCSP absent or ambiguous certificate status")
    );
    matched_status.context("OCSP absent or ambiguous certificate status")
}

/// Borrowed artifacts and bounded policy for one chain revocation decision.
#[derive(Debug, Clone)]
pub struct RevocationOptions<'a> {
    pub crls: CertificateStore<'a>,
    pub ocsp: CertificateStore<'a>,
    pub crl_signers: CertificateStore<'a>,
    pub signature_time: u64,
    pub evaluation_time: u64,
    pub limits: RevocationLimits,
}
impl RevocationOptions<'_> {
    pub fn new(signature_time: u64, evaluation_time: u64) -> Self {
        Self {
            crls: CertificateStore::default(),
            ocsp: CertificateStore::default(),
            crl_signers: CertificateStore::default(),
            signature_time,
            evaluation_time,
            limits: RevocationLimits::default(),
        }
    }
}

/// Check each non-anchor certificate using supplied evidence. Authenticated
/// revocation dominates good evidence; invalid artifacts become diagnostics.
pub fn verify_chain_revocation(
    path: CertificateStore<'_>,
    options: &RevocationOptions<'_>,
) -> Result<RevocationReport> {
    let limits = options.limits;
    ensure!(
        !path.is_empty(),
        Error::malformed("revocation chain is empty")
    );
    ensure!(
        path.len() <= limits.max_chain_certificates,
        Error::resource_limit("revocation chain length limit")
    );
    ensure!(
        options
            .crls
            .len()
            .checked_add(options.ocsp.len())
            .is_some_and(|count| count <= limits.max_artifacts),
        Error::resource_limit("revocation artifact count limit")
    );
    ensure!(
        options.crl_signers.len() <= limits.max_chain_certificates.saturating_mul(16),
        Error::resource_limit("CRL signer candidate limit")
    );
    let path_der = path.iter().collect::<Vec<_>>();
    let crls = options.crls.iter().collect::<Vec<_>>();
    let ocsp = options.ocsp.iter().collect::<Vec<_>>();
    let crl_signers = options.crl_signers;
    let verification_time = options.signature_time;
    let now = options.evaluation_time;
    let path = path_der
        .iter()
        .map(|b| Certificate::from_der(b))
        .collect::<core::result::Result<Vec<_>, _>>()
        .map_err(Error::malformed)?;
    let signers = crl_signers
        .iter()
        .map(Certificate::from_der)
        .collect::<core::result::Result<Vec<_>, _>>()
        .map_err(Error::malformed)?;
    let mut certificates = Vec::new();
    for i in 0..path.len() - 1 {
        let mut report = CertificateStatus {
            certificate_sha256: hash(path_der[i])?,
            status: RevocationStatus::Unknown,
            evidence_sha256: Vec::new(),
            diagnostics: Vec::new(),
        };
        if !crls.is_empty() {
            let outcome = crl::evaluate(&crls, &path[i], &path[i + 1..], &signers, now, limits)?;
            for index in &outcome.used {
                report.evidence_sha256.push(hash(crls[*index])?);
            }
            report
                .diagnostics
                .extend(outcome.diagnostics.into_iter().map(|d| format!("CRL: {d}")));
            report.status = outcome.status;
        }
        for artifact in &ocsp {
            match verify_ocsp(artifact, &path[i], &path[i + 1], now, limits) {
                Ok(status) => {
                    report.evidence_sha256.push(hash(artifact)?);
                    if status == RevocationStatus::Revoked
                        || report.status != RevocationStatus::Revoked
                            && status == RevocationStatus::Good
                    {
                        report.status = status;
                    }
                }
                Err(error) => report.diagnostics.push(format!("OCSP: {error}")),
            }
        }
        if report.evidence_sha256.is_empty() {
            report
                .diagnostics
                .push("no authenticated fresh issuer-bound status".into());
        }
        certificates.push(report);
    }
    let status = if certificates
        .iter()
        .any(|r| r.status == RevocationStatus::Revoked)
    {
        RevocationStatus::Revoked
    } else if certificates
        .iter()
        .any(|r| r.status == RevocationStatus::Unknown)
    {
        RevocationStatus::Unknown
    } else {
        RevocationStatus::Good
    };
    Ok(RevocationReport {
        status,
        certificates,
        current_unix_time: now,
        signature_verification_time: verification_time,
        provenance: Vec::new(),
    })
}

#[derive(Debug, Clone, Copy)]
pub struct OnlineLimits {
    pub max_requests: usize,
    pub max_response_bytes: usize,
    pub max_total_bytes: usize,
    pub timeout_seconds: u64,
}
impl Default for OnlineLimits {
    fn default() -> Self {
        Self {
            max_requests: 16,
            max_response_bytes: 16 * 1024 * 1024,
            max_total_bytes: 32 * 1024 * 1024,
            timeout_seconds: 30,
        }
    }
}
/// Signed status evidence format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ArtifactKind {
    Crl,
    DeltaCrl,
    Ocsp,
}
/// Whether bytes were pinned by the caller or acquired online.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ArtifactOrigin {
    Online,
    PinnedFile,
}
/// Mechanism identifying an evidence location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ArtifactSource {
    CrlDistributionPoint,
    FreshestCrl,
    AuthorityInfoAccess,
    Policy,
}

/// Where one piece of revocation evidence came from.
#[derive(Debug, Clone, Serialize)]
pub struct ArtifactProvenance {
    /// `crl`, `delta-crl` or `ocsp`.
    pub kind: ArtifactKind,
    /// `online` for retrieved artifacts, `pinned-file` for policy-pinned cache files.
    pub origin: ArtifactOrigin,
    /// The URL retrieved, or the policy artifact path.
    pub location: String,
    pub sha256: String,
    pub bytes: usize,
    /// Verification time at which an online artifact was retrieved and authenticated;
    /// absent for pinned files, whose digest was verified when the policy was loaded.
    pub retrieved_at: Option<u64>,
    /// The certificate whose status an online request concerned.
    pub certificate_sha256: Option<String>,
    /// `crl-distribution-point`, `freshest-crl`, `authority-info-access` or `policy`.
    pub source: ArtifactSource,
}

/// Provenance for policy-pinned evidence. Each artifact's digest was checked
/// against its pin when the policy was loaded.
#[cfg(feature = "std")]
pub fn pinned_provenance(
    crls: &[(&std::path::Path, &[u8])],
    ocsp: &[(&std::path::Path, &[u8])],
) -> Result<Vec<ArtifactProvenance>> {
    let crl_locations = crls
        .iter()
        .map(|(path, bytes)| (path.display().to_string(), *bytes))
        .collect::<Vec<_>>();
    let ocsp_locations = ocsp
        .iter()
        .map(|(path, bytes)| (path.display().to_string(), *bytes))
        .collect::<Vec<_>>();
    pinned_provenance_labels(
        &crl_locations
            .iter()
            .map(|(name, bytes)| (name.as_str(), *bytes))
            .collect::<Vec<_>>(),
        &ocsp_locations
            .iter()
            .map(|(name, bytes)| (name.as_str(), *bytes))
            .collect::<Vec<_>>(),
    )
}

/// Provenance for pinned bytes using caller-supplied locations, without filesystem access.
pub fn pinned_provenance_labels(
    crls: &[(&str, &[u8])],
    ocsp: &[(&str, &[u8])],
) -> Result<Vec<ArtifactProvenance>> {
    let mut out = Vec::new();
    for (path, bytes) in crls {
        let delta = crl::locations(bytes)
            .map(|(delta, _)| delta)
            .unwrap_or(false);
        out.push(ArtifactProvenance {
            kind: if delta {
                ArtifactKind::DeltaCrl
            } else {
                ArtifactKind::Crl
            },
            origin: ArtifactOrigin::PinnedFile,
            location: (*path).to_owned(),
            sha256: hash(bytes)?,
            bytes: bytes.len(),
            retrieved_at: None,
            certificate_sha256: None,
            source: ArtifactSource::Policy,
        });
    }
    for (path, bytes) in ocsp {
        out.push(ArtifactProvenance {
            kind: ArtifactKind::Ocsp,
            origin: ArtifactOrigin::PinnedFile,
            location: (*path).to_owned(),
            sha256: hash(bytes)?,
            bytes: bytes.len(),
            retrieved_at: None,
            certificate_sha256: None,
            source: ArtifactSource::Policy,
        });
    }
    Ok(out)
}
#[derive(Debug, Default)]
pub struct AcquiredRevocation {
    pub crls: Vec<Vec<u8>>,
    pub ocsp_responses: Vec<Vec<u8>>,
    pub diagnostics: Vec<String>,
    /// One entry per accepted artifact, in the order of `crls` then `ocsp_responses`.
    pub provenance: Vec<ArtifactProvenance>,
}
/// Explicit bounded online acquisition inputs. Online retrieval requires `online`.
#[derive(Debug, Clone)]
pub struct AcquisitionOptions<'a> {
    pub crl_signers: CertificateStore<'a>,
    pub evaluation_time: u64,
    pub limits: RevocationLimits,
    pub online_limits: OnlineLimits,
}
impl AcquisitionOptions<'_> {
    pub fn new(evaluation_time: u64) -> Self {
        Self {
            crl_signers: CertificateStore::default(),
            evaluation_time,
            limits: RevocationLimits::default(),
            online_limits: OnlineLimits::default(),
        }
    }
}

/// Retrieve issuer-bound evidence after the caller authenticated the chain.
#[cfg(feature = "online")]
pub fn acquire_chain_revocation(
    path: CertificateStore<'_>,
    options: &AcquisitionOptions<'_>,
) -> Result<AcquiredRevocation> {
    let crl_signers = options.crl_signers;
    let now = options.evaluation_time;
    let limits = options.limits;
    let online = options.online_limits;
    use std::io::Read;
    use x509_cert::ext::pkix::{
        AuthorityInfoAccessSyntax, CrlDistributionPoints, FreshestCrl,
        name::{DistributionPointName, GeneralName},
    };
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
    enum Kind {
        Crl,
        Ocsp,
    }
    fn uris(points: &[x509_cert::ext::pkix::crl::dp::DistributionPoint]) -> Vec<String> {
        let mut out = Vec::new();
        for point in points {
            if let Some(DistributionPointName::FullName(names)) = &point.distribution_point {
                for name in names {
                    if let GeneralName::UniformResourceIdentifier(uri) = name {
                        out.push(uri.as_str().to_owned());
                    }
                }
            }
        }
        out
    }
    ensure!(
        path.len() <= limits.max_chain_certificates,
        Error::resource_limit("online chain limit")
    );
    ensure!(
        online.timeout_seconds > 0
            && online.timeout_seconds <= 120
            && online.max_requests <= 64
            && online.max_response_bytes <= limits.max_artifact_bytes,
        Error::configuration("invalid online limits")
    );
    ensure!(
        crl_signers.len() <= limits.max_chain_certificates.saturating_mul(16),
        Error::resource_limit("CRL signer candidate limit")
    );
    let path_der = path.iter().collect::<Vec<_>>();
    let path = path_der
        .iter()
        .map(|b| Certificate::from_der(b))
        .collect::<core::result::Result<Vec<_>, _>>()?;
    let signers = crl_signers
        .iter()
        .map(Certificate::from_der)
        .collect::<core::result::Result<Vec<_>, _>>()?;
    let client = reqwest::blocking::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .connect_timeout(std::time::Duration::from_secs(5))
        .build()
        .map_err(|error| Error::Io(format!("{error}")))?;
    let start = std::time::Instant::now();
    let deadline = std::time::Duration::from_secs(online.timeout_seconds);
    let mut output = AcquiredRevocation::default();
    let mut count = 0usize;
    let mut total = 0usize;
    let mut attempted = BTreeSet::new();
    for (position, pair) in path.windows(2).enumerate() {
        let cert = &pair[0];
        let issuer = &pair[1];
        let certificate_sha256 = hash(path_der[position])?;
        // (kind, url, source)
        let mut requests: Vec<(Kind, String, ArtifactSource)> = Vec::new();
        if let Some((_, points)) = cert.tbs_certificate.get::<CrlDistributionPoints>()? {
            ensure!(
                points.0.len() <= 64,
                Error::resource_limit("online distribution point limit")
            );
            requests.extend(
                uris(&points.0)
                    .into_iter()
                    .map(|u| (Kind::Crl, u, ArtifactSource::CrlDistributionPoint)),
            );
        }
        if let Some((_, points)) = cert.tbs_certificate.get::<FreshestCrl>()? {
            ensure!(
                points.0.len() <= 64,
                Error::resource_limit("online distribution point limit")
            );
            requests.extend(
                uris(&points.0)
                    .into_iter()
                    .map(|u| (Kind::Crl, u, ArtifactSource::FreshestCrl)),
            );
        }
        if let Some((_, access)) = cert.tbs_certificate.get::<AuthorityInfoAccessSyntax>()? {
            ensure!(
                access.0.len() <= 64,
                Error::resource_limit("online AIA limit")
            );
            for description in access.0 {
                if description.access_method.to_string() == "1.3.6.1.5.5.7.48.1"
                    && let GeneralName::UniformResourceIdentifier(uri) = description.access_location
                {
                    requests.push((
                        Kind::Ocsp,
                        uri.as_str().to_owned(),
                        ArtifactSource::AuthorityInfoAccess,
                    ));
                }
            }
        }
        let mut cursor = 0;
        while cursor < requests.len() {
            let (kind, url, source) = requests[cursor].clone();
            cursor += 1;
            if !attempted.insert((
                kind,
                url.clone(),
                cert.tbs_certificate.serial_number.as_bytes().to_vec(),
            )) {
                continue;
            }
            if count >= online.max_requests
                || start.elapsed() >= deadline
                || total >= online.max_total_bytes
            {
                output
                    .diagnostics
                    .push("online revocation request/time/total byte limit reached".into());
                return Ok(output);
            }
            let is_ocsp = kind == Kind::Ocsp;
            let result = (|| -> Result<(Vec<u8>, bool, Vec<String>)> {
                ensure!(
                    url.len() <= 8192,
                    Error::resource_limit("revocation URL length limit")
                );
                let parsed = reqwest::Url::parse(&url).map_err(Error::malformed)?;
                ensure!(
                    matches!(parsed.scheme(), "http" | "https")
                        && parsed.host_str().is_some()
                        && parsed.username().is_empty()
                        && parsed.password().is_none()
                        && parsed.fragment().is_none(),
                    Error::unsupported("unsupported revocation URL")
                );
                let timeout = deadline
                    .checked_sub(start.elapsed())
                    .ok_or_else(|| Error::resource_limit("online time limit"))?;
                let request = if is_ocsp {
                    client
                        .post(parsed)
                        .header("Content-Type", "application/ocsp-request")
                        .header("Accept", "application/ocsp-response")
                        .body(ocsp_request(cert, issuer)?)
                } else {
                    client.get(parsed)
                };
                let mut response = request
                    .timeout(timeout)
                    .send()
                    .map_err(|error| Error::Io(format!("{error}")))?
                    .error_for_status()
                    .map_err(|error| Error::Io(format!("{error}")))?;
                ensure!(
                    response.status().is_success(),
                    "revocation redirect or non-success status"
                );
                let remaining = online.max_total_bytes.saturating_sub(total);
                let response_limit = online.max_response_bytes.min(remaining);
                if let Some(length) = response.content_length() {
                    ensure!(
                        length <= response_limit as u64,
                        Error::resource_limit("revocation response declared byte limit")
                    );
                }
                let mut bytes = Vec::new();
                response
                    .by_ref()
                    .take(response_limit as u64 + 1)
                    .read_to_end(&mut bytes)?;
                total = total
                    .checked_add(bytes.len())
                    .ok_or_else(|| Error::resource_limit("online total overflow"))?;
                ensure!(
                    bytes.len() <= response_limit,
                    Error::resource_limit("revocation response byte limit")
                );
                ensure!(
                    total <= online.max_total_bytes,
                    Error::resource_limit("online response total byte limit")
                );
                if is_ocsp {
                    ensure!(
                        verify_ocsp(&bytes, cert, issuer, now, limits)?
                            != RevocationStatus::Unknown,
                        "online responder status unknown"
                    );
                    return Ok((bytes, false, Vec::new()));
                }
                // A CRL is accepted when authenticated and authorized for this
                // certificate. Completeness and freshness are decided later, so
                // delta and scoped CRLs are retained.
                let outcome = crl::evaluate(
                    &[&bytes],
                    cert,
                    &path[position + 1..],
                    &signers,
                    now,
                    limits,
                )?;
                ensure!(
                    !outcome.relevant.is_empty(),
                    "online CRL not authenticated for the certificate: {}",
                    outcome.diagnostics.join("; ")
                );
                let (is_delta, locations) = crl::locations(&bytes)?;
                Ok((bytes, is_delta, locations))
            })();
            count += 1;
            match result {
                Ok((bytes, is_delta, locations)) => {
                    output.provenance.push(ArtifactProvenance {
                        kind: if is_ocsp {
                            ArtifactKind::Ocsp
                        } else if is_delta {
                            ArtifactKind::DeltaCrl
                        } else {
                            ArtifactKind::Crl
                        },
                        origin: ArtifactOrigin::Online,
                        location: url,
                        sha256: hash(&bytes)?,
                        bytes: bytes.len(),
                        retrieved_at: Some(now),
                        certificate_sha256: Some(certificate_sha256.clone()),
                        source,
                    });
                    if is_ocsp {
                        output.ocsp_responses.push(bytes)
                    } else {
                        output.crls.push(bytes);
                        if requests.len() + locations.len() <= 256 {
                            requests.extend(
                                locations
                                    .into_iter()
                                    .map(|u| (Kind::Crl, u, ArtifactSource::FreshestCrl)),
                            );
                        }
                    }
                }
                Err(error) => output.diagnostics.push(format!(
                    "online {}: {error}",
                    if is_ocsp { "OCSP" } else { "CRL" }
                )),
            }
        }
    }
    Ok(output)
}
#[cfg(feature = "online")]
fn ocsp_request(certificate: &Certificate, issuer: &Certificate) -> Result<Vec<u8>> {
    use der::asn1::{Null, ObjectIdentifier, OctetString};
    let hash_oid = "1.3.14.3.2.26";
    let id = x509_ocsp::CertId {
        hash_algorithm: x509_cert::spki::AlgorithmIdentifierOwned {
            oid: ObjectIdentifier::new(hash_oid)?,
            parameters: Some(Null.into()),
        },
        issuer_name_hash: OctetString::new(crypto::digest(
            (hash_oid).parse().map_err(Error::malformed)?,
            &issuer.tbs_certificate.subject.to_der()?,
            &crypto::CryptoOptions { allow_sha1: true },
        )?)?,
        issuer_key_hash: OctetString::new(crypto::digest(
            (hash_oid).parse().map_err(Error::malformed)?,
            issuer
                .tbs_certificate
                .subject_public_key_info
                .subject_public_key
                .as_bytes()
                .context("unaligned issuer key")?,
            &crypto::CryptoOptions { allow_sha1: true },
        )?)?,
        serial_number: certificate.tbs_certificate.serial_number.clone(),
    };
    let request = x509_ocsp::OcspRequest {
        tbs_request: x509_ocsp::TbsRequest {
            version: Default::default(),
            requestor_name: None,
            request_list: vec![x509_ocsp::Request {
                req_cert: id,
                single_request_extensions: None,
            }],
            request_extensions: None,
        },
        optional_signature: None,
    };
    Ok(request.to_der()?)
}

/// Acquisition is unavailable unless the explicit `online` capability is enabled.
#[cfg(not(feature = "online"))]
pub fn acquire_chain_revocation(
    _path: CertificateStore<'_>,
    _options: &AcquisitionOptions<'_>,
) -> Result<AcquiredRevocation> {
    Err(Error::configuration(
        "online revocation acquisition requires the wintrust online feature",
    ))
}