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