kerbcore 0.3.0

Pure-Rust Kerberos: full etype crypto (AES-SHA1/SHA2 + RC4, RFC 3961/3962/8009/4757) + DER/RFC 4120 codec + AS/TGS client. No FFI, no host krb5.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
//! Server-side AP-REQ acceptor scaffold — the half kerbcore was missing.
//!
//! For the client role, [`crate::client`] builds AP-REQ, decrypts AP-REP, and
//! runs the AS/TGS exchange. The acceptor side — parse an inbound AP-REQ,
//! decrypt the authenticator, validate timestamps, defend against replay — is
//! what libgssapi's `gss_accept_sec_context` does behind an FFI wall. This
//! module ships the primitives so a Rust acceptor (an HTTP service, an SMB
//! server, a custom protocol) can do it without libclang / libkrb5.
//!
//! ## What ships in 0.3
//!
//! - [`parse_ap_req`] — total decoder for `[APPLICATION 14] AP-REQ` → [`ApReq`]
//!   (ticket + encrypted authenticator + AP options).
//! - [`Authenticator`] + [`parse_authenticator`] — decode the decrypted
//!   `[APPLICATION 2]` plaintext into a plain struct.
//! - [`ReplayCache`] trait — storage-agnostic anti-replay for
//!   `(client-principal, ctime, cusec)` triples. Two impls: an in-memory
//!   [`HashSetReplayCache`] (RFC 4120 §3.2.3-compliant when the caller
//!   expires entries at `authenticator.ctime + skew`), and a
//!   [`NoopReplayCache`] for the "I don't care about replay in this deployment"
//!   case (documented, not the default).
//! - [`verify_ap_req`] — pin them all together: decrypt the authenticator with
//!   a caller-supplied session key, check the ctime against `now ± skew`,
//!   record the replay ID, return an [`AuthContext`] the acceptor can use to
//!   pull the negotiated subkey / seq_number / client principal.
//!
//! ## What's deferred to 1.0
//!
//! - **Ticket decrypt** — extracting the session key from
//!   `ticket.enc_part.cipher` needs an `EncTicketPart` parser (currently the
//!   ticket-plaintext parser isn't public). Callers who have the session key
//!   from a keytab-decrypted ticket (or, in a test harness, from a prior AS/TGS
//!   round-trip) can already use `verify_ap_req` today.
//! - **AP-REP builder** — the caller can echo the authenticator's
//!   ctime/cusec back through [`crate::client::parse_enc_ap_rep_part`]-shaped
//!   encoding by hand for now; a `build_ap_rep` is 1.0-scope.
//! - **PAC extraction** — sits inside the ticket plaintext, unblocked by the
//!   same EncTicketPart work.

use crate::client::KU_AP_REQ_AUTH;
use crate::der::{
    application_tag, context_tag, one_or, read_u32, Der, DerError, TAG_BIT_STRING, TAG_SEQUENCE,
};
use crate::keys::{KerberosKey, KeyError};
use crate::messages::Ticket;
use crate::types::{Checksum, EncryptedData, EncryptionKey, KerberosTime, PrincipalName};
use std::collections::HashMap;

// ── AP-REQ ───────────────────────────────────────────────────────────────────

/// Parsed AP-REQ — the acceptor-facing view.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ApReq {
    /// Always 5.
    pub pvno: i32,
    /// Always 14.
    pub msg_type: i32,
    /// 32-bit `APOptions` flags (`AP_OPTS_MUTUAL_REQUIRED`, `AP_OPTS_USE_SESSION_KEY`).
    pub ap_options: u32,
    /// The service ticket.
    pub ticket: Ticket,
    /// Encrypted `Authenticator`.
    pub enc_auth: EncryptedData,
}

/// Total decoder for `[APPLICATION 14] AP-REQ` — malformed input errors, never
/// panics. Structural check only; the authenticator is not decrypted here (the
/// acceptor needs the session key first — see [`verify_ap_req`]).
pub fn parse_ap_req(der: &[u8]) -> Result<ApReq, DerError> {
    let mut r = Der::new(der);
    let (tag, inner) = r.read_tlv()?;
    if tag != application_tag(14) {
        return Err(DerError::TagMismatch {
            expected: application_tag(14),
            found: tag,
        });
    }
    let seq = one_or(inner, TAG_SEQUENCE)?;
    let mut sr = Der::new(seq);
    let pvno = read_i32(sr.expect(context_tag(0))?)?;
    let msg_type = read_i32(sr.expect(context_tag(1))?)?;
    if pvno != 5 || msg_type != 14 {
        return Err(DerError::MsgTypeMismatch);
    }
    // ap-options [2] BIT STRING — one unused-bits octet, then 4 flag octets big-endian.
    let opt_bytes = one_or(sr.expect(context_tag(2))?, TAG_BIT_STRING)?;
    if opt_bytes.len() < 5 {
        return Err(DerError::Truncated);
    }
    let ap_options = u32::from_be_bytes([opt_bytes[1], opt_bytes[2], opt_bytes[3], opt_bytes[4]]);
    let ticket = Ticket::decode(sr.expect(context_tag(3))?)?;
    let enc_auth = EncryptedData::decode(sr.expect(context_tag(4))?)?;
    Ok(ApReq {
        pvno,
        msg_type,
        ap_options,
        ticket,
        enc_auth,
    })
}

// ── Authenticator ────────────────────────────────────────────────────────────

/// `Authenticator ::= [APPLICATION 2] SEQUENCE { authenticator-vno [0] INTEGER,
/// crealm [1] Realm, cname [2] PrincipalName, cksum [3] Checksum OPTIONAL,
/// cusec [4] INTEGER, ctime [5] KerberosTime, subkey [6] EncryptionKey OPTIONAL,
/// seq-number [7] UInt32 OPTIONAL, authorization-data [8] ... OPTIONAL }`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Authenticator {
    /// Always 5.
    pub authenticator_vno: i32,
    /// Client realm.
    pub crealm: String,
    /// Client principal name.
    pub cname: PrincipalName,
    /// Optional application checksum (RFC 4121 GSS uses this heavily).
    pub cksum: Option<Checksum>,
    /// Client microseconds within `ctime`.
    pub cusec: i32,
    /// Client time (Kerberos-format).
    pub ctime: String,
    /// Optional session-subkey the client negotiates for per-message tokens.
    pub subkey: Option<EncryptionKey>,
    /// Optional starting sequence number the client picks.
    pub seq_number: Option<u32>,
}

/// Parse a decrypted `[APPLICATION 2] Authenticator`. Total: malformed input
/// errors. Authorization-data ([8]) is currently skipped without surfacing —
/// unblock-later when the PAC-in-authenticator flow lands (S4U2Self chains
/// carry them).
pub fn parse_authenticator(plaintext: &[u8]) -> Result<Authenticator, DerError> {
    let mut r = Der::new(plaintext);
    let (tag, inner) = r.read_tlv()?;
    if tag != application_tag(2) {
        return Err(DerError::TagMismatch {
            expected: application_tag(2),
            found: tag,
        });
    }
    let seq = one_or(inner, TAG_SEQUENCE)?;
    let mut sr = Der::new(seq);
    let authenticator_vno = read_i32(sr.expect(context_tag(0))?)?;
    if authenticator_vno != 5 {
        return Err(DerError::BadProtocolVersion);
    }
    let crealm = crate::types::decode_realm(sr.expect(context_tag(1))?)?;
    let cname = PrincipalName::decode(sr.expect(context_tag(2))?)?;
    let cksum = if sr.peek_tag() == Some(context_tag(3)) {
        Some(Checksum::decode(sr.expect(context_tag(3))?)?)
    } else {
        None
    };
    let cusec = read_i32(sr.expect(context_tag(4))?)?;
    let ctime = KerberosTime::decode(sr.expect(context_tag(5))?)?.0;
    let subkey = if sr.peek_tag() == Some(context_tag(6)) {
        Some(EncryptionKey::decode(sr.expect(context_tag(6))?)?)
    } else {
        None
    };
    let seq_number = if sr.peek_tag() == Some(context_tag(7)) {
        Some(read_u32(sr.expect(context_tag(7))?)?)
    } else {
        None
    };
    Ok(Authenticator {
        authenticator_vno,
        crealm,
        cname,
        cksum,
        cusec,
        ctime,
        subkey,
        seq_number,
    })
}

// ── Replay cache ────────────────────────────────────────────────────────────

/// Anti-replay storage. An acceptor must reject an `AP-REQ` whose
/// `(client-principal, ctime, cusec)` was seen before within the allowed clock
/// skew — RFC 4120 §3.2.3. The concrete storage (in-memory, Redis, SQLite,
/// distributed cache) is caller-owned; this trait is the boundary.
pub trait ReplayCache {
    /// Try to record `id` with `expires_at` as its watermark. Returns
    /// [`Replay`] when `id` is already present. Implementations SHOULD
    /// garbage-collect entries whose `expires_at` is in the past.
    fn remember(&mut self, id: [u8; 32], expires_at: u64) -> Result<(), Replay>;
}

/// Marker returned when an ID is already in the replay cache — the AP-REQ
/// MUST be rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Replay;

/// In-memory replay cache backed by a `HashMap`. Sufficient for a single-process
/// acceptor; NOT sufficient for a horizontally-scaled service where two
/// instances could each accept the same AP-REQ. For that, plug your own
/// [`ReplayCache`] on top of shared storage.
#[derive(Debug, Default)]
pub struct HashSetReplayCache {
    seen: HashMap<[u8; 32], u64>,
}

impl HashSetReplayCache {
    /// Fresh empty cache.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sweep entries whose `expires_at` is at or before `now_secs`. Call
    /// periodically from the acceptor's housekeeping loop.
    pub fn expire(&mut self, now_secs: u64) {
        self.seen.retain(|_, exp| *exp > now_secs);
    }

    /// How many entries the cache currently holds (post-expiry, if you called
    /// `expire` first).
    #[must_use]
    pub fn len(&self) -> usize {
        self.seen.len()
    }

    /// True when the cache holds no entries.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.seen.is_empty()
    }
}

impl ReplayCache for HashSetReplayCache {
    fn remember(&mut self, id: [u8; 32], expires_at: u64) -> Result<(), Replay> {
        if self.seen.contains_key(&id) {
            return Err(Replay);
        }
        self.seen.insert(id, expires_at);
        Ok(())
    }
}

/// Reject-nothing cache — every `remember` returns `Ok(())`. Use ONLY when the
/// deployment can accept replay (e.g. an idempotent, single-request read
/// endpoint). Named explicitly so `ReplayCache: NoopReplayCache` in the
/// acceptor's config reads as the operator's on-the-record choice.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopReplayCache;

impl ReplayCache for NoopReplayCache {
    fn remember(&mut self, _id: [u8; 32], _expires_at: u64) -> Result<(), Replay> {
        Ok(())
    }
}

// ── verify_ap_req ───────────────────────────────────────────────────────────

/// Outcome of a successful [`verify_ap_req`]. The acceptor uses this to bind
/// the incoming request to the authenticated identity and to pick up any
/// subkey the client negotiated for per-message tokens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthContext {
    /// The decrypted authenticator (ctime, cusec, cksum, subkey, seq_number).
    pub authenticator: Authenticator,
    /// The client realm from the authenticator.
    pub client_realm: String,
    /// The client principal from the authenticator.
    pub client_principal: PrincipalName,
    /// Convenience: same as `authenticator.subkey` — pull if you want the
    /// service-side session key for [`crate::gss`] per-message tokens.
    pub subkey: Option<EncryptionKey>,
    /// Convenience: same as `authenticator.seq_number` — starting seq number.
    pub sequence_number: Option<u32>,
}

/// Errors from [`verify_ap_req`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AcceptorError {
    /// The authenticator ciphertext did not decrypt cleanly under the supplied
    /// session key (integrity check failed OR the wrong key was used).
    Decrypt(&'static str),
    /// The ticket ciphertext did not decrypt cleanly under the service key.
    TicketDecrypt(&'static str),
    /// The decrypted ticket plaintext did not parse as `EncTicketPart`.
    BadTicket(DerError),
    /// Ticket `endtime` is at or before `now_secs`.
    TicketExpired {
        /// The ticket's `endtime` (Kerberos generalized-time).
        endtime: String,
        /// Server-provided `now` in Unix seconds.
        now_secs: u64,
    },
    /// Authenticator `(crealm, cname)` did not match the ticket `(crealm, cname)`.
    /// RFC 4120 §3.2.3 — the authenticator MUST bind to the same principal the
    /// ticket was issued to.
    PrincipalMismatch,
    /// The decrypted plaintext did not parse as `Authenticator`.
    BadAuthenticator(DerError),
    /// `ctime` was outside `now ± clock_skew_seconds`. Prevents a stale
    /// authenticator from being replayed after the skew window.
    ClockSkewExceeded {
        /// Client time (Kerberos generalized-time).
        ctime: String,
        /// Server-provided `now` in Unix seconds.
        now_secs: u64,
        /// The configured skew window.
        allowed_skew_seconds: u64,
    },
    /// Malformed `ctime` — not a Kerberos generalized-time (`YYYYMMDDHHMMSSZ`).
    BadClientTime(String),
    /// The `(cname, ctime, cusec)` triple was seen before within the skew
    /// window — replay rejected.
    Replay,
}

impl std::fmt::Display for AcceptorError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AcceptorError::Decrypt(s) => write!(f, "authenticator decrypt failed: {s}"),
            AcceptorError::TicketDecrypt(s) => write!(f, "ticket decrypt failed: {s}"),
            AcceptorError::BadTicket(e) => write!(f, "ticket parse: {e:?}"),
            AcceptorError::TicketExpired { endtime, now_secs } => {
                write!(f, "ticket endtime {endtime} <= now={now_secs}")
            }
            AcceptorError::PrincipalMismatch => {
                write!(f, "authenticator principal does not match ticket principal")
            }
            AcceptorError::BadAuthenticator(e) => write!(f, "authenticator parse: {e:?}"),
            AcceptorError::ClockSkewExceeded {
                ctime,
                now_secs,
                allowed_skew_seconds,
            } => write!(
                f,
                "authenticator ctime {ctime} outside {allowed_skew_seconds}s of now={now_secs}"
            ),
            AcceptorError::BadClientTime(s) => write!(f, "malformed ctime: {s}"),
            AcceptorError::Replay => write!(f, "AP-REQ replay rejected"),
        }
    }
}

impl std::error::Error for AcceptorError {}

impl From<KeyError> for AcceptorError {
    fn from(_: KeyError) -> Self {
        AcceptorError::Decrypt("KeyError from KerberosKey::decrypt")
    }
}

/// Verify an inbound AP-REQ and gate it against clock skew + replay.
///
/// **Preconditions**: the caller has already extracted `session_key` from the
/// ticket (typical shape: decrypt `ap_req.ticket.enc_part.cipher` with the
/// service's long-term key at key-usage 2, parse `EncTicketPart`, pull `.key`).
/// The full ticket-plaintext parser lands in 1.0; today the shape works for
/// callers who plug the session key in from a keytab or an out-of-band path
/// (tests, fixtures).
///
/// **Postconditions on `Ok`**: the authenticator decrypted cleanly, its
/// `ctime` was within `clock_skew_seconds` of `now_secs`, and the
/// `(cname, ctime, cusec)` replay ID was inserted into `replay_cache` with
/// expiry `now_secs + clock_skew_seconds`. Return value carries the
/// authenticator + convenience aliases for the negotiated subkey / seq_number.
pub fn verify_ap_req<C: ReplayCache>(
    ap_req: &ApReq,
    session_key: &KerberosKey,
    clock_skew_seconds: u64,
    now_secs: u64,
    replay_cache: &mut C,
) -> Result<AuthContext, AcceptorError> {
    // 1) Decrypt the authenticator under the session key at usage 11.
    let plaintext = session_key
        .decrypt(KU_AP_REQ_AUTH, &ap_req.enc_auth.cipher)
        .map_err(AcceptorError::from)?;

    // 2) Parse.
    let authenticator =
        parse_authenticator(&plaintext).map_err(AcceptorError::BadAuthenticator)?;

    // 3) Clock-skew check.
    let ctime_secs = parse_kerberos_time(&authenticator.ctime)
        .ok_or_else(|| AcceptorError::BadClientTime(authenticator.ctime.clone()))?;
    let skew = clock_skew_seconds as i64;
    let delta = ctime_secs as i64 - now_secs as i64;
    if delta.abs() > skew {
        return Err(AcceptorError::ClockSkewExceeded {
            ctime: authenticator.ctime.clone(),
            now_secs,
            allowed_skew_seconds: clock_skew_seconds,
        });
    }

    // 4) Replay check — hash (cname bytes || ctime || cusec).
    let id = replay_id(&authenticator);
    replay_cache
        .remember(id, now_secs.saturating_add(clock_skew_seconds))
        .map_err(|_| AcceptorError::Replay)?;

    Ok(AuthContext {
        subkey: authenticator.subkey.clone(),
        sequence_number: authenticator.seq_number,
        client_realm: authenticator.crealm.clone(),
        client_principal: authenticator.cname.clone(),
        authenticator,
    })
}

/// SHA-256 hash of `(cname bytes || ctime bytes || cusec bytes)` — the replay ID.
fn replay_id(a: &Authenticator) -> [u8; 32] {
    use sha2::{Digest, Sha256};
    let mut h = Sha256::new();
    // A stable-ish serialization: name components joined by 0x1f (unit
    // separator, ASCII), then ctime, then cusec.
    for comp in &a.cname.name_string {
        h.update(comp.as_bytes());
        h.update([0x1f]);
    }
    h.update(a.crealm.as_bytes());
    h.update([0x1e]); // record separator
    h.update(a.ctime.as_bytes());
    h.update([0x1e]);
    h.update((a.cusec as i64).to_be_bytes());
    h.finalize().into()
}

/// Kerberos `GeneralizedTime` (`YYYYMMDDHHMMSSZ`) → Unix seconds. `None` for
/// any parse failure — the caller surfaces a `BadClientTime` in that case.
/// Kerberos always uses UTC, so no timezone offset handling.
fn parse_kerberos_time(s: &str) -> Option<u64> {
    if s.len() != 15 || !s.ends_with('Z') {
        return None;
    }
    let n = |a: usize, b: usize| s[a..b].parse::<u32>().ok();
    let y = n(0, 4)? as i64;
    let mo = n(4, 6)? as i64;
    let d = n(6, 8)? as i64;
    let h = n(8, 10)? as i64;
    let mi = n(10, 12)? as i64;
    let se = n(12, 14)? as i64;
    if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {
        return None;
    }
    // Days-from-civil (Howard Hinnant), UTC epoch anchor.
    let y2 = y - i64::from(mo <= 2);
    let era = if y2 >= 0 { y2 } else { y2 - 399 } / 400;
    let yoe = y2 - era * 400;
    let doy = (153 * (mo + if mo > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    let days = era * 146_097 + doe - 719_468;
    let secs = days * 86_400 + h * 3600 + mi * 60 + se;
    if secs < 0 {
        None
    } else {
        Some(secs as u64)
    }
}

/// Read a KRB Int32 as `i32` from a bare-DER integer element.
fn read_i32(der: &[u8]) -> Result<i32, DerError> {
    let mut r = Der::new(der);
    let n = r.read_integer()?;
    r.finish()?;
    i32::try_from(n).map_err(|_| DerError::IntTooLarge)
}

// ── EncTicketPart + full ticket decrypt ─────────────────────────────────────

/// Key usage — `Ticket` `EncryptedData.cipher`. RFC 4120 §5.4.1: the
/// `EncTicketPart` inside a ticket is encrypted under the service's long-term
/// key at key usage 2.
pub const KU_TICKET: u32 = 2;

/// Parsed `[APPLICATION 3] EncTicketPart` — the ticket plaintext. RFC 4120 §5.3.
///
/// The `caddr` and `transited` fields are not surfaced here (rarely populated
/// in modern deployments; the acceptor cares about the session key, principal,
/// and endtime). `authorization_data` is exposed as raw DER for PAC extraction:
/// the WIN2K-PAC (`ad_type = 128`) sits inside the AD-IF-RELEVANT container per
/// MS-PAC §2.6, which downstream code can walk.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EncTicketPart {
    /// 32-bit `TicketFlags` value (FORWARDABLE, RENEWABLE, INVALID, HW-AUTH, …).
    pub flags: u32,
    /// The session key the KDC issued for this ticket — the whole reason to
    /// decrypt the ticket. Feed this to [`verify_ap_req`] to unlock the
    /// authenticator.
    pub key: EncryptionKey,
    /// Client realm.
    pub crealm: String,
    /// Client principal name.
    pub cname: PrincipalName,
    /// Ticket authentication time (Kerberos generalized-time).
    pub authtime: String,
    /// Optional earliest-use time (usually equal to authtime).
    pub starttime: Option<String>,
    /// Ticket expiry.
    pub endtime: String,
    /// Optional renewal deadline.
    pub renew_till: Option<String>,
    /// Optional raw `AuthorizationData` DER (SEQUENCE OF SEQUENCE { ad-type, ad-data }).
    /// Contains the Windows PAC on MS-KILE. Empty vec when absent.
    pub authorization_data: Vec<u8>,
}

/// Parse a decrypted `[APPLICATION 3] EncTicketPart`. Total: malformed input
/// errors.
pub fn parse_enc_ticket_part(plaintext: &[u8]) -> Result<EncTicketPart, DerError> {
    let mut r = Der::new(plaintext);
    let (tag, inner) = r.read_tlv()?;
    if tag != application_tag(3) {
        return Err(DerError::TagMismatch {
            expected: application_tag(3),
            found: tag,
        });
    }
    let seq = one_or(inner, TAG_SEQUENCE)?;
    let mut sr = Der::new(seq);
    // [0] flags — TicketFlags is a KerberosFlags BIT STRING (1 unused-bits octet + 4 flag octets big-endian).
    let flags_bytes = one_or(sr.expect(context_tag(0))?, TAG_BIT_STRING)?;
    if flags_bytes.len() < 5 {
        return Err(DerError::Truncated);
    }
    let flags = u32::from_be_bytes([
        flags_bytes[1],
        flags_bytes[2],
        flags_bytes[3],
        flags_bytes[4],
    ]);
    // [1] key — EncryptionKey
    let key = EncryptionKey::decode(sr.expect(context_tag(1))?)?;
    // [2] crealm — Realm
    let crealm = crate::types::decode_realm(sr.expect(context_tag(2))?)?;
    // [3] cname — PrincipalName
    let cname = PrincipalName::decode(sr.expect(context_tag(3))?)?;
    // [4] transited — skip (raw)
    let _transited = sr.expect(context_tag(4))?;
    // [5] authtime
    let authtime = KerberosTime::decode(sr.expect(context_tag(5))?)?.0;
    // [6] starttime OPTIONAL
    let starttime = if sr.peek_tag() == Some(context_tag(6)) {
        Some(KerberosTime::decode(sr.expect(context_tag(6))?)?.0)
    } else {
        None
    };
    // [7] endtime
    let endtime = KerberosTime::decode(sr.expect(context_tag(7))?)?.0;
    // [8] renew-till OPTIONAL
    let renew_till = if sr.peek_tag() == Some(context_tag(8)) {
        Some(KerberosTime::decode(sr.expect(context_tag(8))?)?.0)
    } else {
        None
    };
    // [9] caddr OPTIONAL — skip
    if sr.peek_tag() == Some(context_tag(9)) {
        let _ = sr.expect(context_tag(9))?;
    }
    // [10] authorization-data OPTIONAL — raw passthrough
    let authorization_data = if sr.peek_tag() == Some(context_tag(10)) {
        sr.expect(context_tag(10))?.to_vec()
    } else {
        Vec::new()
    };
    Ok(EncTicketPart {
        flags,
        key,
        crealm,
        cname,
        authtime,
        starttime,
        endtime,
        renew_till,
        authorization_data,
    })
}

/// Decrypt `ap_req.ticket.enc_part.cipher` with the service's long-term key
/// (key usage 2 = [`KU_TICKET`]) and parse the resulting `EncTicketPart`.
///
/// This is the first step of a full acceptor: the extracted session key is
/// then fed to [`verify_ap_req`] to unlock the authenticator.
pub fn decrypt_ticket(
    ap_req: &ApReq,
    service_key: &KerberosKey,
) -> Result<EncTicketPart, AcceptorError> {
    let plaintext = service_key
        .decrypt(KU_TICKET, &ap_req.ticket.enc_part.cipher)
        .map_err(|_| AcceptorError::TicketDecrypt("service key rejected ticket ciphertext"))?;
    parse_enc_ticket_part(&plaintext).map_err(AcceptorError::BadTicket)
}

/// Full acceptor pipeline — the "no caller-supplied session key required"
/// variant. Decrypts the ticket with `service_key`, then unlocks the
/// authenticator with the ticket's session key, then does clock-skew + replay.
///
/// Bindings enforced (RFC 4120 §3.2.3):
/// - `authenticator.(crealm, cname)` must equal `enc_ticket.(crealm, cname)`.
/// - `enc_ticket.endtime` must be strictly after `now_secs`.
///
/// Returns the [`AuthContext`] on success — same shape as [`verify_ap_req`]
/// but the pipeline chose the session key itself.
pub fn verify_ap_req_full<C: ReplayCache>(
    ap_req: &ApReq,
    service_key: &KerberosKey,
    clock_skew_seconds: u64,
    now_secs: u64,
    replay_cache: &mut C,
) -> Result<(AuthContext, EncTicketPart), AcceptorError> {
    let enc_ticket = decrypt_ticket(ap_req, service_key)?;

    // Ticket endtime must be in the future.
    let endtime_secs = parse_kerberos_time(&enc_ticket.endtime)
        .ok_or_else(|| AcceptorError::BadClientTime(enc_ticket.endtime.clone()))?;
    if endtime_secs <= now_secs {
        return Err(AcceptorError::TicketExpired {
            endtime: enc_ticket.endtime.clone(),
            now_secs,
        });
    }

    // Build a KerberosKey from the session key stored in the ticket.
    let session = KerberosKey::from_i32(enc_ticket.key.keytype, enc_ticket.key.keyvalue.clone())
        .map_err(AcceptorError::from)?;

    // Run the existing authenticator pipeline.
    let ctx = verify_ap_req(ap_req, &session, clock_skew_seconds, now_secs, replay_cache)?;

    // Bind check — authenticator's (crealm, cname) MUST match the ticket's.
    if ctx.client_realm != enc_ticket.crealm || ctx.client_principal != enc_ticket.cname {
        return Err(AcceptorError::PrincipalMismatch);
    }

    Ok((ctx, enc_ticket))
}

// ── AP-REP builder ──────────────────────────────────────────────────────────

/// Build a mutual-auth `AP-REP` (RFC 4120 §5.5.2) as the service's response to
/// an AP-REQ carrying `AP_OPTS_MUTUAL_REQUIRED`. Echoes the authenticator's
/// `(ctime, cusec)` back to the client (encrypted under the ticket session key
/// at key usage 12) so the client can confirm the service could actually read
/// its authenticator — i.e., holds the ticket session key.
///
/// `subkey` and `seq_number`, when supplied, negotiate a service-chosen
/// per-message key + starting sequence for the subsequent GSS-Wrap traffic.
///
/// **Deterministic-confounder variant**: `confounder` is passed in for tests.
/// The confounder length MUST equal the session key's confounder length
/// (`session_key.enctype().confounder_len()` — 16 for the AES profiles, 8 for
/// RC4). In production the caller fills it from OS CSPRNG; a helper
/// [`build_ap_rep`] with a fresh confounder is offered below.
pub fn build_ap_rep_with_confounder(
    session_key: &KerberosKey,
    client_authenticator: &Authenticator,
    subkey: Option<&EncryptionKey>,
    seq_number: Option<u32>,
    confounder: &[u8],
) -> Vec<u8> {
    use crate::client::KU_AP_REP_ENC_PART;
    use crate::der::{encode_integer, encode_sequence, explicit, tlv};

    // EncAPRepPart ::= [APPLICATION 27] SEQUENCE {
    //     ctime [0] KerberosTime, cusec [1] Microseconds,
    //     subkey [2] EncryptionKey OPTIONAL, seq-number [3] UInt32 OPTIONAL }
    let mut inner = explicit(0, &KerberosTime(client_authenticator.ctime.clone()).encode());
    inner.extend_from_slice(&explicit(
        1,
        &encode_integer(client_authenticator.cusec as i64),
    ));
    if let Some(sk) = subkey {
        inner.extend_from_slice(&explicit(2, &sk.encode()));
    }
    if let Some(n) = seq_number {
        inner.extend_from_slice(&explicit(3, &encode_integer(n as i64)));
    }
    let enc_ap_rep_part = tlv(application_tag(27), &encode_sequence(&inner));

    // Encrypt under the ticket session key at usage 12.
    let cipher = session_key.encrypt_with_confounder(
        KU_AP_REP_ENC_PART,
        confounder,
        &enc_ap_rep_part,
    );
    let enc_part = EncryptedData {
        etype: session_key.enctype().to_i32(),
        kvno: None,
        cipher,
    };

    // AP-REP ::= [APPLICATION 15] SEQUENCE { pvno [0] INTEGER(5), msg-type [1] INTEGER(15),
    //     enc-part [2] EncryptedData }
    let body = [
        explicit(0, &encode_integer(5)),
        explicit(1, &encode_integer(15)),
        explicit(2, &enc_part.encode()),
    ]
    .concat();
    tlv(application_tag(15), &encode_sequence(&body))
}

/// Build an AP-REP with a fresh OS-CSPRNG confounder — the production path.
/// See [`build_ap_rep_with_confounder`] for the deterministic-confounder
/// variant used in tests.
pub fn build_ap_rep(
    session_key: &KerberosKey,
    client_authenticator: &Authenticator,
    subkey: Option<&EncryptionKey>,
    seq_number: Option<u32>,
) -> Vec<u8> {
    let mut conf = vec![0u8; session_key.enctype().confounder_len()];
    getrandom::getrandom(&mut conf)
        .expect("OS CSPRNG available for AP-REP confounder");
    build_ap_rep_with_confounder(session_key, client_authenticator, subkey, seq_number, &conf)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::{build_ap_req_with_confounder, AP_OPTS_MUTUAL_REQUIRED};
    use crate::keys::Enctype;
    use crate::messages::Ticket;

    fn ticket_stub() -> Ticket {
        Ticket {
            tkt_vno: 5,
            realm: "CORP.LOCAL".into(),
            sname: PrincipalName {
                name_type: 2,
                name_string: vec!["HTTP".into(), "web.corp.local".into()],
            },
            enc_part: EncryptedData {
                etype: 18,
                kvno: None,
                cipher: vec![0u8; 32], // opaque placeholder — never decrypted in these tests
            },
        }
    }

    fn make_ap_req(session_key: &KerberosKey, ctime: &str, cusec: i32) -> Vec<u8> {
        build_ap_req_with_confounder(
            &ticket_stub(),
            session_key,
            "CORP.LOCAL",
            &PrincipalName {
                name_type: 1,
                name_string: vec!["alice".into()],
            },
            ctime,
            cusec,
            AP_OPTS_MUTUAL_REQUIRED,
            None,
            None,
            None,
            &[0u8; 16], // deterministic confounder for tests
        )
    }

    fn key() -> KerberosKey {
        KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x42u8; 32]).unwrap()
    }

    #[test]
    fn ap_req_round_trips_through_parse() {
        let k = key();
        let der = make_ap_req(&k, "20260101120000Z", 0);
        let parsed = parse_ap_req(&der).unwrap();
        assert_eq!(parsed.pvno, 5);
        assert_eq!(parsed.msg_type, 14);
        assert_eq!(parsed.ap_options, AP_OPTS_MUTUAL_REQUIRED);
        assert_eq!(parsed.ticket.sname.name_string[0], "HTTP");
    }

    #[test]
    fn verify_ap_req_happy_path() {
        let k = key();
        // 2026-01-01 12:00:00 UTC = 1_767_268_800 unix
        let now: u64 = 1_767_268_800;
        let der = make_ap_req(&k, "20260101120000Z", 0);
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        let ctx = verify_ap_req(&ap, &k, 300, now, &mut cache).unwrap();
        assert_eq!(ctx.client_realm, "CORP.LOCAL");
        assert_eq!(ctx.client_principal.name_string[0], "alice");
        assert_eq!(cache.len(), 1);
    }

    #[test]
    fn verify_ap_req_rejects_wrong_key() {
        let k = key();
        let now: u64 = 1_767_268_800;
        let der = make_ap_req(&k, "20260101120000Z", 0);
        let ap = parse_ap_req(&der).unwrap();
        let wrong = KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0xffu8; 32]).unwrap();
        let mut cache = HashSetReplayCache::new();
        let err = verify_ap_req(&ap, &wrong, 300, now, &mut cache).unwrap_err();
        assert!(matches!(err, AcceptorError::Decrypt(_)));
    }

    #[test]
    fn verify_ap_req_rejects_replay() {
        let k = key();
        let now: u64 = 1_767_268_800;
        let der = make_ap_req(&k, "20260101120000Z", 0);
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        verify_ap_req(&ap, &k, 300, now, &mut cache).unwrap();
        let err = verify_ap_req(&ap, &k, 300, now, &mut cache).unwrap_err();
        assert_eq!(err, AcceptorError::Replay);
    }

    #[test]
    fn verify_ap_req_rejects_stale_ctime() {
        let k = key();
        // ctime is at 2026-01-01 12:00:00; check with now = 1 hour later, skew = 60s.
        let now: u64 = 1_767_268_800 + 3600;
        let der = make_ap_req(&k, "20260101120000Z", 0);
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        let err = verify_ap_req(&ap, &k, 60, now, &mut cache).unwrap_err();
        assert!(matches!(err, AcceptorError::ClockSkewExceeded { .. }));
    }

    #[test]
    fn noop_replay_cache_accepts_everything() {
        let mut c = NoopReplayCache;
        assert!(c.remember([0u8; 32], 0).is_ok());
        assert!(c.remember([0u8; 32], 0).is_ok());
        assert!(c.remember([0u8; 32], 0).is_ok());
    }

    #[test]
    fn hash_set_replay_cache_expires() {
        let mut c = HashSetReplayCache::new();
        c.remember([1u8; 32], 100).unwrap();
        c.remember([2u8; 32], 200).unwrap();
        assert_eq!(c.len(), 2);
        c.expire(150);
        assert_eq!(c.len(), 1);
        c.expire(999);
        assert!(c.is_empty());
    }

    #[test]
    fn parse_kerberos_time_epoch_and_2026() {
        assert_eq!(parse_kerberos_time("19700101000000Z"), Some(0));
        // 2026-01-01T12:00:00Z = 1_767_268_800
        assert_eq!(parse_kerberos_time("20260101120000Z"), Some(1_767_268_800));
    }

    #[test]
    fn parse_kerberos_time_rejects_bogus() {
        assert!(parse_kerberos_time("20260132120000Z").is_none()); // day 32
        assert!(parse_kerberos_time("20260101120000").is_none()); // no Z
        assert!(parse_kerberos_time("XXXX0101120000Z").is_none()); // non-digit
    }

    // ── EncTicketPart + verify_ap_req_full + AP-REP tests ─────────────────

    /// Encode a synthetic EncTicketPart for `alice@CORP.LOCAL` with the given
    /// endtime and session key, then encrypt it under `service_key` at
    /// KU_TICKET so parse+decrypt round-trips.
    fn synth_enc_ticket_part(
        session_key: &EncryptionKey,
        crealm: &str,
        cname: &PrincipalName,
        authtime: &str,
        endtime: &str,
    ) -> Vec<u8> {
        use crate::der::{encode_integer, encode_sequence, explicit, tlv};
        use crate::types::encode_realm;
        let _ = encode_integer;
        // flags [0] BIT STRING — 0x40000000 = FORWARDABLE (any nonzero pattern OK).
        let mut flags_bytes = vec![0u8]; // unused-bits
        flags_bytes.extend_from_slice(&0x4000_0000u32.to_be_bytes());
        let flags = explicit(0, &tlv(TAG_BIT_STRING, &flags_bytes));
        let key = explicit(1, &session_key.encode());
        let crealm = explicit(2, &encode_realm(crealm));
        let cname_der = explicit(3, &cname.encode());
        // transited [4] TransitedEncoding ::= SEQUENCE { tr-type [0] Int32, contents [1] OCTET STRING }
        let tr_body = [
            explicit(0, &crate::der::encode_integer(0)),
            explicit(1, &crate::der::encode_octet_string(&[])),
        ]
        .concat();
        let transited = explicit(4, &encode_sequence(&tr_body));
        let authtime = explicit(5, &KerberosTime(authtime.to_string()).encode());
        let endtime = explicit(7, &KerberosTime(endtime.to_string()).encode());
        let inner: Vec<u8> = [flags, key, crealm, cname_der, transited, authtime, endtime]
            .concat();
        tlv(application_tag(3), &encode_sequence(&inner))
    }

    /// Full round-trip AP-REQ builder that puts a real encrypted ticket in
    /// the AP-REQ (unlike `make_ap_req` which uses opaque cipher bytes).
    #[allow(clippy::too_many_arguments)]
    fn make_ap_req_full(
        service_key: &KerberosKey,
        session_key: &KerberosKey,
        crealm: &str,
        cname: &PrincipalName,
        ctime: &str,
        cusec: i32,
        authtime: &str,
        endtime: &str,
    ) -> Vec<u8> {
        // Session key exposed as its wire EncryptionKey.
        let session_wire = EncryptionKey {
            keytype: session_key.enctype().to_i32(),
            keyvalue: session_key.key().to_vec(),
        };
        // Build EncTicketPart plaintext, encrypt under the service key at KU_TICKET.
        let etp_plain = synth_enc_ticket_part(&session_wire, crealm, cname, authtime, endtime);
        let ticket_cipher =
            service_key.encrypt_with_confounder(KU_TICKET, &[0u8; 16], &etp_plain);
        let ticket = Ticket {
            tkt_vno: 5,
            realm: crealm.into(),
            sname: PrincipalName {
                name_type: 2,
                name_string: vec!["HTTP".into(), "web.corp.local".into()],
            },
            enc_part: EncryptedData {
                etype: service_key.enctype().to_i32(),
                kvno: None,
                cipher: ticket_cipher,
            },
        };
        build_ap_req_with_confounder(
            &ticket,
            session_key,
            crealm,
            cname,
            ctime,
            cusec,
            AP_OPTS_MUTUAL_REQUIRED,
            None,
            None,
            None,
            &[0u8; 16],
        )
    }

    #[test]
    fn full_acceptor_end_to_end_happy_path() {
        let service_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x11u8; 32]).unwrap();
        let session_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x22u8; 32]).unwrap();
        let cname = PrincipalName {
            name_type: 1,
            name_string: vec!["alice".into()],
        };
        // now = 2026-01-01T12:00:00Z; ctime = now; ticket endtime = 10h later.
        let now: u64 = 1_767_268_800;
        let der = make_ap_req_full(
            &service_key,
            &session_key,
            "CORP.LOCAL",
            &cname,
            "20260101120000Z",
            0,
            "20260101120000Z",
            "20260101220000Z",
        );
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        let (ctx, etp) = verify_ap_req_full(&ap, &service_key, 300, now, &mut cache).unwrap();
        assert_eq!(ctx.client_principal.name_string, vec!["alice".to_string()]);
        assert_eq!(etp.crealm, "CORP.LOCAL");
        assert_eq!(etp.flags & 0x4000_0000, 0x4000_0000, "FORWARDABLE bit set");
        assert!(cache.len() == 1);
    }

    #[test]
    fn full_acceptor_rejects_expired_ticket() {
        let service_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x11u8; 32]).unwrap();
        let session_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x22u8; 32]).unwrap();
        let cname = PrincipalName {
            name_type: 1,
            name_string: vec!["alice".into()],
        };
        let now: u64 = 1_767_268_800;
        // Ticket endtime BEFORE now.
        let der = make_ap_req_full(
            &service_key,
            &session_key,
            "CORP.LOCAL",
            &cname,
            "20260101110000Z", // ctime — still within skew (1 hour before now)
            0,
            "20260101100000Z",
            "20260101110000Z", // endtime = now - 3600
        );
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        // Skew needs to be wide enough to accept the ctime (else fails on skew instead).
        let err = verify_ap_req_full(&ap, &service_key, 7200, now, &mut cache).unwrap_err();
        assert!(matches!(err, AcceptorError::TicketExpired { .. }));
    }

    #[test]
    fn full_acceptor_rejects_wrong_service_key() {
        let service_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x11u8; 32]).unwrap();
        let wrong_service_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0xffu8; 32]).unwrap();
        let session_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x22u8; 32]).unwrap();
        let cname = PrincipalName {
            name_type: 1,
            name_string: vec!["alice".into()],
        };
        let now: u64 = 1_767_268_800;
        let der = make_ap_req_full(
            &service_key,
            &session_key,
            "CORP.LOCAL",
            &cname,
            "20260101120000Z",
            0,
            "20260101120000Z",
            "20260101220000Z",
        );
        let ap = parse_ap_req(&der).unwrap();
        let mut cache = HashSetReplayCache::new();
        let err =
            verify_ap_req_full(&ap, &wrong_service_key, 300, now, &mut cache).unwrap_err();
        assert!(matches!(err, AcceptorError::TicketDecrypt(_)));
    }

    #[test]
    fn ap_rep_round_trips_ctime_cusec() {
        use crate::client::{parse_ap_rep, parse_enc_ap_rep_part, KU_AP_REP_ENC_PART};
        let session_key =
            KerberosKey::new(Enctype::Aes256CtsHmacSha1_96, vec![0x33u8; 32]).unwrap();
        let auth = Authenticator {
            authenticator_vno: 5,
            crealm: "CORP.LOCAL".into(),
            cname: PrincipalName {
                name_type: 1,
                name_string: vec!["alice".into()],
            },
            cksum: None,
            cusec: 12345,
            ctime: "20260101120000Z".into(),
            subkey: None,
            seq_number: None,
        };
        let der =
            build_ap_rep_with_confounder(&session_key, &auth, None, Some(42), &[0u8; 16]);
        let enc = parse_ap_rep(&der).unwrap();
        let plaintext = session_key
            .decrypt(KU_AP_REP_ENC_PART, &enc.cipher)
            .expect("AP-REP decrypt");
        let part = parse_enc_ap_rep_part(&plaintext).unwrap();
        assert_eq!(part.ctime, "20260101120000Z");
        assert_eq!(part.cusec, 12345);
        assert_eq!(part.seq_number, Some(42));
        assert!(part.subkey.is_none());
    }
}