1use std::collections::BTreeSet;
7use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
8
9use url::Url;
10
11use crate::error::PolicyError;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum IpClass {
17 Public,
19 Loopback,
21 Private,
23 LinkLocal,
25 Documentation,
27 Multicast,
29 Reserved,
31}
32
33impl IpClass {
34 #[must_use]
36 pub fn is_public(self) -> bool {
37 matches!(self, Self::Public)
38 }
39}
40
41#[must_use]
43pub fn classify_ip(ip: IpAddr) -> IpClass {
44 match ip {
45 IpAddr::V4(v4) => classify_v4(v4),
46 IpAddr::V6(v6) => classify_v6(v6),
47 }
48}
49
50fn classify_v4(ip: Ipv4Addr) -> IpClass {
51 let [a, b, _, _] = ip.octets();
52 if ip.is_unspecified() || a >= 240 {
53 return IpClass::Reserved;
54 }
55 if ip.is_loopback() {
56 return IpClass::Loopback;
57 }
58 if ip.is_private() || (a == 100 && (64..128).contains(&b)) {
59 return IpClass::Private;
60 }
61 if ip.is_link_local() {
62 return IpClass::LinkLocal;
63 }
64 if ip.is_multicast() || ip.is_broadcast() {
65 return IpClass::Multicast;
66 }
67 if a == 0 {
68 return IpClass::Reserved;
69 }
70 if a == 198 && (b == 18 || b == 19) {
72 return IpClass::Documentation;
73 }
74 let third = ip.octets()[2];
75 if a == 192 && b == 0 && (third == 0 || third == 2)
76 || (a == 198 && b == 51 && third == 100)
77 || (a == 203 && b == 0 && third == 113)
78 {
79 return IpClass::Documentation;
80 }
81 IpClass::Public
82}
83
84fn classify_v6(ip: Ipv6Addr) -> IpClass {
85 if let Some(v4) = ip.to_ipv4_mapped() {
86 return classify_v4(v4);
87 }
88 if let Some(v4) = embedded_transition_v4(ip) {
89 return classify_v4(v4);
90 }
91 if ip.is_unspecified() {
92 return IpClass::Reserved;
93 }
94 if ip.is_loopback() {
95 return IpClass::Loopback;
96 }
97 if ip.segments()[..6].iter().all(|s| *s == 0) {
100 let octets = ip.octets();
101 return classify_v4(Ipv4Addr::new(
102 octets[12], octets[13], octets[14], octets[15],
103 ));
104 }
105 if is_unique_local(ip) || is_site_local(ip) || is_nat64_local_use(ip) {
106 return IpClass::Private;
107 }
108 if is_link_local_v6(ip) {
109 return IpClass::LinkLocal;
110 }
111 if ip.is_multicast() {
112 return IpClass::Multicast;
113 }
114 if is_documentation_v6(ip) || is_teredo(ip) || is_discard_v6(ip) {
115 return IpClass::Documentation;
116 }
117 IpClass::Public
118}
119
120fn embedded_transition_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
121 let segments = ip.segments();
122 if segments[0] == 0x2002 {
124 return Some(Ipv4Addr::new(
125 (segments[1] >> 8) as u8,
126 segments[1] as u8,
127 (segments[2] >> 8) as u8,
128 segments[2] as u8,
129 ));
130 }
131 if segments[0] == 0x0064 && segments[1] == 0xff9b && segments[2..6].iter().all(|s| *s == 0) {
133 let octets = ip.octets();
134 return Some(Ipv4Addr::new(
135 octets[12], octets[13], octets[14], octets[15],
136 ));
137 }
138 None
139}
140
141fn is_unique_local(ip: Ipv6Addr) -> bool {
142 (ip.segments()[0] & 0xfe00) == 0xfc00
143}
144
145fn is_site_local(ip: Ipv6Addr) -> bool {
147 (ip.segments()[0] & 0xffc0) == 0xfec0
148}
149
150fn is_nat64_local_use(ip: Ipv6Addr) -> bool {
152 let [first, second, third, ..] = ip.segments();
153 first == 0x0064 && second == 0xff9b && third == 0x0001
154}
155
156fn is_link_local_v6(ip: Ipv6Addr) -> bool {
157 (ip.segments()[0] & 0xffc0) == 0xfe80
158}
159
160fn is_documentation_v6(ip: Ipv6Addr) -> bool {
161 let [first, second, ..] = ip.segments();
162 first == 0x2001 && (second == 0x0db8 || second == 0x0002)
163}
164
165fn is_teredo(ip: Ipv6Addr) -> bool {
166 ip.segments()[0] == 0x2001 && ip.segments()[1] == 0
167}
168
169fn is_discard_v6(ip: Ipv6Addr) -> bool {
170 ip.segments()[0] == 0x0100 && ip.segments()[1] == 0
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct DestinationPolicy {
176 exceptions: BTreeSet<String>,
181}
182
183impl Default for DestinationPolicy {
184 fn default() -> Self {
185 Self::public_https()
186 }
187}
188
189impl DestinationPolicy {
190 #[must_use]
192 pub fn public_https() -> Self {
193 Self {
194 exceptions: BTreeSet::new(),
195 }
196 }
197
198 pub fn allow_origin(origin: &Url) -> Result<Self, PolicyError> {
207 let mut policy = Self::public_https();
208 policy.exceptions.insert(origin_key(origin)?);
209 Ok(policy)
210 }
211
212 pub fn and_allow(mut self, origin: &Url) -> Result<Self, PolicyError> {
218 self.exceptions.insert(origin_key(origin)?);
219 Ok(self)
220 }
221
222 #[must_use]
229 pub fn allows_origin(&self, url: &Url) -> bool {
230 origin_key(url)
231 .map(|key| self.exceptions.contains(&key))
232 .unwrap_or(false)
233 }
234
235 pub fn check_url(&self, url: &Url) -> Result<(), PolicyError> {
243 if url.username() != "" || url.password().is_some() {
244 return Err(PolicyError::Userinfo);
245 }
246 let host = url.host_str().ok_or(PolicyError::Host)?;
247 match url.scheme() {
248 "https" => {}
249 "http" if self.allows_origin(url) => {}
250 other => return Err(PolicyError::Scheme(other.to_owned())),
251 }
252 if !self.allows_origin(url) && blocked_hostname(host) {
253 return Err(PolicyError::Hostname(host.to_owned()));
254 }
255 if let Some(ip) = url.host().and_then(|host| match host {
256 url::Host::Ipv4(ip) => Some(IpAddr::V4(ip)),
257 url::Host::Ipv6(ip) => Some(IpAddr::V6(ip)),
258 url::Host::Domain(_) => None,
259 }) {
260 self.allows_resolved_ip(url, ip)?;
261 }
262 Ok(())
263 }
264
265 pub fn allows_resolved_ip(&self, url: &Url, ip: IpAddr) -> Result<(), PolicyError> {
271 let class = classify_ip(ip);
272 if class.is_public() || self.allows_origin(url) {
273 Ok(())
274 } else {
275 Err(PolicyError::Destination(format!("{ip} ({class:?})")))
276 }
277 }
278}
279
280pub fn origin_key(url: &Url) -> Result<String, PolicyError> {
286 let host = url.host_str().ok_or(PolicyError::Host)?;
287 let port = url
288 .port_or_known_default()
289 .ok_or(PolicyError::Scheme(url.scheme().into()))?;
290 if host.contains(':') {
291 Ok(format!("{}://[{host}]:{port}", url.scheme()))
292 } else {
293 Ok(format!("{}://{host}:{port}", url.scheme()))
294 }
295}
296
297fn blocked_hostname(host: &str) -> bool {
298 let host = host.trim_end_matches('.').to_ascii_lowercase();
299 host == "localhost"
300 || host.ends_with(".localhost")
301 || host.ends_with(".local")
302 || host == "metadata.google.internal"
303 || host == "metadata.google.com"
304}
305
306pub fn parse_api_base(text: &str) -> Result<Url, PolicyError> {
313 if text.chars().any(|c| c.is_whitespace()) {
314 return Err(PolicyError::QueryOrFragment);
315 }
316 let url = Url::parse(text).map_err(|_| PolicyError::Host)?;
317 if url.username() != "" || url.password().is_some() {
318 return Err(PolicyError::Userinfo);
319 }
320 if url.query().is_some() || url.fragment().is_some() {
321 return Err(PolicyError::QueryOrFragment);
322 }
323 if !matches!(url.scheme(), "https" | "http") {
324 return Err(PolicyError::Scheme(url.scheme().to_owned()));
325 }
326 if url.host_str().is_none() {
327 return Err(PolicyError::Host);
328 }
329 let path = url.path();
330 if path.len() > 1 && path.ends_with('/') {
331 return Err(PolicyError::TrailingSlash);
332 }
333 if text.ends_with('/') {
334 return Err(PolicyError::TrailingSlash);
335 }
336 Ok(url)
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[test]
344 fn blocks_metadata_and_loopback_by_default() {
345 let policy = DestinationPolicy::public_https();
346 let metadata = Url::parse("https://169.254.169.254/latest").unwrap();
347 assert!(policy.check_url(&metadata).is_err());
348 let loopback = Url::parse("https://127.0.0.1/").unwrap();
349 assert!(policy.check_url(&loopback).is_err());
350 let http = Url::parse("http://example.com/.well-known/tea").unwrap();
351 assert!(policy.check_url(&http).is_err());
352 let ok = Url::parse("https://api.example.com/tea").unwrap();
353 assert!(policy.check_url(&ok).is_ok());
354 }
355
356 #[test]
357 fn exception_is_scoped_to_one_origin() {
358 let allowed = Url::parse("http://127.0.0.1:8080/tea").unwrap();
359 let policy = DestinationPolicy::allow_origin(&allowed).unwrap();
360 assert!(policy.check_url(&allowed).is_ok());
361 let other_port = Url::parse("http://127.0.0.1:9/").unwrap();
362 assert!(policy.check_url(&other_port).is_err());
363 let metadata = Url::parse("http://169.254.169.254/").unwrap();
364 assert!(policy.check_url(&metadata).is_err());
365 }
366
367 #[test]
368 fn classifies_embedded_private_addresses() {
369 let mapped: IpAddr = "0:0:0:0:0:ffff:127.0.0.1".parse().unwrap();
370 assert_eq!(classify_ip(mapped), IpClass::Loopback);
371 let nat64: IpAddr = "64:ff9b::a00:1".parse().unwrap();
372 assert_eq!(classify_ip(nat64), IpClass::Private);
373 assert_eq!(classify_ip("0.1.2.3".parse().unwrap()), IpClass::Reserved);
374 assert_eq!(
375 classify_ip("198.18.0.1".parse().unwrap()),
376 IpClass::Documentation
377 );
378 }
379
380 #[test]
381 fn deprecated_ipv6_forms_are_not_public() {
382 assert_eq!(
384 classify_ip("::127.0.0.1".parse().unwrap()),
385 IpClass::Loopback
386 );
387 assert_eq!(classify_ip("::10.0.0.1".parse().unwrap()), IpClass::Private);
388 assert_eq!(
389 classify_ip("::169.254.169.254".parse().unwrap()),
390 IpClass::LinkLocal
391 );
392 assert_eq!(classify_ip("fec0::1".parse().unwrap()), IpClass::Private);
394 assert_eq!(
395 classify_ip("64:ff9b:1::1".parse().unwrap()),
396 IpClass::Private
397 );
398 assert_eq!(classify_ip("::1".parse().unwrap()), IpClass::Loopback);
400 assert_eq!(classify_ip("::".parse().unwrap()), IpClass::Reserved);
401 assert_eq!(classify_ip("fe80::1".parse().unwrap()), IpClass::LinkLocal);
402 assert_eq!(
403 classify_ip("2606:4700::1".parse().unwrap()),
404 IpClass::Public
405 );
406 let policy = DestinationPolicy::public_https();
407 for url in [
408 "https://[::127.0.0.1]/",
409 "https://[fec0::1]/",
410 "https://[::ffff:127.0.0.1]/",
411 ] {
412 assert!(
413 policy.check_url(&Url::parse(url).unwrap()).is_err(),
414 "{url}"
415 );
416 }
417 }
418
419 #[test]
420 fn exception_is_scheme_host_and_port() {
421 let allowed = Url::parse("http://allowed.test:8080/tea").unwrap();
422 let policy = DestinationPolicy::allow_origin(&allowed).unwrap();
423 let private: IpAddr = "10.1.2.3".parse().unwrap();
424 let v6: IpAddr = "fd00::1".parse().unwrap();
425 assert!(policy.allows_resolved_ip(&allowed, private).is_ok());
426 assert!(policy
427 .allows_resolved_ip(
428 &Url::parse("http://allowed.test:8080/other").unwrap(),
429 private
430 )
431 .is_ok());
432 assert!(policy
433 .allows_resolved_ip(&Url::parse("https://allowed.test:8080/").unwrap(), private)
434 .is_err());
435 assert!(policy
436 .allows_resolved_ip(&Url::parse("http://allowed.test:8443/").unwrap(), private)
437 .is_err());
438 assert!(policy
439 .allows_resolved_ip(&Url::parse("http://other.test:8080/").unwrap(), private)
440 .is_err());
441 assert!(policy.allows_resolved_ip(&allowed, v6).is_ok());
442 assert!(policy
443 .allows_resolved_ip(&Url::parse("http://other.test:8080/").unwrap(), v6)
444 .is_err());
445
446 let https = Url::parse("https://example.test/tea").unwrap();
447 let explicit = Url::parse("https://example.test:443/tea").unwrap();
448 let policy = DestinationPolicy::allow_origin(&https).unwrap();
449 assert!(policy.allows_origin(&explicit));
450 assert_eq!(origin_key(&https).unwrap(), origin_key(&explicit).unwrap());
451 let v6_origin = Url::parse("http://[::1]:8080/").unwrap();
452 let v6_policy = DestinationPolicy::allow_origin(&v6_origin).unwrap();
453 assert!(v6_policy.check_url(&v6_origin).is_ok());
454 assert!(v6_policy
455 .check_url(&Url::parse("http://[::1]:8081/").unwrap())
456 .is_err());
457 }
458}