cant-proxy 0.0.21

The filtering CONNECT proxy behind Cantainer's network allow lists.
Documentation
//! Reading a request head: only `CONNECT host:port HTTP/1.x`, the host canonical by the same
//! rules as a manifest's allow list (`cant_manifest::net::canonical_name`). Anything else is
//! refused with a status, never "fixed up": name parsing is where egress proxies had their CVEs.

use std::io::Read;

/// A refused request: the HTTP status to answer and why (for the log).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    pub status: u16,
    pub reason: String,
}

fn refuse(status: u16, reason: impl Into<String>) -> Refusal {
    Refusal {
        status,
        reason: reason.into(),
    }
}

/// A `CONNECT` the proxy may consider: a canonical host name and a port.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
    /// The canonical name, or the address as text (`10.0.0.5`, `[fd00::1]`).
    pub host: String,
    pub port: u16,
    /// Set when the target is an IP address (only a user-named IP entry can allow it).
    pub ip: Option<std::net::IpAddr>,
}

/// Reads up to and including the blank line ending the head, at most `max` bytes. Returns the
/// head and any bytes read after it (a client may send its TLS hello right behind).
pub fn read_head(r: &mut dyn Read, max: usize) -> Result<(Vec<u8>, Vec<u8>), Refusal> {
    let mut buf = Vec::with_capacity(1024);
    let mut chunk = [0u8; 1024];
    loop {
        if let Some(end) = find_end(&buf) {
            let rest = buf.split_off(end);
            return Ok((buf, rest));
        }
        if buf.len() >= max {
            return Err(refuse(431, "request head too large"));
        }
        let n = match r.read(&mut chunk) {
            Ok(0) => return Err(refuse(400, "connection closed before the request ended")),
            Ok(n) => n,
            Err(e)
                if matches!(
                    e.kind(),
                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                ) =>
            {
                return Err(refuse(408, "request head took too long"));
            }
            Err(e) => return Err(refuse(400, format!("reading the request: {e}"))),
        };
        buf.extend_from_slice(&chunk[..n]);
    }
}

/// The index just past `\r\n\r\n` (or `\n\n`), if the head is complete.
fn find_end(buf: &[u8]) -> Option<usize> {
    let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4);
    let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| i + 2);
    match (crlf, lf) {
        (Some(a), Some(b)) => Some(a.min(b)),
        (a, b) => a.or(b),
    }
}

/// Parses a complete head into a [`Connect`]. Header lines are ignored (nothing in them is
/// trusted); only the request line counts.
pub fn parse(head: &[u8]) -> Result<Connect, Refusal> {
    let head = std::str::from_utf8(head).map_err(|_| refuse(400, "request is not UTF-8"))?;
    let line = head.split('\n').next().unwrap_or("").trim_end_matches('\r');
    let parts: Vec<&str> = line.split(' ').collect();
    let [method, target, version] = parts.as_slice() else {
        return Err(refuse(
            400,
            format!("malformed request line `{}`", printable(line)),
        ));
    };
    if !matches!(*version, "HTTP/1.1" | "HTTP/1.0") {
        return Err(refuse(
            400,
            format!("unsupported version `{}`", printable(version)),
        ));
    }
    if *method != "CONNECT" {
        // An absolute-form request (`POST http://...`) is a program ignoring HTTPS: say which.
        return Err(refuse(
            405,
            format!("not CONNECT: {} {}", printable(method), printable(target)),
        ));
    }
    let Some((host, port)) = target.rsplit_once(':') else {
        return Err(refuse(400, format!("`{}` has no port", printable(target))));
    };
    let port = match port.parse::<u16>() {
        Ok(p) if p > 0 && !port.starts_with('0') && port.bytes().all(|b| b.is_ascii_digit()) => p,
        _ => return Err(refuse(400, format!("bad port `{}`", printable(port)))),
    };
    // An IPv6 address in brackets, or a plain dotted-quad IPv4 address; anything else must be
    // a canonical name (so `127.1` and `0x7f.1` stay refused).
    if let Some(inner) = host.strip_prefix('[') {
        let ip = inner
            .strip_suffix(']')
            .and_then(|a| a.parse::<std::net::Ipv6Addr>().ok())
            .ok_or_else(|| refuse(400, format!("bad IPv6 address `{}`", printable(host))))?;
        return Ok(Connect {
            host: format!("[{ip}]"),
            port,
            ip: Some(ip.into()),
        });
    }
    if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() {
        return Ok(Connect {
            host: ip.to_string(),
            port,
            ip: Some(ip.into()),
        });
    }
    let host = host.to_ascii_lowercase();
    cant_manifest::net::canonical_name(&host).map_err(|e| refuse(400, e))?;
    Ok(Connect {
        host,
        port,
        ip: None,
    })
}

/// For the log: at most 100 characters, control characters as `?`.
fn printable(s: &str) -> String {
    s.chars()
        .take(100)
        .map(|c| if c.is_control() { '?' } else { c })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn p(line: &str) -> Result<Connect, Refusal> {
        parse(format!("{line}\r\nHost: x\r\n\r\n").as_bytes())
    }

    #[test]
    fn a_plain_connect_parses() {
        assert_eq!(
            p("CONNECT api.github.com:443 HTTP/1.1"),
            Ok(Connect {
                host: "api.github.com".into(),
                port: 443,
                ip: None
            })
        );
        // Case is folded before the canonical check; HTTP/1.0 and bare LF are fine.
        assert_eq!(
            p("CONNECT API.GitHub.com:8443 HTTP/1.0").expect("ok").host,
            "api.github.com"
        );
        assert!(parse(b"CONNECT a.com:443 HTTP/1.1\n\n").is_ok());
        // IP addresses parse; only a host the user named as that IP lets them through.
        let v4 = p("CONNECT 10.0.0.5:6443 HTTP/1.1").expect("v4");
        assert_eq!(
            (v4.host.as_str(), v4.ip),
            ("10.0.0.5", Some("10.0.0.5".parse().expect("ip")))
        );
        let v6 = p("CONNECT [FD00::1]:443 HTTP/1.1").expect("v6");
        assert_eq!(
            (v6.host.as_str(), v6.ip),
            ("[fd00::1]", Some("fd00::1".parse().expect("ip")))
        );
    }

    #[test]
    fn anything_else_is_refused_with_a_status() {
        for (line, status, why) in [
            (
                "GET http://a.com/ HTTP/1.1",
                405,
                "not CONNECT: GET http://a.com/",
            ),
            ("POST https://api.agnost.ai/x HTTP/1.1", 405, "not CONNECT"),
            ("connect a.com:443 HTTP/1.1", 405, "not CONNECT"),
            ("CONNECT a.com:443 HTTP/2", 400, "unsupported version"),
            ("CONNECT a.com:443", 400, "malformed request line"),
            ("CONNECT  a.com:443 HTTP/1.1", 400, "malformed request line"),
            ("CONNECT a.com HTTP/1.1", 400, "has no port"),
            ("CONNECT a.com:0 HTTP/1.1", 400, "bad port"),
            ("CONNECT a.com:0443 HTTP/1.1", 400, "bad port"),
            ("CONNECT a.com:65536 HTTP/1.1", 400, "bad port"),
            ("CONNECT a.com:+443 HTTP/1.1", 400, "bad port"),
            (
                "CONNECT 2130706433:443 HTTP/1.1",
                400,
                "reads as an IP address",
            ),
            ("CONNECT 0x7f.1:443 HTTP/1.1", 400, "reads as an IP address"),
            ("CONNECT 127.1:443 HTTP/1.1", 400, "reads as an IP address"),
            (
                "CONNECT 01.2.3.4:443 HTTP/1.1",
                400,
                "reads as an IP address",
            ),
            ("CONNECT [::1:443 HTTP/1.1", 400, "bad IPv6 address"),
            (
                "CONNECT [fe80::1%eth0]:443 HTTP/1.1",
                400,
                "bad IPv6 address",
            ),
            ("CONNECT a.com.:443 HTTP/1.1", 400, "ends with a dot"),
            ("CONNECT a_b.com:443 HTTP/1.1", 400, "contains `_`"),
            ("CONNECT a%2ecom:443 HTTP/1.1", 400, "contains `%`"),
            ("CONNECT user@a.com:443 HTTP/1.1", 400, "contains `@`"),
            ("CONNECT bücher.de:443 HTTP/1.1", 400, "contains `ü`"),
            ("CONNECT :443 HTTP/1.1", 400, "no host name"),
        ] {
            let r = p(line).expect_err(line);
            assert_eq!(r.status, status, "{line}: {r:?}");
            assert!(r.reason.contains(why), "{line}: {r:?}");
        }
        let r = parse(b"CONNECT \xff:443 HTTP/1.1\r\n\r\n").expect_err("utf8");
        assert_eq!(r.status, 400);
        // Control characters never reach the log.
        let r = p("GET \x1b[31mx HTTP/1.1").expect_err("ctl");
        assert!(r.reason.contains("GET ?[31mx"), "{r:?}");
    }

    #[test]
    fn heads_are_read_whole_and_bounded() {
        let mut ok: &[u8] =
            b"CONNECT a.com:443 HTTP/1.1\r\nHost: a.com:443\r\n\r\n\x16\x03\x01hello";
        let (head, rest) = read_head(&mut ok, 8192).expect("head");
        assert!(head.ends_with(b"\r\n\r\n"));
        assert_eq!(rest, b"\x16\x03\x01hello", "bytes after the head are kept");
        let big = format!(
            "CONNECT a.com:443 HTTP/1.1\r\nX: {}\r\n\r\n",
            "a".repeat(9000)
        );
        assert_eq!(
            read_head(&mut big.as_bytes(), 8192)
                .expect_err("big")
                .status,
            431
        );
        let mut cut: &[u8] = b"CONNECT a.com:443 HTTP/1.1\r\n";
        assert_eq!(read_head(&mut cut, 8192).expect_err("eof").status, 400);
        struct Slow;
        impl Read for Slow {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::ErrorKind::WouldBlock.into())
            }
        }
        assert_eq!(read_head(&mut Slow, 8192).expect_err("slow").status, 408);
        struct Broken;
        impl Read for Broken {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::ErrorKind::ConnectionReset.into())
            }
        }
        assert_eq!(read_head(&mut Broken, 8192).expect_err("reset").status, 400);
        assert_eq!(find_end(b"a\n\nb\r\n\r\n"), Some(3));
    }

    proptest::proptest! {
        #[test]
        fn parsing_never_panics(bytes in proptest::collection::vec(proptest::num::u8::ANY, 0..200)) {
            let _ = parse(&bytes);
            let _ = read_head(&mut bytes.as_slice(), 64);
        }

        #[test]
        fn proxy_and_manifest_agree_on_names(labels in proptest::collection::vec("[a-z]([a-z0-9-]{0,6}[a-z0-9])?", 1..4), port in 1u16..) {
            let name = labels.join(".");
            let manifest = cant_manifest::net::HostPort::parse(&format!("{name}:{port}"));
            let proxy = p(&format!("CONNECT {name}:{port} HTTP/1.1"));
            proptest::prop_assert_eq!(manifest.is_ok(), proxy.is_ok(), "{}", name);
            if let (Ok(m), Ok(c)) = (manifest, proxy) {
                proptest::prop_assert!(m.matches(&c.host, c.port));
            }
        }
    }
}