1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
4use std::time::Duration;
5
6use url::{Host, Url};
7
8#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct EgressPolicy {
11 pub allow_private: bool,
14 pub allowed_hosts: Vec<String>,
17 pub denied_hosts: Vec<String>,
19 pub allowed_schemes: Vec<String>,
21 pub max_redirects: usize,
23 pub max_response_bytes: usize,
25 pub connect_timeout: Duration,
26 pub read_timeout: Duration,
28 pub total_timeout: Duration,
30 pub proxy: Option<String>,
32}
33
34impl Default for EgressPolicy {
35 fn default() -> Self {
36 Self {
37 allow_private: false,
38 allowed_hosts: Vec::new(),
39 denied_hosts: Vec::new(),
40 allowed_schemes: vec!["http".to_owned(), "https".to_owned()],
41 max_redirects: 5,
42 max_response_bytes: 10 * 1024 * 1024,
43 connect_timeout: Duration::from_secs(10),
44 read_timeout: Duration::from_secs(60),
45 total_timeout: Duration::from_secs(300),
46 proxy: None,
47 }
48 }
49}
50
51#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
53#[non_exhaustive]
54pub enum EgressError {
55 #[error("invalid URL `{0}`")]
56 InvalidUrl(String),
57 #[error("URL scheme `{0}` is not allowed")]
58 Scheme(String),
59 #[error("URL has no host")]
60 NoHost,
61 #[error("host `{0}` is not allowed by the egress policy")]
62 HostDenied(String),
63 #[error("address {0} is not a public address (private/loopback/link-local/reserved)")]
64 BlockedAddress(IpAddr),
65}
66
67impl EgressPolicy {
68 pub fn trusted() -> Self {
71 Self { allow_private: true, ..Self::default() }
72 }
73
74 pub fn check_url(&self, url: &Url) -> Result<(), EgressError> {
76 let scheme = url.scheme();
77 if !self.allowed_schemes.iter().any(|s| s.eq_ignore_ascii_case(scheme)) {
78 return Err(EgressError::Scheme(scheme.to_owned()));
79 }
80 let host = url.host().ok_or(EgressError::NoHost)?;
81 let host_text = match &host {
82 Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(),
83 Host::Ipv4(ip) => ip.to_string(),
84 Host::Ipv6(ip) => ip.to_string(),
85 };
86 self.check_host_name(&host_text)?;
87 match host {
88 Host::Ipv4(ip) => self.check_ip(IpAddr::V4(ip)),
89 Host::Ipv6(ip) => self.check_ip(IpAddr::V6(ip)),
90 Host::Domain(_) => Ok(()),
92 }
93 }
94
95 pub fn check_host_name(&self, host: &str) -> Result<(), EgressError> {
97 let host = host.trim_end_matches('.').to_ascii_lowercase();
98 if self.denied_hosts.iter().any(|p| host_matches(p, &host)) {
99 return Err(EgressError::HostDenied(host));
100 }
101 if !self.allowed_hosts.is_empty() && !self.allowed_hosts.iter().any(|p| host_matches(p, &host)) {
102 return Err(EgressError::HostDenied(host));
103 }
104 Ok(())
105 }
106
107 pub fn check_ip(&self, ip: IpAddr) -> Result<(), EgressError> {
109 if self.allow_private || is_public(ip) { Ok(()) } else { Err(EgressError::BlockedAddress(ip)) }
110 }
111}
112
113fn host_matches(pattern: &str, host: &str) -> bool {
115 let pattern = pattern.trim().trim_end_matches('.').to_ascii_lowercase();
116 if let Some(suffix) = pattern.strip_prefix("*.").or_else(|| pattern.strip_prefix('.')) {
117 host == suffix || host.ends_with(&format!(".{suffix}"))
118 } else {
119 host == pattern
120 }
121}
122
123pub fn is_public(ip: IpAddr) -> bool {
125 match ip {
126 IpAddr::V4(v4) => is_public_v4(v4),
127 IpAddr::V6(v6) => is_public_v6(v6),
128 }
129}
130
131fn is_public_v4(ip: Ipv4Addr) -> bool {
132 let [a, b, c, _] = ip.octets();
133 let blocked = ip.is_unspecified() || a == 0 || ip.is_loopback() || ip.is_private() || ip.is_link_local() || (a == 100 && (64..=127).contains(&b)) || (a == 192 && b == 0 && c == 0) || (a == 192 && b == 0 && c == 2) || (a == 198 && b == 51 && c == 100) || (a == 203 && b == 0 && c == 113) || (a == 198 && (b == 18 || b == 19)) || (a == 192 && b == 88 && c == 99) || ip == Ipv4Addr::new(168, 63, 129, 16) || ip.is_multicast() || a >= 240; !blocked
149}
150
151fn is_public_v6(ip: Ipv6Addr) -> bool {
152 if let Some(v4) = embedded_v4(ip) {
154 return is_public_v4(v4);
155 }
156 let segments = ip.segments();
157 let first = segments.first().copied().unwrap_or(0);
158 let blocked = ip.is_unspecified() || ip.is_loopback() || ip.is_multicast() || (first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80 || (first & 0xffc0) == 0xfec0 || first == 0x2001 && segments.get(1) == Some(&0x0db8) || first == 0x0100 && segments.get(1..4) == Some(&[0, 0, 0]) || first == 0x0064 && segments.get(1..3) == Some(&[0xff9b, 0x0001]) || first == 0x2001 && segments.get(1) == Some(&0) || segments.get(..6) == Some(&[0, 0, 0, 0, 0, 0]); !blocked
170}
171
172fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
176 if let Some(v4) = ip.to_ipv4_mapped() {
177 return Some(v4);
178 }
179 let s = ip.segments();
180 let from_pair = |hi: u16, lo: u16| {
181 let [a, b] = hi.to_be_bytes();
182 let [c, d] = lo.to_be_bytes();
183 Ipv4Addr::new(a, b, c, d)
184 };
185 match s {
186 [0x0064, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from_pair(hi, lo)),
187 [0, 0, 0, 0, 0xffff, 0, hi, lo] => Some(from_pair(hi, lo)),
188 [0x2002, hi, lo, ..] => Some(from_pair(hi, lo)),
189 [0, 0, 0, 0, 0, 0, hi, lo] if (hi, lo) != (0, 0) && (hi, lo) != (0, 1) => Some(from_pair(hi, lo)),
190 _ => None,
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 fn ip(s: &str) -> IpAddr {
199 s.parse().unwrap()
200 }
201
202 #[test]
203 fn classification_table() {
204 let blocked = [
205 "0.0.0.0",
206 "0.1.2.3",
207 "127.0.0.1",
208 "127.255.255.254",
209 "10.0.0.1",
210 "172.16.0.1",
211 "172.31.255.255",
212 "192.168.1.1",
213 "169.254.169.254",
214 "169.254.0.1",
215 "100.64.0.1",
216 "100.127.255.255",
217 "192.0.0.8",
218 "192.0.2.1",
219 "198.51.100.7",
220 "203.0.113.9",
221 "198.18.0.1",
222 "198.19.255.255",
223 "224.0.0.1",
224 "239.255.255.250",
225 "240.0.0.1",
226 "255.255.255.255",
227 "::",
228 "::1",
229 "::ffff:127.0.0.1",
230 "::ffff:0:7f00:1",
231 "::ffff:0:a9fe:a9fe",
232 "64:ff9b:1::a00:1",
233 "2001:0:4136:e378:8000:63bf:3fff:fdd2",
234 "168.63.129.16",
235 "::ffff:10.0.0.1",
236 "::ffff:169.254.169.254",
237 "::127.0.0.1",
238 "64:ff9b::7f00:1",
239 "64:ff9b::a9fe:a9fe",
240 "2002:7f00:1::",
241 "2002:c0a8:101::1",
242 "fc00::1",
243 "fd00::1",
244 "fd00:ec2::254",
245 "fe80::1",
246 "febf::1",
247 "fec0::1",
248 "ff02::1",
249 "2001:db8::1",
250 "100::1",
251 ];
252 for s in blocked {
253 assert!(!is_public(ip(s)), "{s} should be blocked");
254 }
255 let public = [
256 "1.1.1.1",
257 "8.8.8.8",
258 "93.184.216.34",
259 "100.63.255.255",
260 "100.128.0.1",
261 "172.15.255.255",
262 "172.32.0.1",
263 "192.169.0.1",
264 "169.253.0.1",
265 "2606:4700:4700::1111",
266 "2001:4860:4860::8888",
267 "::ffff:8.8.8.8",
268 "64:ff9b::808:808",
269 "2002:808:808::",
270 ];
271 for s in public {
272 assert!(is_public(ip(s)), "{s} should be public");
273 }
274 }
275
276 #[test]
277 fn literal_urls_are_checked() {
278 let p = EgressPolicy::default();
279 let check = |u: &str| p.check_url(&Url::parse(u).unwrap());
280 assert!(check("http://127.0.0.1/").is_err());
281 assert!(check("http://[::1]:8080/").is_err());
282 assert!(check("http://[::ffff:7f00:1]/").is_err());
283 assert!(check("http://2130706433/").is_err());
285 assert!(check("http://0x7f.1/").is_err());
286 assert!(check("http://0177.0.0.1/").is_err());
287 assert!(check("http://169.254.169.254/latest/meta-data").is_err());
288 assert!(check("ftp://example.com/").is_err());
289 assert!(check("file:///etc/passwd").is_err());
290 assert!(check("https://example.com/").is_ok());
291 assert!(check("http://8.8.8.8/").is_ok());
292 let open = EgressPolicy::trusted();
293 assert!(open.check_url(&Url::parse("http://127.0.0.1/").unwrap()).is_ok());
294 }
295
296 #[test]
297 fn host_lists() {
298 let p = EgressPolicy {
299 allowed_hosts: vec!["*.example.com".into(), "api.other.org".into()],
300 denied_hosts: vec!["evil.example.com".into()],
301 ..EgressPolicy::default()
302 };
303 assert!(p.check_host_name("example.com").is_ok());
304 assert!(p.check_host_name("a.b.example.com").is_ok());
305 assert!(p.check_host_name("API.other.org.").is_ok());
306 assert!(p.check_host_name("evil.example.com").is_err());
307 assert!(p.check_host_name("other.org").is_err());
308 assert!(p.check_host_name("notexample.com").is_err());
309 }
310}