cant-proxy 0.0.18

The filtering CONNECT proxy behind Cantainer's network allow lists.
Documentation
//! The filtering proxy for network allow lists (Phase 6.3; docs/NETWORK-ALLOWLIST.md §6).
//!
//! A cant with `network = { allow = [...] }` will run in a network namespace whose only way out
//! is this proxy (Phase 6.4). It accepts `CONNECT host:port` only, checks the name against the
//! allow list **before** any DNS lookup, resolves once, refuses a name with any answer in a
//! private, loopback, link-local or otherwise special range ([`deny`]), dials the checked
//! address (never the name), and splices bytes both ways. One log line per decision, never
//! payload. Threads and `std::net` only: no async runtime, no dependency but the manifest's
//! canonicaliser, so the proxy and the manifest agree on what a name is.

#![forbid(unsafe_code)]

pub mod deny;
mod request;

use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use cant_manifest::net::HostPort;

pub use request::{Connect, Refusal};

/// Time and size limits (NETWORK-ALLOWLIST.md §6).
#[derive(Debug, Clone, Copy)]
pub struct Limits {
    pub max_tunnels: usize,
    pub max_head: usize,
    pub head: Duration,
    pub dns: Duration,
    pub connect: Duration,
    pub idle: Duration,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            max_tunnels: 64,
            max_head: 8192,
            head: Duration::from_secs(10),
            dns: Duration::from_secs(5),
            connect: Duration::from_secs(10),
            idle: Duration::from_secs(300),
        }
    }
}

/// An upstream HTTP proxy to chain through (the user's own `HTTPS_PROXY`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream {
    pub host: String,
    pub port: u16,
}

impl Upstream {
    /// `http://host:port` (or `host:port`); no credentials, no path.
    pub fn parse(url: &str) -> Result<Upstream, String> {
        let rest = url.strip_prefix("http://").unwrap_or(url);
        if url.starts_with("https://") || rest.contains("://") {
            return Err(format!("upstream `{url}` must be an http:// proxy"));
        }
        let rest = rest.strip_suffix('/').unwrap_or(rest);
        if rest.contains('@') {
            return Err("upstream proxy credentials aren't supported".into());
        }
        if rest.contains('/') {
            return Err(format!("upstream `{url}` must be http://host:port"));
        }
        let (host, port) = rest
            .rsplit_once(':')
            .ok_or_else(|| format!("upstream `{url}` has no port"))?;
        let port = port
            .parse::<u16>()
            .ok()
            .filter(|p| *p > 0)
            .ok_or_else(|| format!("upstream `{url}` has a bad port"))?;
        if host.is_empty() {
            return Err(format!("upstream `{url}` has no host"));
        }
        Ok(Upstream {
            host: host.to_string(),
            port,
        })
    }
}

/// What the proxy allows and how.
#[derive(Debug, Clone, Default)]
pub struct Rules {
    pub allow: Vec<HostPort>,
    pub upstream: Option<Upstream>,
    pub limits: Limits,
}

/// Receives one line per decision.
pub type Log = Arc<dyn Fn(&str) + Send + Sync>;

type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
type Deny = Arc<dyn Fn(IpAddr) -> Option<&'static str> + Send + Sync>;

/// A configured proxy; [`Proxy::serve`] runs it on a listener.
#[derive(Clone)]
pub struct Proxy {
    rules: Arc<Rules>,
    log: Log,
    resolve: Resolve,
    deny: Deny,
    active: Arc<AtomicUsize>,
}

impl Proxy {
    /// The proxy as it runs for real: the system resolver, and [`deny::denied`] with this
    /// machine's own addresses.
    pub fn new(rules: Rules, log: Log) -> Proxy {
        let own = deny::own_addresses();
        Proxy {
            rules: Arc::new(rules),
            log,
            resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
            deny: Arc::new(move |ip| deny::denied(ip, &own)),
            active: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Accepts connections on `listener` until it fails, one thread per connection.
    pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
        std::thread::spawn(move || {
            // A failed accept (the client gave up before it was accepted) is skipped.
            for conn in listener.incoming().flatten() {
                let me = self.clone();
                std::thread::spawn(move || me.handle(conn));
            }
        })
    }

    fn log(&self, line: String) {
        (self.log)(&line);
    }

    /// One client connection, start to end.
    fn handle(&self, mut client: TcpStream) {
        let start = Instant::now();
        let ms = || start.elapsed().as_millis();
        let n = self.active.fetch_add(1, Ordering::SeqCst);
        let _slot = Slot(&self.active);
        if n >= self.rules.limits.max_tunnels {
            return self.refuse(&mut client, 503, "", "too many tunnels", ms());
        }
        let _ = client.set_read_timeout(Some(self.rules.limits.head));
        let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
            Ok(h) => h,
            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
        };
        let c = match request::parse(&head) {
            Ok(c) => c,
            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
        };
        let target = format!("{}:{}", c.host, c.port);
        // The allow list first: a refused name is never looked up.
        if !self.rules.allow.iter().any(|e| e.matches(&c.host, c.port)) {
            return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
        }
        let (upstream, via) = match &self.rules.upstream {
            Some(up) => match self.through(up, &c) {
                Ok(s) => (s, format!("via {}:{}", up.host, up.port)),
                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
            },
            None => match self.dial(&c) {
                Ok((s, ip)) => (s, format!("ip={ip}")),
                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
            },
        };
        // A client already gone just makes the splice below end at once.
        let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
        self.log(format!("allow CONNECT {target} {via} ms={}", ms()));
        let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
        self.log(format!("close {target} up={up} down={down} ms={}", ms()));
    }

    fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
        let text = match status {
            400 => "Bad Request",
            403 => "Forbidden",
            405 => "Method Not Allowed",
            408 => "Request Timeout",
            431 => "Request Header Fields Too Large",
            502 => "Bad Gateway",
            503 => "Service Unavailable",
            _ => "Gateway Timeout",
        };
        let _ = client.write_all(
            format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                .as_bytes(),
        );
        let sep = if target.is_empty() { "" } else { " " };
        self.log(format!("deny {status}{sep}{target} reason={why} ms={ms}"));
    }

    /// Resolves once (within the DNS limit), refuses if any answer is denied, and connects to
    /// the first answer that accepts.
    fn dial(&self, c: &Connect) -> Result<(TcpStream, IpAddr), (u16, String)> {
        let resolve = Arc::clone(&self.resolve);
        let (host, port) = (c.host.clone(), c.port);
        let (tx, rx) = std::sync::mpsc::channel();
        // A lookup can't be cancelled; past the limit it is left to finish alone.
        std::thread::spawn(move || {
            let _ = tx.send(resolve(&host, port));
        });
        let addrs = match rx.recv_timeout(self.rules.limits.dns) {
            Ok(Ok(a)) if !a.is_empty() => a,
            Ok(Ok(_)) => return Err((502, "the name has no address".into())),
            Ok(Err(e)) => return Err((502, format!("lookup failed: {e}"))),
            Err(_) => return Err((504, "lookup took too long".into())),
        };
        if let Some((ip, why)) = addrs
            .iter()
            .find_map(|a| (self.deny)(a.ip()).map(|w| (a.ip(), w)))
        {
            return Err((403, format!("resolves to {ip}: {why}")));
        }
        let mut last = String::new();
        for a in &addrs {
            match TcpStream::connect_timeout(a, self.rules.limits.connect) {
                Ok(s) => return Ok((s, a.ip())),
                Err(e) => last = format!("connecting to {}: {e}", a.ip()),
            }
        }
        Err((502, last))
    }

    /// Opens the tunnel through the upstream proxy, which does the resolving.
    fn through(&self, up: &Upstream, c: &Connect) -> Result<TcpStream, (u16, String)> {
        let addrs = (up.host.as_str(), up.port)
            .to_socket_addrs()
            .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
        let mut s = addrs
            .into_iter()
            .find_map(|a| TcpStream::connect_timeout(&a, self.rules.limits.connect).ok())
            .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
        let target = format!("{}:{}", c.host, c.port);
        // A failed write shows as the missing answer read next.
        let _ =
            s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes());
        let _ = s.set_read_timeout(Some(self.rules.limits.connect));
        let (head, rest) = request::read_head(&mut s, self.rules.limits.max_head)
            .map_err(|r| (502, format!("upstream: {}", r.reason)))?;
        let status = std::str::from_utf8(&head)
            .ok()
            .and_then(|h| h.split(' ').nth(1))
            .unwrap_or("");
        if status != "200" || !rest.is_empty() {
            return Err((502, format!("upstream answered {status}")));
        }
        let _ = s.set_read_timeout(None);
        Ok(s)
    }

    #[cfg(test)]
    fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
        Proxy {
            rules: Arc::new(rules),
            log,
            resolve,
            deny,
            active: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl std::fmt::Debug for Proxy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Proxy")
            .field("rules", &self.rules)
            .field("active", &self.active.load(Ordering::SeqCst))
            .finish_non_exhaustive()
    }
}

/// Frees a tunnel slot when the connection ends.
struct Slot<'a>(&'a AtomicUsize);

impl Drop for Slot<'_> {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

/// Copies both ways until both sides are done (half-close on EOF) or a side is idle for
/// `idle`. Returns the bytes sent up (client to server, `early` first) and down.
fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
    let _ = client.set_read_timeout(Some(idle));
    let _ = server.set_read_timeout(Some(idle));
    let (c, s) = (&client, &server);
    let (up, down) = std::thread::scope(|scope| {
        let up = scope.spawn(move || {
            let n = copy(&mut early.chain(c), &mut { s });
            let _ = s.shutdown(Shutdown::Write);
            n
        });
        let down = copy(&mut { s }, &mut { c });
        let _ = c.shutdown(Shutdown::Write);
        (up.join().unwrap_or(0), down)
    });
    let _ = server.shutdown(Shutdown::Both);
    let _ = client.shutdown(Shutdown::Both);
    (up, down)
}

/// Like `io::copy`, but a read timeout or error just ends it.
fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
    let mut buf = [0u8; 16 * 1024];
    let mut n = 0u64;
    loop {
        match from.read(&mut buf) {
            Ok(0) | Err(_) => return n,
            Ok(k) => {
                if to.write_all(&buf[..k]).is_err() {
                    return n;
                }
                n += k as u64;
            }
        }
    }
}

#[cfg(test)]
mod tests;