Skip to main content

cant_proxy/
request.rs

1//! Reading a request head: only `CONNECT host:port HTTP/1.x`, the host canonical by the same
2//! rules as a manifest's allow list (`cant_manifest::net::canonical_name`). Anything else is
3//! refused with a status, never "fixed up": name parsing is where egress proxies had their CVEs.
4
5use std::io::Read;
6
7/// A refused request: the HTTP status to answer and why (for the log).
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Refusal {
10    pub status: u16,
11    pub reason: String,
12}
13
14fn refuse(status: u16, reason: impl Into<String>) -> Refusal {
15    Refusal {
16        status,
17        reason: reason.into(),
18    }
19}
20
21/// A `CONNECT` the proxy may consider: a canonical host name and a port.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Connect {
24    pub host: String,
25    pub port: u16,
26}
27
28/// Reads up to and including the blank line ending the head, at most `max` bytes. Returns the
29/// head and any bytes read after it (a client may send its TLS hello right behind).
30pub fn read_head(r: &mut dyn Read, max: usize) -> Result<(Vec<u8>, Vec<u8>), Refusal> {
31    let mut buf = Vec::with_capacity(1024);
32    let mut chunk = [0u8; 1024];
33    loop {
34        if let Some(end) = find_end(&buf) {
35            let rest = buf.split_off(end);
36            return Ok((buf, rest));
37        }
38        if buf.len() >= max {
39            return Err(refuse(431, "request head too large"));
40        }
41        let n = match r.read(&mut chunk) {
42            Ok(0) => return Err(refuse(400, "connection closed before the request ended")),
43            Ok(n) => n,
44            Err(e)
45                if matches!(
46                    e.kind(),
47                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
48                ) =>
49            {
50                return Err(refuse(408, "request head took too long"));
51            }
52            Err(e) => return Err(refuse(400, format!("reading the request: {e}"))),
53        };
54        buf.extend_from_slice(&chunk[..n]);
55    }
56}
57
58/// The index just past `\r\n\r\n` (or `\n\n`), if the head is complete.
59fn find_end(buf: &[u8]) -> Option<usize> {
60    let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4);
61    let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| i + 2);
62    match (crlf, lf) {
63        (Some(a), Some(b)) => Some(a.min(b)),
64        (a, b) => a.or(b),
65    }
66}
67
68/// Parses a complete head into a [`Connect`]. Header lines are ignored (nothing in them is
69/// trusted); only the request line counts.
70pub fn parse(head: &[u8]) -> Result<Connect, Refusal> {
71    let head = std::str::from_utf8(head).map_err(|_| refuse(400, "request is not UTF-8"))?;
72    let line = head.split('\n').next().unwrap_or("").trim_end_matches('\r');
73    let parts: Vec<&str> = line.split(' ').collect();
74    let [method, target, version] = parts.as_slice() else {
75        return Err(refuse(
76            400,
77            format!("malformed request line `{}`", printable(line)),
78        ));
79    };
80    if !matches!(*version, "HTTP/1.1" | "HTTP/1.0") {
81        return Err(refuse(
82            400,
83            format!("unsupported version `{}`", printable(version)),
84        ));
85    }
86    if *method != "CONNECT" {
87        // An absolute-form request (`POST http://...`) is a program ignoring HTTPS: say which.
88        return Err(refuse(
89            405,
90            format!("not CONNECT: {} {}", printable(method), printable(target)),
91        ));
92    }
93    if target.starts_with('[') {
94        return Err(refuse(400, "an IP address; only host names are allowed"));
95    }
96    let Some((host, port)) = target.rsplit_once(':') else {
97        return Err(refuse(400, format!("`{}` has no port", printable(target))));
98    };
99    let port = match port.parse::<u16>() {
100        Ok(p) if p > 0 && !port.starts_with('0') && port.bytes().all(|b| b.is_ascii_digit()) => p,
101        _ => return Err(refuse(400, format!("bad port `{}`", printable(port)))),
102    };
103    let host = host.to_ascii_lowercase();
104    cant_manifest::net::canonical_name(&host).map_err(|e| refuse(400, e))?;
105    Ok(Connect { host, port })
106}
107
108/// For the log: at most 100 characters, control characters as `?`.
109fn printable(s: &str) -> String {
110    s.chars()
111        .take(100)
112        .map(|c| if c.is_control() { '?' } else { c })
113        .collect()
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    fn p(line: &str) -> Result<Connect, Refusal> {
121        parse(format!("{line}\r\nHost: x\r\n\r\n").as_bytes())
122    }
123
124    #[test]
125    fn a_plain_connect_parses() {
126        assert_eq!(
127            p("CONNECT api.github.com:443 HTTP/1.1"),
128            Ok(Connect {
129                host: "api.github.com".into(),
130                port: 443
131            })
132        );
133        // Case is folded before the canonical check; HTTP/1.0 and bare LF are fine.
134        assert_eq!(
135            p("CONNECT API.GitHub.com:8443 HTTP/1.0").expect("ok").host,
136            "api.github.com"
137        );
138        assert!(parse(b"CONNECT a.com:443 HTTP/1.1\n\n").is_ok());
139    }
140
141    #[test]
142    fn anything_else_is_refused_with_a_status() {
143        for (line, status, why) in [
144            (
145                "GET http://a.com/ HTTP/1.1",
146                405,
147                "not CONNECT: GET http://a.com/",
148            ),
149            ("POST https://api.agnost.ai/x HTTP/1.1", 405, "not CONNECT"),
150            ("connect a.com:443 HTTP/1.1", 405, "not CONNECT"),
151            ("CONNECT a.com:443 HTTP/2", 400, "unsupported version"),
152            ("CONNECT a.com:443", 400, "malformed request line"),
153            ("CONNECT  a.com:443 HTTP/1.1", 400, "malformed request line"),
154            ("CONNECT a.com HTTP/1.1", 400, "has no port"),
155            ("CONNECT a.com:0 HTTP/1.1", 400, "bad port"),
156            ("CONNECT a.com:0443 HTTP/1.1", 400, "bad port"),
157            ("CONNECT a.com:65536 HTTP/1.1", 400, "bad port"),
158            ("CONNECT a.com:+443 HTTP/1.1", 400, "bad port"),
159            ("CONNECT [::1]:443 HTTP/1.1", 400, "IP address"),
160            (
161                "CONNECT 127.0.0.1:443 HTTP/1.1",
162                400,
163                "reads as an IP address",
164            ),
165            (
166                "CONNECT 2130706433:443 HTTP/1.1",
167                400,
168                "reads as an IP address",
169            ),
170            ("CONNECT 0x7f.1:443 HTTP/1.1", 400, "reads as an IP address"),
171            ("CONNECT a.com.:443 HTTP/1.1", 400, "ends with a dot"),
172            ("CONNECT a_b.com:443 HTTP/1.1", 400, "contains `_`"),
173            ("CONNECT a%2ecom:443 HTTP/1.1", 400, "contains `%`"),
174            ("CONNECT user@a.com:443 HTTP/1.1", 400, "contains `@`"),
175            ("CONNECT bücher.de:443 HTTP/1.1", 400, "contains `ü`"),
176            ("CONNECT :443 HTTP/1.1", 400, "no host name"),
177        ] {
178            let r = p(line).expect_err(line);
179            assert_eq!(r.status, status, "{line}: {r:?}");
180            assert!(r.reason.contains(why), "{line}: {r:?}");
181        }
182        let r = parse(b"CONNECT \xff:443 HTTP/1.1\r\n\r\n").expect_err("utf8");
183        assert_eq!(r.status, 400);
184        // Control characters never reach the log.
185        let r = p("GET \x1b[31mx HTTP/1.1").expect_err("ctl");
186        assert!(r.reason.contains("GET ?[31mx"), "{r:?}");
187    }
188
189    #[test]
190    fn heads_are_read_whole_and_bounded() {
191        let mut ok: &[u8] =
192            b"CONNECT a.com:443 HTTP/1.1\r\nHost: a.com:443\r\n\r\n\x16\x03\x01hello";
193        let (head, rest) = read_head(&mut ok, 8192).expect("head");
194        assert!(head.ends_with(b"\r\n\r\n"));
195        assert_eq!(rest, b"\x16\x03\x01hello", "bytes after the head are kept");
196        let big = format!(
197            "CONNECT a.com:443 HTTP/1.1\r\nX: {}\r\n\r\n",
198            "a".repeat(9000)
199        );
200        assert_eq!(
201            read_head(&mut big.as_bytes(), 8192)
202                .expect_err("big")
203                .status,
204            431
205        );
206        let mut cut: &[u8] = b"CONNECT a.com:443 HTTP/1.1\r\n";
207        assert_eq!(read_head(&mut cut, 8192).expect_err("eof").status, 400);
208        struct Slow;
209        impl Read for Slow {
210            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
211                Err(std::io::ErrorKind::WouldBlock.into())
212            }
213        }
214        assert_eq!(read_head(&mut Slow, 8192).expect_err("slow").status, 408);
215        struct Broken;
216        impl Read for Broken {
217            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
218                Err(std::io::ErrorKind::ConnectionReset.into())
219            }
220        }
221        assert_eq!(read_head(&mut Broken, 8192).expect_err("reset").status, 400);
222        assert_eq!(find_end(b"a\n\nb\r\n\r\n"), Some(3));
223    }
224
225    proptest::proptest! {
226        #[test]
227        fn parsing_never_panics(bytes in proptest::collection::vec(proptest::num::u8::ANY, 0..200)) {
228            let _ = parse(&bytes);
229            let _ = read_head(&mut bytes.as_slice(), 64);
230        }
231
232        #[test]
233        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..) {
234            let name = labels.join(".");
235            let manifest = cant_manifest::net::HostPort::parse(&format!("{name}:{port}"));
236            let proxy = p(&format!("CONNECT {name}:{port} HTTP/1.1"));
237            proptest::prop_assert_eq!(manifest.is_ok(), proxy.is_ok(), "{}", name);
238            if let (Ok(m), Ok(c)) = (manifest, proxy) {
239                proptest::prop_assert!(m.matches(&c.host, c.port));
240            }
241        }
242    }
243}