Skip to main content

openmoat_proxy/
upstream.rs

1//! Resolving and connecting to the destination.
2//!
3//! The proxy resolves names itself and checks every address it gets back
4//! before connecting to one of exactly those addresses, so the check and the
5//! connection cannot disagree (no second lookup an attacker could race).
6
7use std::io;
8use std::net::{IpAddr, SocketAddr, TcpStream, ToSocketAddrs as _};
9use std::time::Duration;
10
11use openmoat_core::rule_id::{PROXY_ADDRESS, PROXY_UPSTREAM};
12use openmoat_core::{CompiledPolicy, Decision, Verdict};
13
14use crate::decide::{self, Forbidden};
15
16/// Name resolution, injectable so tests can map names without a DNS server.
17pub trait Resolve: Send + Sync {
18    /// Every address the DNS name `host` resolves to, with `port` attached.
19    /// IP literals never reach the resolver.
20    fn resolve(&self, host: &str, port: u16) -> io::Result<Vec<SocketAddr>>;
21}
22
23/// The operating system's resolver (`getaddrinfo` and its equivalents).
24#[derive(Debug, Clone, Copy, Default)]
25pub struct SystemResolver;
26
27impl Resolve for SystemResolver {
28    fn resolve(&self, host: &str, port: u16) -> io::Result<Vec<SocketAddr>> {
29        Ok((resolver_name(host).as_str(), port)
30            .to_socket_addrs()?
31            .collect())
32    }
33}
34
35/// The name the system resolver is given for `host` (normalised, without a
36/// trailing dot): absolute, `host.`, so the resolver never tries
37/// `host.<search domain>` first (with `ndots` above the name's dots, as in
38/// Kubernetes, a wildcard in a search domain would answer for the allowed
39/// name). glibc, musl and macOS's resolver read a trailing dot as a fully
40/// qualified name. On Windows the name is passed as it is: its DNS client
41/// already appends no suffix to a name with a dot in it, and how
42/// `getaddrinfo` there treats a trailing dot with the hosts file and other
43/// name services is not documented.
44#[cfg(not(windows))]
45pub(crate) fn resolver_name(host: &str) -> String {
46    format!("{host}.")
47}
48
49/// See the other platforms' `resolver_name`.
50#[cfg(windows)]
51pub(crate) fn resolver_name(host: &str) -> String {
52    host.to_owned()
53}
54
55/// Why no connection was made.
56#[derive(Debug)]
57#[non_exhaustive]
58pub enum Refusal {
59    /// A resolved address the proxy never connects to.
60    Address(SocketAddr, Forbidden),
61    /// A resolved address a policy deny rule matches, with that rule's decision.
62    Denied(SocketAddr, Decision),
63    /// The name did not resolve, or no address accepted the connection.
64    Unreachable(String),
65}
66
67impl Refusal {
68    /// The decision recorded for this refusal.
69    #[must_use]
70    pub fn decision(&self, host: &str) -> Decision {
71        match self {
72            Self::Address(addr, why) => Decision::single(
73                Verdict::Deny,
74                PROXY_ADDRESS,
75                format!("{host} resolves to {}, {}", addr.ip(), why.describe()),
76            ),
77            Self::Denied(addr, denied) => {
78                let rules = denied
79                    .rules
80                    .iter()
81                    .zip(&denied.reasons)
82                    .map(|(rule, reason)| format!("`{rule}` ({reason})"))
83                    .collect::<Vec<_>>()
84                    .join(", ");
85                Decision::single(
86                    Verdict::Deny,
87                    PROXY_ADDRESS,
88                    format!(
89                        "{host} resolves to {}, refused by deny rule {rules}",
90                        addr.ip()
91                    ),
92                )
93            }
94            Self::Unreachable(why) => Decision::single(Verdict::Deny, PROXY_UPSTREAM, why.clone()),
95        }
96    }
97}
98
99/// Resolve `host`, refuse if any address is forbidden or matched by a deny
100/// rule of `addresses` (compiled from [`decide::address_policy`]), then
101/// connect to the first address that answers. A private address passes only
102/// when `addresses` names it, alone or with `port`.
103/// `loopback_ok` lists loopback addresses that may be reached anyway (tests);
104/// nothing exempts link-local or metadata.
105pub fn connect(
106    resolver: &dyn Resolve,
107    host: &str,
108    port: u16,
109    addresses: &CompiledPolicy<'_>,
110    loopback_ok: &[SocketAddr],
111    timeout: Duration,
112) -> Result<TcpStream, Refusal> {
113    let addrs = match host.parse::<IpAddr>() {
114        Ok(ip) => vec![SocketAddr::new(ip, port)],
115        Err(_) => resolver
116            .resolve(host, port)
117            .map_err(|e| Refusal::Unreachable(format!("cannot resolve {host}: {e}")))?,
118    };
119    if addrs.is_empty() {
120        return Err(Refusal::Unreachable(format!("{host} has no addresses")));
121    }
122    // One bad address refuses the name: an allowed name that also points at
123    // a metadata service is an attack, not a fallback.
124    for addr in &addrs {
125        match decide::forbidden(addr.ip()) {
126            Some(Forbidden::Loopback) if loopback_ok.contains(addr) => {}
127            Some(Forbidden::Private(_)) if decide::named_on(addresses, *addr) => {}
128            Some(why) => return Err(Refusal::Address(*addr, why)),
129            None => {}
130        }
131        // The host decision matched only the name; a deny naming one of its
132        // addresses still holds.
133        if let Some(denied) = decide::denied(addresses, addr.ip()) {
134            return Err(Refusal::Denied(*addr, denied));
135        }
136    }
137    let mut last = None;
138    for addr in &addrs {
139        match TcpStream::connect_timeout(addr, timeout) {
140            // A connection to this machine leaves from the address it goes
141            // to (RFC 6724 rule 1, and the local route on IPv4). Nothing has
142            // been sent yet; the stream is dropped, so it closes.
143            Ok(stream) if !loopback_ok.contains(addr) && to_this_machine(&stream, addr.ip()) => {
144                return Err(Refusal::Address(*addr, Forbidden::ThisMachine));
145            }
146            Ok(stream) => return Ok(stream),
147            Err(e) => last = Some(e),
148        }
149    }
150    Err(Refusal::Unreachable(match last {
151        Some(e) => format!("cannot connect to {host}:{port}: {e}"),
152        None => format!("cannot connect to {host}:{port}"),
153    }))
154}
155
156/// Whether `stream`, connected to `peer`, reached this machine: its own end
157/// has the same address. A stream whose own address cannot be read counts.
158fn to_this_machine(stream: &TcpStream, peer: IpAddr) -> bool {
159    stream
160        .local_addr()
161        .map_or(true, |own| own.ip().to_canonical() == peer.to_canonical())
162}