1use 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
68pub struct HttpsClient {
71 stream: tokio_rustls::client::TlsStream<TcpStream>,
72 host: String,
73}
74
75struct 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 let host = if port == 443 {
115 host.to_string()
116 } else {
117 format!("{host}:{port}")
118 };
119 Ok(HttpsClient { stream, host })
120 }
121
122 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 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 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
178async 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 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(); 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 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
247pub 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
265pub 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
284pub 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
296pub fn cert_request_form(csr_pem: &str, template: &str) -> String {
299 let attrs = format!("CertificateTemplate:{template}");
300 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
313fn 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
328const 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"); }
415
416 #[test]
417 fn ntlm_challenge_extracted_across_multi_line_iis_headers() {
418 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}