cant-proxy 0.0.22

The filtering CONNECT proxy behind Cantainer's network allow lists.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! The filtering proxy for network allow lists (Phase 6.3; docs/NETWORK-ALLOWLIST.md §6).
//!
//! A cant with `network = { allow = [...] }` will run in a network namespace whose only way out
//! is this proxy (Phase 6.4). It accepts `CONNECT host:port` only, checks the name against the
//! allow list **before** any DNS lookup, resolves once, refuses a name with any answer in a
//! private, loopback, link-local or otherwise special range ([`deny`]), dials the checked
//! address (never the name), and splices bytes both ways. One log line per decision, never
//! payload. Threads and `std::net` only: no async runtime, no dependency but the manifest's
//! canonicaliser, so the proxy and the manifest agree on what a name is.

#![forbid(unsafe_code)]

pub mod deny;
mod request;
pub mod upstream;

use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use cant_manifest::net::{HostPort, UserHost};

pub use request::{Connect, Refusal};
pub use upstream::{Auth, Kind, NoProxy, Upstream, redact};

/// Time and size limits (NETWORK-ALLOWLIST.md §6).
#[derive(Debug, Clone, Copy)]
pub struct Limits {
    pub max_tunnels: usize,
    pub max_head: usize,
    pub head: Duration,
    pub dns: Duration,
    pub connect: Duration,
    pub idle: Duration,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            max_tunnels: 64,
            max_head: 8192,
            head: Duration::from_secs(10),
            dns: Duration::from_secs(5),
            connect: Duration::from_secs(10),
            idle: Duration::from_secs(300),
        }
    }
}

/// What the proxy allows and how.
#[derive(Debug, Clone, Default)]
pub struct Rules {
    /// The manifest's entries: public names only.
    pub allow: Vec<HostPort>,
    /// Hosts the user named: names that may resolve to private addresses, and IP addresses.
    pub user: Vec<UserHost>,
    /// The user's hosts may also be loopback and this machine's own addresses.
    pub loopback: bool,
    pub upstream: Option<Upstream>,
    /// The user's `NO_PROXY`: these targets are dialled directly, not through `upstream`.
    pub no_upstream: NoProxy,
    pub limits: Limits,
}

impl Rules {
    /// Whether the user named this target (an IP `CONNECT` matches only an IP entry).
    fn user_named(&self, c: &Connect) -> bool {
        self.user.iter().any(|u| match c.ip {
            Some(ip) => u.matches_ip(ip, c.port),
            None => u.matches_name(&c.host, c.port),
        })
    }

    /// Whether the manifest's list allows this target (names only).
    fn listed(&self, c: &Connect) -> bool {
        c.ip.is_none() && self.allow.iter().any(|e| e.matches(&c.host, c.port))
    }

    /// Whether a refused address is still allowed for a host the user named.
    fn user_may(&self, d: deny::Denial) -> bool {
        match d.class {
            deny::Class::Private => true,
            deny::Class::Loopback | deny::Class::Own => self.loopback,
            deny::Class::Other => false,
        }
    }
}

/// One decision of the proxy. `Display` gives the log line: `allow CONNECT host:port ip=…`,
/// `deny 403 host:port reason=…`, `close host:port up=… down=…`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
    /// A tunnel opened: `via` is `ip=…` or `via host:port` (an upstream proxy).
    Allowed {
        target: String,
        via: String,
        ms: u128,
    },
    /// Refused with an HTTP status; `target` is empty when the request never named one.
    Refused {
        status: u16,
        target: String,
        reason: String,
        ms: u128,
    },
    /// A tunnel ended, with the bytes each way.
    Closed {
        target: String,
        up: u64,
        down: u64,
        ms: u128,
    },
}

impl std::fmt::Display for Decision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Decision::Allowed { target, via, ms } => {
                write!(f, "allow CONNECT {target} {via} ms={ms}")
            }
            Decision::Refused {
                status,
                target,
                reason,
                ms,
            } => {
                let sep = if target.is_empty() { "" } else { " " };
                write!(f, "deny {status}{sep}{target} reason={reason} ms={ms}")
            }
            Decision::Closed {
                target,
                up,
                down,
                ms,
            } => write!(f, "close {target} up={up} down={down} ms={ms}"),
        }
    }
}

/// Receives each decision.
pub type Log = Arc<dyn Fn(&Decision) + Send + Sync>;

type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
type Deny = Arc<dyn Fn(IpAddr) -> Option<deny::Denial> + Send + Sync>;

/// A configured proxy; [`Proxy::serve`] runs it on a listener.
#[derive(Clone)]
pub struct Proxy {
    rules: Arc<Rules>,
    log: Log,
    resolve: Resolve,
    deny: Deny,
    active: Arc<AtomicUsize>,
}

impl Proxy {
    /// The proxy as it runs for real: the system resolver, and [`deny::denied`] with this
    /// machine's own addresses.
    pub fn new(rules: Rules, log: Log) -> Proxy {
        let own = deny::own_addresses();
        Proxy {
            rules: Arc::new(rules),
            log,
            resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
            deny: Arc::new(move |ip| deny::denied(ip, &own)),
            active: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Accepts connections on `listener` until it fails, one thread per connection.
    pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
        std::thread::spawn(move || {
            // A failed accept (the client gave up before it was accepted) is skipped.
            for conn in listener.incoming().flatten() {
                let me = self.clone();
                std::thread::spawn(move || me.handle(conn));
            }
        })
    }

    fn log(&self, d: Decision) {
        (self.log)(&d);
    }

    /// One client connection, start to end.
    fn handle(&self, mut client: TcpStream) {
        let start = Instant::now();
        let ms = || start.elapsed().as_millis();
        let n = self.active.fetch_add(1, Ordering::SeqCst);
        let _slot = Slot(&self.active);
        if n >= self.rules.limits.max_tunnels {
            return self.refuse(&mut client, 503, "", "too many tunnels", ms());
        }
        let _ = client.set_read_timeout(Some(self.rules.limits.head));
        let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
            Ok(h) => h,
            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
        };
        let c = match request::parse(&head) {
            Ok(c) => c,
            Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
        };
        let target = format!("{}:{}", c.host, c.port);
        // The allow list first: a refused name is never looked up.
        let user = self.rules.user_named(&c);
        if !user && !self.rules.listed(&c) {
            return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
        }
        let (upstream, via) = match &self.rules.upstream {
            Some(up) if !self.rules.no_upstream.matches(&c) => {
                match up.open(&c, self.rules.limits.connect) {
                    Ok(s) => (s, format!("via {up}")),
                    Err((status, why)) => {
                        return self.refuse(&mut client, status, &target, &why, ms());
                    }
                }
            }
            _ => match self.dial(&c, user) {
                Ok((s, ip)) => (s, format!("ip={ip}")),
                Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
            },
        };
        // A client already gone just makes the splice below end at once.
        let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
        self.log(Decision::Allowed {
            target: target.clone(),
            via,
            ms: ms(),
        });
        let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
        self.log(Decision::Closed {
            target,
            up,
            down,
            ms: ms(),
        });
    }

    fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
        let text = match status {
            400 => "Bad Request",
            403 => "Forbidden",
            405 => "Method Not Allowed",
            408 => "Request Timeout",
            431 => "Request Header Fields Too Large",
            502 => "Bad Gateway",
            503 => "Service Unavailable",
            _ => "Gateway Timeout",
        };
        // Log first: the client prints its own error once it reads the answer, and the two
        // often share a terminal; this way the reason comes first, whole.
        self.log(Decision::Refused {
            status,
            target: target.to_string(),
            reason: why.to_string(),
            ms,
        });
        let _ = client.write_all(
            format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                .as_bytes(),
        );
    }

    /// Resolves once (within the DNS limit), refuses if any answer is denied, and connects to
    /// the first answer that accepts.
    /// Connects to the target, refusing addresses the deny table names; a host the user named
    /// (`user`) may also reach the classes [`Rules::user_may`] allows. An IP target isn't
    /// looked up.
    fn dial(&self, c: &Connect, user: bool) -> Result<(TcpStream, IpAddr), (u16, String)> {
        let addrs = match c.ip {
            Some(ip) => vec![SocketAddr::new(ip, c.port)],
            None => self.lookup(c)?,
        };
        if let Some((ip, d)) = addrs.iter().find_map(|a| {
            (self.deny)(a.ip())
                .filter(|d| !(user && self.rules.user_may(*d)))
                .map(|d| (a.ip(), d))
        }) {
            let hint = if user && matches!(d.class, deny::Class::Loopback | deny::Class::Own) {
                "; cant run --allow-loopback allows it"
            } else {
                ""
            };
            let what = match c.ip {
                Some(_) => format!("{ip}"),
                None => format!("resolves to {ip}"),
            };
            return Err((403, format!("{what}: {}{hint}", d.why)));
        }
        let mut last = String::new();
        for a in &addrs {
            match TcpStream::connect_timeout(a, self.rules.limits.connect) {
                Ok(s) => return Ok((s, a.ip())),
                Err(e) => last = format!("connecting to {}: {e}", a.ip()),
            }
        }
        Err((502, last))
    }

    /// The target's addresses, from the resolver, within the DNS time limit.
    fn lookup(&self, c: &Connect) -> Result<Vec<SocketAddr>, (u16, String)> {
        let resolve = Arc::clone(&self.resolve);
        let (host, port) = (c.host.clone(), c.port);
        let (tx, rx) = std::sync::mpsc::channel();
        // A lookup can't be cancelled; past the limit it is left to finish alone.
        std::thread::spawn(move || {
            let _ = tx.send(resolve(&host, port));
        });
        match rx.recv_timeout(self.rules.limits.dns) {
            Ok(Ok(a)) if !a.is_empty() => Ok(a),
            Ok(Ok(_)) => Err((502, "the name has no address".into())),
            Ok(Err(e)) => Err((502, format!("lookup failed: {e}"))),
            Err(_) => Err((504, "lookup took too long".into())),
        }
    }

    #[cfg(test)]
    fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
        Proxy {
            rules: Arc::new(rules),
            log,
            resolve,
            deny,
            active: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl std::fmt::Debug for Proxy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Proxy")
            .field("rules", &self.rules)
            .field("active", &self.active.load(Ordering::SeqCst))
            .finish_non_exhaustive()
    }
}

/// Frees a tunnel slot when the connection ends.
struct Slot<'a>(&'a AtomicUsize);

impl Drop for Slot<'_> {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::SeqCst);
    }
}

/// Forwards connections on `listener` (a loopback port inside the cant's network namespace) to
/// the first of `targets` (this machine's loopback, the same port) that accepts, one thread per
/// connection, at most `limits.max_tunnels` at once. For loopback hosts the user added with
/// `--allow-loopback`: Go's `net/http` never sends loopback to a proxy, so those connections
/// must work without one. A connection no target accepts is closed.
pub fn forward(
    listener: TcpListener,
    targets: Vec<SocketAddr>,
    limits: Limits,
) -> std::thread::JoinHandle<()> {
    let active = Arc::new(AtomicUsize::new(0));
    let targets = Arc::new(targets);
    std::thread::spawn(move || {
        for client in listener.incoming().flatten() {
            let (active, targets) = (Arc::clone(&active), Arc::clone(&targets));
            std::thread::spawn(move || {
                let n = active.fetch_add(1, Ordering::SeqCst);
                let _slot = Slot(&active);
                if n >= limits.max_tunnels {
                    return;
                }
                if let Some(server) = targets
                    .iter()
                    .find_map(|a| TcpStream::connect_timeout(a, limits.connect).ok())
                {
                    splice(client, server, &[], limits.idle);
                }
            });
        }
    })
}

/// Copies both ways until both sides are done (half-close on EOF) or a side is idle for
/// `idle`. Returns the bytes sent up (client to server, `early` first) and down.
fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
    let _ = client.set_read_timeout(Some(idle));
    let _ = server.set_read_timeout(Some(idle));
    let (c, s) = (&client, &server);
    let (up, down) = std::thread::scope(|scope| {
        let up = scope.spawn(move || {
            let n = copy(&mut early.chain(c), &mut { s });
            let _ = s.shutdown(Shutdown::Write);
            n
        });
        let down = copy(&mut { s }, &mut { c });
        let _ = c.shutdown(Shutdown::Write);
        (up.join().unwrap_or(0), down)
    });
    let _ = server.shutdown(Shutdown::Both);
    let _ = client.shutdown(Shutdown::Both);
    (up, down)
}

/// Like `io::copy`, but a read timeout or error just ends it.
fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
    let mut buf = [0u8; 16 * 1024];
    let mut n = 0u64;
    loop {
        match from.read(&mut buf) {
            Ok(0) | Err(_) => return n,
            Ok(k) => {
                if to.write_all(&buf[..k]).is_err() {
                    return n;
                }
                n += k as u64;
            }
        }
    }
}

#[cfg(test)]
mod tests;