rusthound-ce 2.5.14

Active Directory data collector for Bloodhound Community Edition written in rust.
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
//! ESC8 scanner, Web Enrollment HTTP/HTTPS probe + EPA (Channel Binding) detection.
//!
//! Detects whether a CA exposes the `/certsrv/certfnsh.asp` endpoint over HTTP
//! (always vulnerable to NTLM relay) or over HTTPS without Extended Protection for
//! Authentication (EPA / Channel Binding), which is also vulnerable.
//!
//! The EPA check works by sending a minimal NTLM Type 1 (Negotiate) message to the
//! HTTPS endpoint and parsing the server's NTLM Type 2 (Challenge) response. If the
//! `MsvAvChannelBindings` AvPair (AvId `0x000A`) is absent from the challenge's
//! `TargetInfo`, EPA is not enforced and the endpoint is relay-able.
//!
//! This approach requires a single HTTP round-trip, no credentials, no full
//! NTLM handshake, no relay attempted.
//!
//! Three outcomes are distinguished per endpoint, matching SharpHound's JSON shape:
//!
//! | Situation                          | JSON                                               |
//! |------------------------------------|----------------------------------------------------|
//! | TCP port closed / unreachable      | `Collected: true`, `NotVulnerable_PortInaccessible` |
//! | Port open, HTTP request failed     | `Collected: false` + `FailureReason`                |
//! | Port open, status determined       | `Collected: true` + the matching status             |
//!
//! A closed port is a *result*, not a collection failure: the CA was successfully
//! determined not to expose web enrollment there. A 404 on an open port is the
//! opposite, the probe could not conclude, so it is reported as not collected.
//! Both endpoints are ALWAYS emitted, so an empty `HttpEnrollmentEndpoints` array
//! now only ever means "the module did not run".
//!
//! Module path: `src/modules/adcs/esc8.rs`
//! Required Cargo dependency: `reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls-ring"] }`

use crate::objects::enterpriseca::{WebEnrollmentEndpoint, WebEnrollmentResult};
use crate::utils::b64::{b64_decode, b64_encode};
use log::{debug, warn};
use reqwest::blocking::Client;
use reqwest::header::{AUTHORIZATION, WWW_AUTHENTICATE};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;

// NTLM AvPair IDs

/// End-of-list marker in NTLM TargetInfo AvPairs.
const MV_AV_EOL: u16 = 0x0000;

/// `MsvAvChannelBindings`, present with non-zero length when EPA is required.
const MV_AV_CHANNEL_BINDINGS: u16 = 0x000A;

// Timeouts

/// TCP connect timeout for the port-reachability pre-check.
const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
/// Connect timeout for the reqwest clients.
const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
/// Total request timeout, plain HTTP.
const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
/// Total request timeout, HTTPS (TLS handshake included).
const HTTPS_TIMEOUT: Duration = Duration::from_secs(8);

// Minimal NTLM Type 1 (Negotiate)

/// Anonymous NTLM Type 1 Negotiate token.
///
/// Flags encoded (little-endian `0xa0088207`):
///  NTLMSSP_NEGOTIATE_UNICODE                  (0x00000001)
///  NTLMSSP_NEGOTIATE_OEM                      (0x00000002)
///  NTLMSSP_REQUEST_TARGET                     (0x00000004)
///  NTLMSSP_NEGOTIATE_NTLM                     (0x00000200)
///  NTLMSSP_NEGOTIATE_ALWAYS_SIGN              (0x00008000)
///  NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY (0x00080000)
///  NTLMSSP_NEGOTIATE_128                      (0x20000000)
///  NTLMSSP_NEGOTIATE_56                       (0x80000000)
///
/// NEGOTIATE_VERSION (0x02000000) MUST NOT be set here: MS-NLMP ยง2.2.1.1
/// requires an 8-byte Version block when that flag is present, and this
/// minimal 32-byte token omits it. IIS/HTTP.sys rejects a Type 1 that claims
/// NEGOTIATE_VERSION without a Version block: it never returns a Type 2
/// challenge, so the EPA probe cannot see MsvAvChannelBindings and the CA
/// is silently reported as not ESC8-vulnerable.
///
/// Domain and Workstation fields are empty; no version block.
const NTLM_NEGOTIATE: &[u8] = &[
    // Signature
    0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00,
    // MessageType = 1
    0x01, 0x00, 0x00, 0x00,
    // NegotiateFlags LE 0xa0088207 (no NEGOTIATE_VERSION 0x02000000: without a Version block
    // present, IIS rejects the Type 1 as malformed and never returns a Type 2 challenge).
    0x07, 0x82, 0x08, 0xa0,
    // DomainNameFields: empty
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // WorkstationFields: empty
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

// Status string values matching BloodHound CE expected format.
pub const STATUS_VULNERABLE_HTTP:  &str = "Vulnerable_NtlmHttpEndpoint";
pub const STATUS_VULNERABLE_HTTPS: &str = "Vulnerable_NtlmHttpsEndpointWithoutEpa";
pub const STATUS_NOT_VULN_EPA:     &str = "NotVulnerable_EpaEnabled";
pub const STATUS_NOT_VULN_PORT:    &str = "NotVulnerable_PortInaccessible";

/// Value of `Type` in the serialized endpoint, matching SharpHound.
const TYPE_WEB_ENROLLMENT: &str = "WebEnrollmentApplication";

/// URL reported in the JSON, kept identical to SharpHound for ingest parity.
/// The probe itself targets `certfnsh.asp` under this path.
fn display_url(scheme: &str, host: &str) -> String {
    format!("{}://{}/certsrv/", scheme, host)
}

/// URL actually requested by the probes.
fn probe_url(scheme: &str, host: &str) -> String {
    format!("{}://{}/certsrv/certfnsh.asp", scheme, host)
}

// Public types

/// Status of a single web-enrollment endpoint (HTTP or HTTPS).
#[derive(Debug, Clone, PartialEq)]
pub enum WebEnrollmentStatus {
    /// Endpoint answered but web enrollment is not exposed, or NTLM not offered.
    NotFound,
    /// Web enrollment is reachable and NTLM auth is available, relay possible.
    Vulnerable,
    /// Web enrollment is on HTTPS and EPA/channel binding is enforced, protected.
    Protected,
}

/// Outcome of a single probe, mapped 1:1 onto the three JSON shapes.
#[derive(Debug, Clone, PartialEq)]
pub enum ProbeOutcome {
    /// The port answered and a status could be determined.
    Reached(WebEnrollmentStatus),
    /// TCP connection refused, filtered or timed out. This is a result.
    PortClosed,
    /// Port open but the HTTP exchange failed (404, TLS error, timeout...).
    Failed(String),
}

/// Reduce an outcome to a status; anything but `Reached` counts as not found.
fn outcome_status(outcome: &ProbeOutcome) -> WebEnrollmentStatus {
    match outcome {
        ProbeOutcome::Reached(status) => status.clone(),
        _ => WebEnrollmentStatus::NotFound,
    }
}

// Builder functions for WebEnrollmentEndpoint
// (impl on an external type would violate the orphan rule)

/// Shared tail of both builders: a closed port and a failed request.
fn build_non_result(
    url: String,
    outcome: &ProbeOutcome,
) -> Option<WebEnrollmentEndpoint> {
    match outcome {
        ProbeOutcome::PortClosed => Some(WebEnrollmentEndpoint {
            result: Some(WebEnrollmentResult {
                url,
                enrollment_type:           TYPE_WEB_ENROLLMENT.to_string(),
                status:                    STATUS_NOT_VULN_PORT.to_string(),
                adcs_web_enrollment_http:  false,
                adcs_web_enrollment_https: false,
                adcs_web_enrollment_epa:   false,
            }),
            collected:      true,
            failure_reason: None,
        }),
        ProbeOutcome::Failed(reason) => Some(WebEnrollmentEndpoint {
            result:         None,
            collected:      false,
            failure_reason: Some(reason.clone()),
        }),
        ProbeOutcome::Reached(_) => None,
    }
}

/// Build a WebEnrollmentEndpoint from a plain-HTTP probe outcome.
fn build_http_endpoint(host: &str, outcome: &ProbeOutcome) -> WebEnrollmentEndpoint {
    let url = display_url("http", host);

    if let Some(ep) = build_non_result(url.clone(), outcome) {
        return ep;
    }

    let vulnerable = outcome_status(outcome) == WebEnrollmentStatus::Vulnerable;

    WebEnrollmentEndpoint {
        result: Some(WebEnrollmentResult {
            url,
            enrollment_type:           TYPE_WEB_ENROLLMENT.to_string(),
            status: if vulnerable {
                STATUS_VULNERABLE_HTTP.to_string()
            } else {
                STATUS_NOT_VULN_PORT.to_string()
            },
            adcs_web_enrollment_http:  vulnerable,
            adcs_web_enrollment_https: false,
            adcs_web_enrollment_epa:   false,
        }),
        collected:      true,
        failure_reason: None,
    }
}

/// Build a WebEnrollmentEndpoint from an HTTPS probe outcome.
fn build_https_endpoint(host: &str, outcome: &ProbeOutcome) -> WebEnrollmentEndpoint {
    let url = display_url("https", host);

    if let Some(ep) = build_non_result(url.clone(), outcome) {
        return ep;
    }

    let (status, https, epa) = match outcome_status(outcome) {
        WebEnrollmentStatus::Vulnerable => (STATUS_VULNERABLE_HTTPS.to_string(), true,  false),
        WebEnrollmentStatus::Protected  => (STATUS_NOT_VULN_EPA.to_string(),     true,  true),
        WebEnrollmentStatus::NotFound   => (STATUS_NOT_VULN_PORT.to_string(),    false, false),
    };

    WebEnrollmentEndpoint {
        result: Some(WebEnrollmentResult {
            url,
            enrollment_type:           TYPE_WEB_ENROLLMENT.to_string(),
            status,
            adcs_web_enrollment_http:  false,
            adcs_web_enrollment_https: https,
            adcs_web_enrollment_epa:   epa,
        }),
        collected:      true,
        failure_reason: None,
    }
}

/// Full ESC8 probe result for a CA host.
#[derive(Debug, Clone)]
pub struct Esc8Result {
    pub host: String,
    /// HTTP endpoint status (a closed port or failed request collapses to `NotFound`).
    pub http: WebEnrollmentStatus,
    /// HTTPS endpoint status (checks EPA via NTLM Type 2 parsing).
    pub https: WebEnrollmentStatus,
    /// `true` if either endpoint is relay-able.
    pub vulnerable: bool,
    /// Both endpoints (HTTP + HTTPS), ready for JSON serialization.
    /// Never empty: two entries are always produced.
    pub endpoints: Vec<WebEnrollmentEndpoint>,
}

// Public API

/// Run the full ESC8 probe against a CA host (both HTTP and HTTPS).
///
/// Always returns a result carrying exactly two endpoints, so the caller can
/// tell "probed, nothing found" apart from "never probed".
pub fn check_esc8(host: &str) -> Esc8Result {
    let http_outcome  = probe_http(host);
    let https_outcome = probe_https(host);

    let http  = outcome_status(&http_outcome);
    let https = outcome_status(&https_outcome);

    let vulnerable = http  == WebEnrollmentStatus::Vulnerable
        || https == WebEnrollmentStatus::Vulnerable;

    if http == WebEnrollmentStatus::Vulnerable {
        warn!(
            "ESC8 detected on {}, Web Enrollment exposed over HTTP without EPA \
             (NTLM relay possible on {})",
            host,
            probe_url("http", host)
        );
    }
    if https == WebEnrollmentStatus::Vulnerable {
        warn!(
            "ESC8 detected on {}, Web Enrollment over HTTPS without Channel Binding \
             (NTLM relay possible on {})",
            host,
            probe_url("https", host)
        );
    }
    if https == WebEnrollmentStatus::Protected {
        debug!("ESC8 HTTPS {}: EPA/Channel Binding enforced, protected", host);
    }
    if let ProbeOutcome::Failed(ref reason) = http_outcome {
        debug!("ESC8 HTTP {} not collected: {}", host, reason);
    }
    if let ProbeOutcome::Failed(ref reason) = https_outcome {
        debug!("ESC8 HTTPS {} not collected: {}", host, reason);
    }

    let endpoints = vec![
        build_http_endpoint(host, &http_outcome),
        build_https_endpoint(host, &https_outcome),
    ];

    Esc8Result {
        host: host.to_string(),
        http,
        https,
        vulnerable,
        endpoints,
    }
}

// Port reachability

/// Result of the TCP pre-check.
enum PortState {
    /// At least one resolved address accepted the connection.
    Open,
    /// Every resolved address refused, filtered or timed out.
    Closed,
    /// The name could not be resolved at all.
    Unresolved(String),
}

/// Test whether `host:port` accepts a TCP connection.
///
/// Run before the HTTP request so that "nothing is listening" can be reported as
/// `NotVulnerable_PortInaccessible` rather than as a transport failure.
fn check_port(host: &str, port: u16) -> PortState {
    let addrs = match (host, port).to_socket_addrs() {
        Ok(a) => a.collect::<Vec<_>>(),
        Err(e) => {
            return PortState::Unresolved(format!(
                "DNS resolution failed for {}:{}: {}",
                host, port, e
            ));
        }
    };

    if addrs.is_empty() {
        return PortState::Unresolved(format!("no address resolved for {}:{}", host, port));
    }

    for addr in &addrs {
        match TcpStream::connect_timeout(addr, TCP_CONNECT_TIMEOUT) {
            Ok(_) => {
                debug!("ESC8 port check {}:{} open ({})", host, port, addr);
                return PortState::Open;
            }
            Err(e) => debug!("ESC8 port check {} unreachable: {}", addr, e),
        }
    }

    PortState::Closed
}

// Internal probes

/// Probe the plain-HTTP enrollment endpoint.
///
/// A `401` response carrying `WWW-Authenticate: NTLM` or `Negotiate` over HTTP
/// is sufficient to flag ESC8, HTTP provides no channel-binding protection.
///
/// A `404` means IIS is up but web enrollment is not installed: the probe cannot
/// conclude, so it is reported as not collected, like SharpHound does.
fn probe_http(host: &str) -> ProbeOutcome {
    let url = probe_url("http", host);
    debug!("ESC8 HTTP probe: {}", url);

    match check_port(host, 80) {
        PortState::Open => {}
        PortState::Closed => return ProbeOutcome::PortClosed,
        PortState::Unresolved(reason) => return ProbeOutcome::Failed(reason),
    }

    let client = match Client::builder()
        .timeout(HTTP_TIMEOUT)
        .connect_timeout(HTTP_CONNECT_TIMEOUT)
        .redirect(reqwest::redirect::Policy::limited(3))
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            return ProbeOutcome::Failed(format!("failed to build HTTP client for {}: {}", url, e));
        }
    };

    let response = match client.head(&url).send() {
        Ok(r) => r,
        Err(e) => {
            return ProbeOutcome::Failed(format!("HTTP request to {} failed: {}", url, e));
        }
    };

    let status = response.status();
    let code   = status.as_u16();
    let has_ntlm = response
        .headers()
        .get_all(WWW_AUTHENTICATE)
        .iter()
        .any(|v| {
            let s = v.to_str().unwrap_or("").to_lowercase();
            s.starts_with("ntlm") || s.starts_with("negotiate")
        });

    debug!("ESC8 HTTP probe {}: status={} ntlm={}", host, code, has_ntlm);

    if code == 401 {
        return if has_ntlm {
            ProbeOutcome::Reached(WebEnrollmentStatus::Vulnerable)
        } else {
            // Authentication required but NTLM is not offered (Kerberos-only).
            ProbeOutcome::Reached(WebEnrollmentStatus::NotFound)
        };
    }

    if status.is_success() || status.is_redirection() {
        // Endpoint answers without requiring authentication: nothing to relay.
        return ProbeOutcome::Reached(WebEnrollmentStatus::NotFound);
    }

    ProbeOutcome::Failed(format!(
        "Response status code does not indicate success: {} ({}) for {}",
        code,
        status.canonical_reason().unwrap_or("Unknown"),
        url
    ))
}

/// Probe the HTTPS enrollment endpoint and check for EPA (Channel Binding).
///
/// Sends a minimal NTLM Type 1 Negotiate. If the server responds with a Type 2
/// Challenge, parses the `TargetInfo` AvPairs to check for `MsvAvChannelBindings`.
/// Absent: EPA disabled: relay possible.
fn probe_https(host: &str) -> ProbeOutcome {
    let url = probe_url("https", host);
    debug!("ESC8 HTTPS probe: {}", url);

    match check_port(host, 443) {
        PortState::Open => {}
        PortState::Closed => return ProbeOutcome::PortClosed,
        PortState::Unresolved(reason) => return ProbeOutcome::Failed(reason),
    }

    let neg_b64    = b64_encode(NTLM_NEGOTIATE);
    let auth_value = format!("NTLM {}", neg_b64);

    let client = match Client::builder()
        .timeout(HTTPS_TIMEOUT)
        .connect_timeout(HTTP_CONNECT_TIMEOUT)
        .danger_accept_invalid_certs(true)
        .build()
    {
        Ok(c) => c,
        Err(e) => {
            return ProbeOutcome::Failed(format!("failed to build HTTPS client for {}: {}", url, e));
        }
    };

    let response = match client.get(&url).header(AUTHORIZATION, &auth_value).send() {
        Ok(r) => r,
        Err(e) => {
            return ProbeOutcome::Failed(format!("HTTPS request to {} failed: {}", url, e));
        }
    };

    let status = response.status();
    let code   = status.as_u16();
    debug!("ESC8 HTTPS probe {}: status={}", host, code);

    if code != 401 {
        if status.is_success() || status.is_redirection() {
            return ProbeOutcome::Reached(WebEnrollmentStatus::NotFound);
        }
        return ProbeOutcome::Failed(format!(
            "Response status code does not indicate success: {} ({}) for {}",
            code,
            status.canonical_reason().unwrap_or("Unknown"),
            url
        ));
    }

    // Find the NTLM Type 2 Challenge token in WWW-Authenticate headers
    let challenge_token = response
        .headers()
        .get_all(WWW_AUTHENTICATE)
        .iter()
        .find_map(|v| {
            let s = v.to_str().unwrap_or("");
            let lower = s.to_ascii_lowercase();
            if let Some(rest) = lower.strip_prefix("ntlm ") {
                let token_b64 = rest.trim();
                if token_b64.len() > 16 {
                    let orig = s["ntlm ".len()..].trim();
                    return b64_decode(orig);
                }
            }
            None
        });

    match challenge_token {
        None => {
            debug!(
                "ESC8 HTTPS {}: no NTLM challenge received (Kerberos-only or not installed)",
                host
            );
            ProbeOutcome::Reached(WebEnrollmentStatus::NotFound)
        }
        Some(token) => {
            if parse_epa_channel_bindings(&token) {
                debug!("ESC8 HTTPS {}: MsvAvChannelBindings present: EPA enforced", host);
                ProbeOutcome::Reached(WebEnrollmentStatus::Protected)
            } else {
                debug!("ESC8 HTTPS {}: MsvAvChannelBindings absent: EPA disabled", host);
                ProbeOutcome::Reached(WebEnrollmentStatus::Vulnerable)
            }
        }
    }
}

// NTLM Type 2 / EPA parsing

/// Parse an NTLM Type 2 (Challenge) token and return `true` if
/// `MsvAvChannelBindings` (AvId `0x000A`) is present with a **non-zero** length.
/// <https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/34a9417d-7cc0-43b0-b61c-1f19740df66f>
///
/// NTLM Type 2 layout (all little-endian):
///
/// | Offset | Size | Field               |
/// |--------|------|---------------------|
/// |  0     |  8   | Signature           |
/// |  8     |  4   | MessageType = 2     |
/// | 12     |  8   | TargetNameFields    |
/// | 20     |  4   | NegotiateFlags      |
/// | 24     |  8   | ServerChallenge     |
/// | 32     |  8   | Reserved            |
/// | 40     |  8   | TargetInfoFields    |
/// | 48     |  8   | Version (optional)  |
/// | 56+    |  โ€ฆ   | Payload             |
///
/// AvPair layout: `AvId u16 | AvLen u16 | AvValue [u8; AvLen]`
pub fn parse_epa_channel_bindings(token: &[u8]) -> bool {
    if token.len() < 48 {
        debug!("NTLM token too short ({} bytes), cannot parse as Type 2", token.len());
        return false;
    }

    if &token[0..8] != b"NTLMSSP\0" {
        debug!("NTLM signature mismatch");
        return false;
    }

    let msg_type = u32::from_le_bytes([token[8], token[9], token[10], token[11]]);
    if msg_type != 2 {
        debug!("Not a Type 2 message (MessageType={})", msg_type);
        return false;
    }

    let ti_len = u16::from_le_bytes([token[40], token[41]]) as usize;
    let ti_off = u32::from_le_bytes([token[44], token[45], token[46], token[47]]) as usize;

    if ti_len == 0 {
        debug!("TargetInfo is empty, no AvPairs to inspect");
        return false;
    }
    if token.len() < ti_off.saturating_add(ti_len) {
        debug!(
            "TargetInfo out of bounds (off={}, len={}, token_len={})",
            ti_off, ti_len, token.len()
        );
        return false;
    }

    let avpairs = &token[ti_off..ti_off + ti_len];
    debug!("Parsing {} bytes of AvPairs", avpairs.len());

    let mut i = 0;
    while i + 4 <= avpairs.len() {
        let av_id  = u16::from_le_bytes([avpairs[i],     avpairs[i + 1]]);
        let av_len = u16::from_le_bytes([avpairs[i + 2], avpairs[i + 3]]) as usize;

        match av_id {
            MV_AV_EOL => {
                debug!("MsvAvEOL reached");
                break;
            }
            MV_AV_CHANNEL_BINDINGS => {
                debug!("MsvAvChannelBindings found (av_len={})", av_len);
                return av_len > 0;
            }
            other => {
                debug!("AvPair id=0x{:04x} len={}, skipping", other, av_len);
                i += 4 + av_len;
            }
        }
    }

    false
}

// Tests

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

    // Test helpers

    fn build_type2(avpairs: &[u8]) -> Vec<u8> {
        let mut t = Vec::new();
        t.extend_from_slice(b"NTLMSSP\0");
        t.extend_from_slice(&2u32.to_le_bytes());
        t.extend_from_slice(&0u16.to_le_bytes());
        t.extend_from_slice(&0u16.to_le_bytes());
        t.extend_from_slice(&56u32.to_le_bytes());
        t.extend_from_slice(&0u32.to_le_bytes());
        t.extend_from_slice(&[0x01u8; 8]);
        t.extend_from_slice(&[0u8; 8]);
        let ti_len = avpairs.len() as u16;
        t.extend_from_slice(&ti_len.to_le_bytes());
        t.extend_from_slice(&ti_len.to_le_bytes());
        t.extend_from_slice(&56u32.to_le_bytes());
        t.extend_from_slice(&[0u8; 8]);
        t.extend_from_slice(avpairs);
        t
    }

    fn avpairs_with_channel_bindings(value: &[u8]) -> Vec<u8> {
        let mut p = Vec::new();
        p.extend_from_slice(&MV_AV_CHANNEL_BINDINGS.to_le_bytes());
        p.extend_from_slice(&(value.len() as u16).to_le_bytes());
        p.extend_from_slice(value);
        p.extend_from_slice(&MV_AV_EOL.to_le_bytes());
        p.extend_from_slice(&0u16.to_le_bytes());
        p
    }

    fn avpairs_without_channel_bindings() -> Vec<u8> {
        let name: Vec<u8> = "SERVER"
            .encode_utf16()
            .flat_map(|u| u.to_le_bytes())
            .collect();
        let mut p = Vec::new();
        p.extend_from_slice(&0x0001u16.to_le_bytes());
        p.extend_from_slice(&(name.len() as u16).to_le_bytes());
        p.extend_from_slice(&name);
        p.extend_from_slice(&MV_AV_EOL.to_le_bytes());
        p.extend_from_slice(&0u16.to_le_bytes());
        p
    }

    // parse_epa_channel_bindings

    #[test]
    fn epa_present_with_non_zero_value() {
        let cbt = [0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE,
                   0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
        let token = build_type2(&avpairs_with_channel_bindings(&cbt));
        assert!(parse_epa_channel_bindings(&token));
    }

    #[test]
    fn epa_present_but_zero_length() {
        let token = build_type2(&avpairs_with_channel_bindings(&[]));
        assert!(!parse_epa_channel_bindings(&token));
    }

    #[test]
    fn epa_absent_from_avpairs() {
        let token = build_type2(&avpairs_without_channel_bindings());
        assert!(!parse_epa_channel_bindings(&token));
    }

    #[test]
    fn epa_multiple_avpairs_with_channel_bindings_last() {
        let name: Vec<u8> = "DC01"
            .encode_utf16()
            .flat_map(|u| u.to_le_bytes())
            .collect();
        let cbt = [0xAA, 0xBB, 0xCC, 0xDD];
        let mut avpairs = Vec::new();
        avpairs.extend_from_slice(&0x0001u16.to_le_bytes());
        avpairs.extend_from_slice(&(name.len() as u16).to_le_bytes());
        avpairs.extend_from_slice(&name);
        avpairs.extend_from_slice(&MV_AV_CHANNEL_BINDINGS.to_le_bytes());
        avpairs.extend_from_slice(&(cbt.len() as u16).to_le_bytes());
        avpairs.extend_from_slice(&cbt);
        avpairs.extend_from_slice(&MV_AV_EOL.to_le_bytes());
        avpairs.extend_from_slice(&0u16.to_le_bytes());
        let token = build_type2(&avpairs);
        assert!(parse_epa_channel_bindings(&token));
    }

    #[test]
    fn epa_empty_avpairs() {
        let token = build_type2(&[]);
        assert!(!parse_epa_channel_bindings(&token));
    }

    // Structural validation

    #[test]
    fn token_too_short_returns_false() {
        assert!(!parse_epa_channel_bindings(&[0u8; 10]));
        assert!(!parse_epa_channel_bindings(&[]));
    }

    #[test]
    fn invalid_signature_returns_false() {
        let mut token = build_type2(&avpairs_without_channel_bindings());
        token[0] = 0xFF;
        assert!(!parse_epa_channel_bindings(&token));
    }

    #[test]
    fn wrong_message_type_returns_false() {
        let mut token = build_type2(&avpairs_without_channel_bindings());
        token[8]  = 0x01;
        token[9]  = 0x00;
        token[10] = 0x00;
        token[11] = 0x00;
        assert!(!parse_epa_channel_bindings(&token));
    }

    #[test]
    fn target_info_offset_out_of_bounds_returns_false() {
        let avpairs = avpairs_without_channel_bindings();
        let mut token = build_type2(&avpairs);
        let bad_offset = (token.len() + 1024) as u32;
        token[44..48].copy_from_slice(&bad_offset.to_le_bytes());
        assert!(!parse_epa_channel_bindings(&token));
    }

    // Base64 helpers

    #[test]
    fn base64_roundtrip_ntlm_negotiate() {
        let encoded = b64_encode(NTLM_NEGOTIATE);
        let decoded = b64_decode(&encoded).expect("base64_decode should succeed");
        assert_eq!(NTLM_NEGOTIATE, decoded.as_slice());
    }

    #[test]
    fn base64_known_vector() {
        assert_eq!(b64_encode(b"Man"), "TWFu");
        assert_eq!(b64_decode("TWFu"), Some(b"Man".to_vec()));
    }

    #[test]
    fn base64_with_padding() {
        assert_eq!(b64_encode(b"Ma"), "TWE=");
        assert_eq!(b64_decode("TWE="), Some(b"Ma".to_vec()));
        assert_eq!(b64_encode(b"M"), "TQ==");
        assert_eq!(b64_decode("TQ=="), Some(b"M".to_vec()));
    }

    #[test]
    fn base64_decode_invalid_char_returns_none() {
        assert_eq!(b64_decode("TQ!Q"), None);
    }

    #[test]
    fn base64_decode_empty_input() {
        assert_eq!(b64_decode(""), Some(vec![]));
    }

    // URL helpers

    #[test]
    fn urls_match_sharphound_shape() {
        assert_eq!(display_url("http", "ca.corp.local"), "http://ca.corp.local/certsrv/");
        assert_eq!(
            probe_url("https", "ca.corp.local"),
            "https://ca.corp.local/certsrv/certfnsh.asp"
        );
    }

    // Network probe (non-routable host)

    /// Regression test for the empty `HttpEnrollmentEndpoints` bug: an
    /// unreachable host must still produce two endpoints, and a closed port is a
    /// result (`Collected: true`), not a collection failure.
    #[test]
    fn unreachable_host_reports_two_inaccessible_endpoints() {
        let result = check_esc8("192.0.2.1");

        assert_eq!(result.endpoints.len(), 2, "both endpoints must be reported");
        assert!(!result.vulnerable, "non-routable host must not be flagged");
        assert_eq!(result.http, WebEnrollmentStatus::NotFound);
        assert_eq!(result.https, WebEnrollmentStatus::NotFound);

        for ep in &result.endpoints {
            assert!(ep.collected, "a closed port is collected data");
            assert!(ep.failure_reason.is_none());
            assert_eq!(ep.result.as_ref().unwrap().status, STATUS_NOT_VULN_PORT);
        }
    }

    // WebEnrollmentEndpoint builders

    #[test]
    fn from_http_vulnerable() {
        let ep = build_http_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Reached(WebEnrollmentStatus::Vulnerable),
        );
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.url, "http://ca.corp.local/certsrv/");
        assert_eq!(r.enrollment_type, TYPE_WEB_ENROLLMENT);
        assert_eq!(r.status, STATUS_VULNERABLE_HTTP);
        assert!(r.adcs_web_enrollment_http);
        assert!(!r.adcs_web_enrollment_https);
        assert!(!r.adcs_web_enrollment_epa);
        assert!(ep.collected);
        assert!(ep.failure_reason.is_none());
    }

    #[test]
    fn from_http_reached_but_not_exposed() {
        let ep = build_http_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Reached(WebEnrollmentStatus::NotFound),
        );
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.status, STATUS_NOT_VULN_PORT);
        assert!(!r.adcs_web_enrollment_http);
        assert!(ep.collected);
    }

    /// Port 80 closed: reported as a result, mirroring SharpHound.
    #[test]
    fn from_http_port_closed() {
        let ep = build_http_endpoint("ca.corp.local", &ProbeOutcome::PortClosed);
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.status, STATUS_NOT_VULN_PORT);
        assert!(ep.collected);
        assert!(ep.failure_reason.is_none());
    }

    /// Port open but IIS answered 404: web enrollment not installed, the probe
    /// could not conclude, so nothing is collected.
    #[test]
    fn from_http_request_failed() {
        let ep = build_http_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Failed("Response status code does not indicate success: 404".into()),
        );
        assert!(ep.result.is_none());
        assert!(!ep.collected);
        assert!(ep.failure_reason.as_ref().unwrap().contains("404"));
    }

    #[test]
    fn from_https_vulnerable() {
        let ep = build_https_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Reached(WebEnrollmentStatus::Vulnerable),
        );
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.url, "https://ca.corp.local/certsrv/");
        assert_eq!(r.status, STATUS_VULNERABLE_HTTPS);
        assert!(!r.adcs_web_enrollment_http);
        assert!(r.adcs_web_enrollment_https);
        assert!(!r.adcs_web_enrollment_epa);
    }

    #[test]
    fn from_https_protected() {
        let ep = build_https_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Reached(WebEnrollmentStatus::Protected),
        );
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.status, STATUS_NOT_VULN_EPA);
        assert!(r.adcs_web_enrollment_https);
        assert!(r.adcs_web_enrollment_epa);
    }

    #[test]
    fn from_https_port_closed() {
        let ep = build_https_endpoint("ca.corp.local", &ProbeOutcome::PortClosed);
        let r = ep.result.as_ref().unwrap();
        assert_eq!(r.status, STATUS_NOT_VULN_PORT);
        assert!(!r.adcs_web_enrollment_https);
        assert!(!r.adcs_web_enrollment_epa);
        assert!(ep.collected);
    }

    #[test]
    fn from_https_request_failed() {
        let ep = build_https_endpoint(
            "ca.corp.local",
            &ProbeOutcome::Failed("TLS handshake failed".into()),
        );
        assert!(ep.result.is_none());
        assert!(!ep.collected);
        assert!(ep.failure_reason.as_ref().unwrap().contains("TLS handshake failed"));
    }
}