utility-pki 0.1.0

TLS and certificate profiles of the German energy sector (BDEW AS4, BSI TR-03116-3, BSI TR-02102-2) as Rust data: check sessions, SM-PKI certificates and OpenSSL configurations
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
//! Certificate checks: read a DER certificate once, then check it against any profile.
//!
//! ```
//! # fn main() -> Result<(), utility_pki::x509::ParseError> {
//! use utility_pki::profiles::BDEW_AS4;
//! use utility_pki::x509::Certificate;
//!
//! # let der = include_bytes!("../../tests/data/as4_ok.der");
//! let cert = Certificate::from_der(der)?;
//! let report = BDEW_AS4.check_certificate(&cert);
//! for v in report.violations() {
//!     eprintln!("{v}");
//! }
//! assert!(report.is_ok());
//! assert_eq!(cert.mp_id(), Some("9900000000003"));
//! # Ok(()) }
//! ```
//!
//! The reader is strict DER and needs no allocator. It judges the certificate's content
//! only: it does not verify signatures, build chains or fetch CRLs. That is your PKI
//! stack's job.

mod der;

use core::fmt;

pub use der::ParseError;
use der::{Reader, Result, Tlv};

use crate::cert::{CertSignature, ExtendedKeyUsage, Extension, KeyUsage};
use crate::profile::{Allowed, Curve, Profile, PublicKey};

const ID_EC_PUBLIC_KEY: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01];
const RSA_ENCRYPTION: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01];
const RSASSA_PSS: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0A];
const ED25519: &[u8] = &[0x2B, 0x65, 0x70];
const SHA256: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];
const SHA384: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02];
const SHA512: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03];
const AT_CN: &[u8] = &[0x55, 0x04, 0x03];
const AT_O: &[u8] = &[0x55, 0x04, 0x0A];
const AT_OU: &[u8] = &[0x55, 0x04, 0x0B];

/// An object identifier borrowed from a certificate. `Display` prints its name when the
/// crate knows it, and the dotted form otherwise.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Oid<'a>(&'a [u8]);

impl<'a> Oid<'a> {
    /// The DER content bytes.
    pub const fn as_bytes(&self) -> &'a [u8] {
        self.0
    }

    fn write_name(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        const NAMES: &[(&[u8], &str)] = &[
            (ID_EC_PUBLIC_KEY, "id-ecPublicKey"),
            (RSA_ENCRYPTION, "rsaEncryption"),
            (RSASSA_PSS, "RSASSA-PSS"),
            (&[0x2B, 0x81, 0x04, 0x00, 0x0A], "secp256k1"),
        ];
        if let Some(e) = Extension::from_oid(self.0) {
            write!(f, " ({e})")
        } else if let Some(e) = ExtendedKeyUsage::from_oid(self.0) {
            write!(f, " ({e})")
        } else if let Some((_, n)) = NAMES.iter().find(|(o, _)| *o == self.0) {
            write!(f, " ({n})")
        } else {
            Ok(())
        }
    }
}

impl fmt::Display for Oid<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut arcs = self.0.iter();
        let mut value: u64 = 0;
        let mut first = true;
        let mut overflow = false;
        for &b in arcs.by_ref() {
            overflow |= value > (u64::MAX >> 7);
            value = (value << 7) | u64::from(b & 0x7F);
            if b & 0x80 != 0 {
                continue;
            }
            if first {
                let (a, b) = match value {
                    0..=39 => (0, value),
                    40..=79 => (1, value - 40),
                    _ => (2, value - 80),
                };
                write!(f, "{a}.{b}")?;
                first = false;
            } else {
                write!(f, ".{value}")?;
            }
            value = 0;
        }
        if overflow {
            f.write_str("(overflow)")?;
        }
        self.write_name(f)
    }
}

/// One extension as it appears in the certificate.
#[derive(Clone, Copy, Debug)]
struct Ext<'a> {
    oid: &'a [u8],
    critical: bool,
}

/// A parsed X.509 certificate. Every accessor is infallible: `from_der` has validated
/// everything they read.
#[derive(Clone, Copy, Debug)]
pub struct Certificate<'a> {
    version: u8,
    serial: &'a [u8],
    sig_oid: &'a [u8],
    sig_params: Option<Tlv<'a>>,
    not_before: i64,
    not_after: i64,
    subject: Tlv<'a>,
    key_alg: &'a [u8],
    key_params: Option<Tlv<'a>>,
    key: &'a [u8],
    extensions: Option<Tlv<'a>>,
    key_usage: Option<u16>,
    is_ca: bool,
    eku: Option<Tlv<'a>>,
    san: Option<Tlv<'a>>,
}

impl<'a> Certificate<'a> {
    /// Reads exactly one DER-encoded X.509 certificate.
    ///
    /// # Errors
    ///
    /// [`ParseError`] if `der` is not exactly one strict-DER certificate (BER, trailing
    /// bytes, non-minimal lengths, a time not in Zulu form, an attribute string type other
    /// than UTF8String, PrintableString or IA5String, or a malformed KeyUsage,
    /// BasicConstraints, ExtendedKeyUsage or SubjectAltName).
    pub fn from_der(der: &'a [u8]) -> Result<Self> {
        let mut top = Reader::new(der);
        let cert = top.read(der::SEQUENCE, "expected a Certificate SEQUENCE")?;
        top.finish("trailing data after the certificate")?;
        let mut outer = cert.reader();
        let tbs = outer.read(der::SEQUENCE, "expected TBSCertificate")?;
        let (sig_oid, sig_params) = algorithm(&mut outer, "expected signatureAlgorithm")?;
        der::bit_string(&outer.read(der::BIT_STRING, "expected signatureValue")?)?;
        outer.finish("trailing data in Certificate")?;

        let mut fields = tbs.reader();
        let version = match fields.optional(0xA0)? {
            None => 1,
            Some(explicit) => {
                let mut version_field = explicit.reader();
                let int = version_field.read(der::INTEGER, "expected version INTEGER")?;
                version_field.finish("trailing data in version")?;
                match der::integer(&int)? {
                    [1] => 2,
                    [2] => 3,
                    _ => return Err(int.err("version must be v2 or v3 when present (DER omits v1)")),
                }
            }
        };
        let serial = der::integer(&fields.read(der::INTEGER, "expected serialNumber")?)?;
        let (inner_oid, inner_params) = algorithm(&mut fields, "expected signature AlgorithmIdentifier")?;
        // RFC 5280 §4.1.1.2: both fields MUST be the same.
        if inner_oid != sig_oid || inner_params.map(|p| p.content) != sig_params.map(|p| p.content) {
            return Err(ParseError::new(
                tbs.offset,
                "signature algorithms in TBSCertificate and Certificate differ",
            ));
        }
        fields.read(der::SEQUENCE, "expected issuer Name")?;
        let validity = fields.read(der::SEQUENCE, "expected Validity")?;
        let mut times = validity.reader();
        let not_before = der::time(&times.any()?)?;
        let not_after = der::time(&times.any()?)?;
        times.finish("trailing data in Validity")?;
        let subject = fields.read(der::SEQUENCE, "expected subject Name")?;
        validate_name(&subject)?;
        let spki = fields.read(der::SEQUENCE, "expected SubjectPublicKeyInfo")?;
        let mut spki_fields = spki.reader();
        let (key_alg, key_params) = algorithm(&mut spki_fields, "expected public key AlgorithmIdentifier")?;
        let (key, _) = der::bit_string(&spki_fields.read(der::BIT_STRING, "expected subjectPublicKey")?)?;
        spki_fields.finish("trailing data in SubjectPublicKeyInfo")?;
        fields.optional(0x81)?;
        fields.optional(0x82)?;
        let extensions = match fields.optional(0xA3)? {
            None => None,
            Some(explicit) => {
                let mut list_field = explicit.reader();
                let list = list_field.read(der::SEQUENCE, "expected Extensions SEQUENCE")?;
                list_field.finish("trailing data in extensions")?;
                if list.content.is_empty() {
                    return Err(list.err("empty Extensions"));
                }
                Some(list)
            }
        };
        fields.finish("trailing data in TBSCertificate")?;

        let mut cert = Self {
            version,
            serial,
            sig_oid,
            sig_params,
            not_before,
            not_after,
            subject,
            key_alg,
            key_params,
            key,
            extensions,
            key_usage: None,
            is_ca: false,
            eku: None,
            san: None,
        };
        cert.read_extensions()?;
        Ok(cert)
    }

    fn read_extensions(&mut self) -> Result<()> {
        let Some(list) = self.extensions else { return Ok(()) };
        let mut r = list.reader();
        while !r.is_empty() {
            let ext = r.read(der::SEQUENCE, "expected Extension")?;
            let mut e = ext.reader();
            let oid = der::oid(&e.read(der::OID, "expected extnID")?)?;
            if let Some(c) = e.optional(der::BOOLEAN)? {
                if !der::boolean(&c)? {
                    return Err(c.err("critical FALSE must be omitted in DER"));
                }
            }
            let value = e.read(der::OCTET_STRING, "expected extnValue")?;
            e.finish("trailing data in Extension")?;
            let mut v = value.reader();
            let inner = v.any()?;
            v.finish("trailing data in extension value")?;
            match Extension::from_oid(oid) {
                Some(Extension::KeyUsage) if self.key_usage.is_none() => {
                    self.key_usage = Some(key_usage(&inner)?);
                }
                Some(Extension::BasicConstraints) if !self.is_ca => self.is_ca = basic_constraints(&inner)?,
                Some(Extension::ExtendedKeyUsage) if self.eku.is_none() => {
                    self.eku = Some(seq_of(&inner, der::OID, "malformed ExtendedKeyUsage")?);
                }
                Some(Extension::SubjectAltName) if self.san.is_none() => {
                    self.san = Some(general_names(&inner)?);
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn exts(&self) -> impl Iterator<Item = Ext<'a>> + 'a {
        let mut r = self.extensions.map_or(Reader::new(&[]), |l| l.reader());
        core::iter::from_fn(move || {
            let ext = r.any().ok()?;
            let mut e = ext.reader();
            let oid = e.any().ok()?.content;
            let critical = e.peek_tag() == Some(der::BOOLEAN);
            Some(Ext { oid, critical })
        })
    }

    fn has(&self, ext: Extension) -> bool {
        self.exts().any(|e| e.oid == ext.oid())
    }

    /// The X.509 version: 1, 2 or 3.
    pub const fn version(&self) -> u8 {
        self.version
    }

    /// The certificate's public key, or `None` for a key type or curve this crate does not
    /// know, or an EC key with explicit parameters.
    pub fn public_key(&self) -> Option<PublicKey> {
        match self.key_alg {
            ID_EC_PUBLIC_KEY => {
                let p = self.key_params?;
                let curve = (p.tag == der::OID).then(|| Curve::from_oid(p.content)).flatten()?;
                ec_point_fits(curve, self.key).then_some(PublicKey::Ec(curve))
            }
            // rsaEncryption carries NULL parameters (RFC 3279 §2.3.1); RSASSA-PSS keys may
            // carry PSS parameters.
            RSA_ENCRYPTION
                if !self.key_params.is_some_and(|p| p.tag == der::NULL && p.content.is_empty()) =>
            {
                None
            }
            RSA_ENCRYPTION | RSASSA_PSS => rsa_bits(self.key).map(PublicKey::Rsa),
            ED25519 if self.key_params.is_none() && self.key.len() == 32 => Some(PublicKey::Ed25519),
            _ => None,
        }
    }

    /// The issuer's signature algorithm, or `None` if this crate does not know it.
    pub fn signature(&self) -> Option<CertSignature> {
        let p = self.sig_params;
        let absent = p.is_none();
        let null_or_absent = p.is_none_or(|p| p.tag == der::NULL && p.content.is_empty());
        match self.sig_oid {
            [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, n @ 0x02..=0x04] if absent => Some(match n {
                0x02 => CertSignature::EcdsaSha256,
                0x03 => CertSignature::EcdsaSha384,
                _ => CertSignature::EcdsaSha512,
            }),
            [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, n @ 0x0B..=0x0D] if null_or_absent => {
                Some(match n {
                    0x0B => CertSignature::RsaPkcs1Sha256,
                    0x0C => CertSignature::RsaPkcs1Sha384,
                    _ => CertSignature::RsaPkcs1Sha512,
                })
            }
            RSASSA_PSS => match pss_hash(p?)? {
                SHA256 => Some(CertSignature::RsaPssSha256),
                SHA384 => Some(CertSignature::RsaPssSha384),
                SHA512 => Some(CertSignature::RsaPssSha512),
                _ => None,
            },
            ED25519 if absent => Some(CertSignature::Ed25519),
            _ => None,
        }
    }

    /// notAfter − notBefore in whole days, rounded up; 0 if notAfter is before notBefore.
    pub fn validity_days(&self) -> u32 {
        let secs = self.not_after.saturating_sub(self.not_before).max(0);
        u32::try_from((secs + 86_399) / 86_400).unwrap_or(u32::MAX)
    }

    /// notBefore and notAfter, in seconds since 1970-01-01T00:00:00Z.
    pub const fn validity(&self) -> (i64, i64) {
        (self.not_before, self.not_after)
    }

    fn attributes(&self, ty: &'static [u8]) -> impl Iterator<Item = &'a str> + 'a {
        let mut rdns = self.subject.reader();
        let mut atvs = Reader::new(&[]);
        core::iter::from_fn(move || {
            loop {
                if atvs.is_empty() {
                    atvs = rdns.any().ok()?.reader();
                }
                let atv = atvs.any().ok()?;
                let mut a = atv.reader();
                let oid = a.any().ok()?.content;
                if oid == ty {
                    return der::string(&a.any().ok()?).ok();
                }
            }
        })
    }

    fn single(&self, ty: &'static [u8]) -> Option<&'a str> {
        let mut it = self.attributes(ty);
        let first = it.next()?;
        it.next().is_none().then_some(first)
    }

    /// The market partner ID: the subject's organisational unit (OU), only if there is
    /// exactly one (CP SM-PKI Tab. 23). Compare it with the AS4 PartyId.
    pub fn mp_id(&self) -> Option<&'a str> {
        self.single(AT_OU)
    }

    /// The subject's organisation (O), if there is exactly one.
    pub fn organization(&self) -> Option<&'a str> {
        self.single(AT_O)
    }

    /// The subject's common name (CN), if there is exactly one.
    pub fn common_name(&self) -> Option<&'a str> {
        self.single(AT_CN)
    }

    fn names(&self, tag: u8) -> impl Iterator<Item = &'a str> + 'a {
        let mut r = self.san.map_or(Reader::new(&[]), |s| s.reader());
        core::iter::from_fn(move || {
            loop {
                let gn = r.any().ok()?;
                if gn.tag == tag {
                    return core::str::from_utf8(gn.content).ok();
                }
            }
        })
    }

    /// The SubjectAltName dNSName entries.
    pub fn dns_names(&self) -> impl Iterator<Item = &'a str> + 'a {
        self.names(0x82)
    }

    /// The SubjectAltName uniformResourceIdentifier entries.
    pub fn uris(&self) -> impl Iterator<Item = &'a str> + 'a {
        self.names(0x86)
    }

    /// The AS4 endpoint: the SubjectAltName URI, only if there is exactly one (RzÜ AS4 §5.2).
    pub fn endpoint_uri(&self) -> Option<&'a str> {
        let mut it = self.uris();
        let first = it.next()?;
        it.next().is_none().then_some(first)
    }

    /// Whether BasicConstraints says cA = TRUE.
    pub const fn is_ca(&self) -> bool {
        self.is_ca
    }

    /// Whether the KeyUsage extension has this bit set.
    pub fn has_key_usage(&self, usage: KeyUsage) -> bool {
        self.key_usage.is_some_and(|bits| bits & (1 << usage.bit()) != 0)
    }

    fn eku_oids(&self) -> impl Iterator<Item = &'a [u8]> + 'a {
        let mut r = self.eku.map_or(Reader::new(&[]), |e| e.reader());
        core::iter::from_fn(move || r.any().ok().map(|t| t.content))
    }

    /// Whether the ExtendedKeyUsage extension lists this purpose.
    pub fn has_extended_key_usage(&self, purpose: ExtendedKeyUsage) -> bool {
        self.eku_oids().any(|o| o == purpose.oid())
    }
}

fn algorithm<'a>(r: &mut Reader<'a>, what: &'static str) -> Result<(&'a [u8], Option<Tlv<'a>>)> {
    let seq = r.read(der::SEQUENCE, what)?;
    let mut a = seq.reader();
    let oid = der::oid(&a.read(der::OID, "expected algorithm OID")?)?;
    let params = if a.is_empty() { None } else { Some(a.any()?) };
    a.finish("trailing data in AlgorithmIdentifier")?;
    Ok((oid, params))
}

fn validate_name(name: &Tlv<'_>) -> Result<()> {
    let mut rdns = name.reader();
    while !rdns.is_empty() {
        let rdn = rdns.read(der::SET, "expected RelativeDistinguishedName SET")?;
        let mut atvs = rdn.reader();
        if atvs.is_empty() {
            return Err(rdn.err("empty RelativeDistinguishedName"));
        }
        while !atvs.is_empty() {
            let atv = atvs.read(der::SEQUENCE, "expected AttributeTypeAndValue")?;
            let mut a = atv.reader();
            let oid = der::oid(&a.read(der::OID, "expected attribute type")?)?;
            let value = a.any()?;
            a.finish("trailing data in AttributeTypeAndValue")?;
            if [AT_CN, AT_O, AT_OU].contains(&oid) {
                der::string(&value)?;
            }
        }
    }
    Ok(())
}

fn key_usage(inner: &Tlv<'_>) -> Result<u16> {
    if inner.tag != der::BIT_STRING {
        return Err(inner.err("malformed KeyUsage"));
    }
    let (bits, unused) = der::bit_string(inner)?;
    // DER named-bit list (X.690 §11.2.2): no trailing zero bits, so the last used bit is set.
    let last_used = bits.last().is_some_and(|&b| b & (1 << unused) != 0);
    if bits.len() > 2 || !last_used {
        return Err(inner.err("KeyUsage is not a DER named-bit list"));
    }
    // Bit n of the BIT STRING (MSB first) becomes bit n of the result.
    let mut out = 0u16;
    for (i, &byte) in bits.iter().enumerate() {
        for j in 0..8 {
            if byte & (0x80 >> j) != 0 {
                out |= 1 << (i * 8 + j);
            }
        }
    }
    Ok(out)
}

fn basic_constraints(inner: &Tlv<'_>) -> Result<bool> {
    if inner.tag != der::SEQUENCE {
        return Err(inner.err("malformed BasicConstraints"));
    }
    let mut r = inner.reader();
    let ca = match r.optional(der::BOOLEAN)? {
        Some(b) if der::boolean(&b)? => true,
        Some(b) => return Err(b.err("cA FALSE must be omitted in DER")),
        None => false,
    };
    if let Some(p) = r.optional(der::INTEGER)? {
        der::integer(&p)?;
    }
    r.finish("trailing data in BasicConstraints")?;
    Ok(ca)
}

fn seq_of<'a>(inner: &Tlv<'a>, tag: u8, what: &'static str) -> Result<Tlv<'a>> {
    if inner.tag != der::SEQUENCE || inner.content.is_empty() {
        return Err(inner.err(what));
    }
    let mut r = inner.reader();
    while !r.is_empty() {
        let item = r.read(tag, what)?;
        if tag == der::OID {
            der::oid(&item)?;
        }
    }
    Ok(*inner)
}

fn general_names<'a>(inner: &Tlv<'a>) -> Result<Tlv<'a>> {
    if inner.tag != der::SEQUENCE || inner.content.is_empty() {
        return Err(inner.err("malformed SubjectAltName"));
    }
    let mut r = inner.reader();
    while !r.is_empty() {
        let gn = r.any()?;
        match gn.tag {
            // rfc822Name, dNSName, uniformResourceIdentifier: IA5String.
            0x81 | 0x82 | 0x86 => {
                der::ia5(&gn)?;
            }
            // otherName, x400Address, directoryName, ediPartyName, iPAddress, registeredID.
            0xA0 | 0xA3 | 0xA4 | 0xA5 | 0x87 | 0x88 => {}
            _ => return Err(gn.err("unknown GeneralName")),
        }
    }
    Ok(*inner)
}

/// An uncompressed (0x04) or compressed (0x02, 0x03) point of the curve's size.
fn ec_point_fits(curve: Curve, point: &[u8]) -> bool {
    let n = match curve {
        Curve::P256 | Curve::BrainpoolP256r1 => 32,
        Curve::P384 | Curve::BrainpoolP384r1 => 48,
        Curve::BrainpoolP512r1 => 64,
        Curve::P521 => 66,
    };
    match point.first() {
        Some(0x04) => point.len() == 1 + 2 * n,
        Some(0x02 | 0x03) => point.len() == 1 + n,
        _ => false,
    }
}

fn rsa_bits(key: &[u8]) -> Option<u16> {
    let mut r = Reader::new(key);
    let seq = r.read(der::SEQUENCE, "").ok()?;
    let mut s = seq.reader();
    let modulus = der::integer(&s.read(der::INTEGER, "").ok()?).ok()?;
    der::integer(&s.read(der::INTEGER, "").ok()?).ok()?;
    s.finish("").ok()?;
    r.finish("").ok()?;
    let modulus = match modulus {
        [0, rest @ ..] => rest,
        [first, ..] if first & 0x80 != 0 => return None,
        m => m,
    };
    let lead = modulus.first()?.leading_zeros();
    let bits = (modulus.len() * 8).checked_sub(usize::try_from(lead).ok()?)?;
    Some(u16::try_from(bits).unwrap_or(u16::MAX))
}

/// The hash of RSASSA-PSS parameters (RFC 4055 §3.1), only if they are the consistent form
/// TLS and RFC 8446 use: MGF1 with the same hash, salt length equal to the hash length, and
/// the default trailer field. Anything else, including the SHA-1 defaults, is `None`.
fn pss_hash(params: Tlv<'_>) -> Option<&[u8]> {
    fn hash_alg<'a>(r: &mut Reader<'a>) -> Option<&'a [u8]> {
        let alg = r.read(der::SEQUENCE, "").ok()?;
        let mut a = alg.reader();
        let oid = der::oid(&a.read(der::OID, "").ok()?).ok()?;
        // Parameters are absent or NULL.
        if let Some(p) = a.optional(der::NULL).ok()? {
            if !p.content.is_empty() {
                return None;
            }
        }
        a.finish("").ok()?;
        Some(oid)
    }
    if params.tag != der::SEQUENCE {
        return None;
    }
    let mut r = params.reader();
    let hash = hash_alg(&mut r.read(0xA0, "").ok()?.reader())?;
    let mgf = r.read(0xA1, "").ok()?;
    let mut m = mgf.reader();
    let mut mgf_seq = m.read(der::SEQUENCE, "").ok()?.reader();
    let mgf1 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x08];
    if der::oid(&mgf_seq.read(der::OID, "").ok()?).ok()? != mgf1 || hash_alg(&mut mgf_seq)? != hash {
        return None;
    }
    let salt = der::integer(&r.read(0xA2, "").ok()?.reader().read(der::INTEGER, "").ok()?).ok()?;
    let expected: &[u8] = match hash {
        SHA256 => &[32],
        SHA384 => &[48],
        SHA512 => &[64],
        _ => return None,
    };
    // A trailerField present with its default value 1 is not DER; any other value is wrong.
    (salt == expected && r.is_empty()).then_some(hash)
}

/// Whether `needle` occurs in `haystack`, without core's indexing substring search (which
/// links a bounds-check panic into `no_std` builds).
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
    (0..=haystack.len().saturating_sub(needle.len()))
        .any(|i| haystack.get(i..i + needle.len()) == Some(needle))
}

/// A certificate string, escaped for safe display: non-printable and non-ASCII
/// characters are shown as escapes (THREAT_MODEL.md SR-009).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Escaped<'a>(&'a str);

impl fmt::Display for Escaped<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for c in self.0.chars() {
            if c.is_ascii_graphic() || c == ' ' {
                fmt::Write::write_char(f, c)?;
            } else {
                write!(f, "\\u{{{:x}}}", u32::from(c))?;
            }
        }
        Ok(())
    }
}

/// One way a certificate breaks a profile.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CertViolation<'a> {
    /// Not an X.509 v3 certificate (TR-03109-4 Tab. 15; extensions need v3).
    Version(u8),
    /// The serial number is longer than 20 octets (RFC 5280 §4.1.2.2).
    SerialTooLong(usize),
    /// The issuer's signature algorithm is not allowed.
    Signature(CertSignature),
    /// The issuer's signature algorithm is unknown to this crate.
    UnknownSignature(Oid<'a>),
    /// The key is not allowed.
    Key(PublicKey),
    /// The key type or curve is unknown to this crate.
    UnknownKey(Oid<'a>),
    /// An EC key with explicit curve parameters instead of a named curve (TR-03109-4 A.1.2).
    ExplicitCurve,
    /// Valid for longer than the profile allows.
    Validity {
        /// The certificate's validity in days.
        days: u32,
        /// The profile's maximum.
        max: u32,
    },
    /// notAfter is before notBefore.
    ValidityInverted,
    /// A required extension is absent.
    ExtensionMissing(Extension),
    /// An extension the profile does not allow.
    ExtensionNotAllowed(Oid<'a>),
    /// The same extension appears twice (RFC 5280 §4.2).
    ExtensionDuplicate(Oid<'a>),
    /// An extension's critical flag is wrong.
    Criticality {
        /// The extension.
        extension: Oid<'a>,
        /// Whether it must be critical.
        critical: bool,
    },
    /// A required KeyUsage bit is not set.
    KeyUsageMissing(KeyUsage),
    /// A required extended key usage purpose is absent.
    ExtendedKeyUsageMissing(ExtendedKeyUsage),
    /// An extended key usage purpose the profile does not allow.
    ExtendedKeyUsageNotAllowed(Oid<'a>),
    /// BasicConstraints says cA = TRUE.
    CaCertificate,
    /// A wildcard in a SubjectAltName entry.
    Wildcard(&'a str),
    /// More dNSName entries than allowed.
    TooManyDnsNames {
        /// How many there are.
        count: usize,
        /// The maximum.
        max: u8,
    },
    /// A server certificate without a dNSName.
    DnsNameMissing,
    /// The wrong number of URI entries.
    UriCount {
        /// How many there are.
        count: usize,
        /// How many are required.
        expected: u8,
    },
    /// The organisation (O) is not the required one.
    Organization {
        /// The required value.
        expected: &'static str,
        /// What the certificate has, if exactly one O.
        found: Option<&'a str>,
    },
    /// The organisational unit (OU) is required exactly once.
    OrganizationalUnit {
        /// How many there are.
        count: usize,
    },
    /// The common name (CN) lacks the required marker.
    CommonName {
        /// What it must contain.
        expected: &'static str,
    },
}

impl fmt::Display for CertViolation<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Version(v) => write!(f, "X.509 v{v} certificate, v3 required"),
            Self::SerialTooLong(n) => write!(f, "serial number of {n} octets, at most 20 allowed"),
            Self::Signature(s) => write!(f, "certificate signature {s} is not allowed"),
            Self::UnknownSignature(o) => write!(f, "certificate signature algorithm {o} is not supported"),
            Self::Key(k) => write!(f, "certificate key {k} is not allowed"),
            Self::UnknownKey(o) => write!(f, "certificate key {o} is not supported"),
            Self::ExplicitCurve => f.write_str("EC key with explicit parameters, a named curve is required"),
            Self::Validity { days, max } => {
                write!(f, "certificate valid for {days} days, at most {max} allowed")
            }
            Self::ValidityInverted => f.write_str("notAfter is before notBefore"),
            Self::ExtensionMissing(e) => write!(f, "extension {e} is required"),
            Self::ExtensionNotAllowed(o) => write!(f, "extension {o} is not allowed"),
            Self::ExtensionDuplicate(o) => write!(f, "extension {o} appears more than once"),
            Self::Criticality { extension, critical: true } => {
                write!(f, "extension {extension} must be critical")
            }
            Self::Criticality { extension, critical: false } => {
                write!(f, "extension {extension} must not be critical")
            }
            Self::KeyUsageMissing(u) => write!(f, "KeyUsage {u} is required"),
            Self::ExtendedKeyUsageMissing(e) => write!(f, "ExtendedKeyUsage {e} is required"),
            Self::ExtendedKeyUsageNotAllowed(o) => write!(f, "ExtendedKeyUsage {o} is not allowed"),
            Self::CaCertificate => f.write_str("a CA certificate (cA = TRUE) is not allowed"),
            Self::Wildcard(s) => write!(f, "wildcard in SubjectAltName entry \"{}\"", Escaped(s)),
            Self::TooManyDnsNames { count, max } => {
                write!(f, "{count} DNS names in SubjectAltName, at most {max} allowed")
            }
            Self::DnsNameMissing => f.write_str("a server certificate needs a DNS name in SubjectAltName"),
            Self::UriCount { count, expected } => {
                write!(f, "{count} URIs in SubjectAltName, exactly {expected} required (the AS4 endpoint)")
            }
            Self::Organization { expected, found: Some(o) } => {
                write!(f, "organisation (O) \"{}\", \"{expected}\" required", Escaped(o))
            }
            Self::Organization { expected, found: None } => {
                write!(f, "organisation (O) \"{expected}\" required exactly once")
            }
            Self::OrganizationalUnit { count } => {
                write!(f, "{count} organisational units (OU), exactly one (the MP-ID) required")
            }
            Self::CommonName { expected } => write!(f, "common name (CN) must contain \"{expected}\""),
        }
    }
}

/// The result of [`Profile::check_certificate`]: every violation, without allocating.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CertReport<'a> {
    items: [Option<CertViolation<'a>>; CertReport::CAPACITY],
    len: usize,
    truncated: bool,
}

impl<'a> CertReport<'a> {
    /// The most violations one report holds. More set [`CertReport::truncated`].
    pub const CAPACITY: usize = 16;

    const fn new() -> Self {
        Self { items: [None; Self::CAPACITY], len: 0, truncated: false }
    }

    fn push(&mut self, v: CertViolation<'a>) {
        match self.items.get_mut(self.len) {
            Some(slot) => {
                *slot = Some(v);
                self.len += 1;
            }
            None => self.truncated = true,
        }
    }

    /// Whether the certificate meets every rule. Never true for a truncated report.
    pub const fn is_ok(&self) -> bool {
        self.len == 0 && !self.truncated
    }

    /// Whether more violations were found than the report holds.
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// The violations, in rule order.
    pub fn violations(&self) -> impl Iterator<Item = CertViolation<'a>> + '_ {
        self.items.iter().take(self.len).filter_map(|v| *v)
    }
}

impl Profile {
    /// Check a certificate against this profile's [`CertRules`](crate::CertRules) and
    /// the RFC 5280 baseline: v3, serial ≤ 20 octets, no duplicate extensions, and
    /// notBefore ≤ notAfter.
    #[allow(clippy::too_many_lines)]
    pub fn check_certificate<'a>(&self, cert: &Certificate<'a>) -> CertReport<'a> {
        let rules = &self.cert;
        let mut r = CertReport::new();
        if cert.version != 3 {
            r.push(CertViolation::Version(cert.version));
        }
        if cert.serial.len() > 20 {
            r.push(CertViolation::SerialTooLong(cert.serial.len()));
        }
        if matches!(rules.signatures, Allowed::Only { .. }) {
            match cert.signature() {
                Some(s) if !rules.signatures.allows(&s) => r.push(CertViolation::Signature(s)),
                Some(_) => {}
                None => r.push(CertViolation::UnknownSignature(Oid(cert.sig_oid))),
            }
        }
        if matches!(rules.keys, Allowed::Only { .. }) {
            match cert.public_key() {
                Some(k) if !rules.keys.iter().any(|rule| rule.accepts(k)) => r.push(CertViolation::Key(k)),
                Some(_) => {}
                None => match cert.key_params {
                    Some(p) if cert.key_alg == ID_EC_PUBLIC_KEY && p.tag == der::OID => {
                        r.push(CertViolation::UnknownKey(Oid(p.content)));
                    }
                    _ if cert.key_alg == ID_EC_PUBLIC_KEY => r.push(CertViolation::ExplicitCurve),
                    _ => r.push(CertViolation::UnknownKey(Oid(cert.key_alg))),
                },
            }
        }
        if cert.not_after < cert.not_before {
            r.push(CertViolation::ValidityInverted);
        } else if let Some(max) = rules.max_validity_days {
            if cert.not_after - cert.not_before > i64::from(max) * 86_400 {
                r.push(CertViolation::Validity { days: cert.validity_days(), max });
            }
        }

        // Extensions: duplicates, allowed, required, criticality.
        for (i, ext) in cert.exts().enumerate() {
            match cert.exts().take(i).filter(|e| e.oid == ext.oid).count() {
                0 => {}
                1 => {
                    r.push(CertViolation::ExtensionDuplicate(Oid(ext.oid)));
                    continue;
                }
                _ => continue,
            }
            let known = Extension::from_oid(ext.oid);
            if matches!(rules.extensions, Allowed::Only { .. })
                && !known.is_some_and(|k| rules.extensions.allows(&k))
            {
                r.push(CertViolation::ExtensionNotAllowed(Oid(ext.oid)));
                continue;
            }
            if let (Some(critical), Some(k)) = (rules.critical, known) {
                let must = critical.contains(&k);
                if ext.critical != must {
                    r.push(CertViolation::Criticality { extension: Oid(ext.oid), critical: must });
                }
            }
        }
        let required = rules.extensions.required();
        for &ext in required {
            if !cert.has(ext) {
                r.push(CertViolation::ExtensionMissing(ext));
            }
        }

        // Absent KU or EKU is already reported as a missing extension when it is required.
        let reported = |e: Extension| required.contains(&e) && !cert.has(e);
        if !reported(Extension::KeyUsage) {
            for &usage in rules.key_usage {
                if !cert.has_key_usage(usage) {
                    r.push(CertViolation::KeyUsageMissing(usage));
                }
            }
        }
        if let Allowed::Only { required: must, .. } = rules.extended_key_usage {
            if !reported(Extension::ExtendedKeyUsage) {
                for &purpose in must {
                    if !cert.has_extended_key_usage(purpose) {
                        r.push(CertViolation::ExtendedKeyUsageMissing(purpose));
                    }
                }
            }
            for oid in cert.eku_oids() {
                if !ExtendedKeyUsage::from_oid(oid).is_some_and(|e| rules.extended_key_usage.allows(&e)) {
                    r.push(CertViolation::ExtendedKeyUsageNotAllowed(Oid(oid)));
                }
            }
        }
        if rules.end_entity && cert.is_ca {
            r.push(CertViolation::CaCertificate);
        }

        // SubjectAltName (SR-004: every string-valued name).
        let san = &rules.san;
        if !san.wildcards {
            for name in cert.names(0x81).chain(cert.dns_names()).chain(cert.uris()) {
                if name.bytes().any(|b| b == b'*') {
                    r.push(CertViolation::Wildcard(name));
                }
            }
        }
        let dns = cert.dns_names().count();
        if let Some(max) = san.max_dns_names {
            if dns > usize::from(max) {
                r.push(CertViolation::TooManyDnsNames { count: dns, max });
            }
        }
        if san.dns_name_for_server_auth
            && dns == 0
            && cert.has_extended_key_usage(ExtendedKeyUsage::ServerAuth)
        {
            r.push(CertViolation::DnsNameMissing);
        }
        if let Some(expected) = san.uris {
            let count = cert.uris().count();
            if count != usize::from(expected) {
                r.push(CertViolation::UriCount { count, expected });
            }
        }

        // Subject.
        let subject = &rules.subject;
        if let Some(expected) = subject.organization {
            let found = cert.organization();
            if found != Some(expected) {
                r.push(CertViolation::Organization { expected, found });
            }
        }
        if subject.organizational_unit {
            let count = cert.attributes(AT_OU).count();
            if count != 1 {
                r.push(CertViolation::OrganizationalUnit { count });
            }
        }
        if let Some(expected) = subject.common_name_contains {
            // CP Tab. 23: "<org>.EMT.MAK[<extension>]": the marker follows a non-empty <org>.
            let marked = cert.common_name().is_some_and(|cn| {
                cn.as_bytes().get(1..).is_some_and(|rest| contains(rest, expected.as_bytes()))
            });
            if !marked {
                r.push(CertViolation::CommonName { expected });
            }
        }
        r
    }
}