Files
pruefwerk/compliance-core/src/guarded_net.rs
T
sharang 40c7557349
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Successful in 54s
CI / Deploy MCP (push) Successful in 3m41s
CI / Deploy Dashboard (push) Successful in 5m20s
CI / Deploy Agent (push) Successful in 6m41s
feat(security): pin resolved addresses and check every redirect hop (#294) (#322)
2026-09-21 20:26:43 +00:00

404 lines
15 KiB
Rust

//! Connections to tenant-chosen addresses that stay where the guard said (#294).
//!
//! [`NetGuard`] decides whether an address is acceptable, but a check made
//! before a request leaves two gaps:
//!
//! - **DNS rebinding.** The HTTP client resolves the name again when it
//! connects, so a record that answers a public address to the check and
//! `169.254.169.254` to the connection gets through.
//! - **Redirects.** A public URL can answer `302 http://mongo:27017/`, and the
//! client follows it.
//!
//! Here the resolver *is* the check: [`guarded_client_builder`] gives reqwest a
//! resolver that returns only addresses the guard approved, so there is no
//! second lookup to win, and a redirect policy that re-checks every hop. Plain
//! TCP callers (ICS probes, the TLS analyzer) use [`resolve_approved`] and
//! connect to the returned address themselves.
use std::future::Future;
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::pin::Pin;
use std::sync::Arc;
use reqwest::dns::{Addrs, Name, Resolve, Resolving};
use reqwest::redirect;
use crate::net_guard::{NetGuard, NetGuardError};
/// Most redirects a guarded client follows before giving up.
pub const MAX_REDIRECTS: usize = 5;
/// A boxed future, so [`Lookup`] can be used as a trait object.
pub type LookupFuture = Pin<Box<dyn Future<Output = io::Result<Vec<IpAddr>>> + Send>>;
/// Name resolution, behind a trait so tests can answer without live DNS.
pub trait Lookup: Send + Sync + 'static {
/// Every address `host` resolves to.
fn lookup(&self, host: &str) -> LookupFuture;
}
/// The operating system's resolver.
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemLookup;
impl Lookup for SystemLookup {
fn lookup(&self, host: &str) -> LookupFuture {
let host = host.to_string();
Box::pin(async move {
// Port 0: only the addresses matter; callers supply their own port.
let addrs = tokio::net::lookup_host((host.as_str(), 0)).await?;
Ok(addrs.map(|a| a.ip()).collect())
})
}
}
/// Resolve `host` and return its addresses only if the guard accepts **every**
/// one of them. An IP literal is classified without a lookup.
///
/// # Errors
///
/// [`NetGuardError`] if the host is refused by name, does not resolve, or any
/// address it resolves to is refused.
pub async fn resolve_approved(
guard: NetGuard,
lookup: &dyn Lookup,
host: &str,
) -> Result<Vec<IpAddr>, NetGuardError> {
let host = host.trim().trim_matches(['[', ']']);
guard.check_host(host)?;
if let Ok(ip) = host.parse::<IpAddr>() {
return Ok(vec![ip]);
}
let addrs = lookup
.lookup(host)
.await
.map_err(|e| NetGuardError::Unresolvable {
host: host.to_string(),
reason: e.to_string(),
})?;
if addrs.is_empty() {
return Err(NetGuardError::Unresolvable {
host: host.to_string(),
reason: "no addresses".to_string(),
});
}
// One refused answer refuses the name: which address a connection would
// pick is not ours to decide.
for ip in &addrs {
guard
.check_ip(*ip)
.map_err(|_| NetGuardError::PrivateAddress {
host: host.to_string(),
ip: *ip,
})?;
}
Ok(addrs)
}
/// A reqwest resolver that returns only guard-approved addresses.
struct GuardedResolver {
guard: NetGuard,
lookup: Arc<dyn Lookup>,
}
impl Resolve for GuardedResolver {
fn resolve(&self, name: Name) -> Resolving {
let guard = self.guard;
let lookup = Arc::clone(&self.lookup);
Box::pin(async move {
let ips = resolve_approved(guard, lookup.as_ref(), name.as_str()).await?;
// reqwest sets the port from the URL; 0 is a placeholder.
let addrs: Addrs = Box::new(ips.into_iter().map(|ip| SocketAddr::new(ip, 0)));
Ok(addrs)
})
}
}
/// Whether a guarded client may follow a redirect to `hop`, after
/// `hops_so_far` redirects.
///
/// Checks the scheme and the host name (an IP literal is classified here,
/// because reqwest connects to a literal without asking the resolver); a named
/// host is checked again by the resolver when the hop connects.
///
/// # Errors
///
/// [`NetGuardError::TooManyRedirects`] past [`MAX_REDIRECTS`], or
/// [`NetGuardError::RedirectRefused`] naming the hop.
pub fn check_redirect(guard: NetGuard, hop: &str, hops_so_far: usize) -> Result<(), NetGuardError> {
if hops_so_far >= MAX_REDIRECTS {
return Err(NetGuardError::TooManyRedirects(MAX_REDIRECTS));
}
guard
.check_url(hop)
.map(drop)
.map_err(|reason| NetGuardError::RedirectRefused {
hop: hop.to_string(),
reason: reason.to_string(),
})
}
/// A client builder for requests to tenant-chosen URLs: guarded resolver,
/// guarded redirects, no proxy (a proxy would resolve the name itself).
/// Callers add their own timeouts and TLS settings.
///
/// An IP-literal URL never reaches the resolver, so check the *first* URL with
/// [`NetGuard::check_url`] before sending, as every call site already does.
pub fn guarded_client_builder(guard: NetGuard) -> reqwest::ClientBuilder {
guarded_client_builder_with(guard, Arc::new(SystemLookup))
}
/// [`guarded_client_builder`] with a custom [`Lookup`] (tests).
pub fn guarded_client_builder_with(
guard: NetGuard,
lookup: Arc<dyn Lookup>,
) -> reqwest::ClientBuilder {
let policy = redirect::Policy::custom(move |attempt| {
// `previous()` includes the original request, so it holds one more
// URL than the redirects already followed.
let followed = attempt.previous().len().saturating_sub(1);
match check_redirect(guard, attempt.url().as_str(), followed) {
Ok(()) => attempt.follow(),
Err(e) => attempt.error(e),
}
});
reqwest::Client::builder()
.no_proxy()
.dns_resolver(Arc::new(GuardedResolver { guard, lookup }))
.redirect(policy)
}
// The tests serve over axum, which only the `axum` feature brings in.
#[cfg(all(test, feature = "axum"))]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
use super::*;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
use axum::routing::get;
/// An error and its sources, as the user-facing messages read.
fn chain(e: &(dyn std::error::Error + 'static)) -> String {
let mut out = e.to_string();
let mut source = e.source();
while let Some(s) = source {
out.push_str(": ");
out.push_str(&s.to_string());
source = s.source();
}
out
}
/// Answers from a table; each host's answers are consumed in order, the
/// last one repeating, so a record can "flip" between lookups.
#[derive(Default)]
struct StubLookup {
answers: Mutex<HashMap<String, Vec<Vec<IpAddr>>>>,
calls: AtomicUsize,
}
impl StubLookup {
fn answer(self, host: &str, answers: &[&[&str]]) -> Self {
let parsed = answers
.iter()
.map(|a| a.iter().map(|ip| ip.parse().unwrap()).collect())
.collect();
self.answers
.lock()
.unwrap()
.insert(host.to_string(), parsed);
self
}
}
impl Lookup for StubLookup {
fn lookup(&self, host: &str) -> LookupFuture {
self.calls.fetch_add(1, Ordering::SeqCst);
let mut table = self.answers.lock().unwrap();
let result = match table.get_mut(host) {
Some(queue) if queue.len() > 1 => Ok(queue.remove(0)),
Some(queue) => Ok(queue[0].clone()),
None => Err(io::Error::new(io::ErrorKind::NotFound, "no such host")),
};
Box::pin(async move { result })
}
}
/// A local server counting the requests that reach it.
async fn counting_server(router: axum::Router) -> (SocketAddr, Arc<AtomicUsize>) {
let hits = Arc::new(AtomicUsize::new(0));
let counter = Arc::clone(&hits);
let app = router.layer(axum::middleware::from_fn(
move |req: axum::extract::Request, next: axum::middleware::Next| {
let counter = Arc::clone(&counter);
async move {
counter.fetch_add(1, Ordering::SeqCst);
next.run(req).await
}
},
));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.ok() });
(addr, hits)
}
#[tokio::test]
async fn every_answer_must_be_public() {
let guard = NetGuard::public_only();
let lookup = StubLookup::default()
.answer("public.example", &[&["93.184.215.14"]])
.answer("mixed.example", &[&["93.184.215.14", "10.0.0.5"]])
.answer("metadata.example", &[&["169.254.169.254"]]);
assert!(resolve_approved(guard, &lookup, "public.example")
.await
.is_ok());
for host in ["mixed.example", "metadata.example"] {
let err = resolve_approved(guard, &lookup, host).await.unwrap_err();
assert!(
matches!(err, NetGuardError::PrivateAddress { .. }),
"{host}: {err}"
);
}
assert!(matches!(
resolve_approved(guard, &lookup, "missing.example").await,
Err(NetGuardError::Unresolvable { .. })
));
// Literals are classified without a lookup.
let before = lookup.calls.load(Ordering::SeqCst);
assert!(resolve_approved(guard, &lookup, "127.0.0.1").await.is_err());
assert_eq!(lookup.calls.load(Ordering::SeqCst), before);
}
#[tokio::test]
async fn a_rebinding_name_never_reaches_the_private_address() {
// The attack: answer a public address to the check, then the private
// one (where the server listens) to the connection. With the guard as
// the resolver there is exactly one lookup per connection, and the
// connection goes where that lookup said.
let (addr, hits) =
counting_server(axum::Router::new().route("/", get(|| async { "x" }))).await;
let lookup = Arc::new(
StubLookup::default().answer("rebind.example", &[&["1.1.1.1"], &["127.0.0.1"]]),
);
let client = guarded_client_builder_with(NetGuard::public_only(), lookup.clone())
.connect_timeout(std::time::Duration::from_millis(300))
.build()
.unwrap();
let result = client
.get(format!("http://rebind.example:{}/", addr.port()))
.send()
.await;
assert!(result.is_err(), "must not connect to the private address");
assert_eq!(hits.load(Ordering::SeqCst), 0);
assert_eq!(lookup.calls.load(Ordering::SeqCst), 1, "no second lookup");
// Once the name answers private it is refused outright.
let refused = client
.get(format!("http://rebind.example:{}/", addr.port()))
.send()
.await
.unwrap_err();
assert!(
chain(&refused).contains("not a public address"),
"{}",
chain(&refused)
);
assert_eq!(hits.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn the_resolver_is_what_connects() {
// Positive control: when the guard allows it, the stubbed name really
// is how the request finds the server.
let (addr, hits) =
counting_server(axum::Router::new().route("/", get(|| async { "x" }))).await;
let lookup = Arc::new(StubLookup::default().answer("plc.example", &[&["127.0.0.1"]]));
let client = guarded_client_builder_with(NetGuard::allow_private(), lookup)
.build()
.unwrap();
let body = client
.get(format!("http://plc.example:{}/", addr.port()))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert_eq!(body, "x");
assert_eq!(hits.load(Ordering::SeqCst), 1);
}
#[test]
fn redirect_hops_are_checked_and_named() {
let guard = NetGuard::public_only();
assert!(check_redirect(guard, "https://example.com/next", 0).is_ok());
for hop in [
"http://169.254.169.254/latest/meta-data/",
"http://10.0.0.5/",
"http://mongo:27017/",
"http://metadata.google.internal/",
"ftp://example.com/x",
"file:///etc/passwd",
] {
let err = check_redirect(guard, hop, 0).unwrap_err();
assert!(
matches!(&err, NetGuardError::RedirectRefused { hop: h, .. } if h == hop),
"{hop}: {err}"
);
assert!(err.to_string().contains(hop), "{err}");
}
assert!(matches!(
check_redirect(guard, "https://example.com/", MAX_REDIRECTS),
Err(NetGuardError::TooManyRedirects(MAX_REDIRECTS))
));
}
#[tokio::test]
async fn a_client_stops_at_a_refused_hop_and_at_the_cap() {
// allow_private lets the test reach its local server; scheme and hop
// count are enforced regardless of that policy.
let router = axum::Router::new()
.route(
"/to-ftp",
get(|| async { axum::response::Redirect::temporary("ftp://example.com/x") }),
)
.route(
"/loop",
get(|| async { axum::response::Redirect::temporary("/loop") }),
);
let (addr, hits) = counting_server(router).await;
let client = guarded_client_builder_with(NetGuard::allow_private(), Arc::new(SystemLookup))
.build()
.unwrap();
let err = client
.get(format!("http://{addr}/to-ftp"))
.send()
.await
.unwrap_err();
assert!(
chain(&err).contains("ftp://example.com/x"),
"{}",
chain(&err)
);
let before = hits.load(Ordering::SeqCst);
let err = client
.get(format!("http://{addr}/loop"))
.send()
.await
.unwrap_err();
assert!(chain(&err).contains("more than"), "{}", chain(&err));
// The first request plus exactly MAX_REDIRECTS followed hops.
assert_eq!(hits.load(Ordering::SeqCst) - before, MAX_REDIRECTS + 1);
}
}