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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! The user's own proxy, which the cant's proxy chains through after its own checks: an HTTP
//! proxy (`CONNECT`, optionally with Basic credentials) or a SOCKS5 proxy (RFC 1928, optionally
//! with a user name and password, RFC 1929), and the user's `NO_PROXY`, whose hosts are dialled
//! directly instead. Credentials never appear in `Debug`, `Display`, log lines or errors.

use std::fmt;
use std::io::{Read, Write};
use std::net::{IpAddr, TcpStream, ToSocketAddrs};
use std::time::Duration;

use crate::request::{self, Connect};

/// How to talk to the upstream proxy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// `http://`: `CONNECT host:port`.
    Http,
    /// `socks5://` or `socks5h://`: both send the host *name* (address type 3), so the SOCKS
    /// server resolves it, as `socks5h` means. A name is never resolved here and sent as an
    /// address: that would bypass the upstream's own name rules.
    Socks5,
}

/// A user name and password for the upstream. `Debug` shows the user only.
#[derive(Clone, PartialEq, Eq)]
pub struct Auth {
    pub user: String,
    pub pass: String,
}

impl fmt::Debug for Auth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Auth")
            .field("user", &self.user)
            .field("pass", &"<redacted>")
            .finish()
    }
}

/// An upstream proxy to chain through (the user's own `HTTPS_PROXY` or `ALL_PROXY`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream {
    pub kind: Kind,
    pub host: String,
    pub port: u16,
    pub auth: Option<Auth>,
}

/// The URL without its credentials: `scheme://host:port`.
impl fmt::Display for Upstream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let scheme = match self.kind {
            Kind::Http => "http",
            Kind::Socks5 => "socks5h",
        };
        if self.host.contains(':') {
            write!(f, "{scheme}://[{}]:{}", self.host, self.port)
        } else {
            write!(f, "{scheme}://{}:{}", self.host, self.port)
        }
    }
}

/// `url` with any password replaced by `***`, for messages about a proxy URL.
pub fn redact(url: &str) -> String {
    let (scheme, rest) = match url.split_once("://") {
        Some((s, r)) => (format!("{s}://"), r),
        None => (String::new(), url),
    };
    let authority_end = rest.find('/').unwrap_or(rest.len());
    match rest[..authority_end].rfind('@') {
        Some(at) => {
            let user = rest[..at].split(':').next().unwrap_or("");
            format!("{scheme}{user}:***{}", &rest[at..])
        }
        None => url.to_string(),
    }
}

impl Upstream {
    /// `http://[user:pass@]host:port` (the scheme may be left out), or
    /// `socks5://[user:pass@]host[:port]` / `socks5h://...` (port 1080 by default). User name
    /// and password are percent-decoded. No path; `https://` proxies aren't supported.
    pub fn parse(url: &str) -> Result<Upstream, String> {
        let shown = redact(url);
        let (kind, rest) = if let Some(r) = url.strip_prefix("http://") {
            (Kind::Http, r)
        } else if let Some(r) = url
            .strip_prefix("socks5h://")
            .or_else(|| url.strip_prefix("socks5://"))
        {
            (Kind::Socks5, r)
        } else if url.contains("://") {
            return Err(format!(
                "upstream `{shown}` must be an http://, socks5:// or socks5h:// proxy"
            ));
        } else {
            (Kind::Http, url)
        };
        let rest = rest.strip_suffix('/').unwrap_or(rest);
        if rest.contains('/') {
            return Err(format!("upstream `{shown}` must be scheme://host:port"));
        }
        let (auth, hostport) = match rest.rsplit_once('@') {
            Some((userinfo, hp)) => (Some(auth(userinfo, kind, &shown)?), hp),
            None => (None, rest),
        };
        let (host, port) = split_host_port(hostport, kind, &shown)?;
        Ok(Upstream {
            kind,
            host,
            port,
            auth,
        })
    }

    /// Connects to the upstream and asks it for a tunnel to `c`. The stream is ready for the
    /// client's bytes; errors are an HTTP status and a reason for the log.
    pub(crate) fn open(&self, c: &Connect, timeout: Duration) -> Result<TcpStream, (u16, String)> {
        let addrs = (self.host.as_str(), self.port)
            .to_socket_addrs()
            .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
        let mut s = addrs
            .into_iter()
            .find_map(|a| TcpStream::connect_timeout(&a, timeout).ok())
            .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
        let _ = s.set_read_timeout(Some(timeout));
        match self.kind {
            Kind::Http => self.http_connect(&mut s, c)?,
            Kind::Socks5 => self.socks5_connect(&mut s, c).map_err(|why| (502, why))?,
        }
        let _ = s.set_read_timeout(None);
        Ok(s)
    }

    fn http_connect(&self, s: &mut TcpStream, c: &Connect) -> Result<(), (u16, String)> {
        let target = format!("{}:{}", c.host, c.port);
        let login = self
            .auth
            .as_ref()
            .map(|a| {
                format!(
                    "Proxy-Authorization: Basic {}\r\n",
                    base64(format!("{}:{}", a.user, a.pass).as_bytes())
                )
            })
            .unwrap_or_default();
        // A failed write shows as the missing answer read next.
        let _ = s.write_all(
            format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{login}\r\n").as_bytes(),
        );
        let (head, rest) =
            request::read_head(s, 8192).map_err(|r| (502, format!("upstream: {}", r.reason)))?;
        let status = std::str::from_utf8(&head)
            .ok()
            .and_then(|h| h.split(' ').nth(1))
            .unwrap_or("");
        match status {
            "200" if rest.is_empty() => Ok(()),
            "407" => Err((
                502,
                format!(
                    "upstream answered 407 (proxy login {})",
                    if self.auth.is_some() {
                        "refused"
                    } else {
                        "required: put user:password@ in the proxy URL"
                    }
                ),
            )),
            _ => Err((502, format!("upstream answered {status}"))),
        }
    }

    fn socks5_connect(&self, s: &mut TcpStream, c: &Connect) -> Result<(), String> {
        let method = if self.auth.is_some() { 2 } else { 0 };
        let closed = |e: std::io::Error| format!("the SOCKS proxy closed the connection ({e})");
        let _ = s.write_all(&[5, 1, method]);
        let mut choice = [0u8; 2];
        s.read_exact(&mut choice).map_err(closed)?;
        if choice[0] != 5 {
            return Err("upstream isn't a SOCKS5 proxy".into());
        }
        if choice[1] != method {
            return Err(format!(
                "the SOCKS proxy wants another login method ({})",
                if self.auth.is_some() {
                    "it was given a user name and password"
                } else {
                    "put user:password@ in the proxy URL"
                }
            ));
        }
        if let Some(a) = &self.auth {
            let len = |s: &str| {
                u8::try_from(s.len()).map_err(|_| {
                    "SOCKS5 user names and passwords are at most 255 bytes".to_string()
                })
            };
            let mut m = vec![1, len(&a.user)?];
            m.extend_from_slice(a.user.as_bytes());
            m.push(len(&a.pass)?);
            m.extend_from_slice(a.pass.as_bytes());
            let _ = s.write_all(&m);
            let mut status = [0u8; 2];
            s.read_exact(&mut status).map_err(closed)?;
            if status[1] != 0 {
                return Err("the SOCKS proxy refused the user name and password".into());
            }
        }
        let mut req = vec![5, 1, 0];
        match c.ip {
            Some(IpAddr::V4(ip)) => {
                req.push(1);
                req.extend_from_slice(&ip.octets());
            }
            Some(IpAddr::V6(ip)) => {
                req.push(4);
                req.extend_from_slice(&ip.octets());
            }
            None => {
                // Canonical names are at most 253 bytes.
                let n = u8::try_from(c.host.len()).map_err(|_| "name too long for SOCKS5")?;
                req.push(3);
                req.push(n);
                req.extend_from_slice(c.host.as_bytes());
            }
        }
        req.extend_from_slice(&c.port.to_be_bytes());
        let _ = s.write_all(&req);
        // The reply, read exactly: anything after it belongs to the tunnel.
        let mut head = [0u8; 4];
        s.read_exact(&mut head).map_err(closed)?;
        if head[0] != 5 {
            return Err("upstream isn't a SOCKS5 proxy".into());
        }
        if head[1] != 0 {
            return Err(format!("the SOCKS proxy refused: {}", socks_reply(head[1])));
        }
        let addr_len = match head[3] {
            1 => 4,
            4 => 16,
            3 => {
                let mut n = [0u8; 1];
                s.read_exact(&mut n).map_err(closed)?;
                usize::from(n[0])
            }
            t => {
                return Err(format!(
                    "the SOCKS proxy answered an unknown address type {t}"
                ));
            }
        };
        let mut rest = vec![0u8; addr_len + 2];
        s.read_exact(&mut rest).map_err(closed)?;
        Ok(())
    }
}

/// RFC 1928 §6 reply codes.
fn socks_reply(code: u8) -> String {
    match code {
        1 => "general failure".into(),
        2 => "connection not allowed by ruleset".into(),
        3 => "network unreachable".into(),
        4 => "host unreachable".into(),
        5 => "connection refused".into(),
        6 => "TTL expired".into(),
        7 => "command not supported".into(),
        8 => "address type not supported".into(),
        n => format!("error {n}"),
    }
}

fn auth(userinfo: &str, kind: Kind, shown: &str) -> Result<Auth, String> {
    let (user, pass) = userinfo.split_once(':').unwrap_or((userinfo, ""));
    let decode =
        |s: &str| percent_decode(s).ok_or_else(|| format!("upstream `{shown}` has a bad %-escape"));
    let (user, pass) = (decode(user)?, decode(pass)?);
    if user.is_empty() {
        return Err(format!("upstream `{shown}` has an empty user name"));
    }
    if kind == Kind::Socks5 && (user.len() > 255 || pass.len() > 255) {
        return Err(format!(
            "upstream `{shown}`: SOCKS5 user names and passwords are at most 255 bytes"
        ));
    }
    Ok(Auth { user, pass })
}

fn split_host_port(hp: &str, kind: Kind, shown: &str) -> Result<(String, u16), String> {
    let (host, port) = if let Some(v6) = hp.strip_prefix('[') {
        let (h, after) = v6
            .split_once(']')
            .ok_or_else(|| format!("upstream `{shown}` has a bad [address]"))?;
        (h, after.strip_prefix(':'))
    } else {
        match hp.rsplit_once(':') {
            Some((h, p)) => (h, Some(p)),
            None => (hp, None),
        }
    };
    if host.is_empty() {
        return Err(format!("upstream `{shown}` has no host"));
    }
    let port = match (port, kind) {
        (Some(p), _) => p
            .parse::<u16>()
            .ok()
            .filter(|p| *p > 0)
            .ok_or_else(|| format!("upstream `{shown}` has a bad port"))?,
        (None, Kind::Socks5) => 1080,
        (None, Kind::Http) => return Err(format!("upstream `{shown}` has no port")),
    };
    Ok((host.to_string(), port))
}

/// `%XX` escapes to bytes; `None` for a bad escape or a result that isn't UTF-8.
fn percent_decode(s: &str) -> Option<String> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
            out.push(u8::from_str_radix(hex, 16).ok()?);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8(out).ok()
}

/// Standard base64 with padding (RFC 4648 §4), for `Proxy-Authorization: Basic`.
fn base64(data: &[u8]) -> String {
    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
    for chunk in data.chunks(3) {
        let n = chunk
            .iter()
            .enumerate()
            .fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(char::from(A[((n >> (18 - 6 * i)) & 63) as usize]));
            } else {
                out.push('=');
            }
        }
    }
    out
}

/// The user's `NO_PROXY`: targets matching it are dialled directly (with every check), not
/// through the upstream. Matching follows Go's `golang.org/x/net/http/httpproxy` (which curl
/// shares in the essentials): `*` matches everything; `name` matches the name and the names
/// under it, `.name` only those under it; an IP matches that address, `a.b.c.d/n` a range (a
/// name target is never resolved to match an IP entry); `:port` limits an entry to that port.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NoProxy {
    all: bool,
    entries: Vec<NoProxyEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Pattern {
    /// Matches the name and below (`sub` false), or only below (`sub` true).
    Name {
        name: String,
        sub: bool,
    },
    Net {
        ip: IpAddr,
        bits: u8,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct NoProxyEntry {
    pattern: Pattern,
    port: Option<u16>,
}

impl NoProxy {
    /// Parses a `NO_PROXY` value; entries it can't read are skipped (as curl and Go do).
    pub fn parse(list: &str) -> NoProxy {
        let mut out = NoProxy::default();
        for raw in list.split(',').map(str::trim).filter(|e| !e.is_empty()) {
            if raw == "*" {
                out.all = true;
                continue;
            }
            if let Some(e) = entry(&raw.to_ascii_lowercase()) {
                out.entries.push(e);
            }
        }
        out
    }

    /// Whether nothing is listed.
    pub fn is_empty(&self) -> bool {
        !self.all && self.entries.is_empty()
    }

    /// Whether `c` goes directly.
    pub(crate) fn matches(&self, c: &Connect) -> bool {
        self.all
            || self.entries.iter().any(|e| {
                e.port.is_none_or(|p| p == c.port)
                    && match (&e.pattern, c.ip) {
                        (Pattern::Name { name, sub }, None) => {
                            c.host.ends_with(&format!(".{name}")) || (!sub && c.host == *name)
                        }
                        (Pattern::Net { ip, bits }, Some(t)) => in_net(t, *ip, *bits),
                        _ => false,
                    }
            })
    }
}

/// One entry: `name`, `.name`, `*.name`, `ip`, `[v6]`, `ip/bits`, each with an optional
/// `:port` (not for a bare IPv6 address, whose colons are its own).
fn entry(raw: &str) -> Option<NoProxyEntry> {
    if let Some((net, bits)) = raw.split_once('/') {
        let ip: IpAddr = net.parse().ok()?;
        let max = if ip.is_ipv4() { 32 } else { 128 };
        let bits: u8 = bits.parse().ok().filter(|b| *b <= max)?;
        return Some(NoProxyEntry {
            pattern: Pattern::Net { ip, bits },
            port: None,
        });
    }
    if let Ok(ip) = raw.parse::<IpAddr>() {
        return Some(NoProxyEntry {
            pattern: Pattern::Net {
                ip,
                bits: if ip.is_ipv4() { 32 } else { 128 },
            },
            port: None,
        });
    }
    let (host, port) = if let Some(v6) = raw.strip_prefix('[') {
        let (h, after) = v6.split_once(']')?;
        let port = match after {
            "" => None,
            _ => Some(after.strip_prefix(':')?.parse().ok()?),
        };
        let ip: IpAddr = h.parse().ok()?;
        return Some(NoProxyEntry {
            pattern: Pattern::Net { ip, bits: 128 },
            port,
        });
    } else {
        match raw.rsplit_once(':') {
            Some((h, p)) => (h, Some(p.parse::<u16>().ok()?)),
            None => (raw, None),
        }
    };
    if let Ok(ip) = host.parse::<IpAddr>() {
        return Some(NoProxyEntry {
            pattern: Pattern::Net {
                ip,
                bits: if ip.is_ipv4() { 32 } else { 128 },
            },
            port,
        });
    }
    let (name, sub) = match host.strip_prefix("*.").or_else(|| host.strip_prefix('.')) {
        Some(n) => (n, true),
        None => (host, false),
    };
    (!name.is_empty()).then(|| NoProxyEntry {
        pattern: Pattern::Name {
            name: name.to_string(),
            sub,
        },
        port,
    })
}

fn in_net(target: IpAddr, net: IpAddr, bits: u8) -> bool {
    match (target, net) {
        (IpAddr::V4(t), IpAddr::V4(n)) => {
            let mask = u32::MAX.checked_shl(32 - u32::from(bits)).unwrap_or(0);
            u32::from(t) & mask == u32::from(n) & mask
        }
        (IpAddr::V6(t), IpAddr::V6(n)) => {
            let mask = u128::MAX.checked_shl(128 - u32::from(bits)).unwrap_or(0);
            u128::from(t) & mask == u128::from(n) & mask
        }
        _ => false,
    }
}

#[cfg(test)]
mod tests;