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, UserHost};
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    /// The manifest's entries: public names only.
93    pub allow: Vec<HostPort>,
94    /// Hosts the user named: names that may resolve to private addresses, and IP addresses.
95    pub user: Vec<UserHost>,
96    /// The user's hosts may also be loopback and this machine's own addresses.
97    pub loopback: bool,
98    pub upstream: Option<Upstream>,
99    pub limits: Limits,
100}
101
102impl Rules {
103    /// Whether the user named this target (an IP `CONNECT` matches only an IP entry).
104    fn user_named(&self, c: &Connect) -> bool {
105        self.user.iter().any(|u| match c.ip {
106            Some(ip) => u.matches_ip(ip, c.port),
107            None => u.matches_name(&c.host, c.port),
108        })
109    }
110
111    /// Whether the manifest's list allows this target (names only).
112    fn listed(&self, c: &Connect) -> bool {
113        c.ip.is_none() && self.allow.iter().any(|e| e.matches(&c.host, c.port))
114    }
115
116    /// Whether a refused address is still allowed for a host the user named.
117    fn user_may(&self, d: deny::Denial) -> bool {
118        match d.class {
119            deny::Class::Private => true,
120            deny::Class::Loopback | deny::Class::Own => self.loopback,
121            deny::Class::Other => false,
122        }
123    }
124}
125
126/// One decision of the proxy. `Display` gives the log line: `allow CONNECT host:port ip=…`,
127/// `deny 403 host:port reason=…`, `close host:port up=… down=…`.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum Decision {
130    /// A tunnel opened: `via` is `ip=…` or `via host:port` (an upstream proxy).
131    Allowed {
132        target: String,
133        via: String,
134        ms: u128,
135    },
136    /// Refused with an HTTP status; `target` is empty when the request never named one.
137    Refused {
138        status: u16,
139        target: String,
140        reason: String,
141        ms: u128,
142    },
143    /// A tunnel ended, with the bytes each way.
144    Closed {
145        target: String,
146        up: u64,
147        down: u64,
148        ms: u128,
149    },
150}
151
152impl std::fmt::Display for Decision {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        match self {
155            Decision::Allowed { target, via, ms } => {
156                write!(f, "allow CONNECT {target} {via} ms={ms}")
157            }
158            Decision::Refused {
159                status,
160                target,
161                reason,
162                ms,
163            } => {
164                let sep = if target.is_empty() { "" } else { " " };
165                write!(f, "deny {status}{sep}{target} reason={reason} ms={ms}")
166            }
167            Decision::Closed {
168                target,
169                up,
170                down,
171                ms,
172            } => write!(f, "close {target} up={up} down={down} ms={ms}"),
173        }
174    }
175}
176
177/// Receives each decision.
178pub type Log = Arc<dyn Fn(&Decision) + Send + Sync>;
179
180type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
181type Deny = Arc<dyn Fn(IpAddr) -> Option<deny::Denial> + Send + Sync>;
182
183/// A configured proxy; [`Proxy::serve`] runs it on a listener.
184#[derive(Clone)]
185pub struct Proxy {
186    rules: Arc<Rules>,
187    log: Log,
188    resolve: Resolve,
189    deny: Deny,
190    active: Arc<AtomicUsize>,
191}
192
193impl Proxy {
194    /// The proxy as it runs for real: the system resolver, and [`deny::denied`] with this
195    /// machine's own addresses.
196    pub fn new(rules: Rules, log: Log) -> Proxy {
197        let own = deny::own_addresses();
198        Proxy {
199            rules: Arc::new(rules),
200            log,
201            resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
202            deny: Arc::new(move |ip| deny::denied(ip, &own)),
203            active: Arc::new(AtomicUsize::new(0)),
204        }
205    }
206
207    /// Accepts connections on `listener` until it fails, one thread per connection.
208    pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
209        std::thread::spawn(move || {
210            // A failed accept (the client gave up before it was accepted) is skipped.
211            for conn in listener.incoming().flatten() {
212                let me = self.clone();
213                std::thread::spawn(move || me.handle(conn));
214            }
215        })
216    }
217
218    fn log(&self, d: Decision) {
219        (self.log)(&d);
220    }
221
222    /// One client connection, start to end.
223    fn handle(&self, mut client: TcpStream) {
224        let start = Instant::now();
225        let ms = || start.elapsed().as_millis();
226        let n = self.active.fetch_add(1, Ordering::SeqCst);
227        let _slot = Slot(&self.active);
228        if n >= self.rules.limits.max_tunnels {
229            return self.refuse(&mut client, 503, "", "too many tunnels", ms());
230        }
231        let _ = client.set_read_timeout(Some(self.rules.limits.head));
232        let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
233            Ok(h) => h,
234            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
235        };
236        let c = match request::parse(&head) {
237            Ok(c) => c,
238            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
239        };
240        let target = format!("{}:{}", c.host, c.port);
241        // The allow list first: a refused name is never looked up.
242        let user = self.rules.user_named(&c);
243        if !user && !self.rules.listed(&c) {
244            return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
245        }
246        let (upstream, via) = match &self.rules.upstream {
247            Some(up) => match self.through(up, &c) {
248                Ok(s) => (s, format!("via {}:{}", up.host, up.port)),
249                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
250            },
251            None => match self.dial(&c, user) {
252                Ok((s, ip)) => (s, format!("ip={ip}")),
253                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
254            },
255        };
256        // A client already gone just makes the splice below end at once.
257        let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
258        self.log(Decision::Allowed {
259            target: target.clone(),
260            via,
261            ms: ms(),
262        });
263        let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
264        self.log(Decision::Closed {
265            target,
266            up,
267            down,
268            ms: ms(),
269        });
270    }
271
272    fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
273        let text = match status {
274            400 => "Bad Request",
275            403 => "Forbidden",
276            405 => "Method Not Allowed",
277            408 => "Request Timeout",
278            431 => "Request Header Fields Too Large",
279            502 => "Bad Gateway",
280            503 => "Service Unavailable",
281            _ => "Gateway Timeout",
282        };
283        // Log first: the client prints its own error once it reads the answer, and the two
284        // often share a terminal; this way the reason comes first, whole.
285        self.log(Decision::Refused {
286            status,
287            target: target.to_string(),
288            reason: why.to_string(),
289            ms,
290        });
291        let _ = client.write_all(
292            format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
293                .as_bytes(),
294        );
295    }
296
297    /// Resolves once (within the DNS limit), refuses if any answer is denied, and connects to
298    /// the first answer that accepts.
299    /// Connects to the target, refusing addresses the deny table names; a host the user named
300    /// (`user`) may also reach the classes [`Rules::user_may`] allows. An IP target isn't
301    /// looked up.
302    fn dial(&self, c: &Connect, user: bool) -> Result<(TcpStream, IpAddr), (u16, String)> {
303        let addrs = match c.ip {
304            Some(ip) => vec![SocketAddr::new(ip, c.port)],
305            None => self.lookup(c)?,
306        };
307        if let Some((ip, d)) = addrs.iter().find_map(|a| {
308            (self.deny)(a.ip())
309                .filter(|d| !(user && self.rules.user_may(*d)))
310                .map(|d| (a.ip(), d))
311        }) {
312            let hint = if user && matches!(d.class, deny::Class::Loopback | deny::Class::Own) {
313                "; cant run --allow-loopback allows it"
314            } else {
315                ""
316            };
317            let what = match c.ip {
318                Some(_) => format!("{ip}"),
319                None => format!("resolves to {ip}"),
320            };
321            return Err((403, format!("{what}: {}{hint}", d.why)));
322        }
323        let mut last = String::new();
324        for a in &addrs {
325            match TcpStream::connect_timeout(a, self.rules.limits.connect) {
326                Ok(s) => return Ok((s, a.ip())),
327                Err(e) => last = format!("connecting to {}: {e}", a.ip()),
328            }
329        }
330        Err((502, last))
331    }
332
333    /// The target's addresses, from the resolver, within the DNS time limit.
334    fn lookup(&self, c: &Connect) -> Result<Vec<SocketAddr>, (u16, String)> {
335        let resolve = Arc::clone(&self.resolve);
336        let (host, port) = (c.host.clone(), c.port);
337        let (tx, rx) = std::sync::mpsc::channel();
338        // A lookup can't be cancelled; past the limit it is left to finish alone.
339        std::thread::spawn(move || {
340            let _ = tx.send(resolve(&host, port));
341        });
342        match rx.recv_timeout(self.rules.limits.dns) {
343            Ok(Ok(a)) if !a.is_empty() => Ok(a),
344            Ok(Ok(_)) => Err((502, "the name has no address".into())),
345            Ok(Err(e)) => Err((502, format!("lookup failed: {e}"))),
346            Err(_) => Err((504, "lookup took too long".into())),
347        }
348    }
349
350    /// Opens the tunnel through the upstream proxy, which does the resolving.
351    fn through(&self, up: &Upstream, c: &Connect) -> Result<TcpStream, (u16, String)> {
352        let addrs = (up.host.as_str(), up.port)
353            .to_socket_addrs()
354            .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
355        let mut s = addrs
356            .into_iter()
357            .find_map(|a| TcpStream::connect_timeout(&a, self.rules.limits.connect).ok())
358            .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
359        let target = format!("{}:{}", c.host, c.port);
360        // A failed write shows as the missing answer read next.
361        let _ =
362            s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes());
363        let _ = s.set_read_timeout(Some(self.rules.limits.connect));
364        let (head, rest) = request::read_head(&mut s, self.rules.limits.max_head)
365            .map_err(|r| (502, format!("upstream: {}", r.reason)))?;
366        let status = std::str::from_utf8(&head)
367            .ok()
368            .and_then(|h| h.split(' ').nth(1))
369            .unwrap_or("");
370        if status != "200" || !rest.is_empty() {
371            return Err((502, format!("upstream answered {status}")));
372        }
373        let _ = s.set_read_timeout(None);
374        Ok(s)
375    }
376
377    #[cfg(test)]
378    fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
379        Proxy {
380            rules: Arc::new(rules),
381            log,
382            resolve,
383            deny,
384            active: Arc::new(AtomicUsize::new(0)),
385        }
386    }
387}
388
389impl std::fmt::Debug for Proxy {
390    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391        f.debug_struct("Proxy")
392            .field("rules", &self.rules)
393            .field("active", &self.active.load(Ordering::SeqCst))
394            .finish_non_exhaustive()
395    }
396}
397
398/// Frees a tunnel slot when the connection ends.
399struct Slot<'a>(&'a AtomicUsize);
400
401impl Drop for Slot<'_> {
402    fn drop(&mut self) {
403        self.0.fetch_sub(1, Ordering::SeqCst);
404    }
405}
406
407/// Copies both ways until both sides are done (half-close on EOF) or a side is idle for
408/// `idle`. Returns the bytes sent up (client to server, `early` first) and down.
409fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
410    let _ = client.set_read_timeout(Some(idle));
411    let _ = server.set_read_timeout(Some(idle));
412    let (c, s) = (&client, &server);
413    let (up, down) = std::thread::scope(|scope| {
414        let up = scope.spawn(move || {
415            let n = copy(&mut early.chain(c), &mut { s });
416            let _ = s.shutdown(Shutdown::Write);
417            n
418        });
419        let down = copy(&mut { s }, &mut { c });
420        let _ = c.shutdown(Shutdown::Write);
421        (up.join().unwrap_or(0), down)
422    });
423    let _ = server.shutdown(Shutdown::Both);
424    let _ = client.shutdown(Shutdown::Both);
425    (up, down)
426}
427
428/// Like `io::copy`, but a read timeout or error just ends it.
429fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
430    let mut buf = [0u8; 16 * 1024];
431    let mut n = 0u64;
432    loop {
433        match from.read(&mut buf) {
434            Ok(0) | Err(_) => return n,
435            Ok(k) => {
436                if to.write_all(&buf[..k]).is_err() {
437                    return n;
438                }
439                n += k as u64;
440            }
441        }
442    }
443}
444
445#[cfg(test)]
446mod tests;