rama-crypto 0.3.0

All crypto logic used by rama
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
//! BoringSSL-backed self-signed certificate generation (feature `boring`).

use super::{SelfSignedData, SelfSignedKeyKind};
use crate::dep::boring::{
    asn1::{Asn1Object, Asn1ObjectRef, Asn1Time},
    bn::{BigNum, MsbOption},
    ec::{EcGroup, EcKey},
    hash::MessageDigest,
    nid::Nid,
    pkey::{Id, PKey, PKeyRef, Private},
    rand::rand_bytes,
    rsa::Rsa,
    x509::{
        X509, X509Extension, X509NameBuilder, X509Ref,
        extension::{
            AuthorityKeyIdentifier, BasicConstraints, KeyUsage, SubjectAlternativeName,
            SubjectKeyIdentifier,
        },
    },
};
use crate::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use rama_core::error::{BoxError, ErrorContext};
use rama_core::telemetry::tracing;
use rama_net::address::Domain;

/// Generate a self-signed server certificate (leaf signed by a generated CA).
///
/// Returns the certificate chain (`[leaf, ca]`) and the leaf private key, all
/// DER-encoded.
#[expect(clippy::needless_pass_by_value)]
pub(super) fn self_signed_server_auth(
    data: SelfSignedData,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), BoxError> {
    let (ca_cert, ca_key) = self_signed_server_auth_gen_ca(&data)?;
    let (cert, key) = self_signed_server_auth_gen_cert(&data, &ca_cert, &ca_key)?;

    let cert_der = CertificateDer::from(
        cert.to_der()
            .context("boring self-signed: serialize leaf cert to DER")?,
    );
    let ca_der = CertificateDer::from(
        ca_cert
            .to_der()
            .context("boring self-signed: serialize ca cert to DER")?,
    );
    let key_pkcs8 = key
        .private_key_to_der_pkcs8()
        .context("boring self-signed: serialize leaf key to PKCS#8 DER")?;
    let key_der: PrivateKeyDer<'static> = PrivatePkcs8KeyDer::from(key_pkcs8).into();

    Ok((vec![cert_der, ca_der], key_der))
}

/// Build an `AuthorityKeyIdentifier` extension whose `keyIdentifier` is derived from
/// the CA's public key per RFC 5280 ยง4.2.1.2 method (1): SHA-1 of the SubjectPublicKey
/// BIT STRING contents. Used as a fallback when the CA certificate carries no SKI extension.
pub fn aki_from_ca_pubkey_keyid(ca_cert: &X509Ref) -> Result<X509Extension, BoxError> {
    let digest = ca_cert
        .pubkey_digest(MessageDigest::sha1())
        .context("compute SHA-1 of CA SubjectPublicKey BIT STRING")?;
    let keyid: &[u8] = &digest[..];
    debug_assert_eq!(keyid.len(), 20, "SHA-1 digest must be 20 bytes");

    // AuthorityKeyIdentifier ::= SEQUENCE { [0] IMPLICIT OCTET STRING keyIdentifier }
    let mut payload = Vec::with_capacity(4 + keyid.len());
    payload.push(0x30); // SEQUENCE
    payload.push((2 + keyid.len()) as u8);
    payload.push(0x80); // [0] IMPLICIT OCTET STRING
    payload.push(keyid.len() as u8);
    payload.extend_from_slice(keyid);

    // 2.5.29.35 = id-ce-authorityKeyIdentifier
    let aki_oid =
        Asn1Object::from_str("2.5.29.35").context("construct AuthorityKeyIdentifier OID object")?;
    X509Extension::from_der_payload(aki_oid.as_ref(), false, &payload)
        .context("build AuthorityKeyIdentifier extension from raw DER payload")
}

/// Message digest to use when signing a certificate with `key`.
///
/// - EdDSA (Ed25519 / Ed448) is a "pure" signature scheme: `X509_sign` must be
///   invoked with a NULL digest because the algorithm signs the message
///   directly instead of a prehash. Passing a real digest makes BoringSSL's
///   `EVP_DigestSignInit` fail.
/// - ECDSA pairs the digest to the curve strength (P-384 โ†’ SHA-384,
///   P-521 โ†’ SHA-512), per common practice / CA-Browser-Forum guidance; an
///   unnamed (explicit-parameter) curve falls back to SHA-256.
/// - Everything else (RSA, RSA-PSS, DSA) signs over SHA-256, as before.
pub fn signing_digest_for(key: &PKeyRef<Private>) -> MessageDigest {
    match key.id() {
        Id::ED25519 | Id::ED448 => {
            // SAFETY: a null `EVP_MD` is precisely what `X509_sign` expects for
            // EdDSA keys; BoringSSL reads it as "no prehash".
            unsafe { MessageDigest::from_ptr(std::ptr::null()) }
        }
        Id::EC => match key.ec_key().ok().and_then(|ec| ec.group().curve_name()) {
            Some(Nid::SECP521R1) => MessageDigest::sha512(),
            Some(Nid::SECP384R1) => MessageDigest::sha384(),
            _ => MessageDigest::sha256(),
        },
        _ => MessageDigest::sha256(),
    }
}

/// Generate a fresh private key of the requested [`SelfSignedKeyKind`].
fn generate_self_signed_key(kind: SelfSignedKeyKind) -> Result<PKey<Private>, BoxError> {
    fn ec(curve: Nid) -> Result<PKey<Private>, BoxError> {
        let group =
            EcGroup::from_curve_name(curve).context("create EC group for self-signed key")?;
        let ec_key = EcKey::generate(&group).context("generate EC key for self-signed key")?;
        PKey::from_ec_key(ec_key).context("create private key from generated EC key")
    }

    match kind {
        SelfSignedKeyKind::Rsa2048 => {
            let rsa = Rsa::generate(2048).context("generate 2048-bit RSA key")?;
            PKey::from_rsa(rsa).context("create private key from 2048-bit RSA key")
        }
        SelfSignedKeyKind::Rsa4096 => {
            let rsa = Rsa::generate(4096).context("generate 4096-bit RSA key")?;
            PKey::from_rsa(rsa).context("create private key from 4096-bit RSA key")
        }
        SelfSignedKeyKind::EcP256 => ec(Nid::X9_62_PRIME256V1),
        SelfSignedKeyKind::EcP384 => ec(Nid::SECP384R1),
        SelfSignedKeyKind::EcP521 => ec(Nid::SECP521R1),
        SelfSignedKeyKind::Ed25519 => {
            let mut seed = [0_u8; 32];
            rand_bytes(&mut seed).context("generate Ed25519 private key bytes")?;
            PKey::from_ed25519_private_key(&seed)
                .context("create private key from Ed25519 key bytes")
        }
    }
}

/// Generate a server cert for the [`SelfSignedData`] using the given CA Cert + Key.
///
/// In most cases you probably want more refined configuration and controls,
/// so in general we recommend to not use this utility outside of experimental or testing purposes.
pub fn self_signed_server_auth_gen_cert(
    data: &SelfSignedData,
    ca_cert: &X509,
    ca_privkey: &PKey<Private>,
) -> Result<(X509, PKey<Private>), BoxError> {
    let privkey = generate_self_signed_key(data.key_kind)?;

    let common_name = data
        .common_name
        .clone()
        .unwrap_or_else(|| Domain::from_static("localhost"));

    let mut x509_name = X509NameBuilder::new().context("create x509 name builder")?;
    x509_name
        .append_entry_by_nid(
            Nid::ORGANIZATIONNAME,
            data.organisation_name.as_deref().unwrap_or("Anonymous"),
        )
        .context("append organisation name to x509 name builder")?;
    x509_name
        .append_entry_by_nid(Nid::COMMONNAME, common_name.as_str())
        .context("append common name to x509 name builder")?;
    let x509_name = x509_name.build();

    let mut cert_builder = X509::builder().context("create x509 (cert) builder")?;
    cert_builder
        .set_version(2)
        .context("x509 cert builder: set version = 2")?;
    let serial_number = {
        let mut serial = BigNum::new().context("x509 cert builder: create big num (serial")?;
        serial
            .rand(159, MsbOption::MAYBE_ZERO, false)
            .context("x509 cert builder: randomise serial number (big num)")?;
        serial
            .to_asn1_integer()
            .context("x509 cert builder: convert serial to ASN1 integer")?
    };
    cert_builder
        .set_serial_number(&serial_number)
        .context("x509 cert builder: set serial number")?;
    cert_builder
        .set_issuer_name(ca_cert.subject_name())
        .context("x509 cert builder: set issuer name")?;
    cert_builder
        .set_pubkey(&privkey)
        .context("x509 cert builder: set pub key")?;
    cert_builder
        .set_subject_name(&x509_name)
        .context("x509 cert builder: set subject name")?;
    cert_builder
        .set_pubkey(&privkey)
        .context("x509 cert builder: set public key using private key (ref)")?;
    let not_before =
        Asn1Time::days_from_now(0).context("x509 cert builder: create ASN1Time for today")?;
    cert_builder
        .set_not_before(&not_before)
        .context("x509 cert builder: set not before to today")?;
    let not_after = Asn1Time::days_from_now(90)
        .context("x509 cert builder: create ASN1Time for 90 days in future")?;
    cert_builder
        .set_not_after(&not_after)
        .context("x509 cert builder: set not after to 90 days in future")?;

    cert_builder
        .append_extension(
            BasicConstraints::new()
                .build()
                .context("x509 cert builder: build basic constraints")?
                .as_ref(),
        )
        .context("x509 cert builder: add basic constraints as x509 extension")?;
    cert_builder
        .append_extension(
            KeyUsage::new()
                .critical()
                .non_repudiation()
                .digital_signature()
                .key_encipherment()
                .build()
                .context("x509 cert builder: create key usage")?
                .as_ref(),
        )
        .context("x509 cert builder: add key usage x509 extension")?;

    let mut subject_alt_name = SubjectAlternativeName::new();
    subject_alt_name.dns(common_name.as_str());
    for extra_san in data.subject_alternative_names.iter().flatten() {
        if extra_san.as_str() != common_name.as_str() {
            subject_alt_name.dns(extra_san.as_str());
        }
    }
    let subject_alt_name = subject_alt_name
        .build(&cert_builder.x509v3_context(Some(ca_cert), None))
        .context("x509 cert builder: build subject alt name")?;

    cert_builder
        .append_extension(subject_alt_name.as_ref())
        .context("x509 cert builder: add subject alt name")?;

    let subject_key_identifier = SubjectKeyIdentifier::new()
        .build(&cert_builder.x509v3_context(Some(ca_cert), None))
        .context("x509 cert builder: build subject key id")?;
    cert_builder
        .append_extension(subject_key_identifier.as_ref())
        .context("x509 cert builder: add subject key id x509 extension")?;

    if ca_cert.subject_key_id().is_some() {
        let auth_key_identifier = AuthorityKeyIdentifier::new()
            .keyid(false)
            .issuer(false)
            .build(&cert_builder.x509v3_context(Some(ca_cert), None))
            .context("x509 cert builder: build auth key id")?;
        cert_builder
            .append_extension(auth_key_identifier.as_ref())
            .context("x509 cert builder: set auth key id extension")?;
    } else {
        let auth_key_identifier = aki_from_ca_pubkey_keyid(ca_cert)?;
        cert_builder
            .append_extension(auth_key_identifier.as_ref())
            .context("x509 cert builder: set derived auth key id extension")?;
    }

    cert_builder
        .sign(ca_privkey, signing_digest_for(ca_privkey))
        .context("x509 cert builder: sign cert")?;

    let cert = cert_builder.build();

    Ok((cert, privkey))
}

/// Generate a self-signed server CA from the given [`SelfSignedData`].
///
/// This should not be used in production but mostly for experimental / testing purposes.
pub fn self_signed_server_auth_gen_ca(
    data: &SelfSignedData,
) -> Result<(X509, PKey<Private>), BoxError> {
    let privkey = generate_self_signed_key(data.key_kind)?;

    let mut x509_name = X509NameBuilder::new().context("create x509 name builder")?;
    x509_name
        .append_entry_by_nid(
            Nid::ORGANIZATIONNAME,
            data.organisation_name.as_deref().unwrap_or("Anonymous"),
        )
        .context("append organisation name to x509 name builder")?;
    if let Some(cn) = data.common_name.as_ref() {
        x509_name
            .append_entry_by_nid(Nid::COMMONNAME, cn.as_str())
            .context("append common name to x509 name builder")?;
    }

    let x509_name = x509_name.build();

    let mut ca_cert_builder = X509::builder().context("create x509 (cert) builder")?;
    ca_cert_builder
        .set_version(2)
        .context("x509 cert builder: set version = 2")?;
    let serial_number = {
        let mut serial = BigNum::new().context("x509 cert builder: create big num (serial")?;
        serial
            .rand(159, MsbOption::MAYBE_ZERO, false)
            .context("x509 cert builder: randomise serial number (big num)")?;
        serial
            .to_asn1_integer()
            .context("x509 cert builder: convert serial to ASN1 integer")?
    };
    ca_cert_builder
        .set_serial_number(&serial_number)
        .context("x509 cert builder: set serial number")?;
    ca_cert_builder
        .set_subject_name(&x509_name)
        .context("x509 cert builder: set subject name")?;
    ca_cert_builder
        .set_issuer_name(&x509_name)
        .context("x509 cert builder: set issuer (self-signed")?;
    ca_cert_builder
        .set_pubkey(&privkey)
        .context("x509 cert builder: set public key using private key (ref)")?;
    let not_before =
        Asn1Time::days_from_now(0).context("x509 cert builder: create ASN1Time for today")?;
    ca_cert_builder
        .set_not_before(&not_before)
        .context("x509 cert builder: set not before to today")?;
    let not_after = Asn1Time::days_from_now(365 * 20)
        .context("x509 cert builder: create ASN1Time for 20 years in future")?;
    ca_cert_builder
        .set_not_after(&not_after)
        .context("x509 cert builder: set not after to 20 years in future")?;

    ca_cert_builder
        .append_extension(
            BasicConstraints::new()
                .critical()
                .ca()
                .build()
                .context("x509 cert builder: build basic constraints")?
                .as_ref(),
        )
        .context("x509 cert builder: add basic constraints as x509 extension")?;
    ca_cert_builder
        .append_extension(
            KeyUsage::new()
                .critical()
                .key_cert_sign()
                .crl_sign()
                .build()
                .context("x509 cert builder: create key usage")?
                .as_ref(),
        )
        .context("x509 cert builder: add key usage x509 extension")?;

    let subject_key_identifier = SubjectKeyIdentifier::new()
        .build(&ca_cert_builder.x509v3_context(None, None))
        .context("x509 cert builder: build subject key id")?;
    ca_cert_builder
        .append_extension(subject_key_identifier.as_ref())
        .context("x509 cert builder: add subject key id x509 extension")?;

    ca_cert_builder
        .sign(&privkey, signing_digest_for(&privkey))
        .context("x509 cert builder: sign cert")?;

    let cert = ca_cert_builder.build();

    Ok((cert, privkey))
}

/// OID of the RFC 7633 TLS Feature extension (OCSP "must-staple").
const OID_TLS_FEATURE: &str = "1.3.6.1.5.5.7.1.24";
/// OID of the RFC 6962 embedded Signed Certificate Timestamp (SCT) list.
const OID_SCT_LIST: &str = "1.3.6.1.4.1.11129.2.4.2";

/// Canonical OID renderings of the extensions we strip by OID rather than by
/// [`Nid`] (rama-boring exposes no stable constant for these). Resolving them
/// once keeps the per-extension membership check cheap.
fn mirror_strip_oid_texts() -> Vec<String> {
    [OID_TLS_FEATURE, OID_SCT_LIST]
        .into_iter()
        .filter_map(|oid| Asn1Object::from_str(oid).ok().map(|obj| obj.to_string()))
        .collect()
}

/// Returns `true` when a source-certificate extension must NOT be mirrored onto
/// a leaf that we re-sign with our own MITM CA.
///
/// Two classes are stripped (see [`self_signed_server_auth_mirror_cert`]):
///
/// 1. Revocation / authority-info pointers bound to the *real* issuer โ€” CRL
///    Distribution Points, Authority Information Access (OCSP responder +
///    caIssuers) and Freshest CRL (delta CRL). A leaf re-signed by our CA can
///    never be covered by those responders, so a client that follows them
///    (notably Windows schannel via `lsass.exe`) hits an issuer mismatch and
///    aborts the handshake with `CRYPT_E_REVOCATION_OFFLINE`. Both are OPTIONAL
///    and non-critical (RFC 5280 ยง4.2): with no pointer present, conformant
///    clients simply skip the revocation check, which is the correct behaviour
///    for a locally-trusted MITM CA.
///
/// 2. Assertions we cannot honour after re-signing โ€” the RFC 7633 TLS Feature
///    extension ("must-staple") would force the client to *require* a stapled
///    OCSP response we never produce (handshake abort), and RFC 6962 embedded
///    SCTs are signed over the original `TBSCertificate` and become invalid the
///    instant we re-sign. These have no stable `Nid` constant, so they are
///    matched by canonical OID text, which is robust whether or not BoringSSL
///    knows the OID by name.
fn should_strip_mirrored_extension(
    ext_nid: Nid,
    ext_obj: &Asn1ObjectRef,
    strip_oid_texts: &[String],
) -> bool {
    if ext_nid == Nid::CRL_DISTRIBUTION_POINTS
        || ext_nid == Nid::INFO_ACCESS
        || ext_nid == Nid::FRESHEST_CRL
    {
        return true;
    }

    let ext_text = ext_obj.to_string();
    strip_oid_texts.contains(&ext_text)
}

/// Generate a mirrored server certificate based on a source certificate.
///
/// The generated certificate mirrors identity data from `source_cert` (subject and SAN, when
/// present), but is signed by the provided `ca_cert` + `ca_privkey`.
pub fn self_signed_server_auth_mirror_cert(
    source_cert: &X509Ref,
    ca_cert: &X509,
    ca_privkey: &PKey<Private>,
) -> Result<(X509, PKey<Private>), BoxError> {
    self_signed_server_auth_mirror_cert_with_extensions(source_cert, ca_cert, ca_privkey, &[])
}

/// Like [`self_signed_server_auth_mirror_cert`], additionally appending
/// `extra_extensions` (e.g. proxy-hosted CRL/OCSP revocation pointers) to the
/// re-signed leaf before signing.
pub fn self_signed_server_auth_mirror_cert_with_extensions(
    source_cert: &X509Ref,
    ca_cert: &X509,
    ca_privkey: &PKey<Private>,
    extra_extensions: &[X509Extension],
) -> Result<(X509, PKey<Private>), BoxError> {
    let source_pubkey = source_cert
        .public_key()
        .context("x509 cert builder: read source public key")?;
    let privkey = match source_pubkey.id() {
        // RSA-PSS leaves are mirrored as plain RSA (`rsaEncryption`) keys: the
        // leaf still works for the TLS handshake, but its SPKI algorithm OID is
        // not preserved, as rama-boring exposes no safe `id-RSASSA-PSS` key
        // constructor. This is a fidelity-only gap, not a functional one.
        Id::RSA | Id::RSAPSS => {
            let bits = source_pubkey.bits().max(2048);
            let rsa =
                Rsa::generate(bits).with_context(|| format!("generate {bits}-bit RSA key"))?;
            PKey::from_rsa(rsa)
                .with_context(|| format!("create private key from {bits}-bit RSA key"))?
        }
        Id::EC => {
            let source_ec_key = source_pubkey
                .ec_key()
                .context("x509 cert builder: read source EC key")?;
            // Generate on the source key's own group rather than going through
            // `curve_name()`, so explicit-parameter curves are mirrored too
            // instead of hard-failing the whole interception.
            let ec_key = EcKey::generate(source_ec_key.group())
                .context("x509 cert builder: generate mirrored EC key")?;
            PKey::from_ec_key(ec_key)
                .context("x509 cert builder: create private key from EC key")?
        }
        Id::ED25519 => {
            let mut key = [0_u8; 32];
            rand_bytes(&mut key).context("generate Ed25519 private key bytes")?;
            PKey::from_ed25519_private_key(&key)
                .context("create private key from Ed25519 key bytes")?
        }
        // Everything else โ€” DSA, X25519/X448, Ed448, or anything exotic โ€” cannot
        // serve as a TLS server-auth leaf key (key-agreement-only, disabled in
        // modern TLS, or not constructible here). Mirroring such a key would
        // yield a leaf the MITM server can never complete a handshake with, so
        // fall back to a universally functional RSA-2048 key instead.
        other => {
            tracing::debug!(
                key_type = ?other,
                "source cert key type cannot serve as a TLS leaf key; using RSA-2048 for the mirrored leaf"
            );
            let rsa = Rsa::generate(2048).context("generate fallback 2048 RSA key")?;
            PKey::from_rsa(rsa).context("create private key from fallback 2048 RSA key")?
        }
    };

    let mut cert_builder = X509::builder().context("create x509 (cert) builder")?;
    cert_builder
        .set_version(2)
        .context("x509 cert builder: set version = 2")?;
    let serial_number = {
        let mut serial = BigNum::new().context("x509 cert builder: create big num (serial")?;
        serial
            .rand(159, MsbOption::MAYBE_ZERO, false)
            .context("x509 cert builder: randomise serial number (big num)")?;
        serial
            .to_asn1_integer()
            .context("x509 cert builder: convert serial to ASN1 integer")?
    };
    cert_builder
        .set_serial_number(&serial_number)
        .context("x509 cert builder: set serial number")?;
    cert_builder
        .set_issuer_name(ca_cert.subject_name())
        .context("x509 cert builder: set issuer name from CA")?;
    cert_builder
        .set_subject_name(source_cert.subject_name())
        .context("x509 cert builder: set mirrored subject name")?;
    cert_builder
        .set_pubkey(&privkey)
        .context("x509 cert builder: set public key using generated private key (ref)")?;

    let not_before = if source_cert.not_before() < ca_cert.not_before() {
        ca_cert.not_before()
    } else {
        source_cert.not_before()
    };
    let not_after = if source_cert.not_after() > ca_cert.not_after() {
        ca_cert.not_after()
    } else {
        source_cert.not_after()
    };
    cert_builder
        .set_not_before(not_before)
        .context("x509 cert builder: set mirrored not-before (clamped to CA)")?;
    cert_builder
        .set_not_after(not_after)
        .context("x509 cert builder: set mirrored not-after (clamped to CA)")?;

    let source_had_ski = source_cert.subject_key_id().is_some();
    let source_had_aki = source_cert.authority_key_id().is_some();

    let strip_oid_texts = mirror_strip_oid_texts();

    for source_ext in source_cert.extensions() {
        let ext_nid = source_ext.object().nid();
        if ext_nid == Nid::SUBJECT_KEY_IDENTIFIER || ext_nid == Nid::AUTHORITY_KEY_IDENTIFIER {
            tracing::trace!(
                ?ext_nid,
                "skip source key identifier extension (will regenerate if applicable)"
            );
            continue;
        }

        if should_strip_mirrored_extension(ext_nid, source_ext.object(), &strip_oid_texts) {
            tracing::trace!(
                ?ext_nid,
                "skip source extension invalid for a re-signed MITM leaf \
                 (issuer-bound revocation/authority pointer, or assertion we cannot honour)"
            );
            continue;
        }

        cert_builder
            .append_extension_der_payload(
                source_ext.object(),
                source_ext.critical(),
                source_ext.data().as_slice(),
            )
            .context("x509 cert builder: append mirrored source extension")?;
    }

    if source_had_ski {
        let subject_key_identifier = SubjectKeyIdentifier::new()
            .build(&cert_builder.x509v3_context(Some(ca_cert), None))
            .context("x509 cert builder: build mirrored subject key identifier")?;
        cert_builder
            .append_extension(subject_key_identifier.as_ref())
            .context("x509 cert builder: append mirrored subject key identifier")?;
    }

    if source_had_aki {
        if ca_cert.subject_key_id().is_some() {
            let auth_key_identifier = AuthorityKeyIdentifier::new()
                .keyid(false)
                .issuer(false)
                .build(&cert_builder.x509v3_context(Some(ca_cert), None))
                .context("x509 cert builder: build mirrored authority key identifier")?;
            cert_builder
                .append_extension(auth_key_identifier.as_ref())
                .context("x509 cert builder: append mirrored authority key identifier")?;
        } else {
            let auth_key_identifier = aki_from_ca_pubkey_keyid(ca_cert)?;
            cert_builder
                .append_extension(auth_key_identifier.as_ref())
                .context("x509 cert builder: append derived mirrored authority key identifier")?;
        }
    }

    for ext in extra_extensions {
        cert_builder
            .append_extension(ext.as_ref())
            .context("x509 cert builder: append extra revocation extension")?;
    }

    cert_builder
        .sign(ca_privkey, signing_digest_for(ca_privkey))
        .context("x509 cert builder: sign mirrored cert")?;

    Ok((cert_builder.build(), privkey))
}

#[cfg(test)]
#[path = "boring_tests.rs"]
mod tests;