Skip to main content

cant_proxy/
lib.rs

1//! The filtering proxy for network allow lists (Phase 6.3; docs/NETWORK-ALLOWLIST.md §6).
2//!
3//! A cant with `network = { allow = [...] }` will run in a network namespace whose only way out
4//! is this proxy (Phase 6.4). It accepts `CONNECT host:port` only, checks the name against the
5//! allow list **before** any DNS lookup, resolves once, refuses a name with any answer in a
6//! private, loopback, link-local or otherwise special range ([`deny`]), dials the checked
7//! address (never the name), and splices bytes both ways. One log line per decision, never
8//! payload. Threads and `std::net` only: no async runtime, no dependency but the manifest's
9//! canonicaliser, so the proxy and the manifest agree on what a name is.
10
11#![forbid(unsafe_code)]
12
13pub mod deny;
14mod request;
15
16use std::io::{Read, Write};
17use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicUsize, Ordering};
20use std::time::{Duration, Instant};
21
22use cant_manifest::net::HostPort;
23
24pub use request::{Connect, Refusal};
25
26/// Time and size limits (NETWORK-ALLOWLIST.md §6).
27#[derive(Debug, Clone, Copy)]
28pub struct Limits {
29    pub max_tunnels: usize,
30    pub max_head: usize,
31    pub head: Duration,
32    pub dns: Duration,
33    pub connect: Duration,
34    pub idle: Duration,
35}
36
37impl Default for Limits {
38    fn default() -> Self {
39        Limits {
40            max_tunnels: 64,
41            max_head: 8192,
42            head: Duration::from_secs(10),
43            dns: Duration::from_secs(5),
44            connect: Duration::from_secs(10),
45            idle: Duration::from_secs(300),
46        }
47    }
48}
49
50/// An upstream HTTP proxy to chain through (the user's own `HTTPS_PROXY`).
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Upstream {
53    pub host: String,
54    pub port: u16,
55}
56
57impl Upstream {
58    /// `http://host:port` (or `host:port`); no credentials, no path.
59    pub fn parse(url: &str) -> Result<Upstream, String> {
60        let rest = url.strip_prefix("http://").unwrap_or(url);
61        if url.starts_with("https://") || rest.contains("://") {
62            return Err(format!("upstream `{url}` must be an http:// proxy"));
63        }
64        let rest = rest.strip_suffix('/').unwrap_or(rest);
65        if rest.contains('@') {
66            return Err("upstream proxy credentials aren't supported".into());
67        }
68        if rest.contains('/') {
69            return Err(format!("upstream `{url}` must be http://host:port"));
70        }
71        let (host, port) = rest
72            .rsplit_once(':')
73            .ok_or_else(|| format!("upstream `{url}` has no port"))?;
74        let port = port
75            .parse::<u16>()
76            .ok()
77            .filter(|p| *p > 0)
78            .ok_or_else(|| format!("upstream `{url}` has a bad port"))?;
79        if host.is_empty() {
80            return Err(format!("upstream `{url}` has no host"));
81        }
82        Ok(Upstream {
83            host: host.to_string(),
84            port,
85        })
86    }
87}
88
89/// What the proxy allows and how.
90#[derive(Debug, Clone, Default)]
91pub struct Rules {
92    pub allow: Vec<HostPort>,
93    pub upstream: Option<Upstream>,
94    pub limits: Limits,
95}
96
97/// Receives one line per decision.
98pub type Log = Arc<dyn Fn(&str) + Send + Sync>;
99
100type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
101type Deny = Arc<dyn Fn(IpAddr) -> Option<&'static str> + Send + Sync>;
102
103/// A configured proxy; [`Proxy::serve`] runs it on a listener.
104#[derive(Clone)]
105pub struct Proxy {
106    rules: Arc<Rules>,
107    log: Log,
108    resolve: Resolve,
109    deny: Deny,
110    active: Arc<AtomicUsize>,
111}
112
113impl Proxy {
114    /// The proxy as it runs for real: the system resolver, and [`deny::denied`] with this
115    /// machine's own addresses.
116    pub fn new(rules: Rules, log: Log) -> Proxy {
117        let own = deny::own_addresses();
118        Proxy {
119            rules: Arc::new(rules),
120            log,
121            resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
122            deny: Arc::new(move |ip| deny::denied(ip, &own)),
123            active: Arc::new(AtomicUsize::new(0)),
124        }
125    }
126
127    /// Accepts connections on `listener` until it fails, one thread per connection.
128    pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
129        std::thread::spawn(move || {
130            // A failed accept (the client gave up before it was accepted) is skipped.
131            for conn in listener.incoming().flatten() {
132                let me = self.clone();
133                std::thread::spawn(move || me.handle(conn));
134            }
135        })
136    }
137
138    fn log(&self, line: String) {
139        (self.log)(&line);
140    }
141
142    /// One client connection, start to end.
143    fn handle(&self, mut client: TcpStream) {
144        let start = Instant::now();
145        let ms = || start.elapsed().as_millis();
146        let n = self.active.fetch_add(1, Ordering::SeqCst);
147        let _slot = Slot(&self.active);
148        if n >= self.rules.limits.max_tunnels {
149            return self.refuse(&mut client, 503, "", "too many tunnels", ms());
150        }
151        let _ = client.set_read_timeout(Some(self.rules.limits.head));
152        let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
153            Ok(h) => h,
154            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
155        };
156        let c = match request::parse(&head) {
157            Ok(c) => c,
158            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
159        };
160        let target = format!("{}:{}", c.host, c.port);
161        // The allow list first: a refused name is never looked up.
162        if !self.rules.allow.iter().any(|e| e.matches(&c.host, c.port)) {
163            return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
164        }
165        let (upstream, via) = match &self.rules.upstream {
166            Some(up) => match self.through(up, &c) {
167                Ok(s) => (s, format!("via {}:{}", up.host, up.port)),
168                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
169            },
170            None => match self.dial(&c) {
171                Ok((s, ip)) => (s, format!("ip={ip}")),
172                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
173            },
174        };
175        // A client already gone just makes the splice below end at once.
176        let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
177        self.log(format!("allow CONNECT {target} {via} ms={}", ms()));
178        let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
179        self.log(format!("close {target} up={up} down={down} ms={}", ms()));
180    }
181
182    fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
183        let text = match status {
184            400 => "Bad Request",
185            403 => "Forbidden",
186            405 => "Method Not Allowed",
187            408 => "Request Timeout",
188            431 => "Request Header Fields Too Large",
189            502 => "Bad Gateway",
190            503 => "Service Unavailable",
191            _ => "Gateway Timeout",
192        };
193        let _ = client.write_all(
194            format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
195                .as_bytes(),
196        );
197        let sep = if target.is_empty() { "" } else { " " };
198        self.log(format!("deny {status}{sep}{target} reason={why} ms={ms}"));
199    }
200
201    /// Resolves once (within the DNS limit), refuses if any answer is denied, and connects to
202    /// the first answer that accepts.
203    fn dial(&self, c: &Connect) -> Result<(TcpStream, IpAddr), (u16, String)> {
204        let resolve = Arc::clone(&self.resolve);
205        let (host, port) = (c.host.clone(), c.port);
206        let (tx, rx) = std::sync::mpsc::channel();
207        // A lookup can't be cancelled; past the limit it is left to finish alone.
208        std::thread::spawn(move || {
209            let _ = tx.send(resolve(&host, port));
210        });
211        let addrs = match rx.recv_timeout(self.rules.limits.dns) {
212            Ok(Ok(a)) if !a.is_empty() => a,
213            Ok(Ok(_)) => return Err((502, "the name has no address".into())),
214            Ok(Err(e)) => return Err((502, format!("lookup failed: {e}"))),
215            Err(_) => return Err((504, "lookup took too long".into())),
216        };
217        if let Some((ip, why)) = addrs
218            .iter()
219            .find_map(|a| (self.deny)(a.ip()).map(|w| (a.ip(), w)))
220        {
221            return Err((403, format!("resolves to {ip}: {why}")));
222        }
223        let mut last = String::new();
224        for a in &addrs {
225            match TcpStream::connect_timeout(a, self.rules.limits.connect) {
226                Ok(s) => return Ok((s, a.ip())),
227                Err(e) => last = format!("connecting to {}: {e}", a.ip()),
228            }
229        }
230        Err((502, last))
231    }
232
233    /// Opens the tunnel through the upstream proxy, which does the resolving.
234    fn through(&self, up: &Upstream, c: &Connect) -> Result<TcpStream, (u16, String)> {
235        let addrs = (up.host.as_str(), up.port)
236            .to_socket_addrs()
237            .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
238        let mut s = addrs
239            .into_iter()
240            .find_map(|a| TcpStream::connect_timeout(&a, self.rules.limits.connect).ok())
241            .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
242        let target = format!("{}:{}", c.host, c.port);
243        // A failed write shows as the missing answer read next.
244        let _ =
245            s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes());
246        let _ = s.set_read_timeout(Some(self.rules.limits.connect));
247        let (head, rest) = request::read_head(&mut s, self.rules.limits.max_head)
248            .map_err(|r| (502, format!("upstream: {}", r.reason)))?;
249        let status = std::str::from_utf8(&head)
250            .ok()
251            .and_then(|h| h.split(' ').nth(1))
252            .unwrap_or("");
253        if status != "200" || !rest.is_empty() {
254            return Err((502, format!("upstream answered {status}")));
255        }
256        let _ = s.set_read_timeout(None);
257        Ok(s)
258    }
259
260    #[cfg(test)]
261    fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
262        Proxy {
263            rules: Arc::new(rules),
264            log,
265            resolve,
266            deny,
267            active: Arc::new(AtomicUsize::new(0)),
268        }
269    }
270}
271
272impl std::fmt::Debug for Proxy {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.debug_struct("Proxy")
275            .field("rules", &self.rules)
276            .field("active", &self.active.load(Ordering::SeqCst))
277            .finish_non_exhaustive()
278    }
279}
280
281/// Frees a tunnel slot when the connection ends.
282struct Slot<'a>(&'a AtomicUsize);
283
284impl Drop for Slot<'_> {
285    fn drop(&mut self) {
286        self.0.fetch_sub(1, Ordering::SeqCst);
287    }
288}
289
290/// Copies both ways until both sides are done (half-close on EOF) or a side is idle for
291/// `idle`. Returns the bytes sent up (client to server, `early` first) and down.
292fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
293    let _ = client.set_read_timeout(Some(idle));
294    let _ = server.set_read_timeout(Some(idle));
295    let (c, s) = (&client, &server);
296    let (up, down) = std::thread::scope(|scope| {
297        let up = scope.spawn(move || {
298            let n = copy(&mut early.chain(c), &mut { s });
299            let _ = s.shutdown(Shutdown::Write);
300            n
301        });
302        let down = copy(&mut { s }, &mut { c });
303        let _ = c.shutdown(Shutdown::Write);
304        (up.join().unwrap_or(0), down)
305    });
306    let _ = server.shutdown(Shutdown::Both);
307    let _ = client.shutdown(Shutdown::Both);
308    (up, down)
309}
310
311/// Like `io::copy`, but a read timeout or error just ends it.
312fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
313    let mut buf = [0u8; 16 * 1024];
314    let mut n = 0u64;
315    loop {
316        match from.read(&mut buf) {
317            Ok(0) | Err(_) => return n,
318            Ok(k) => {
319                if to.write_all(&buf[..k]).is_err() {
320                    return n;
321                }
322                n += k as u64;
323            }
324        }
325    }
326}
327
328#[cfg(test)]
329mod tests;