1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
11
12use openmoat_core::{AtomicAction, CompiledPolicy, Decision, Defaults, Kind, Policy, Verdict};
13
14pub const RULE_ADDRESS: &str = "proxy-address";
16pub const RULE_SNI: &str = "proxy-sni";
18pub const RULE_REQUEST: &str = "proxy-request";
20pub const RULE_UPSTREAM: &str = "proxy-upstream";
22pub const RULE_AUDIT: &str = "proxy-audit";
24
25const METADATA_NAMES: &[&str] = &["metadata.google.internal", "metadata.goog"];
27const ALIBABA_METADATA: Ipv4Addr = Ipv4Addr::new(100, 100, 100, 200);
28const AWS_METADATA_V6: Ipv6Addr = Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254);
29const NAT64: [u16; 6] = [0x64, 0xff9b, 0, 0, 0, 0];
31const PRIVATE_V4: [(Ipv4Addr, u8, &str); 5] = [
33 (
34 Ipv4Addr::new(10, 0, 0, 0),
35 8,
36 "a private address (10.0.0.0/8)",
37 ),
38 (
39 Ipv4Addr::new(172, 16, 0, 0),
40 12,
41 "a private address (172.16.0.0/12)",
42 ),
43 (
44 Ipv4Addr::new(192, 168, 0, 0),
45 16,
46 "a private address (192.168.0.0/16)",
47 ),
48 (
49 Ipv4Addr::new(100, 64, 0, 0),
50 10,
51 "a shared CGNAT address (100.64.0.0/10)",
52 ),
53 (
54 Ipv4Addr::new(198, 18, 0, 0),
55 15,
56 "a benchmarking address (198.18.0.0/15)",
57 ),
58];
59
60#[must_use]
63pub fn host(policy: &CompiledPolicy<'_>, host: &str) -> Decision {
64 if METADATA_NAMES
65 .iter()
66 .any(|m| host == *m || host.strip_suffix(m).is_some_and(|p| p.ends_with('.')))
67 {
68 return Decision::single(
69 Verdict::Deny,
70 RULE_ADDRESS,
71 format!("{host} is a cloud metadata service"),
72 );
73 }
74 let atom = AtomicAction::Fetch {
75 host: host.to_owned(),
76 };
77 let mut decision = policy.evaluate_atomic(&atom).unwrap_or_else(|| {
78 Decision::single(
79 Verdict::Deny,
80 RULE_REQUEST,
81 format!("no rule decided {host}"),
82 )
83 });
84 if decision.verdict == Verdict::Ask {
85 decision.verdict = Verdict::Deny;
86 decision
87 .reasons
88 .push("the proxy cannot ask, so a host that would ask is refused".to_owned());
89 }
90 decision
91}
92
93#[must_use]
97pub fn forbidden(ip: IpAddr) -> Option<Forbidden> {
98 match ip.to_canonical() {
99 IpAddr::V4(v4) => forbidden_v4(v4),
100 IpAddr::V6(v6) => forbidden_v6(v6),
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Forbidden {
107 Loopback,
109 LinkLocal,
111 Metadata,
113 NotUnicast,
115 Private(&'static str),
119}
120
121impl Forbidden {
122 #[must_use]
124 pub fn describe(self) -> &'static str {
125 match self {
126 Self::Loopback => "a loopback address",
127 Self::LinkLocal => "a link-local address",
128 Self::Metadata => "a cloud metadata address",
129 Self::NotUnicast => "not a unicast address",
130 Self::Private(range) => range,
131 }
132 }
133}
134
135fn forbidden_v4(ip: Ipv4Addr) -> Option<Forbidden> {
136 if ip.is_loopback() {
137 Some(Forbidden::Loopback)
138 } else if ip.is_link_local() {
139 Some(Forbidden::LinkLocal)
140 } else if ip == ALIBABA_METADATA {
141 Some(Forbidden::Metadata)
142 } else if ip.is_unspecified() || ip.is_broadcast() || ip.is_multicast() || ip.octets()[0] == 0 {
143 Some(Forbidden::NotUnicast)
144 } else {
145 PRIVATE_V4
146 .iter()
147 .find(|(net, len, _)| u32::from(ip) >> (32 - len) == u32::from(*net) >> (32 - len))
148 .map(|(_, _, range)| Forbidden::Private(range))
149 }
150}
151
152fn forbidden_v6(ip: Ipv6Addr) -> Option<Forbidden> {
153 let seg = ip.segments();
154 if ip.is_loopback() {
155 Some(Forbidden::Loopback)
156 } else if ip.is_unspecified() || ip.is_multicast() {
157 Some(Forbidden::NotUnicast)
158 } else if seg[0] & 0xffc0 == 0xfe80 {
159 Some(Forbidden::LinkLocal)
160 } else if ip == AWS_METADATA_V6 {
161 Some(Forbidden::Metadata)
162 } else if seg[..6] == NAT64 || seg[..6] == [0; 6] {
163 let [a, b] = seg[6].to_be_bytes();
165 let [c, d] = seg[7].to_be_bytes();
166 forbidden_v4(Ipv4Addr::new(a, b, c, d))
167 } else if seg[0] & 0xfe00 == 0xfc00 {
168 Some(Forbidden::Private("a unique local address (fc00::/7)"))
169 } else {
170 None
171 }
172}
173
174#[must_use]
180pub fn address_policy(policy: &Policy) -> Policy {
181 let allow = policy
182 .allow
183 .iter()
184 .map(|g| {
185 let keep = |list: &[String]| {
186 list.iter()
187 .filter(|p| names_address(p))
188 .cloned()
189 .collect::<Vec<_>>()
190 };
191 openmoat_core::RuleGroup {
192 id: g.id.clone(),
193 reason: g.reason.clone(),
194 net: keep(g.patterns(Kind::Net)),
195 fetch: keep(g.patterns(Kind::Fetch)),
196 ..Default::default()
197 }
198 })
199 .collect();
200 Policy {
201 defaults: Defaults::All(Verdict::Deny),
202 deny: policy.deny.clone(),
203 allow,
204 ask: Vec::new(),
205 ..policy.clone()
206 }
207}
208
209fn names_address(pattern: &str) -> bool {
211 !pattern.starts_with(['*', '?', '[', '{'])
212 && (pattern.starts_with(|c: char| c.is_ascii_digit()) || pattern.contains(':'))
213}
214
215#[must_use]
218pub fn named(addresses: &CompiledPolicy<'_>, ip: IpAddr) -> bool {
219 let atom = AtomicAction::Fetch {
220 host: ip.to_canonical().to_string(),
221 };
222 addresses
223 .evaluate_atomic(&atom)
224 .is_some_and(|d| d.verdict == Verdict::Allow)
225}
226
227#[cfg(test)]
228mod tests;