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.is_multicast() || a >= 240; !blocked
148}
149
150fn is_public_v6(ip: Ipv6Addr) -> bool {
151 if let Some(v4) = embedded_v4(ip) {
153 return is_public_v4(v4);
154 }
155 let segments = ip.segments();
156 let first = segments.first().copied().unwrap_or(0);
157 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]) || segments.get(..6) == Some(&[0, 0, 0, 0, 0, 0]); !blocked
167}
168
169fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
172 if let Some(v4) = ip.to_ipv4_mapped() {
173 return Some(v4);
174 }
175 let s = ip.segments();
176 let from_pair = |hi: u16, lo: u16| {
177 let [a, b] = hi.to_be_bytes();
178 let [c, d] = lo.to_be_bytes();
179 Ipv4Addr::new(a, b, c, d)
180 };
181 match s {
182 [0x0064, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from_pair(hi, lo)),
183 [0x2002, hi, lo, ..] => Some(from_pair(hi, lo)),
184 [0, 0, 0, 0, 0, 0, hi, lo] if (hi, lo) != (0, 0) && (hi, lo) != (0, 1) => Some(from_pair(hi, lo)),
185 _ => None,
186 }
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 fn ip(s: &str) -> IpAddr {
194 s.parse().unwrap()
195 }
196
197 #[test]
198 fn classification_table() {
199 let blocked = [
200 "0.0.0.0",
201 "0.1.2.3",
202 "127.0.0.1",
203 "127.255.255.254",
204 "10.0.0.1",
205 "172.16.0.1",
206 "172.31.255.255",
207 "192.168.1.1",
208 "169.254.169.254",
209 "169.254.0.1",
210 "100.64.0.1",
211 "100.127.255.255",
212 "192.0.0.8",
213 "192.0.2.1",
214 "198.51.100.7",
215 "203.0.113.9",
216 "198.18.0.1",
217 "198.19.255.255",
218 "224.0.0.1",
219 "239.255.255.250",
220 "240.0.0.1",
221 "255.255.255.255",
222 "::",
223 "::1",
224 "::ffff:127.0.0.1",
225 "::ffff:10.0.0.1",
226 "::ffff:169.254.169.254",
227 "::127.0.0.1",
228 "64:ff9b::7f00:1",
229 "64:ff9b::a9fe:a9fe",
230 "2002:7f00:1::",
231 "2002:c0a8:101::1",
232 "fc00::1",
233 "fd00::1",
234 "fd00:ec2::254",
235 "fe80::1",
236 "febf::1",
237 "fec0::1",
238 "ff02::1",
239 "2001:db8::1",
240 "100::1",
241 ];
242 for s in blocked {
243 assert!(!is_public(ip(s)), "{s} should be blocked");
244 }
245 let public = [
246 "1.1.1.1",
247 "8.8.8.8",
248 "93.184.216.34",
249 "100.63.255.255",
250 "100.128.0.1",
251 "172.15.255.255",
252 "172.32.0.1",
253 "192.169.0.1",
254 "169.253.0.1",
255 "2606:4700:4700::1111",
256 "2001:4860:4860::8888",
257 "::ffff:8.8.8.8",
258 "64:ff9b::808:808",
259 "2002:808:808::",
260 ];
261 for s in public {
262 assert!(is_public(ip(s)), "{s} should be public");
263 }
264 }
265
266 #[test]
267 fn literal_urls_are_checked() {
268 let p = EgressPolicy::default();
269 let check = |u: &str| p.check_url(&Url::parse(u).unwrap());
270 assert!(check("http://127.0.0.1/").is_err());
271 assert!(check("http://[::1]:8080/").is_err());
272 assert!(check("http://[::ffff:7f00:1]/").is_err());
273 assert!(check("http://2130706433/").is_err());
275 assert!(check("http://0x7f.1/").is_err());
276 assert!(check("http://0177.0.0.1/").is_err());
277 assert!(check("http://169.254.169.254/latest/meta-data").is_err());
278 assert!(check("ftp://example.com/").is_err());
279 assert!(check("file:///etc/passwd").is_err());
280 assert!(check("https://example.com/").is_ok());
281 assert!(check("http://8.8.8.8/").is_ok());
282 let open = EgressPolicy::trusted();
283 assert!(open.check_url(&Url::parse("http://127.0.0.1/").unwrap()).is_ok());
284 }
285
286 #[test]
287 fn host_lists() {
288 let p = EgressPolicy {
289 allowed_hosts: vec!["*.example.com".into(), "api.other.org".into()],
290 denied_hosts: vec!["evil.example.com".into()],
291 ..EgressPolicy::default()
292 };
293 assert!(p.check_host_name("example.com").is_ok());
294 assert!(p.check_host_name("a.b.example.com").is_ok());
295 assert!(p.check_host_name("API.other.org.").is_ok());
296 assert!(p.check_host_name("evil.example.com").is_err());
297 assert!(p.check_host_name("other.org").is_err());
298 assert!(p.check_host_name("notexample.com").is_err());
299 }
300}