Skip to main content

openmoat_proxy/
decide.rs

1//! Which hosts and addresses the proxy may reach.
2//!
3//! A host is decided exactly as `moat guard` decides a fetch tool's URL: one
4//! `fetch` atom through openmoat-core's [`CompiledPolicy`], so `fetch` and `net`
5//! lists both apply and deny rules come first. The proxy cannot prompt, so an
6//! `review` is refused. Cloud metadata and link-local addresses are refused
7//! whatever the policy says, by name and again after DNS resolution. Private
8//! and CGNAT addresses are refused unless an allow rule names the address.
9//! Every resolved address is also checked against the deny rules, so a deny
10//! naming an address holds for a name that resolves to it.
11
12mod ports;
13
14use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
15
16pub use self::ports::{DEFAULT_PORTS, host_port, port_policy};
17
18use openmoat_core::rule_id::{PROXY_ADDRESS, PROXY_REQUEST};
19use openmoat_core::{
20    Action, AtomicAction, CompiledPolicy, Decision, Defaults, Kind, MapPathResolver, Policy, Taint,
21    Verdict,
22};
23
24/// Metadata services reachable by name on cloud instances.
25const METADATA_NAMES: &[&str] = &["metadata.google.internal", "metadata.goog"];
26const ALIBABA_METADATA: Ipv4Addr = Ipv4Addr::new(100, 100, 100, 200);
27/// Azure's `WireServer`, which serves instance configuration and keys to the VM.
28const AZURE_WIRESERVER: Ipv4Addr = Ipv4Addr::new(168, 63, 129, 16);
29const AWS_METADATA_V6: Ipv6Addr = Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254);
30/// RFC 6052 well-known NAT64 prefix: `64:ff9b::a.b.c.d` reaches `a.b.c.d`.
31const NAT64: [u16; 6] = [0x64, 0xff9b, 0, 0, 0, 0];
32/// RFC 8215 local-use NAT64 prefix `64:ff9b:1::/48`. The operator picks how the
33/// IPv4 address is embedded inside it, so its addresses count as local network.
34const NAT64_LOCAL: [u16; 3] = [0x64, 0xff9b, 1];
35/// RFC 2765 IPv4-translated prefix: `::ffff:0:a.b.c.d` reaches `a.b.c.d`.
36const SIIT: [u16; 6] = [0, 0, 0, 0, 0xffff, 0];
37/// Ranges on the local network (or the carrier's), each with its description.
38const PRIVATE_V4: [(Ipv4Addr, u8, &str); 7] = [
39    (
40        Ipv4Addr::new(10, 0, 0, 0),
41        8,
42        "a private address (10.0.0.0/8)",
43    ),
44    (
45        Ipv4Addr::new(172, 16, 0, 0),
46        12,
47        "a private address (172.16.0.0/12)",
48    ),
49    (
50        Ipv4Addr::new(192, 168, 0, 0),
51        16,
52        "a private address (192.168.0.0/16)",
53    ),
54    (
55        Ipv4Addr::new(100, 64, 0, 0),
56        10,
57        "a shared CGNAT address (100.64.0.0/10)",
58    ),
59    (
60        Ipv4Addr::new(198, 18, 0, 0),
61        15,
62        "a benchmarking address (198.18.0.0/15)",
63    ),
64    (
65        Ipv4Addr::new(192, 0, 0, 0),
66        24,
67        "an IETF protocol address (192.0.0.0/24)",
68    ),
69    // Reserved for future use (RFC 1112 §4, RFC 6890): no public server has
70    // one, while some clouds hand it out inside a private network (GKE uses
71    // it for pod ranges). `255.255.255.255` is broadcast, refused before this.
72    (
73        Ipv4Addr::new(240, 0, 0, 0),
74        4,
75        "a reserved address (240.0.0.0/4)",
76    ),
77];
78
79/// Decide whether `host`, normalised as [`Request::host`](crate::Request::host)
80/// reports it, may be reached. Only an `allow` lets the connection proceed.
81/// The port is not looked at here: [`host_port`] decides both.
82#[must_use]
83pub fn host(policy: &CompiledPolicy<'_>, host: &str) -> Decision {
84    if let Some(refused) = metadata(host) {
85        return refused;
86    }
87    let atom = AtomicAction::Fetch {
88        host: host.to_owned(),
89    };
90    let mut decision = policy.evaluate_atomic(&atom).unwrap_or_else(|| {
91        Decision::single(
92            Verdict::Deny,
93            PROXY_REQUEST,
94            format!("no rule decided {host}"),
95        )
96    });
97    // A deferred host (ADR-025) is refused too: the agent's permission flow never sees
98    // the proxy's connections.
99    if matches!(decision.verdict, Verdict::Review | Verdict::Defer) {
100        decision.verdict = Verdict::Deny;
101        decision
102            .reasons
103            .push("the proxy cannot prompt, so a host the hook would hold for review or leave to the agent is refused".to_owned());
104    }
105    decision
106}
107
108/// Whether `host` is a cloud metadata service's name, or a name under one.
109pub(crate) fn metadata_name(host: &str) -> bool {
110    METADATA_NAMES
111        .iter()
112        .any(|m| host == *m || host.strip_suffix(m).is_some_and(|p| p.ends_with('.')))
113}
114
115/// The refusal of a cloud metadata service's name, whatever the policy says.
116fn metadata(host: &str) -> Option<Decision> {
117    metadata_name(host).then(|| {
118        Decision::single(
119            Verdict::Deny,
120            PROXY_ADDRESS,
121            format!("{host} is a cloud metadata service"),
122        )
123    })
124}
125
126/// The refusal for a request to `host:port` from a session with `taint`, if
127/// any (ADR-027). The core's taint rules decide (POLICY.md §4.1): after the
128/// session read secret material, network to every host but that secret's own
129/// needs review. The proxy cannot prompt, so that review is refused. Untrusted content alone
130/// changes nothing here: its taint protects writes.
131#[must_use]
132pub fn tainted(
133    policy: &CompiledPolicy<'_>,
134    host: &str,
135    port: u16,
136    taint: &Taint,
137) -> Option<Decision> {
138    let authority = if host.contains(':') {
139        format!("[{host}]:{port}")
140    } else {
141        format!("{host}:{port}")
142    };
143    let action = Action::Net {
144        url: format!("https://{authority}/"),
145    };
146    let mut decision = policy.with_taint(
147        Decision::new(Verdict::Allow),
148        &action,
149        &MapPathResolver::default(),
150        taint,
151    );
152    if decision.verdict == Verdict::Allow {
153        return None;
154    }
155    decision.verdict = Verdict::Deny;
156    decision.reasons.push(
157        "the proxy cannot prompt, so a session that read secret material reaches only that \
158         secret's own host until it ends; `openmoat allow` does not answer a secret's taint, \
159         so start a new session"
160            .to_owned(),
161    );
162    Some(decision)
163}
164
165/// Why the proxy never connects to `ip`, if it does not. Checked on every
166/// resolved address, so a name the policy allows cannot be pointed at a local
167/// or metadata service (DNS rebinding).
168#[must_use]
169pub fn forbidden(ip: IpAddr) -> Option<Forbidden> {
170    match ip.to_canonical() {
171        IpAddr::V4(v4) => forbidden_v4(v4),
172        IpAddr::V6(v6) => forbidden_v6(v6),
173    }
174}
175
176/// The classes of address the proxy refuses.
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178#[non_exhaustive]
179pub enum Forbidden {
180    /// This machine (`127.0.0.0/8`, `::1`), including the proxy itself.
181    Loopback,
182    /// Link-local (`169.254.0.0/16`, `fe80::/10`): where cloud metadata lives.
183    LinkLocal,
184    /// A cloud metadata address outside the link-local ranges.
185    Metadata,
186    /// An address of this machine other than loopback (its LAN or public
187    /// address), where services listening on every interface answer. Found
188    /// only once connected ([`connect`](crate::connect)): the connection's
189    /// own end has the same address.
190    ThisMachine,
191    /// Unspecified, broadcast, multicast or `0.0.0.0/8`: never a server.
192    NotUnicast,
193    /// Private, CGNAT, benchmarking, reserved (`240.0.0.0/4`), unique-local
194    /// (`fc00::/7`) or deprecated site-local (`fec0::/10`): reachable
195    /// only when an allow rule names the address ([`named`]). Carries the
196    /// description naming the range.
197    Private(&'static str),
198}
199
200impl Forbidden {
201    /// A short phrase for reasons and the audit log.
202    #[must_use]
203    pub fn describe(self) -> &'static str {
204        match self {
205            Self::Loopback => "a loopback address",
206            Self::LinkLocal => "a link-local address",
207            Self::Metadata => "a cloud metadata address",
208            Self::ThisMachine => "an address of this machine",
209            Self::NotUnicast => "not a unicast address",
210            Self::Private(range) => range,
211        }
212    }
213}
214
215fn forbidden_v4(ip: Ipv4Addr) -> Option<Forbidden> {
216    if ip.is_loopback() {
217        Some(Forbidden::Loopback)
218    } else if ip.is_link_local() {
219        Some(Forbidden::LinkLocal)
220    } else if ip == ALIBABA_METADATA || ip == AZURE_WIRESERVER {
221        Some(Forbidden::Metadata)
222    } else if ip.is_unspecified() || ip.is_broadcast() || ip.is_multicast() || ip.octets()[0] == 0 {
223        Some(Forbidden::NotUnicast)
224    } else {
225        PRIVATE_V4
226            .iter()
227            .find(|(net, len, _)| u32::from(ip) >> (32 - len) == u32::from(*net) >> (32 - len))
228            .map(|(_, _, range)| Forbidden::Private(range))
229    }
230}
231
232fn forbidden_v6(ip: Ipv6Addr) -> Option<Forbidden> {
233    let seg = ip.segments();
234    if ip.is_loopback() {
235        Some(Forbidden::Loopback)
236    } else if ip.is_unspecified() || ip.is_multicast() {
237        Some(Forbidden::NotUnicast)
238    } else if seg[0] & 0xffc0 == 0xfe80 {
239        Some(Forbidden::LinkLocal)
240    } else if ip == AWS_METADATA_V6 {
241        Some(Forbidden::Metadata)
242    } else if let Some(v4) = carried_v4(ip) {
243        forbidden_v4(v4)
244    } else if let Some(why) = tunnelled_v4(ip).find_map(forbidden_v4) {
245        Some(why)
246    } else if seg[..3] == NAT64_LOCAL {
247        // The common /96 layout first, so a metadata or loopback address in it
248        // is named as such; any other layout is local network all the same.
249        let [a, b] = seg[6].to_be_bytes();
250        let [c, d] = seg[7].to_be_bytes();
251        forbidden_v4(Ipv4Addr::new(a, b, c, d)).or(Some(Forbidden::Private(
252            "a local-use NAT64 address (64:ff9b:1::/48)",
253        )))
254    } else if seg[0] & 0xfe00 == 0xfc00 {
255        Some(Forbidden::Private("a unique local address (fc00::/7)"))
256    } else if seg[0] & 0xffc0 == 0xfec0 {
257        // Deprecated (RFC 3879) but still routed inside networks that kept it:
258        // local network all the same, and never a public server.
259        Some(Forbidden::Private(
260            "a deprecated site-local address (fec0::/10)",
261        ))
262    } else {
263        None
264    }
265}
266
267/// The IPv4 address a well-known NAT64 (`64:ff9b::/96`), deprecated
268/// IPv4-compatible (`::/96`) or IPv4-translated (`::ffff:0:0/96`, which a
269/// stateless translator delivers, RFC 6145) address reaches.
270fn carried_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
271    let seg = ip.segments();
272    (seg[..6] == NAT64 || seg[..6] == [0; 6] || seg[..6] == SIIT).then(|| {
273        let [a, b] = seg[6].to_be_bytes();
274        let [c, d] = seg[7].to_be_bytes();
275        Ipv4Addr::new(a, b, c, d)
276    })
277}
278
279/// The IPv4 addresses a 6to4 (`2002::/16`: the address in bits 16..48) or
280/// Teredo (`2001::/32`: the server in bits 32..64, the client inverted in the
281/// last 32 bits) address leads to: a relay or the server delivers it there.
282fn tunnelled_v4(ip: Ipv6Addr) -> impl Iterator<Item = Ipv4Addr> {
283    let o = ip.octets();
284    let six_to_four = (o[..2] == [0x20, 0x02]).then(|| Ipv4Addr::new(o[2], o[3], o[4], o[5]));
285    let teredo = o[..4] == [0x20, 0x01, 0, 0];
286    let client = teredo.then(|| Ipv4Addr::new(!o[12], !o[13], !o[14], !o[15]));
287    let server = teredo.then(|| Ipv4Addr::new(o[4], o[5], o[6], o[7]));
288    [six_to_four, client, server].into_iter().flatten()
289}
290
291/// The part of `policy` that decides a resolved address: its deny rules, and
292/// the allow rules' `net` and `fetch` patterns that name an address: a pattern
293/// starting with a digit or, without a port, containing `:` (a `host:port`
294/// pattern is judged by its host part, so `f*:5432` is a name), not starting
295/// with a glob metacharacter, and made only of what an address's text and a
296/// glob use.
297/// Anything else is left undecided (`review`), which neither opens a
298/// [`Forbidden::Private`] address ([`named`]) nor refuses one ([`denied`]), so
299/// a wildcard such as `*` or `*.example`, or a name such as
300/// `db.internal:5432`, never reaches the local network by DNS. Exclusions are
301/// all kept, and one without a port excludes the address on every port.
302#[must_use]
303pub fn address_policy(policy: &Policy) -> Policy {
304    let allow = policy
305        .allow
306        .iter()
307        .map(|g| {
308            // Every exclusion is kept: it can only narrow what the list names.
309            let keep = |list: &[String]| {
310                let kept: Vec<String> = list
311                    .iter()
312                    .filter(|p| p.starts_with('!') || names_address(p))
313                    .cloned()
314                    .collect();
315                ports::with_ports(&kept, false)
316            };
317            openmoat_core::RuleGroup {
318                id: g.id.clone(),
319                reason: g.reason.clone(),
320                net: keep(g.patterns(Kind::Net)),
321                fetch: keep(g.patterns(Kind::Fetch)),
322                ..Default::default()
323            }
324        })
325        .collect();
326    // Not `deny`: only a deny rule may refuse an address the host check passed.
327    Policy {
328        defaults: Defaults::All(Verdict::Review),
329        deny: policy.deny.clone(),
330        allow,
331        review: Vec::new(),
332        ..policy.clone()
333    }
334}
335
336/// Whether a host pattern names an address (see [`address_policy`]). A
337/// `host:port` pattern ([`port_pattern`](openmoat_core::port_pattern)) is
338/// judged by its host part, so a name made of hex letters with a port
339/// (`f*:5432`, `fac*:5432`) is a name, not an IPv6 glob reaching a unique
340/// local address: only a host part starting with a digit (`10.0.0.*:5432`)
341/// names an address with a port. Without a port, a `:` makes it IPv6 text
342/// (`fd12::*`, `fe80:*`).
343fn names_address(pattern: &str) -> bool {
344    let body = pattern.strip_prefix('!').unwrap_or(pattern);
345    let host = openmoat_core::port_pattern(body).map_or(body, |(host, _)| host);
346    !body.starts_with(['*', '?', '[', '{'])
347        && (host.starts_with(|c: char| c.is_ascii_digit()) || host.contains(':'))
348        && body
349            .chars()
350            .all(|c| c.is_ascii_hexdigit() || ".:*?[]{},-".contains(c))
351}
352
353/// Whether `addresses` (compiled from [`address_policy`]) allows `ip`, matched
354/// in its canonical text form (`::ffff:10.0.0.5` as `10.0.0.5`).
355#[must_use]
356pub fn named(addresses: &CompiledPolicy<'_>, ip: IpAddr) -> bool {
357    let atom = AtomicAction::Fetch {
358        host: ip.to_canonical().to_string(),
359    };
360    addresses
361        .evaluate_atomic(&atom)
362        .is_some_and(|d| d.verdict == Verdict::Allow)
363}
364
365/// Whether `addresses` allows `addr`'s address: [`named`], or, for IPv4, an
366/// allow rule that names it with this port (`10.0.0.5:5432`).
367#[must_use]
368pub fn named_on(addresses: &CompiledPolicy<'_>, addr: SocketAddr) -> bool {
369    if named(addresses, addr.ip()) {
370        return true;
371    }
372    let IpAddr::V4(v4) = addr.ip().to_canonical() else {
373        return false;
374    };
375    let atom = AtomicAction::Fetch {
376        host: format!("{v4}:{}", addr.port()),
377    };
378    addresses
379        .evaluate_atomic(&atom)
380        .is_some_and(|d| d.verdict == Verdict::Allow)
381}
382
383/// The deny rules of `addresses` (compiled from [`address_policy`]) that
384/// match `ip`, if any: a deny naming an address holds for every name that
385/// resolves to it. Matched in canonical text form, and for a NAT64,
386/// IPv4-compatible, IPv4-translated, 6to4 or Teredo address also as the IPv4 addresses it
387/// reaches. Allow rules never widen anything here; an address no deny rule
388/// matches gives `None`.
389#[must_use]
390pub fn denied(addresses: &CompiledPolicy<'_>, ip: IpAddr) -> Option<Decision> {
391    let ip = ip.to_canonical();
392    let carried: Vec<IpAddr> = match ip {
393        IpAddr::V6(v6) => carried_v4(v6)
394            .into_iter()
395            .chain(tunnelled_v4(v6))
396            .map(IpAddr::V4)
397            .collect(),
398        IpAddr::V4(_) => Vec::new(),
399    };
400    std::iter::once(ip).chain(carried).find_map(|ip| {
401        let atom = AtomicAction::Fetch {
402            host: ip.to_string(),
403        };
404        addresses
405            .evaluate_atomic(&atom)
406            .filter(|d| d.verdict == Verdict::Deny)
407    })
408}
409
410#[cfg(test)]
411mod tests;