ms-pkca 0.1.0-dev

PKINIT (RFC 4556) client — PA-PK-AS-REQ / PA-PK-AS-REP with X.509 cert + UnPAC-the-hash (pre-alpha)
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
//! Kerberos AS-REQ TCP send + AS-REP processing (RFC 4120 §7.2.2, RFC 4556 §3.2).
//!
//! Feature-gated behind `network` (default).  With `network` off, the higher-level
//! `PkinitClient::request_tgt_with_cert` returns an [`Error::NetworkDisabled`].
//!
//! We use `picky-krb` for the Kerberos ASN.1 message layer (KdcReq, KdcRep,
//! PaPkAsRep) — hand-rolling application-tagged constructions and their
//! deserializers would double the crate's size for no measurable win.
//! Everything else — the CMS SignedData eContent extraction, the DH-shared →
//! reply-key derivation, the RSA reply-key unwrap — is done here directly.
//!
//! ## Wire flow
//! 1. Build AS-REQ:  KdcReq { padata = [PA-PK-AS-REQ], req-body = { … } }
//! 2. Frame: 4-byte big-endian length prefix, then AS-REQ DER (RFC 4120 §7.2.2)
//! 3. Read reply: 4-byte length prefix, then AS-REP (or KRB-ERROR — we surface it)
//! 4. Parse AS-REP, locate PA-PK-AS-REP padata (type 17)
//! 5. Dispatch:
//!    * dhInfo    → extract signed KDC-DH-Key-Info, DH-derive reply key (RFC 4556 §3.2.3.1)
//!    * encKeyPack → RSA-decrypt to obtain the reply-key
//! 6. Return AS-REP.ticket + derived session_key
//!
//! ## What is *not* here (yet)
//! * KDC signature verification on the CMS SignedData — the eContent is
//!   trusted verbatim.  Add cert-chain + signature check in 0.2.
//! * AS-REP enc-part Kerberos-etype decryption (aes256-cts-hmac-sha1-96 / rc4-hmac).
//!   Needs the etype layer; a caller can drive it with the reply-key we return.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;

use num_bigint_dig::BigUint;
use rsa::RsaPrivateKey;

use crate::der_walk::{extract_signed_data_econtent, tlv_split};
use crate::dh::DhKeyPair;
use crate::enveloped;
use crate::error::{Error, Result};
use crate::kdf::{octet_string_to_key, Hash};
use crate::AsRepResult;

const PA_PK_AS_REQ_TYPE: i32 = 16;
const PA_PK_AS_REP_TYPE: i32 = 17;
const PA_PAC_REQUEST_TYPE: i32 = 128;

/// Send a framed AS-REQ blob to `kdc_addr` (`host:port`) over TCP and return
/// the framed reply body (framing stripped).
///
/// TCP framing per RFC 4120 §7.2.2: 4-byte big-endian length prefix, then payload.
pub fn tcp_exchange(kdc_addr: &str, as_req_der: &[u8], timeout: Duration) -> Result<Vec<u8>> {
    let mut stream = TcpStream::connect_timeout(
        &kdc_addr
            .to_socket_addrs_first()
            .map_err(|e| Error::Io(std::io::Error::new(std::io::ErrorKind::InvalidInput, e)))?,
        timeout,
    )?;
    stream.set_read_timeout(Some(timeout))?;
    stream.set_write_timeout(Some(timeout))?;

    let mut frame = Vec::with_capacity(4 + as_req_der.len());
    frame.extend_from_slice(&(as_req_der.len() as u32).to_be_bytes());
    frame.extend_from_slice(as_req_der);
    stream.write_all(&frame)?;

    let mut len_buf = [0u8; 4];
    stream.read_exact(&mut len_buf)?;
    let len = u32::from_be_bytes(len_buf) as usize;
    if len > 8 * 1024 * 1024 {
        return Err(Error::AsRepParse(format!(
            "reply length {len} exceeds sanity cap"
        )));
    }
    let mut body = vec![0u8; len];
    stream.read_exact(&mut body)?;
    Ok(body)
}

// Tiny helper so this file has no dependency on socket-resolution machinery beyond std.
trait ToSocketAddrsFirst {
    fn to_socket_addrs_first(&self) -> std::io::Result<std::net::SocketAddr>;
}

impl ToSocketAddrsFirst for str {
    fn to_socket_addrs_first(&self) -> std::io::Result<std::net::SocketAddr> {
        use std::net::ToSocketAddrs;
        self.to_socket_addrs()?.next().ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::InvalidInput, "no addr resolved")
        })
    }
}

// ---------------------------------------------------------------------------
// AS-REQ builder — wraps a caller-supplied PA-PK-AS-REQ DER blob into a
// full [APPLICATION 10] KdcReq.

use picky_asn1::bit_string::BitString;
use picky_asn1::restricted_string::Ia5String;
use picky_asn1::wrapper::{
    Asn1SequenceOf, BitStringAsn1, ExplicitContextTag0, ExplicitContextTag1, ExplicitContextTag2,
    ExplicitContextTag3, ExplicitContextTag4, ExplicitContextTag5, ExplicitContextTag7,
    ExplicitContextTag8, GeneralStringAsn1, IntegerAsn1, OctetStringAsn1, Optional,
};
use picky_asn1_der::application_tag::ApplicationTag;
use picky_krb::constants::types::{
    AS_REP_MSG_TYPE, AS_REQ_MSG_TYPE, KRB_ERROR_MSG_TYPE, NT_PRINCIPAL,
};
use picky_krb::data_types::{KerberosStringAsn1, KerberosTime, PaData, PrincipalName};
use picky_krb::messages::{AsRep, AsReq, KdcReq, KdcReqBody};
use picky_krb::pkinit::{KdcDhKeyInfo, PaPkAsRep};

/// Fields the caller supplies to construct an AS-REQ.
#[derive(Debug, Clone)]
pub struct AsReqOpts<'a> {
    pub realm: &'a str,
    /// Client principal parts (usually `["alice"]` or `["alice", "instance"]`).
    pub cname: &'a [&'a str],
    /// Server principal parts (`["krbtgt", REALM]` for a TGT request).
    pub sname: &'a [&'a str],
    /// PKINIT PA-DATA value: the DER of PA-PK-AS-REQ (from `pkinit::build_pa_pk_as_req`).
    pub pa_pk_as_req_der: &'a [u8],
    /// Kerberos nonce (32-bit) — MUST match the one embedded in the PkAuthenticator.
    pub nonce: u32,
    /// Ticket expiry (till).  Typically `now + 8h`; caller-supplied so we can build offline.
    pub till: KerberosTime,
    /// Encryption types the client accepts in the AS-REP enc-part, in preference order.
    /// Default = aes256, aes128, rc4-hmac.
    pub etypes: &'a [i32],
}

/// Construct the KdcReqBody from `opts` — factored out so both `build_as_req`
/// and [`compute_as_req_body_checksum`] hash-then-wrap the *same* bytes.
///
/// RFC 4556 §3.2.1 requires the client to include a SHA-1 checksum over the
/// DER of the KDC-REQ-BODY inside `PkAuthenticator.paChecksum`.  If we hashed a
/// separately-constructed body, the KDC would reject the AS-REQ because the
/// digest wouldn't match the body it actually receives.
fn make_kdc_req_body(opts: &AsReqOpts<'_>) -> Result<KdcReqBody> {
    let cname_names: Asn1SequenceOf<KerberosStringAsn1> = Asn1SequenceOf::from(
        opts.cname
            .iter()
            .map(|p| kerb_string(p))
            .collect::<Result<Vec<_>>>()?,
    );
    let sname_names: Asn1SequenceOf<KerberosStringAsn1> = Asn1SequenceOf::from(
        opts.sname
            .iter()
            .map(|p| kerb_string(p))
            .collect::<Result<Vec<_>>>()?,
    );

    let cname = PrincipalName {
        name_type: ExplicitContextTag0::from(IntegerAsn1::from(vec![NT_PRINCIPAL as u8])),
        name_string: ExplicitContextTag1::from(cname_names),
    };
    let sname = PrincipalName {
        name_type: ExplicitContextTag0::from(IntegerAsn1::from(vec![NT_PRINCIPAL as u8])),
        name_string: ExplicitContextTag1::from(sname_names),
    };
    let realm = kerb_string(opts.realm)?;

    // kdc-options = 0x40800000 (forwardable + renewable-ok).  Encoded as a
    // 32-bit BIT STRING with 0 unused-bits.
    let kdc_options = BitStringAsn1::from(BitString::with_bytes(vec![0x40, 0x80, 0x00, 0x00]));

    let etypes: Asn1SequenceOf<IntegerAsn1> = Asn1SequenceOf::from(
        opts.etypes
            .iter()
            .map(|e| IntegerAsn1::from(i32_to_der_bytes(*e)))
            .collect::<Vec<_>>(),
    );

    Ok(KdcReqBody {
        kdc_options: ExplicitContextTag0::from(kdc_options),
        cname: Optional::from(Some(ExplicitContextTag1::from(cname))),
        realm: ExplicitContextTag2::from(realm),
        sname: Optional::from(Some(ExplicitContextTag3::from(sname))),
        from: Optional::from(None),
        till: ExplicitContextTag5::from(opts.till.clone()),
        rtime: Optional::from(None),
        nonce: ExplicitContextTag7::from(IntegerAsn1::from(u32_to_der_bytes(opts.nonce))),
        etype: ExplicitContextTag8::from(etypes),
        addresses: Optional::from(None),
        enc_authorization_data: Optional::from(None),
        additional_tickets: Optional::from(None),
    })
}

/// SHA-1 of the DER-encoded KDC-REQ-BODY.
///
/// Callers feed the returned 20 bytes into
/// [`crate::pkinit::BuildOptions::as_req_body_checksum`] so the PkAuthenticator
/// binds the CMS-signed payload to the request body the KDC receives
/// (RFC 4556 §3.2.1).  A modern Windows KDC rejects a PKINIT AS-REQ whose
/// `paChecksum` is missing or mismatches.
///
/// Uses `opts` identical to those passed to [`build_as_req`] — anything less
/// would produce a checksum over a *different* body than the one on the wire.
pub fn compute_as_req_body_checksum(opts: &AsReqOpts<'_>) -> Result<[u8; 20]> {
    let body = make_kdc_req_body(opts)?;
    let body_der = picky_asn1_der::to_vec(&body)
        .map_err(|e| Error::AsRepParse(format!("encode KdcReqBody for checksum: {e}")))?;
    use sha1::{Digest, Sha1};
    let mut out = [0u8; 20];
    out.copy_from_slice(&Sha1::digest(&body_der));
    Ok(out)
}

/// Build the DER of an AS-REQ ([APPLICATION 10] KdcReq) wrapping the given
/// PA-PK-AS-REQ padata.
///
/// The caller MUST have already computed
/// [`compute_as_req_body_checksum`] over the same `opts` and included the
/// digest in the PkAuthenticator inside `opts.pa_pk_as_req_der`; otherwise a
/// modern KDC will reject the request.
pub fn build_as_req(opts: &AsReqOpts<'_>) -> Result<Vec<u8>> {
    let req_body = make_kdc_req_body(opts)?;

    // padata: PA-PK-AS-REQ + PA-PAC-REQUEST(include-pac=TRUE).
    let padata = vec![
        PaData {
            padata_type: ExplicitContextTag1::from(IntegerAsn1::from(i32_to_der_bytes(
                PA_PK_AS_REQ_TYPE,
            ))),
            padata_data: ExplicitContextTag2::from(OctetStringAsn1::from(
                opts.pa_pk_as_req_der.to_vec(),
            )),
        },
        PaData {
            padata_type: ExplicitContextTag1::from(IntegerAsn1::from(i32_to_der_bytes(
                PA_PAC_REQUEST_TYPE,
            ))),
            // KERB-PA-PAC-REQUEST ::= SEQUENCE { include-pac [0] BOOLEAN }
            // DER of SEQUENCE { [0] EXPLICIT BOOLEAN TRUE } = 30 05 A0 03 01 01 FF
            padata_data: ExplicitContextTag2::from(OctetStringAsn1::from(vec![
                0x30, 0x05, 0xA0, 0x03, 0x01, 0x01, 0xFF,
            ])),
        },
    ];

    let kdc_req = KdcReq {
        pvno: ExplicitContextTag1::from(IntegerAsn1::from(vec![5])),
        msg_type: ExplicitContextTag2::from(IntegerAsn1::from(vec![AS_REQ_MSG_TYPE])),
        padata: Optional::from(Some(ExplicitContextTag3::from(Asn1SequenceOf::from(
            padata,
        )))),
        req_body: ExplicitContextTag4::from(req_body),
    };
    let as_req: AsReq = ApplicationTag(kdc_req);
    picky_asn1_der::to_vec(&as_req).map_err(|e| Error::AsRepParse(format!("encode AS-REQ: {e}")))
}

fn kerb_string(s: &str) -> Result<KerberosStringAsn1> {
    Ia5String::from_string(s.to_owned())
        .map(|ia5| GeneralStringAsn1::from(ia5))
        .map_err(|e| Error::AsRepParse(format!("kerberos-string {s:?}: {e}")))
}

fn i32_to_der_bytes(v: i32) -> Vec<u8> {
    // Minimal two's-complement big-endian encoding, per DER INTEGER rules.
    if v == 0 {
        return vec![0];
    }
    let mut buf = v.to_be_bytes().to_vec();
    if v > 0 {
        while buf.len() > 1 && buf[0] == 0 && (buf[1] & 0x80) == 0 {
            buf.remove(0);
        }
    } else {
        while buf.len() > 1 && buf[0] == 0xFF && (buf[1] & 0x80) != 0 {
            buf.remove(0);
        }
    }
    buf
}

fn u32_to_der_bytes(v: u32) -> Vec<u8> {
    // DER INTEGER — pad with 0 if MSB is set so it isn't mis-read as negative.
    let mut buf = v.to_be_bytes().to_vec();
    while buf.len() > 1 && buf[0] == 0 && (buf[1] & 0x80) == 0 {
        buf.remove(0);
    }
    if (buf[0] & 0x80) != 0 {
        buf.insert(0, 0);
    }
    buf
}

// ---------------------------------------------------------------------------
// AS-REP processing.

/// Parse an AS-REP blob, run the PKINIT reply-side DH or RSA derivation, and
/// return the ticket + derived reply-key.
///
/// `expected_nonce` must match the nonce embedded in the AuthPack sent in the
/// AS-REQ (RFC 4556 §3.2.3.1 requires the KDC to echo it inside KdcDhKeyInfo).
///
/// `kdf_key_bytes` is the Kerberos etype's key length in bytes — 32 for
/// aes256, 16 for aes128, 16 for rc4-hmac.  The caller chooses based on the
/// etype the KDC picked (readable from `AS-REP.enc_part.etype`).
pub fn process_as_rep(
    as_rep_bytes: &[u8],
    client_dh: &DhKeyPair,
    client_key: &RsaPrivateKey,
    expected_nonce: u32,
    kdf_key_bytes: usize,
) -> Result<AsRepResult> {
    // KRB-ERROR? Peek at the [APPLICATION N] tag byte to route.
    if let Some(first) = as_rep_bytes.first() {
        // [APPLICATION 30] KRB-ERROR = 0x7E.
        if *first == 0x60 | 30 || *first == 0x40 | 30 {
            let err: ApplicationTag<picky_krb::messages::KrbErrorInner, KRB_ERROR_MSG_TYPE> =
                picky_asn1_der::from_bytes(as_rep_bytes)
                    .map_err(|e| Error::AsRepParse(format!("KRB-ERROR parse: {e}")))?;
            return Err(Error::KrbError(format!("code={:?}", err.0.error_code.0)));
        }
    }

    let as_rep: AsRep = picky_asn1_der::from_bytes(as_rep_bytes)
        .map_err(|e| Error::AsRepParse(format!("AS-REP: {e}")))?;
    // Sanity: msg-type == 11.
    let msg_type = as_rep.0.msg_type.0 .0.last().copied().unwrap_or(0);
    if msg_type != AS_REP_MSG_TYPE {
        return Err(Error::AsRepParse(format!(
            "AS-REP msg-type = {msg_type} (expected {AS_REP_MSG_TYPE})"
        )));
    }

    let padata_list = as_rep
        .0
        .padata
        .0
        .as_ref()
        .map(|p| p.0 .0.as_slice())
        .unwrap_or(&[]);

    let pk_rep_padata = padata_list
        .iter()
        .find(|p| padata_type_matches(&p.padata_type.0, PA_PK_AS_REP_TYPE))
        .ok_or_else(|| Error::AsRepParse("no PA-PK-AS-REP padata in AS-REP".into()))?;

    let pa_pk_as_rep: PaPkAsRep = picky_asn1_der::from_bytes(&pk_rep_padata.padata_data.0 .0)
        .map_err(|e| Error::AsRepParse(format!("PA-PK-AS-REP: {e}")))?;

    // Derive the reply-key.
    let reply_key = match pa_pk_as_rep {
        PaPkAsRep::DhInfo(dh_info) => {
            let signed_data = &dh_info.0.dh_signed_data.0 .0;
            let dh_key_info_der = extract_signed_data_econtent(signed_data)?;
            let kdc_dh_info: KdcDhKeyInfo = picky_asn1_der::from_bytes(&dh_key_info_der)
                .map_err(|e| Error::AsRepParse(format!("KdcDhKeyInfo: {e}")))?;
            let nonce_matches_ok = integer_matches_u32(&kdc_dh_info.nonce.0, expected_nonce);
            if !nonce_matches_ok {
                return Err(Error::AsRepParse(format!(
                    "KdcDhKeyInfo nonce mismatch (expected {expected_nonce})"
                )));
            }
            let peer_y = parse_bit_string_integer(&kdc_dh_info.subject_public_key.0)?;
            let zz = client_dh.compute_shared(&peer_y);
            // OtherInfo is empty for the plain DH flow when neither side supplied
            // a DH nonce (RFC 4556 §3.2.3.1 accepts this; k-truncate is the
            // caller-supplied length).
            octet_string_to_key(Hash::Sha256, &zz, &[], kdf_key_bytes)?
        }
        PaPkAsRep::EncKeyPack(bytes) => {
            // RFC 4556 §3.2.3.2: encKeyPack is a CMS ContentInfo wrapping an
            // EnvelopedData(SignedData(ReplyKeyPack)).  The KDC wraps a fresh
            // CEK under our RSA public key (KeyTransRecipientInfo,
            // rsaEncryption), AES-CBC-encrypts the SignedData(ReplyKeyPack)
            // under the CEK, and we do the inverse here.  `kdf_key_bytes` is
            // advisory: the reply-key length is determined by the KDC's
            // chosen Kerberos etype, not the client — we surface a mismatch
            // as a structural error so the caller notices etype confusion.
            let content_info = &bytes.0 .0;
            let reply_key = enveloped::decrypt_enc_key_pack(content_info, client_key)?;
            if reply_key.len() != kdf_key_bytes {
                return Err(Error::AsRepParse(format!(
                    "encKeyPack reply-key is {} bytes, caller expected {} (etype mismatch?)",
                    reply_key.len(),
                    kdf_key_bytes
                )));
            }
            reply_key
        }
    };

    // Ticket bytes — serialize the parsed Ticket back to DER for the caller.
    let ticket_bytes = picky_asn1_der::to_vec(&as_rep.0.ticket.0)
        .map_err(|e| Error::AsRepParse(format!("ticket encode: {e}")))?;

    Ok(AsRepResult {
        ticket: ticket_bytes,
        session_key: reply_key,
        pac_credential_info: None,
        debug_as_req_der: Vec::new(),
    })
}

fn padata_type_matches(v: &IntegerAsn1, expected: i32) -> bool {
    // picky-asn1 IntegerAsn1 wraps the raw DER contents.
    let bytes = &v.0;
    // Interpret up to 4 bytes as signed big-endian; PA data-types fit in a byte.
    let mut acc: i32 = if bytes.first().copied().unwrap_or(0) & 0x80 != 0 {
        -1
    } else {
        0
    };
    for &b in bytes {
        acc = (acc << 8) | (b as i32 & 0xFF);
    }
    acc == expected
}

fn integer_matches_u32(v: &IntegerAsn1, expected: u32) -> bool {
    // Strip leading 0x00 that DER prepends to disambiguate positive numbers.
    let mut bytes = v.0.as_slice();
    while bytes.len() > 1 && bytes[0] == 0 {
        bytes = &bytes[1..];
    }
    if bytes.len() > 4 {
        return false;
    }
    let mut acc: u32 = 0;
    for &b in bytes {
        acc = (acc << 8) | b as u32;
    }
    acc == expected
}

fn parse_bit_string_integer(bs: &BitStringAsn1) -> Result<BigUint> {
    // subjectPublicKey per RFC 4556 §3.2.3.1: BIT STRING wrapping a DER
    // INTEGER (the DH y value).
    let payload = bs.0.payload_view();
    // Payload starts with the DER INTEGER header: tag(0x02) len value.
    if payload.first().copied() != Some(0x02) {
        return Err(Error::AsRepParse("subjectPublicKey not INTEGER".into()));
    }
    let (int_bytes, _rest) = tlv_split(payload)?;
    // int_bytes is the value payload of INTEGER, sign-extended DER form.
    // Strip a single leading 0x00 padding byte if the second byte's MSB is set.
    let mut bs = int_bytes;
    if bs.len() > 1 && bs[0] == 0 && (bs[1] & 0x80) != 0 {
        bs = &bs[1..];
    }
    Ok(BigUint::from_bytes_be(bs))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn i32_der_boundary_values() {
        assert_eq!(i32_to_der_bytes(0), vec![0]);
        assert_eq!(i32_to_der_bytes(1), vec![1]);
        assert_eq!(i32_to_der_bytes(127), vec![127]);
        assert_eq!(i32_to_der_bytes(128), vec![0, 128]); // MSB needs 0x00 pad
        assert_eq!(i32_to_der_bytes(-1), vec![0xFF]);
        assert_eq!(i32_to_der_bytes(-128), vec![0x80]);
    }

    #[test]
    fn u32_der_positive_only() {
        assert_eq!(u32_to_der_bytes(0), vec![0]);
        assert_eq!(
            u32_to_der_bytes(0xDEADBEEF),
            vec![0, 0xDE, 0xAD, 0xBE, 0xEF]
        );
        assert_eq!(u32_to_der_bytes(0x7F), vec![0x7F]);
    }

    #[test]
    fn body_checksum_matches_body_actually_in_as_req() {
        // Build AsReqOpts once, compute the checksum via the public helper,
        // then build the full AS-REQ.  Round-trip: parse the AS-REQ back,
        // re-encode its req_body, SHA-1 it, and confirm the digest matches the
        // checksum we would have embedded — i.e. `compute_as_req_body_checksum`
        // hashes exactly the bytes `build_as_req` puts on the wire.
        //
        // This is the property a strict KDC checks (RFC 4556 §3.2.1): the
        // paChecksum inside the CMS-signed PkAuthenticator must equal
        // SHA-1(DER(KDC-REQ-BODY)) of the request it receives.
        use picky_asn1::date::GeneralizedTime;
        use picky_asn1::wrapper::GeneralizedTimeAsn1;
        use sha1::{Digest, Sha1};

        let till = GeneralizedTime::new(2038, 1, 1, 0, 0, 0).unwrap();
        let etypes = [18i32, 17, 23];
        let cname = ["alice"];
        let sname = ["krbtgt", "EXAMPLE.COM"];
        let opts = AsReqOpts {
            realm: "EXAMPLE.COM",
            cname: &cname,
            sname: &sname,
            pa_pk_as_req_der: &[0x30, 0x00], // stand-in — irrelevant to body
            nonce: 0xDEADBEEF,
            till: GeneralizedTimeAsn1::from(till),
            etypes: &etypes,
        };

        let checksum = compute_as_req_body_checksum(&opts).expect("checksum");
        assert_eq!(checksum.len(), 20, "SHA-1 output is 20 bytes");

        let as_req_der = build_as_req(&opts).expect("build_as_req");
        let parsed: AsReq = picky_asn1_der::from_bytes(&as_req_der).expect("re-parse AS-REQ");
        let body_der = picky_asn1_der::to_vec(&parsed.0.req_body.0).expect("re-encode body");

        let mut expected = [0u8; 20];
        expected.copy_from_slice(&Sha1::digest(&body_der));
        assert_eq!(
            checksum, expected,
            "compute_as_req_body_checksum must hash the exact KdcReqBody DER emitted by build_as_req"
        );
    }

    #[test]
    fn body_checksum_is_deterministic_for_same_opts() {
        // Same inputs → same digest.  Guards against accidental non-determinism
        // creeping into KdcReqBody construction (e.g. reintroducing addresses).
        use picky_asn1::date::GeneralizedTime;
        use picky_asn1::wrapper::GeneralizedTimeAsn1;

        let till = GeneralizedTime::new(2038, 1, 1, 0, 0, 0).unwrap();
        let etypes = [18i32];
        let cname = ["bob"];
        let sname = ["krbtgt", "REALM"];
        let opts = AsReqOpts {
            realm: "REALM",
            cname: &cname,
            sname: &sname,
            pa_pk_as_req_der: &[],
            nonce: 42,
            till: GeneralizedTimeAsn1::from(till),
            etypes: &etypes,
        };
        let a = compute_as_req_body_checksum(&opts).unwrap();
        let b = compute_as_req_body_checksum(&opts).unwrap();
        assert_eq!(a, b);
    }
}