use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::sync::Arc; use std::time::Duration; use url::Url; pub const MAX_BODY_BYTES: usize = 64 * 1024; pub const MAX_REDIRECTS: usize = 3; pub const HANDLE_WELL_KNOWN_PATH: &str = "/.well-known/atproto-did"; #[derive(Debug, thiserror::Error)] pub enum OutboundError { #[error("only https is allowed, not {0}")] Scheme(String), #[error("{0} is not a permitted address")] Address(String), #[error("{0} is not a valid URL")] Url(String), #[error("response exceeds {0} bytes")] TooLarge(usize), #[error("cannot build the outbound client: {0}")] Build(String), #[error(transparent)] Http(#[from] reqwest::Error), } #[derive(Clone, Copy, Debug)] pub struct Policy { allow_private: bool, } impl Policy { pub fn new(allow_private: bool) -> Self { Self { allow_private } } pub fn permits(self, url: &Url) -> Result<(), OutboundError> { let host = url .host() .ok_or_else(|| OutboundError::Url(url.to_string()))?; if url.scheme() != "https" { return Err(OutboundError::Scheme(url.scheme().to_owned())); } match host { url::Host::Domain(_) => Ok(()), url::Host::Ipv4(ip) => self.permits_ip(IpAddr::V4(ip)), url::Host::Ipv6(ip) => self.permits_ip(IpAddr::V6(ip)), } } fn permits_ip(self, ip: IpAddr) -> Result<(), OutboundError> { if self.allow_private || is_public(ip) { Ok(()) } else { Err(OutboundError::Address(ip.to_string())) } } } pub fn is_public(ip: IpAddr) -> bool { match ip { IpAddr::V4(v4) => is_public_v4(v4), IpAddr::V6(v6) => match v6.to_ipv4_mapped() { Some(v4) => is_public_v4(v4), None => is_public_v6(v6), }, } } fn is_public_v4(ip: Ipv4Addr) -> bool { let [a, b, c, _] = ip.octets(); let shared = a == 100 && (64..=127).contains(&b); let protocol_assignments = a == 192 && b == 0 && c == 0; let benchmarking = a == 198 && (b == 18 || b == 19); let reserved = a >= 240; !(ip.is_private() || ip.is_loopback() || ip.is_link_local() || ip.is_documentation() || ip.is_unspecified() || ip.is_multicast() || shared || protocol_assignments || benchmarking || reserved || a == 0) } fn is_public_v6(ip: Ipv6Addr) -> bool { let segments = ip.segments(); let unique_local = (segments[0] & 0xfe00) == 0xfc00; let link_local = (segments[0] & 0xffc0) == 0xfe80; let documentation = segments[0] == 0x2001 && segments[1] == 0x0db8; let teredo = segments[0] == 0x2001 && segments[1] == 0; let nat64 = segments[0] == 0x64 && segments[1] == 0xff9b && segments[2..6] == [0, 0, 0, 0]; let six_to_four = segments[0] == 0x2002; if nat64 { return is_public_v4(embedded_v4(segments[6], segments[7])); } if six_to_four { return is_public_v4(embedded_v4(segments[1], segments[2])); } !(ip.is_loopback() || ip.is_unspecified() || ip.is_multicast() || unique_local || link_local || documentation || teredo) } fn embedded_v4(high: u16, low: u16) -> Ipv4Addr { let [a, b] = high.to_be_bytes(); let [c, d] = low.to_be_bytes(); Ipv4Addr::new(a, b, c, d) } #[derive(Clone, Copy, Debug)] struct Resolver(Policy); impl reqwest::dns::Resolve for Resolver { fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { let policy = self.0; let host = name.as_str().to_owned(); Box::pin(async move { let addresses: Vec = tokio::net::lookup_host((host.as_str(), 0)) .await? .filter(|address| policy.permits_ip(address.ip()).is_ok()) .collect(); if addresses.is_empty() { return Err(format!("{host} has no permitted address").into()); } Ok(Box::new(addresses.into_iter()) as reqwest::dns::Addrs) }) } } #[derive(Clone)] pub struct Client { policy: Policy, http: reqwest::Client, timeout: Duration, max_body: usize, } fn within_handle_domain(lookup: &Url, target: &Url) -> bool { lookup .host_str() .zip(target.host_str()) .is_some_and(|(handle, host)| { host == handle || host .strip_suffix(handle) .is_some_and(|prefix| prefix.ends_with('.')) }) } fn builder(policy: Policy) -> reqwest::ClientBuilder { let redirect = reqwest::redirect::Policy::custom(move |attempt| { if attempt.previous().len() > MAX_REDIRECTS { return attempt.error("too many redirects"); } let leaves_handle_domain = attempt.previous().first().is_some_and(|lookup| { lookup.path() == HANDLE_WELL_KNOWN_PATH && !within_handle_domain(lookup, attempt.url()) }); if leaves_handle_domain { return attempt.error("a handle lookup was redirected outside the handle's domain"); } match policy.permits(attempt.url()) { Ok(()) => attempt.follow(), Err(error) => attempt.error(error.to_string()), } }); let _ = rustls::crypto::ring::default_provider().install_default(); reqwest::Client::builder() .redirect(redirect) .dns_resolver(Arc::new(Resolver(policy))) } impl Client { pub fn new(policy: Policy, timeout: Duration, max_body: usize) -> Result { let http = builder(policy) .build() .map_err(|error| OutboundError::Build(error.to_string()))?; Ok(Self { policy, http, timeout, max_body, }) } pub fn limited(&self, timeout: Duration, max_body: usize) -> Self { Self { timeout, max_body, ..self.clone() } } pub async fn get(&self, url: &Url) -> Result<(http::StatusCode, Vec), OutboundError> { self.policy.permits(url)?; let response = self .http .get(url.clone()) .timeout(self.timeout) .send() .await?; let status = response.status(); let body = read_capped(response, self.max_body).await?; Ok((status, body)) } } pub async fn read_capped( mut response: reqwest::Response, max_body: usize, ) -> Result, OutboundError> { let declared = response .headers() .get(http::header::CONTENT_LENGTH) .and_then(|value| value.to_str().ok()?.parse::().ok()) .or_else(|| response.content_length()); if declared.is_some_and(|length| length > max_body as u64) { return Err(OutboundError::TooLarge(max_body)); } let mut body = Vec::new(); while let Some(chunk) = response.chunk().await? { if body.len() + chunk.len() > max_body { return Err(OutboundError::TooLarge(max_body)); } body.extend_from_slice(&chunk); } Ok(body) } impl jacquard_common::http_client::HttpClient for Client { type Error = OutboundError; async fn send_http( &self, request: http::Request>, ) -> Result>, OutboundError> { let (parts, body) = request.into_parts(); let url = Url::parse(&parts.uri.to_string()) .map_err(|_| OutboundError::Url(parts.uri.to_string()))?; self.policy.permits(&url)?; let mut outgoing = self .http .request(parts.method, url) .timeout(self.timeout) .body(body); for (name, value) in &parts.headers { outgoing = outgoing.header(name.as_str(), value.as_bytes()); } let response = outgoing.send().await?; let mut builder = http::Response::builder().status(response.status()); for (name, value) in response.headers() { builder = builder.header(name.as_str(), value.as_bytes()); } let bytes = read_capped(response, self.max_body).await?; builder .body(bytes) .map_err(|error| OutboundError::Build(error.to_string())) } } #[cfg(test)] mod tests { use super::*; fn url(value: &str) -> Url { Url::parse(value).expect("url") } #[test] fn private_and_special_addresses_are_not_public() { for private in [ "10.1.2.3", "172.16.0.1", "192.168.1.1", "127.0.0.1", "169.254.169.254", "100.64.0.1", "192.0.0.8", "198.18.0.1", "240.0.0.1", "255.255.255.255", "0.0.0.0", "::1", "fc00::1", "fe80::1", "::ffff:10.0.0.1", "64:ff9b::a00:1", "2002:a00:1::1", "2001::1", "2001:db8::1", ] { let ip: IpAddr = private.parse().expect("address"); assert!(!is_public(ip), "{private}"); } for public in [ "93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946", "64:ff9b::5db8:d822", "2002:5db8:d822::1", ] { let ip: IpAddr = public.parse().expect("address"); assert!(is_public(ip), "{public}"); } } #[test] fn policy_requires_https_and_public_literal_hosts() { let strict = Policy::new(false); assert!(strict.permits(&url("https://pds.example/xrpc")).is_ok()); assert!(strict.permits(&url("https://93.184.216.34/")).is_ok()); assert!(matches!( strict.permits(&url("http://pds.example/")), Err(OutboundError::Scheme(_)) )); assert!(matches!( strict.permits(&url("https://127.0.0.1:2019/config/")), Err(OutboundError::Address(_)) )); assert!(matches!( strict.permits(&url("https://[::1]/")), Err(OutboundError::Address(_)) )); assert!(matches!( strict.permits(&url("https://169.254.169.254/latest/meta-data/")), Err(OutboundError::Address(_)) )); for hostless in ["mailto:alice@example.com", "data:text/plain,did"] { assert!( matches!(strict.permits(&url(hostless)), Err(OutboundError::Url(_))), "{hostless}" ); } let lenient = Policy::new(true); assert!(lenient.permits(&url("https://127.0.0.1/")).is_ok()); assert!(matches!( lenient.permits(&url("http://127.0.0.1/")), Err(OutboundError::Scheme(_)) )); } #[tokio::test] async fn bodies_are_capped_while_streaming() { let small = reqwest::Response::from(http::Response::new(vec![b'a'; 10])); assert_eq!(read_capped(small, 10).await.expect("fits").len(), 10); let large = reqwest::Response::from(http::Response::new(vec![b'a'; 11])); assert!(matches!( read_capped(large, 10).await, Err(OutboundError::TooLarge(10)) )); let declared = reqwest::Response::from( http::Response::builder() .header("content-length", "4096") .body(Vec::new()) .expect("response"), ); assert!(matches!( read_capped(declared, 1024).await, Err(OutboundError::TooLarge(1024)) )); } async fn responder() -> (SocketAddr, reqwest::Certificate) { use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_rustls::rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer}; let issued = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_owned()]).expect("certificate"); let der = issued.cert.der().clone(); let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(issued.signing_key.serialize_der())); let tls = rustls::ServerConfig::builder() .with_no_client_auth() .with_single_cert(vec![der.clone()], key) .expect("server config"); let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls)); let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); let address = listener.local_addr().expect("address"); tokio::spawn(async move { while let Ok((stream, _)) = listener.accept().await { let acceptor = acceptor.clone(); tokio::spawn(async move { let Ok(mut stream) = acceptor.accept(stream).await else { return; }; let mut request = Vec::new(); let mut chunk = [0u8; 1024]; while !request.windows(4).any(|window| window == b"\r\n\r\n") { match stream.read(&mut chunk).await { Ok(read) if read > 0 => request.extend_from_slice(&chunk[..read]), _ => return, } } let request = String::from_utf8_lossy(&request).into_owned(); let path = request.split(' ').nth(1).unwrap_or_default(); let probe = request .lines() .find_map(|line| line.strip_prefix("x-probe: ")) .unwrap_or_default(); let redirect = |to: &str| format!("302 Found\r\nlocation: {to}"); let (head, body) = match path { "/hop" => (redirect("/ok"), String::new()), "/.well-known/atproto-did?within" => (redirect("/ok"), String::new()), "/.well-known/atproto-did?outside" => { (redirect("https://localhost/ok"), String::new()) } "/loop" => (redirect("/loop"), String::new()), "/plain" => (redirect("http://127.0.0.1/"), String::new()), "/large" => ("200 OK".to_owned(), "a".repeat(2048)), "/stream" => { let head = "HTTP/1.1 200 OK\r\nconnection: close\r\n\r\n"; let _ = stream.write_all(head.as_bytes()).await; let _ = stream.write_all(&[b'a'; 2048]).await; let _ = stream.shutdown().await; return; } _ => (format!("200 OK\r\nx-echo: {probe}"), "ok".to_owned()), }; let response = format!( "HTTP/1.1 {head}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len() ); let _ = stream.write_all(response.as_bytes()).await; let _ = stream.shutdown().await; }); } }); (address, reqwest::Certificate::from_der(&der).expect("root")) } fn trusting(root: &reqwest::Certificate) -> Client { let policy = Policy::new(true); let http = builder(policy) .add_root_certificate(root.clone()) .build() .expect("client"); Client { policy, http, timeout: Duration::from_secs(5), max_body: MAX_BODY_BYTES, } .limited(Duration::from_secs(5), 1024) } #[tokio::test] async fn redirects_are_capped_and_rechecked_and_bodies_are_capped_over_tls() { use jacquard_common::http_client::HttpClient; let (address, root) = responder().await; let at = |path: &str| url(&format!("https://{address}{path}")); let client = trusting(&root); let (status, body) = client.get(&at("/hop")).await.expect("one hop is followed"); assert_eq!( (status, body.as_slice()), (http::StatusCode::OK, &b"ok"[..]) ); let (status, _) = client .get(&at("/.well-known/atproto-did?within")) .await .expect("a handle lookup may be redirected on its own host"); assert_eq!(status, http::StatusCode::OK); for (path, expected) in [ ("/loop", "too many redirects"), ("/plain", "only https is allowed"), ( "/.well-known/atproto-did?outside", "outside the handle's domain", ), ] { let error = client.get(&at(path)).await.expect_err(path); assert!(matches!(error, OutboundError::Http(_)), "{path}: {error:?}"); assert!(format!("{error:?}").contains(expected), "{path}: {error:?}"); } for path in ["/large", "/stream"] { assert!( matches!( client.get(&at(path)).await, Err(OutboundError::TooLarge(1024)) ), "{path}" ); } let request = http::Request::builder() .uri(at("/echo").as_str()) .header("x-probe", "carried") .body(Vec::new()) .expect("request"); let response = client.send_http(request).await.expect("sent"); assert_eq!(response.status(), http::StatusCode::OK); assert_eq!(response.headers()["x-echo"], "carried"); assert_eq!(response.body().as_slice(), b"ok"); let plain = http::Request::builder() .uri("http://127.0.0.1/") .body(Vec::new()) .expect("request"); assert!(matches!( client.send_http(plain).await, Err(OutboundError::Scheme(_)) )); } #[test] fn a_handle_lookup_may_only_be_redirected_to_its_own_host_or_a_subdomain() { for (target, within) in [ ("https://example.com/elsewhere", true), ("https://www.example.com/.well-known/atproto-did", true), ("https://a.b.example.com/did", true), ("https://evil.test/did", false), ("https://notexample.com/did", false), ("https://example.com.evil.test/did", false), ("https://com/did", false), ] { assert_eq!( within_handle_domain( &url("https://example.com/.well-known/atproto-did"), &url(target) ), within, "{target}" ); } assert!( !within_handle_domain( &url("https://alice.example.com/.well-known/atproto-did"), &url("https://example.com/did") ), "a parent domain is not the handle's domain" ); } #[tokio::test] async fn names_that_resolve_to_private_addresses_are_refused_at_lookup() { let seconds = Duration::from_secs(5); let strict = Client::new(Policy::new(false), seconds, 1024).expect("client"); let error = strict .get(&url("https://localhost:9/")) .await .expect_err("loopback behind a name"); assert!( format!("{error:?}").contains("no permitted address"), "{error:?}" ); let lenient = Client::new(Policy::new(true), seconds, 1024).expect("client"); let error = lenient .get(&url("https://localhost:9/")) .await .expect_err("nothing listens on the discard port"); assert!( !format!("{error:?}").contains("no permitted address"), "{error:?}" ); } }