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
//! RFC 5280 sections 5 and 6.3 CRL evaluation over an explicitly supplied set.
//!
//! Direct, indirect, scoped (issuing distribution point) and delta CRLs are
//! authenticated against the certificate's already validated issuer, or against
//! a CRL signing certificate that issuer directly issued. Status is `Good` only
//! when fresh, in-scope evidence covers every revocation reason; any
//! authenticated listing of the certificate is `Revoked` regardless of
//! freshness. Everything else is `Unknown`.
use super::{RevocationLimits, RevocationStatus, extensions_supported, fresh, verify_signature};
use crate::error::{Context, Error, Result, bail, ensure};
use alloc::{
    borrow::ToOwned,
    collections::BTreeSet,
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};
use core::cmp::Ordering;
use der::{Decode, Encode, asn1::Uint};
use x509_cert::{
    Certificate,
    crl::CertificateList,
    ext::pkix::{
        BasicConstraints, CrlDistributionPoints, KeyUsage, SubjectKeyIdentifier,
        crl::{CrlReason, IssuingDistributionPoint, dp::DistributionPoint},
        name::{DistributionPointName, GeneralName},
    },
    name::Name,
};

/// Reason bits 1 through 8 of ReasonFlags; bit 0 is `unused`.
pub(super) const ALL_REASONS: u16 = 0x1fe;
const OID_CRL_NUMBER: &str = "2.5.29.20";
const OID_DELTA_INDICATOR: &str = "2.5.29.27";
const OID_ISSUING_DISTRIBUTION_POINT: &str = "2.5.29.28";
const OID_CERTIFICATE_ISSUER: &str = "2.5.29.29";
const OID_AUTHORITY_KEY_IDENTIFIER: &str = "2.5.29.35";
const OID_CRL_REASON: &str = "2.5.29.21";

/// What evaluation of a CRL set established for one certificate.
#[derive(Debug)]
pub(super) struct CrlOutcome {
    pub status: RevocationStatus,
    /// Indices of CRLs that determined the status or contributed coverage.
    pub used: Vec<usize>,
    /// Indices of CRLs that authenticated and are bound to the certificate's issuer.
    #[cfg_attr(not(feature = "online"), allow(dead_code))]
    pub relevant: Vec<usize>,
    pub diagnostics: Vec<String>,
}

struct AuthenticatedCrl {
    list: CertificateList,
    crl_number: Option<Vec<u8>>,
    base_number: Option<Vec<u8>>,
    idp: Option<IssuingDistributionPoint>,
    idp_der: Option<Vec<u8>>,
    aki_der: Option<Vec<u8>>,
    this_update: u64,
    next_update: Option<u64>,
}

impl AuthenticatedCrl {
    fn is_delta(&self) -> bool {
        self.base_number.is_some()
    }
    fn issuer(&self) -> &Name {
        &self.list.tbs_cert_list.issuer
    }
}

fn number(value: &Uint) -> Vec<u8> {
    let bytes = value.as_bytes();
    let start = bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len());
    bytes[start..].to_vec()
}

fn compare_numbers(a: &[u8], b: &[u8]) -> Ordering {
    (a.len(), a).cmp(&(b.len(), b))
}

fn authority_matches(aki_der: &[u8], signer: &Certificate) -> Result<bool> {
    let aki = x509_cert::ext::pkix::AuthorityKeyIdentifier::from_der(aki_der)
        .map_err(Error::malformed)?;
    ensure!(
        aki.authority_cert_issuer.is_some() == aki.authority_cert_serial_number.is_some(),
        "CRL authority issuer/serial must appear together"
    );
    if let Some(names) = &aki.authority_cert_issuer
        && !(names.len() == 1
            && matches!(&names[0], GeneralName::DirectoryName(name) if *name == signer.tbs_certificate.issuer))
    {
        return Ok(false);
    }
    if let Some(key) = aki.key_identifier {
        let Some((_, ski)) = signer
            .tbs_certificate
            .get::<SubjectKeyIdentifier>()
            .map_err(Error::malformed)?
        else {
            return Ok(false);
        };
        if key != ski.0 {
            return Ok(false);
        }
    }
    if let Some(serial) = aki.authority_cert_serial_number
        && serial != signer.tbs_certificate.serial_number
    {
        return Ok(false);
    }
    Ok(true)
}

/// A CRL signing certificate other than the issuer must validate to the same
/// trust anchor as the certificate being checked (RFC 5280 6.3.3 (f)): full path
/// validation with time, constraints and policies, but no purpose requirement
/// beyond `cRLSign`. The signer's own revocation status is not evaluated.
fn authorize_signer(
    candidate: &Certificate,
    ancestry: &[Certificate],
    pool: &[Certificate],
    now: u64,
    limits: RevocationLimits,
) -> Result<()> {
    use super::super::chain;
    let anchor = ancestry.last().context("CRL signer path has no anchor")?;
    let mut intermediates = Vec::new();
    for certificate in ancestry[..ancestry.len() - 1].iter().chain(pool) {
        if certificate != candidate {
            intermediates.push(certificate.to_der().map_err(Error::malformed)?);
        }
    }
    let roots = [anchor.to_der().map_err(Error::malformed)?];
    let mut options = super::super::chain::ChainOptions::new(
        &roots,
        now,
        "2.5.29.37.0".parse().map_err(Error::malformed)?,
    );
    options.candidates = (&intermediates).into();
    options.allow_sha1 = limits.allow_sha1;
    options.path.crl_signer = true;
    chain::validate(&candidate.to_der().map_err(Error::malformed)?, &options)
        .map(drop)
        .context("CRL signer does not chain to the trust anchor")
}

fn authenticate(
    bytes: &[u8],
    ancestry: &[Certificate],
    signers: &[Certificate],
    now: u64,
    limits: RevocationLimits,
) -> Result<AuthenticatedCrl> {
    ensure!(
        bytes.len() <= limits.max_artifact_bytes,
        Error::resource_limit("CRL byte limit")
    );
    let issuer = ancestry.first().context("CRL certificate issuer missing")?;
    let list = CertificateList::from_der(bytes).map_err(Error::malformed)?;
    let tbs = &list.tbs_cert_list;
    ensure!(
        tbs.signature == list.signature_algorithm,
        Error::malformed("CRL signature algorithm mismatch")
    );
    let extensions = tbs.crl_extensions.as_deref();
    if extensions.is_some() {
        ensure!(
            tbs.version == x509_cert::certificate::Version::V2,
            "CRL extensions require a version 2 CRL"
        );
    }
    extensions_supported(
        extensions,
        &[OID_ISSUING_DISTRIBUTION_POINT, OID_DELTA_INDICATOR],
    )?;
    let mut crl_number = None;
    let mut base_number = None;
    let mut idp = None;
    let mut idp_der = None;
    let mut aki_der = None;
    for extension in extensions.unwrap_or_default() {
        let id = extension.extn_id.to_string();
        let value = extension.extn_value.as_bytes();
        match id.as_str() {
            OID_CRL_NUMBER => {
                ensure!(!extension.critical, "critical CRL number");
                crl_number = Some(number(&Uint::from_der(value).map_err(Error::malformed)?));
            }
            OID_DELTA_INDICATOR => {
                ensure!(extension.critical, "deltaCRLIndicator must be critical");
                base_number = Some(number(&Uint::from_der(value).map_err(Error::malformed)?));
            }
            OID_ISSUING_DISTRIBUTION_POINT => {
                ensure!(
                    extension.critical,
                    "issuingDistributionPoint must be critical"
                );
                let point = IssuingDistributionPoint::from_der(value).map_err(Error::malformed)?;
                ensure!(
                    u8::from(point.only_contains_user_certs)
                        + u8::from(point.only_contains_ca_certs)
                        + u8::from(point.only_contains_attribute_certs)
                        <= 1,
                    "conflicting issuingDistributionPoint scope flags"
                );
                idp = Some(point);
                idp_der = Some(value.to_vec());
            }
            OID_AUTHORITY_KEY_IDENTIFIER => aki_der = Some(value.to_vec()),
            _ => {}
        }
    }
    ensure!(
        base_number.is_none() || crl_number.is_some(),
        "delta CRL lacks a CRL number"
    );
    if let (Some(base), Some(this)) = (&base_number, &crl_number) {
        ensure!(
            compare_numbers(base, this) == Ordering::Less,
            "delta CRL base number is not below its own number"
        );
    }
    let signature = list
        .signature
        .as_bytes()
        .context("unaligned CRL signature")?;
    let message = tbs.to_der().map_err(Error::malformed)?;
    let algorithm = list
        .signature_algorithm
        .to_der()
        .map_err(Error::malformed)?;
    let mut last_error = Error::signature("no CRL signing certificate for the CRL issuer");
    for (position, candidate) in core::iter::once(issuer).chain(signers).enumerate() {
        if candidate.tbs_certificate.subject != tbs.issuer {
            continue;
        }
        let attempt = (|| -> Result<()> {
            let usage = candidate
                .tbs_certificate
                .get::<KeyUsage>()
                .map_err(Error::malformed)?
                .ok_or_else(|| Error::policy("CRL signer keyUsage missing"))?;
            ensure!(usage.1.crl_sign(), "CRL signer lacks cRLSign usage");
            if position > 0 && candidate != issuer {
                authorize_signer(candidate, ancestry, signers, now, limits)?;
            }
            if let Some(aki) = &aki_der {
                ensure!(
                    authority_matches(aki, candidate)?,
                    Error::malformed("CRL authority key identifier mismatch")
                );
            }
            verify_signature(
                candidate,
                &algorithm,
                &message,
                signature,
                limits.allow_sha1,
            )
        })();
        match attempt {
            Ok(()) => {
                let this_update = tbs.this_update.to_unix_duration().as_secs();
                let next_update = tbs.next_update.map(|t| t.to_unix_duration().as_secs());
                return Ok(AuthenticatedCrl {
                    list,
                    crl_number,
                    base_number,
                    idp,
                    idp_der,
                    aki_der,
                    this_update,
                    next_update,
                });
            }
            Err(error) => last_error = error,
        }
    }
    Err(last_error)
}

#[derive(Clone, Copy)]
struct Listing {
    reason: CrlReason,
}

impl Listing {
    fn revokes(self) -> bool {
        self.reason != CrlReason::RemoveFromCRL
    }
}

/// Find the entry for `certificate`, tracking `certificateIssuer` through indirect CRLs.
fn lookup(
    crl: &AuthenticatedCrl,
    certificate: &Certificate,
    now: u64,
    limits: RevocationLimits,
) -> Result<Option<Listing>> {
    let entries = crl
        .list
        .tbs_cert_list
        .revoked_certificates
        .as_deref()
        .unwrap_or_default();
    ensure!(
        entries.len() <= limits.max_entries,
        Error::resource_limit("CRL entry limit")
    );
    let indirect = crl.idp.as_ref().is_some_and(|idp| idp.indirect_crl);
    let mut current_issuer = crl.issuer().clone();
    let mut seen = BTreeSet::new();
    let mut found = None;
    for entry in entries {
        let extensions = entry.crl_entry_extensions.as_deref();
        extensions_supported(extensions, &[OID_CERTIFICATE_ISSUER])?;
        let mut reason = CrlReason::Unspecified;
        for extension in extensions.unwrap_or_default() {
            match extension.extn_id.to_string().as_str() {
                OID_CERTIFICATE_ISSUER => {
                    ensure!(indirect, "certificateIssuer in a CRL that is not indirect");
                    ensure!(extension.critical, "certificateIssuer must be critical");
                    let names = Vec::<GeneralName>::from_der(extension.extn_value.as_bytes())
                        .map_err(Error::malformed)?;
                    match names.as_slice() {
                        [GeneralName::DirectoryName(name)] => current_issuer = name.clone(),
                        _ => bail!(Error::unsupported("unsupported certificateIssuer form")),
                    }
                }
                OID_CRL_REASON => {
                    ensure!(!extension.critical, "critical CRL reason code");
                    reason = CrlReason::from_der(extension.extn_value.as_bytes())
                        .map_err(Error::malformed)?;
                }
                _ => {}
            }
        }
        ensure!(
            seen.insert((
                current_issuer.to_der().map_err(Error::malformed)?,
                entry.serial_number.as_bytes().to_vec()
            )),
            Error::malformed("duplicate CRL serial")
        );
        ensure!(
            entry.revocation_date.to_unix_duration().as_secs() <= now,
            "CRL revocation date is future"
        );
        if entry.serial_number == certificate.tbs_certificate.serial_number
            && current_issuer == certificate.tbs_certificate.issuer
        {
            found = Some(Listing { reason });
        }
    }
    Ok(found)
}

fn bits(flags: x509_cert::ext::pkix::crl::dp::ReasonFlags) -> u16 {
    flags.bits() & ALL_REASONS
}

/// RFC 5280 6.3.3: the CRL issuer must be the certificate issuer, or the
/// `cRLIssuer` the distribution point names for an indirect CRL.
fn bound(crl: &AuthenticatedCrl, certificate: &Certificate, point: &DistributionPoint) -> bool {
    let issuer = crl.issuer();
    match &point.crl_issuer {
        Some(names) => {
            names
                .iter()
                .any(|n| matches!(n, GeneralName::DirectoryName(name) if name == issuer))
                && (*issuer == certificate.tbs_certificate.issuer
                    || crl.idp.as_ref().is_some_and(|idp| idp.indirect_crl))
        }
        None => *issuer == certificate.tbs_certificate.issuer,
    }
}

/// Names a distribution point name denotes. A relative name extends `base`
/// (the issuer of the CRL it appears in or the `cRLIssuer` it is relative to).
fn full_names(name: &DistributionPointName, base: &Name) -> Vec<GeneralName> {
    match name {
        DistributionPointName::FullName(names) => names.clone(),
        DistributionPointName::NameRelativeToCRLIssuer(rdn) => {
            let mut full = base.clone();
            full.0.push(rdn.clone());
            vec![GeneralName::DirectoryName(full)]
        }
    }
}

/// Reasons this CRL covers for `certificate` under distribution point `point`,
/// or `None` when the CRL's scope excludes the certificate.
fn scope(
    crl: &AuthenticatedCrl,
    certificate: &Certificate,
    is_ca: bool,
    point: &DistributionPoint,
) -> Option<u16> {
    let mut mask = ALL_REASONS;
    if let Some(reasons) = point.reasons {
        mask &= bits(reasons);
    }
    if let Some(idp) = &crl.idp {
        if let Some(name) = &idp.distribution_point {
            let issuer = crl.issuer();
            let idp_names = full_names(name, issuer);
            let responsible = point.crl_issuer.as_ref();
            let matches = match &point.distribution_point {
                Some(point_name) => {
                    let base = responsible
                        .and_then(|names| {
                            names.iter().find_map(|n| match n {
                                GeneralName::DirectoryName(x) => Some(x),
                                _ => None,
                            })
                        })
                        .unwrap_or(&certificate.tbs_certificate.issuer);
                    let point_names = full_names(point_name, base);
                    idp_names.iter().any(|n| point_names.contains(n))
                        || responsible.is_some_and(|names| {
                            names
                                .iter()
                                .any(|n| matches!(n, GeneralName::DirectoryName(x) if x == issuer))
                        })
                }
                None => {
                    responsible.is_some_and(|names| idp_names.iter().any(|n| names.contains(n)))
                }
            };
            if !matches {
                return None;
            }
        }
        if idp.only_contains_user_certs && is_ca {
            return None;
        }
        if idp.only_contains_ca_certs && !is_ca {
            return None;
        }
        if idp.only_contains_attribute_certs {
            return None;
        }
        if let Some(reasons) = idp.only_some_reasons {
            mask &= bits(reasons);
        }
    }
    (mask != 0).then_some(mask)
}

fn delta_applies(delta: &AuthenticatedCrl, base: &AuthenticatedCrl) -> bool {
    match (
        &delta.base_number,
        &delta.crl_number,
        &base.crl_number,
        base.is_delta(),
    ) {
        (Some(base_number), Some(delta_number), Some(number), false) => {
            delta.issuer() == base.issuer()
                && delta.idp_der == base.idp_der
                && delta.aki_der == base.aki_der
                && compare_numbers(base_number, number) != Ordering::Greater
                && compare_numbers(delta_number, number) == Ordering::Greater
        }
        _ => false,
    }
}

/// A view whose freshness was checked for this evaluation's clock and policy.
struct FreshCrl<'a> {
    crl: &'a AuthenticatedCrl,
    now: u64,
    limits: RevocationLimits,
}

impl<'a> FreshCrl<'a> {
    fn new(crl: &'a AuthenticatedCrl, now: u64, limits: RevocationLimits) -> Result<Self> {
        fresh(crl.this_update, crl.next_update, now, limits)?;
        Ok(Self { crl, now, limits })
    }

    // Lookup uses this same checked artifact, so a caller cannot accidentally
    // combine freshness from one delta with a removal entry from another.
    fn releases_hold(&self, certificate: &Certificate) -> Result<bool> {
        ensure!(
            self.crl.is_delta(),
            "only a delta CRL can release certificateHold"
        );
        Ok(lookup(self.crl, certificate, self.now, self.limits)?
            .is_some_and(|entry| !entry.revokes()))
    }
}

/// Evaluate `crls` for `certificate`. `ancestry` runs from its already validated
/// issuer up to the trust anchor.
/// `signers` are candidate CRL signing certificates and are authenticated here.
pub(super) fn evaluate(
    crls: &[&[u8]],
    certificate: &Certificate,
    ancestry: &[Certificate],
    signers: &[Certificate],
    now: u64,
    limits: RevocationLimits,
) -> Result<CrlOutcome> {
    let issuer = ancestry.first().context("CRL certificate issuer missing")?;
    ensure!(
        certificate.tbs_certificate.issuer == issuer.tbs_certificate.subject,
        Error::malformed("CRL certificate issuer mismatch")
    );
    let mut diagnostics = Vec::new();
    let mut parsed = Vec::new();
    for (index, bytes) in crls.iter().enumerate() {
        match authenticate(bytes, ancestry, signers, now, limits) {
            Ok(crl) => parsed.push((index, crl)),
            Err(error) => diagnostics.push(format!("CRL {index}: {error:#}")),
        }
    }
    let points = match certificate
        .tbs_certificate
        .get::<CrlDistributionPoints>()
        .map_err(Error::malformed)?
    {
        Some((_, points)) => {
            ensure!(
                !points.0.is_empty() && points.0.len() <= 64,
                "CRL distribution point count"
            );
            points.0
        }
        None => vec![DistributionPoint {
            distribution_point: None,
            reasons: None,
            crl_issuer: None,
        }],
    };
    let is_ca = certificate
        .tbs_certificate
        .get::<BasicConstraints>()
        .map_err(Error::malformed)?
        .is_some_and(|(_, constraints)| constraints.ca);
    // Per-CRL: whether it is bound to the issuer and the reasons it covers.
    let mut bindings = Vec::new();
    for (index, crl) in &parsed {
        let mut is_bound = false;
        let mut mask = 0u16;
        for point in &points {
            if bound(crl, certificate, point) {
                is_bound = true;
                if let Some(covered) = scope(crl, certificate, is_ca, point) {
                    mask |= covered;
                }
            }
        }
        if !is_bound {
            diagnostics.push(format!(
                "CRL {index}: issuer is not authorized for the certificate"
            ));
        }
        bindings.push((is_bound, mask));
    }
    let relevant = parsed
        .iter()
        .zip(&bindings)
        .filter(|(_, (is_bound, _))| *is_bound)
        .map(|((index, _), _)| *index)
        .collect::<Vec<_>>();
    let mut used = BTreeSet::new();
    let mut revoked = false;
    let mut coverage = 0u16;
    for (position, (index, crl)) in parsed.iter().enumerate() {
        let (is_bound, mask) = bindings[position];
        if !is_bound {
            continue;
        }
        let listing = lookup(crl, certificate, now, limits);
        let listing = match listing {
            Ok(listing) => listing,
            Err(error) => {
                diagnostics.push(format!("CRL {index}: {error:#}"));
                continue;
            }
        };
        if crl.is_delta() {
            // A delta listing is authentic revocation even without its base.
            if listing.is_some_and(Listing::revokes) {
                revoked = true;
                used.insert(*index);
            }
            continue;
        }
        // Newest applicable delta supersedes older deltas on the same base.
        let latest = parsed
            .iter()
            .enumerate()
            .filter(|(p, (_, delta))| bindings[*p].0 && delta_applies(delta, crl))
            .max_by(|(_, (_, a)), (_, (_, b))| {
                compare_numbers(
                    a.crl_number.as_deref().unwrap_or_default(),
                    b.crl_number.as_deref().unwrap_or_default(),
                )
            });
        let mut effective = listing;
        let mut fresh_delta = None;
        if let Some((_, (delta_index, delta))) = latest {
            fresh_delta = match FreshCrl::new(delta, now, limits) {
                Ok(fresh) => Some(fresh),
                Err(error) => {
                    diagnostics.push(format!("CRL {delta_index}: {error:#}"));
                    None
                }
            };
            match lookup(delta, certificate, now, limits) {
                Ok(Some(entry)) if entry.revokes() => effective = Some(entry),
                Ok(Some(_)) => {
                    // removeFromCRL only releases a certificate on hold.
                    // Stale/future evidence may revoke, but cannot prove release.
                    if effective.is_some_and(|l| l.reason == CrlReason::CertificateHold)
                        && fresh_delta
                            .as_ref()
                            .map(|fresh| fresh.releases_hold(certificate))
                            .transpose()?
                            .unwrap_or(false)
                    {
                        effective = None;
                    }
                }
                Ok(None) => {}
                Err(error) => {
                    diagnostics.push(format!("CRL {delta_index}: {error:#}"));
                    continue;
                }
            }
            used.insert(*delta_index);
        }
        if effective.is_some_and(Listing::revokes) {
            revoked = true;
            used.insert(*index);
            continue;
        }
        let base_fresh = match FreshCrl::new(crl, now, limits) {
            Ok(_) => true,
            Err(error) => {
                diagnostics.push(format!("CRL {index}: {error:#}"));
                false
            }
        };
        if (base_fresh || fresh_delta.is_some()) && mask != 0 {
            coverage |= mask;
            used.insert(*index);
        }
    }
    let status = if revoked {
        RevocationStatus::Revoked
    } else if coverage == ALL_REASONS {
        RevocationStatus::Good
    } else {
        if coverage != 0 {
            diagnostics.push(format!(
                "CRL coverage {coverage:#05x} does not include every revocation reason"
            ));
        }
        RevocationStatus::Unknown
    };
    Ok(CrlOutcome {
        status,
        used: used.into_iter().collect(),
        relevant,
        diagnostics,
    })
}

/// Whether `bytes` is a delta CRL and the `freshestCRL` URIs it advertises.
/// Parsing only: nothing here authenticates the CRL.
pub(super) fn locations(bytes: &[u8]) -> Result<(bool, Vec<String>)> {
    use x509_cert::ext::pkix::FreshestCrl;
    let list = CertificateList::from_der(bytes).map_err(Error::malformed)?;
    let mut delta = false;
    let mut out = Vec::new();
    for extension in list.tbs_cert_list.crl_extensions.iter().flatten() {
        match extension.extn_id.to_string().as_str() {
            OID_DELTA_INDICATOR => delta = true,
            "2.5.29.46" => {
                let points = FreshestCrl::from_der(extension.extn_value.as_bytes())
                    .map_err(Error::malformed)?;
                ensure!(points.0.len() <= 64, "freshestCRL point count");
                for point in &points.0 {
                    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());
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
    Ok((delta, out))
}