diego 0.1.0

Pure Rust Active Directory security diagnostic agent. AS-REP Roasting, Kerberoasting, LDAP enumeration, OPSEC-friendly with Claude API analysis and MCP server mode.
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
//! MCP tool definitions and handlers.
//!
//! Each tool corresponds to one or more diagnostic capabilities in the existing
//! modules. Tools run in-process and return JSON-serializable results.

use std::sync::Arc;
use std::time::Duration;

use ldap3::LdapConnAsync;
use serde_json::Value;

use crate::config::Config;
use crate::modules::kerberos::asreq::{build_asrep_roast_request, parse_kdc_response, KdcResponse};
use crate::modules::kerberos::hashcat::format_asrep_18200;
use crate::modules::kerberos::mod_send_kerberos_tcp;
use crate::modules::ldap::parser::extract_spn_accounts;
use crate::modules::ldap::queries::{
    query_asrep_candidates, query_description_leaks, query_password_policy,
    query_spn_accounts, query_unconstrained_delegation,
};
use crate::modules::passive::llmnr::{capture_llmnr, capture_nbtns};
use crate::report::{Finding, Severity};

// ─── Tool schema definitions ──────────────────────────────────────────────────

/// Returns the static list of MCP tools this server exposes.
pub fn tool_list() -> Vec<Value> {
    let ad_args = serde_json::json!({
        "type": "object",
        "properties": {
            "dc_ip":    {"type": "string", "description": "Domain Controller IP address"},
            "domain":   {"type": "string", "description": "AD domain name (e.g. corp.local)"},
            "username": {"type": "string", "description": "Domain username"},
            "password": {"type": "string", "description": "Domain password"},
            "timeout_secs": {"type": "integer", "default": 10}
        },
        "required": ["dc_ip", "domain", "username", "password"]
    });

    vec![
        make_tool(
            "enumerate_asrep_candidates",
            "List domain accounts that have DONT_REQ_PREAUTH set (AS-REP Roasting targets). Returns account names and DNs.",
            ad_args.clone(),
        ),
        make_tool(
            "enumerate_spn_accounts",
            "List service accounts with registered SPNs (Kerberoasting targets). Returns SAM account names, SPN list, and supported encryption types.",
            ad_args.clone(),
        ),
        make_tool(
            "check_unconstrained_delegation",
            "Find computer accounts with Unconstrained Delegation enabled. This is a Critical finding — coercion attacks can lead to full domain compromise.",
            ad_args.clone(),
        ),
        make_tool(
            "check_password_policy",
            "Read the Default Domain Password Policy (min length, lockout threshold, history, etc.).",
            ad_args.clone(),
        ),
        make_tool(
            "scan_description_leaks",
            "Search user account description fields for potential hardcoded credentials or sensitive information.",
            ad_args.clone(),
        ),
        make_tool(
            "run_asrep_roasting",
            "Perform AS-REP Roasting: send AS-REQ without pre-auth to a list of candidate usernames and return Hashcat-mode-18200 hashes for vulnerable accounts.",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "dc_ip":    {"type": "string"},
                    "domain":   {"type": "string"},
                    "usernames": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of usernames to test (obtain from enumerate_asrep_candidates)"
                    },
                    "timeout_secs": {"type": "integer", "default": 10}
                },
                "required": ["dc_ip", "domain", "usernames"]
            }),
        ),
        make_tool(
            "run_kerberoasting",
            "Perform Kerberoasting: authenticate with the provided credentials, then request TGS tickets for all SPN accounts and return Hashcat-mode-13100 hashes.",
            ad_args.clone(),
        ),
        make_tool(
            "listen_llmnr",
            "Passively listen for LLMNR and NBT-NS broadcast queries on the local network. Returns observed queries with source IPs and queried hostnames.",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "timeout_secs": {"type": "integer", "default": 30, "description": "How long to listen (seconds)"}
                }
            }),
        ),
        make_tool(
            "enumerate_constrained_delegation",
            "Find accounts and computers with Constrained Delegation configured (msDS-AllowedToDelegateTo or T2A4D flag). S4U2Proxy abuse can allow impersonating any user to listed services.",
            ad_args.clone(),
        ),
        make_tool(
            "enumerate_rbcd",
            "Find objects with Resource-Based Constrained Delegation (msDS-AllowedToActOnBehalfOfOtherIdentity set). An attacker controlling a listed machine account can impersonate any user.",
            ad_args.clone(),
        ),
        make_tool(
            "enumerate_privileged_groups",
            "List members of high-privilege AD groups: Domain Admins, Enterprise Admins, Backup Operators, Account Operators, etc. Uses recursive membership expansion.",
            ad_args.clone(),
        ),
        make_tool(
            "enumerate_stale_service_passwords",
            "Find service accounts (with SPNs) whose passwords are older than 365 days. Old passwords on Kerberoastable accounts are significantly easier to crack.",
            ad_args.clone(),
        ),
        make_tool(
            "full_scan",
            "Run all diagnostic modules (LDAP enumeration, AS-REP Roasting, Kerberoasting, LLMNR listen) and return all findings as structured JSON.",
            ad_args,
        ),
    ]
}

fn make_tool(name: &str, description: &str, schema: Value) -> Value {
    serde_json::json!({
        "name": name,
        "description": description,
        "inputSchema": schema
    })
}

// ─── Tool dispatcher ──────────────────────────────────────────────────────────

/// Dispatch a tools/call request to the appropriate handler.
pub async fn dispatch(name: &str, args: &Value) -> anyhow::Result<Value> {
    match name {
        "enumerate_asrep_candidates" => enumerate_asrep_candidates(args).await,
        "enumerate_spn_accounts"     => enumerate_spn_accounts(args).await,
        "check_unconstrained_delegation" => check_unconstrained_delegation(args).await,
        "check_password_policy"      => check_password_policy(args).await,
        "scan_description_leaks"     => scan_description_leaks(args).await,
        "run_asrep_roasting"         => run_asrep_roasting(args).await,
        "run_kerberoasting"          => run_kerberoasting(args).await,
        "listen_llmnr"               => listen_llmnr(args).await,
        "enumerate_constrained_delegation" => mcp_constrained_delegation(args).await,
        "enumerate_rbcd"             => mcp_rbcd(args).await,
        "enumerate_privileged_groups" => mcp_privileged_groups(args).await,
        "enumerate_stale_service_passwords" => mcp_stale_passwords(args).await,
        "full_scan"                  => full_scan(args).await,
        _ => anyhow::bail!("Unknown tool: {}", name),
    }
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

fn get_str<'a>(args: &'a Value, key: &str) -> anyhow::Result<&'a str> {
    args.get(key)
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("Missing argument: {}", key))
}

fn get_timeout(args: &Value) -> u64 {
    args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(10)
}

async fn ldap_connect(dc_ip: &str, domain: &str, username: &str, password: &str, timeout_secs: u64)
    -> anyhow::Result<ldap3::Ldap>
{
    let url = format!("ldap://{}:389", dc_ip);
    let (conn, mut ldap) = tokio::time::timeout(
        Duration::from_secs(timeout_secs),
        LdapConnAsync::new(&url),
    )
    .await
    .map_err(|_| anyhow::anyhow!("LDAP connection timeout"))?
    .map_err(|e| anyhow::anyhow!("LDAP connection failed: {}", e))?;

    ldap3::drive!(conn);

    ldap.simple_bind(&format!("{}@{}", username, domain), password)
        .await?
        .success()
        .map_err(|e| anyhow::anyhow!("LDAP bind failed: {}", e))?;

    Ok(ldap)
}

fn domain_to_base_dn(domain: &str) -> String {
    domain.split('.').map(|p| format!("DC={}", p)).collect::<Vec<_>>().join(",")
}

// ─── Tool implementations ─────────────────────────────────────────────────────

async fn enumerate_asrep_candidates(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = query_asrep_candidates(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .filter_map(|o| {
            let sam = o.get_first("sAMAccountName")?;
            Some(serde_json::json!({ "username": sam, "dn": o.dn }))
        })
        .collect();

    Ok(serde_json::json!({ "candidates": result, "count": result.len() }))
}

async fn enumerate_spn_accounts(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = query_spn_accounts(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .filter_map(|o| {
            let sam = o.get_first("sAMAccountName")?;
            let spns = o.get_all("servicePrincipalName");
            let enc = o.get_u32("msDS-SupportedEncryptionTypes").unwrap_or(0);
            Some(serde_json::json!({ "sam_name": sam, "spns": spns, "supported_enc_types": enc }))
        })
        .collect();

    Ok(serde_json::json!({ "spn_accounts": result, "count": result.len() }))
}

async fn check_unconstrained_delegation(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = query_unconstrained_delegation(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .map(|o| serde_json::json!({
            "cn": o.get_first("cn"),
            "dnsHostName": o.get_first("dnsHostName"),
            "os": o.get_first("operatingSystem"),
            "dn": o.dn,
        }))
        .collect();

    Ok(serde_json::json!({
        "unconstrained_delegation_computers": result,
        "count": result.len(),
        "severity": if result.is_empty() { "none" } else { "CRITICAL" }
    }))
}

async fn check_password_policy(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = query_password_policy(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    if let Some(policy) = objs.first() {
        let min_len = policy.get_u32("minPwdLength").unwrap_or(0);
        let lockout = policy.get_u32("lockoutThreshold").unwrap_or(0);
        Ok(serde_json::json!({
            "minPwdLength": min_len,
            "lockoutThreshold": lockout,
            "pwdHistoryLength": policy.get_u32("pwdHistoryLength"),
            "assessment": {
                "min_length_ok": min_len >= 14,
                "lockout_enabled": lockout > 0,
                "brute_force_risk": lockout == 0,
            }
        }))
    } else {
        Ok(serde_json::json!({ "error": "Could not read password policy" }))
    }
}

async fn scan_description_leaks(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = query_description_leaks(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .filter_map(|o| {
            let sam = o.get_first("sAMAccountName")?;
            let desc = o.get_first("description")?;
            Some(serde_json::json!({ "account": sam, "description": desc, "dn": o.dn }))
        })
        .collect();

    Ok(serde_json::json!({ "leaks": result, "count": result.len() }))
}

async fn run_asrep_roasting(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let timeout = get_timeout(args);
    let realm = domain.to_uppercase();

    let usernames: Vec<&str> = args.get("usernames")
        .and_then(Value::as_array)
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();

    let dc_addr: std::net::SocketAddr = format!("{}:88", dc_ip).parse()
        .map_err(|_| anyhow::anyhow!("Invalid DC IP: {}", dc_ip))?;

    let mut hashes = Vec::new();

    for username in usernames {
        let nonce: u32 = rand::random();
        let req = build_asrep_roast_request(username, &realm, nonce);

        match mod_send_kerberos_tcp(&dc_addr, &req, timeout).await {
            Ok(raw) => {
                if let Ok(KdcResponse::AsRep(enc)) = parse_kdc_response(&raw) {
                    let hash = format_asrep_18200(enc.etype, username, &realm, &enc.cipher);
                    hashes.push(serde_json::json!({
                        "username": username,
                        "etype": enc.etype,
                        "hashcat_hash": hash,
                        "hashcat_mode": 18200,
                    }));
                }
            }
            Err(e) => eprintln!("[mcp] AS-REP error for {}: {}", username, e),
        }

        // Jitter
        let ms: u64 = {
            use rand::Rng;
            rand::thread_rng().gen_range(100..=300)
        };
        tokio::time::sleep(Duration::from_millis(ms)).await;
    }

    Ok(serde_json::json!({ "vulnerable_accounts": hashes, "count": hashes.len() }))
}

async fn run_kerberoasting(args: &Value) -> anyhow::Result<Value> {
    // For kerberoasting we need valid credentials and the SPN list from LDAP.
    // This tool combines enumerate_spn_accounts + the kerberoasting logic.
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let spn_objs = query_spn_accounts(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let spn_accounts = extract_spn_accounts(&spn_objs);
    if spn_accounts.is_empty() {
        return Ok(serde_json::json!({ "hashes": [], "count": 0, "message": "No SPN accounts found" }));
    }

    let config = build_minimal_config(dc_ip, domain, username, password, timeout)?;
    let ctx = crate::modules::LdapContext {
        asrep_candidates: vec![],
        spn_accounts,
    };

    // Use the kerberos module to run the full kerberoasting
    use crate::modules::DiagnosticModule;
    let kerb_mod = crate::modules::kerberos::KerberosModule::new(ctx);
    let findings = kerb_mod.run(Arc::new(config)).await.unwrap_or_default();

    let hashes: Vec<Value> = findings.iter()
        .filter(|f| f.id.starts_with("KERB-TGS-"))
        .map(|f| serde_json::json!({
            "id": f.id,
            "account": f.evidence.get("sam_name"),
            "spn": f.evidence.get("spn"),
            "etype": f.evidence.get("etype"),
            "hashcat_hash": f.evidence.get("hashcat_hash"),
            "hashcat_mode": 13100,
        }))
        .collect();

    Ok(serde_json::json!({ "hashes": hashes, "count": hashes.len() }))
}

async fn listen_llmnr(args: &Value) -> anyhow::Result<Value> {
    let timeout = args.get("timeout_secs").and_then(Value::as_u64).unwrap_or(30);

    let (llmnr, nbtns) = tokio::join!(
        capture_llmnr(timeout),
        capture_nbtns(timeout),
    );

    let all: Vec<Value> = llmnr.iter().chain(nbtns.iter())
        .map(|c| serde_json::json!({
            "protocol": c.protocol,
            "source_ip": c.source_ip,
            "queried_name": c.queried_name,
        }))
        .collect();

    Ok(serde_json::json!({
        "broadcasts": all,
        "count": all.len(),
        "spoofing_risk": !all.is_empty(),
    }))
}

async fn mcp_constrained_delegation(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = crate::modules::ldap::queries::query_constrained_delegation(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .filter_map(|o| {
            let name = o.get_first("sAMAccountName")?;
            let targets = o.get_all("msDS-AllowedToDelegateTo");
            let uac = o.get_u32("userAccountControl").unwrap_or(0);
            Some(serde_json::json!({
                "account": name,
                "dn": o.dn,
                "delegation_targets": targets,
                "protocol_transition": uac & 0x100000 != 0,
            }))
        })
        .collect();

    Ok(serde_json::json!({ "constrained_delegation": result, "count": result.len() }))
}

async fn mcp_rbcd(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = crate::modules::ldap::queries::query_rbcd(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .map(|o| serde_json::json!({
            "cn": o.get_first("cn"),
            "sam_name": o.get_first("sAMAccountName"),
            "dnsHostName": o.get_first("dnsHostName"),
            "dn": o.dn,
        }))
        .collect();

    Ok(serde_json::json!({ "rbcd_objects": result, "count": result.len() }))
}

async fn mcp_privileged_groups(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let groups = crate::modules::ldap::queries::query_privileged_groups(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = groups.iter()
        .map(|(group, members)| {
            let names: Vec<&str> = members.iter()
                .filter_map(|m| m.get_first("sAMAccountName"))
                .collect();
            serde_json::json!({ "group": group, "member_count": members.len(), "members": names })
        })
        .collect();

    Ok(serde_json::json!({ "privileged_groups": result }))
}

async fn mcp_stale_passwords(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);
    let base_dn = domain_to_base_dn(domain);

    let mut ldap = ldap_connect(dc_ip, domain, username, password, timeout).await?;
    let objs = crate::modules::ldap::queries::query_stale_service_passwords(&mut ldap, &base_dn).await?;
    ldap.unbind().await.ok();

    let result: Vec<Value> = objs.iter()
        .filter_map(|o| {
            let name = o.get_first("sAMAccountName")?;
            let pwd_ts = o.get_first("pwdLastSet").unwrap_or("0");
            let age_days = pwd_ts.parse::<i64>()
                .map(|ts| (chrono::Utc::now().timestamp() - (ts - 116_444_736_000_000_000) / 10_000_000) / 86400)
                .unwrap_or(0);
            Some(serde_json::json!({
                "account": name,
                "dn": o.dn,
                "password_age_days": age_days,
                "spns": o.get_all("servicePrincipalName"),
            }))
        })
        .collect();

    Ok(serde_json::json!({ "stale_accounts": result, "count": result.len() }))
}

async fn full_scan(args: &Value) -> anyhow::Result<Value> {
    let dc_ip = get_str(args, "dc_ip")?;
    let domain = get_str(args, "domain")?;
    let username = get_str(args, "username")?;
    let password = get_str(args, "password")?;
    let timeout = get_timeout(args);

    let config = Arc::new(build_minimal_config(dc_ip, domain, username, password, timeout)?);

    use crate::modules::DiagnosticModule;
    let ldap_mod = crate::modules::ldap::LdapModule::new();
    let ldap_findings = ldap_mod.run(Arc::clone(&config)).await.unwrap_or_default();

    let (_, ctx) = crate::modules::ldap::run_ldap_and_extract_context(Arc::clone(&config))
        .await
        .unwrap_or_else(|_| (vec![], crate::modules::LdapContext {
            asrep_candidates: vec![],
            spn_accounts: vec![],
        }));

    let kerb_mod = crate::modules::kerberos::KerberosModule::new(ctx);
    let kerb_findings = kerb_mod.run(Arc::clone(&config)).await.unwrap_or_default();

    let all: Vec<&Finding> = ldap_findings.iter().chain(kerb_findings.iter()).collect();

    let summary = serde_json::json!({
        "critical": all.iter().filter(|f| f.severity == Severity::Critical).count(),
        "high":     all.iter().filter(|f| f.severity == Severity::High).count(),
        "medium":   all.iter().filter(|f| f.severity == Severity::Medium).count(),
        "low":      all.iter().filter(|f| f.severity == Severity::Low).count(),
        "total":    all.len(),
    });

    Ok(serde_json::json!({
        "findings": all,
        "summary": summary,
    }))
}

fn build_minimal_config(
    dc_ip: &str,
    domain: &str,
    username: &str,
    password: &str,
    timeout_secs: u64,
) -> anyhow::Result<Config> {
    use std::net::IpAddr;
    use std::str::FromStr;

    let ip = IpAddr::from_str(dc_ip)
        .map_err(|_| anyhow::anyhow!("Invalid DC IP: {}", dc_ip))?;

    Ok(Config {
        dc_ip: ip,
        domain: domain.to_string(),
        base_dn: domain.split('.').map(|p| format!("DC={}", p)).collect::<Vec<_>>().join(","),
        username: username.to_string(),
        password: password.to_string(),
        modules: vec![
            crate::config::ModuleKind::Ldap,
            crate::config::ModuleKind::Kerberos,
        ],
        output: None,
        format: crate::config::ReportFormat::Json,
        timeout_secs,
        interface: None,
        ai_analyze: false,
        chat: false,
        ai_model: crate::ai::claude::DEFAULT_MODEL.to_string(),
        mcp: false,
    })
}