cant-proxy 0.0.21

The filtering CONNECT proxy behind Cantainer's network allow lists.
Documentation
//! Upstream URLs, `NO_PROXY`, and the HTTP and SOCKS5 handshakes against fake proxies.

use super::*;
use std::net::{SocketAddr, TcpListener};
use std::sync::Arc;

const T: Duration = Duration::from_secs(5);

/// A fake proxy: runs `script` on each connection.
fn server(script: impl Fn(&mut TcpStream) + Send + Sync + 'static) -> SocketAddr {
    let l = TcpListener::bind("127.0.0.1:0").expect("bind");
    let addr = l.local_addr().expect("addr");
    let script = Arc::new(script);
    std::thread::spawn(move || {
        for mut c in l.incoming().flatten() {
            let s = Arc::clone(&script);
            std::thread::spawn(move || s(&mut c));
        }
    });
    addr
}

fn read_n(s: &mut TcpStream, n: usize) -> Vec<u8> {
    let mut b = vec![0u8; n];
    s.read_exact(&mut b).expect("read");
    b
}

fn up(url: &str) -> Upstream {
    Upstream::parse(url).expect(url)
}

fn target(host: &str, port: u16) -> Connect {
    Connect {
        host: host.to_string(),
        port,
        ip: host
            .trim_start_matches('[')
            .trim_end_matches(']')
            .parse()
            .ok(),
    }
}

#[test]
fn urls_kinds_credentials_and_ports() {
    let u = up("http://proxy.corp:3128/");
    assert_eq!(
        (u.kind, u.host.as_str(), u.port),
        (Kind::Http, "proxy.corp", 3128)
    );
    assert_eq!(u.auth, None);
    assert_eq!(up("10.0.0.5:8080").port, 8080, "no scheme: http");
    let u = up("socks5h://al%40ice:p%3Ass@[::1]");
    assert_eq!(
        (u.kind, u.host.as_str(), u.port),
        (Kind::Socks5, "::1", 1080)
    );
    let a = u.auth.clone().expect("auth");
    assert_eq!((a.user.as_str(), a.pass.as_str()), ("al@ice", "p:ss"));
    assert_eq!(u.to_string(), "socks5h://[::1]:1080", "no credentials");
    assert!(!format!("{u:?}").contains("p:ss"), "{u:?}");
    assert_eq!(up("socks5://s:1081").kind, Kind::Socks5);
    assert_eq!(up("http://u@p:1").auth.expect("auth").pass, "");
    assert_eq!(up("http://p:3128").to_string(), "http://p:3128");
    let long = "x".repeat(256);
    for (url, why) in [
        ("https://p:3128", "http://, socks5:// or socks5h://"),
        ("socks4://p:1080", "http://, socks5:// or socks5h://"),
        ("http://p:3128/path", "scheme://host:port"),
        ("http://p", "no port"),
        ("http://p:0", "bad port"),
        ("http://p:x", "bad port"),
        ("http://:3128", "no host"),
        ("http://[::1:3128", "bad [address]"),
        ("http://:pw@p:3128", "empty user name"),
        ("http://u:%zz@p:3128", "bad %-escape"),
        ("http://u:%f0%28@p:3128", "bad %-escape"),
        ("http://u:%4@p:3128", "bad %-escape"),
    ] {
        let e = Upstream::parse(url).expect_err(url);
        assert!(e.contains(why), "{url}: {e}");
    }
    let e = Upstream::parse(&format!("socks5://{long}:pw@p:1080")).expect_err("long");
    assert!(e.contains("at most 255 bytes"), "{e}");
    // Errors never show the password.
    let e = Upstream::parse("ftp://user:secret@p:1").expect_err("ftp");
    assert!(!e.contains("secret") && e.contains("user:***@p:1"), "{e}");
}

#[test]
fn redaction() {
    assert_eq!(redact("http://u:pw@p:1"), "http://u:***@p:1");
    assert_eq!(redact("u:pw@p:1/x@y"), "u:***@p:1/x@y");
    assert_eq!(redact("http://p:1"), "http://p:1");
    assert_eq!(
        redact("http://p:1/a@b"),
        "http://p:1/a@b",
        "an @ in the path isn't userinfo"
    );
}

#[test]
fn base64_matches_rfc_4648() {
    for (plain, coded) in [
        ("", ""),
        ("f", "Zg=="),
        ("fo", "Zm8="),
        ("foo", "Zm9v"),
        ("foob", "Zm9vYg=="),
        ("fooba", "Zm9vYmE="),
        ("foobar", "Zm9vYmFy"),
    ] {
        assert_eq!(base64(plain.as_bytes()), coded, "{plain}");
    }
}

#[test]
fn no_proxy_like_go() {
    let n = NoProxy::parse(
        " Corp.Example , .internal,*.dev.local, 10.0.0.0/8, 192.168.1.5,[fd00::1]:8443, fd00:1::/32, api.x:8443 ,, bad/99, 1.2.3.4/x, [zz]:1, a:b, [::1]x, *.",
    );
    let m = |h: &str, p: u16| n.matches(&target(h, p));
    assert!(
        m("corp.example", 443) && m("a.corp.example", 1),
        "name and below"
    );
    assert!(!m("xcorp.example", 443));
    assert!(
        m("a.internal", 443) && !m("internal", 443),
        ".name: below only"
    );
    assert!(
        m("x.dev.local", 1) && !m("dev.local", 1),
        "*.name: below only"
    );
    assert!(m("10.1.2.3", 1) && !m("11.0.0.1", 1), "CIDR");
    assert!(m("192.168.1.5", 1) && !m("192.168.1.6", 1));
    assert!(m("[fd00::1]", 8443) && !m("[fd00::1]", 443), "[v6]:port");
    assert!(m("[fd00:1::5]", 1) && !m("[fd00:2::5]", 1), "v6 CIDR");
    assert!(m("api.x", 8443) && !m("api.x", 443), "name:port");
    assert!(!m("10.example", 1), "a name never matches an IP entry");
    assert!(!m("[::1]", 1), "IPv4 nets don't match IPv6");
    assert!(!n.is_empty());
    let ips = NoProxy::parse("[fd00::7], 10.9.9.9:8080");
    let m = |h: &str, p: u16| ips.matches(&target(h, p));
    assert!(
        m("[fd00::7]", 1) && m("[fd00::7]", 443),
        "[v6] without a port: any port"
    );
    assert!(m("10.9.9.9", 8080) && !m("10.9.9.9", 443), "ip:port");
    assert!(NoProxy::parse("").is_empty() && NoProxy::parse(" , ").is_empty());
    let all = NoProxy::parse("x, *");
    assert!(all.matches(&target("anything.com", 443)) && !all.is_empty());
    assert!(in_net(
        "0.0.0.1".parse().expect("ip"),
        "9.9.9.9".parse().expect("ip"),
        0
    ));
}

#[test]
fn http_connect_with_and_without_a_login() {
    let addr = server(|s| {
        let (head, _) = request::read_head(s, 8192).expect("head");
        let head = String::from_utf8(head).expect("utf8");
        let ok = head.starts_with("CONNECT api.example.com:443 HTTP/1.1\r\n")
            && head.contains("Proxy-Authorization: Basic dTpwdw==\r\n");
        let _ = s.write_all(if ok {
            b"HTTP/1.1 200 OK\r\n\r\n".as_slice()
        } else {
            b"HTTP/1.1 407 Login\r\n\r\n".as_slice()
        });
    });
    let c = target("api.example.com", 443);
    up(&format!("http://u:pw@{addr}"))
        .open(&c, T)
        .expect("tunnel");
    let e = up(&format!("http://{addr}"))
        .open(&c, T)
        .expect_err("no login");
    assert!(e.1.contains("407 (proxy login required"), "{}", e.1);
    let e = up(&format!("http://u:wrong@{addr}"))
        .open(&c, T)
        .expect_err("wrong");
    assert!(e.1.contains("407 (proxy login refused)"), "{}", e.1);
    // Other answers, a bad head, and nobody there.
    let other = server(|s| {
        let _ = request::read_head(s, 8192);
        let _ = s.write_all(b"HTTP/1.1 403 No\r\n\r\n");
    });
    let e = up(&format!("http://{other}")).open(&c, T).expect_err("403");
    assert_eq!(e, (502, "upstream answered 403".to_string()));
    let mute = server(|s| {
        let _ = request::read_head(s, 8192);
    });
    let e = up(&format!("http://{mute}"))
        .open(&c, T)
        .expect_err("closed");
    assert!(e.1.starts_with("upstream: "), "{}", e.1);
    let closed = TcpListener::bind("127.0.0.1:0")
        .expect("bind")
        .local_addr()
        .expect("addr");
    let e = up(&format!("http://{closed}"))
        .open(&c, T)
        .expect_err("closed");
    assert_eq!(e.1, "upstream unreachable");
    let e = up("http://nonexistent.invalid:3128")
        .open(&c, T)
        .expect_err("dns");
    assert!(e.1.contains("upstream lookup failed"), "{}", e.1);
}

/// A SOCKS5 server that checks the greeting, the login (if `login`), and the request, then
/// answers `reply` followed by `after` (tunnel bytes the client must not lose).
fn socks(
    login: Option<(&'static str, &'static str)>,
    want: Vec<u8>,
    reply: Vec<u8>,
    after: &'static [u8],
) -> SocketAddr {
    server(move |s| {
        let greet = read_n(s, 3);
        let method = if login.is_some() { 2 } else { 0 };
        assert_eq!(greet, [5, 1, method]);
        let _ = s.write_all(&[5, method]);
        if let Some((user, pass)) = login {
            let v = read_n(s, 2);
            let u = read_n(s, usize::from(v[1]));
            let pl = read_n(s, 1);
            let p = read_n(s, usize::from(pl[0]));
            let ok = u == user.as_bytes() && p == pass.as_bytes();
            let _ = s.write_all(&[1, if ok { 0 } else { 1 }]);
            if !ok {
                return;
            }
        }
        assert_eq!(read_n(s, want.len()), want);
        let _ = s.write_all(&reply);
        let _ = s.write_all(after);
    })
}

#[test]
fn socks5_tunnels_by_name_with_or_without_a_login() {
    // Name target (type 3); a type-1 reply; tunnel bytes right behind the reply.
    let mut want = vec![5, 1, 0, 3, 15];
    want.extend_from_slice(b"api.example.com");
    want.extend_from_slice(&443u16.to_be_bytes());
    let reply = vec![5, 0, 0, 1, 0, 0, 0, 0, 0, 0];
    let addr = socks(None, want.clone(), reply, b"hello");
    let mut s = up(&format!("socks5h://{addr}"))
        .open(&target("api.example.com", 443), T)
        .expect("tunnel");
    assert_eq!(read_n(&mut s, 5), b"hello");
    // With a login; a type-3 reply.
    let mut reply = vec![5, 0, 0, 3, 4];
    reply.extend_from_slice(b"host");
    reply.extend_from_slice(&[0, 80]);
    let addr = socks(Some(("al", "pw")), want.clone(), reply, b"x");
    let mut s = up(&format!("socks5://al:pw@{addr}"))
        .open(&target("api.example.com", 443), T)
        .expect("login");
    assert_eq!(read_n(&mut s, 1), b"x");
    let e = up(&format!("socks5://al:bad@{addr}"))
        .open(&target("api.example.com", 443), T)
        .expect_err("refused");
    assert!(
        e.1.contains("refused the user name and password"),
        "{}",
        e.1
    );
}

#[test]
fn socks5_tunnels_to_addresses_the_user_named() {
    let mut want = vec![5, 1, 0, 1, 10, 0, 0, 5];
    want.extend_from_slice(&6443u16.to_be_bytes());
    let addr = socks(None, want, vec![5, 0, 0, 1, 0, 0, 0, 0, 0, 0], b"");
    up(&format!("socks5://{addr}"))
        .open(&target("10.0.0.5", 6443), T)
        .expect("v4");
    let v6: std::net::Ipv6Addr = "fd00::1".parse().expect("v6");
    let mut want = vec![5, 1, 0, 4];
    want.extend_from_slice(&v6.octets());
    want.extend_from_slice(&443u16.to_be_bytes());
    let mut reply = vec![5, 0, 0, 4];
    reply.extend_from_slice(&[0; 18]);
    let addr = socks(None, want, reply, b"");
    up(&format!("socks5://{addr}"))
        .open(&target("[fd00::1]", 443), T)
        .expect("v6");
}

#[test]
fn socks5_refusals_are_explained() {
    let name = |host: &str| {
        let mut w = vec![5, 1, 0, 3, u8::try_from(host.len()).expect("len")];
        w.extend_from_slice(host.as_bytes());
        w.extend_from_slice(&443u16.to_be_bytes());
        w
    };
    let c = target("a.com", 443);
    for (code, why) in [
        (1, "general failure"),
        (2, "connection not allowed by ruleset"),
        (3, "network unreachable"),
        (4, "host unreachable"),
        (5, "connection refused"),
        (6, "TTL expired"),
        (7, "command not supported"),
        (8, "address type not supported"),
        (9, "error 9"),
    ] {
        let addr = socks(None, name("a.com"), vec![5, code, 0, 1], b"");
        let e = up(&format!("socks5://{addr}")).open(&c, T).expect_err(why);
        assert_eq!(e, (502, format!("the SOCKS proxy refused: {why}")));
    }
    for (reply, why) in [
        (vec![4, 0, 0, 1], "isn't a SOCKS5 proxy"),
        (vec![5, 0, 0, 7], "unknown address type 7"),
        (vec![5, 0, 0, 1, 1], "closed the connection"),
        (vec![5, 0, 0, 3], "closed the connection"),
        (vec![5, 0], "closed the connection"),
    ] {
        let addr = socks(None, name("a.com"), reply, b"");
        let e = up(&format!("socks5://{addr}")).open(&c, T).expect_err(why);
        assert!(e.1.contains(why), "{why}: {}", e.1);
    }
    // The greeting: not SOCKS5, another method, nothing at all.
    for (answer, url, why) in [
        (&[4u8, 0][..], "socks5://{a}", "isn't a SOCKS5 proxy"),
        (
            &[5, 0xff][..],
            "socks5://{a}",
            "put user:password@ in the proxy URL",
        ),
        (
            &[5, 0xff][..],
            "socks5://u:p@{a}",
            "it was given a user name and password",
        ),
        (&[][..], "socks5://{a}", "closed the connection"),
    ] {
        let addr = server(move |s| {
            let _ = read_n(s, 3);
            let _ = s.write_all(answer);
        });
        let e = up(&url.replace("{a}", &addr.to_string()))
            .open(&c, T)
            .expect_err(why);
        assert!(e.1.contains(why), "{why}: {}", e.1);
    }
    // Closed during the login exchange.
    let addr = server(|s| {
        let _ = read_n(s, 3);
        let _ = s.write_all(&[5, 2]);
    });
    let e = up(&format!("socks5://u:p@{addr}"))
        .open(&c, T)
        .expect_err("login");
    assert!(e.1.contains("closed the connection"), "{}", e.1);
    // Fields too long for SOCKS5 (only possible by building an Upstream by hand).
    let mut u = up(&format!("socks5://u:p@{addr}"));
    u.auth = Some(Auth {
        user: "x".repeat(256),
        pass: String::new(),
    });
    let addr2 = server(|s| {
        let _ = read_n(s, 3);
        let _ = s.write_all(&[5, 2]);
    });
    u.port = addr2.port();
    let e = u.open(&c, T).expect_err("long");
    assert!(e.1.contains("at most 255 bytes"), "{}", e.1);
    let addr3 = server(|s| {
        let _ = read_n(s, 3);
        let _ = s.write_all(&[5, 0]);
    });
    let long = target(&format!("{}.com", "a".repeat(260)), 443);
    let e = up(&format!("socks5://{addr3}"))
        .open(&long, T)
        .expect_err("long name");
    assert!(e.1.contains("name too long"), "{}", e.1);
}