use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use url::{Host, Url};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct EgressPolicy {
pub allow_private: bool,
pub allowed_hosts: Vec<String>,
pub denied_hosts: Vec<String>,
pub allowed_schemes: Vec<String>,
pub max_redirects: usize,
pub max_response_bytes: usize,
pub connect_timeout: Duration,
pub read_timeout: Duration,
pub total_timeout: Duration,
pub proxy: Option<String>,
}
impl Default for EgressPolicy {
fn default() -> Self {
Self {
allow_private: false,
allowed_hosts: Vec::new(),
denied_hosts: Vec::new(),
allowed_schemes: vec!["http".to_owned(), "https".to_owned()],
max_redirects: 5,
max_response_bytes: 10 * 1024 * 1024,
connect_timeout: Duration::from_secs(10),
read_timeout: Duration::from_secs(60),
total_timeout: Duration::from_secs(300),
proxy: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EgressError {
#[error("invalid URL `{0}`")]
InvalidUrl(String),
#[error("URL scheme `{0}` is not allowed")]
Scheme(String),
#[error("URL has no host")]
NoHost,
#[error("host `{0}` is not allowed by the egress policy")]
HostDenied(String),
#[error("address {0} is not a public address (private/loopback/link-local/reserved)")]
BlockedAddress(IpAddr),
}
impl EgressPolicy {
pub fn trusted() -> Self {
Self { allow_private: true, ..Self::default() }
}
pub fn check_url(&self, url: &Url) -> Result<(), EgressError> {
let scheme = url.scheme();
if !self.allowed_schemes.iter().any(|s| s.eq_ignore_ascii_case(scheme)) {
return Err(EgressError::Scheme(scheme.to_owned()));
}
let host = url.host().ok_or(EgressError::NoHost)?;
let host_text = match &host {
Host::Domain(d) => d.trim_end_matches('.').to_ascii_lowercase(),
Host::Ipv4(ip) => ip.to_string(),
Host::Ipv6(ip) => ip.to_string(),
};
self.check_host_name(&host_text)?;
match host {
Host::Ipv4(ip) => self.check_ip(IpAddr::V4(ip)),
Host::Ipv6(ip) => self.check_ip(IpAddr::V6(ip)),
Host::Domain(_) => Ok(()),
}
}
pub fn check_host_name(&self, host: &str) -> Result<(), EgressError> {
let host = host.trim_end_matches('.').to_ascii_lowercase();
if self.denied_hosts.iter().any(|p| host_matches(p, &host)) {
return Err(EgressError::HostDenied(host));
}
if !self.allowed_hosts.is_empty() && !self.allowed_hosts.iter().any(|p| host_matches(p, &host)) {
return Err(EgressError::HostDenied(host));
}
Ok(())
}
pub fn check_ip(&self, ip: IpAddr) -> Result<(), EgressError> {
if self.allow_private || is_public(ip) { Ok(()) } else { Err(EgressError::BlockedAddress(ip)) }
}
}
fn host_matches(pattern: &str, host: &str) -> bool {
let pattern = pattern.trim().trim_end_matches('.').to_ascii_lowercase();
if let Some(suffix) = pattern.strip_prefix("*.").or_else(|| pattern.strip_prefix('.')) {
host == suffix || host.ends_with(&format!(".{suffix}"))
} else {
host == pattern
}
}
pub fn is_public(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => is_public_v4(v4),
IpAddr::V6(v6) => is_public_v6(v6),
}
}
fn is_public_v4(ip: Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
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
}
fn is_public_v6(ip: Ipv6Addr) -> bool {
if let Some(v4) = embedded_v4(ip) {
return is_public_v4(v4);
}
let segments = ip.segments();
let first = segments.first().copied().unwrap_or(0);
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
}
fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
if let Some(v4) = ip.to_ipv4_mapped() {
return Some(v4);
}
let s = ip.segments();
let from_pair = |hi: u16, lo: u16| {
let [a, b] = hi.to_be_bytes();
let [c, d] = lo.to_be_bytes();
Ipv4Addr::new(a, b, c, d)
};
match s {
[0x0064, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from_pair(hi, lo)),
[0, 0, 0, 0, 0xffff, 0, hi, lo] => Some(from_pair(hi, lo)),
[0x2002, hi, lo, ..] => Some(from_pair(hi, lo)),
[0, 0, 0, 0, 0, 0, hi, lo] if (hi, lo) != (0, 0) && (hi, lo) != (0, 1) => Some(from_pair(hi, lo)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn classification_table() {
let blocked = [
"0.0.0.0",
"0.1.2.3",
"127.0.0.1",
"127.255.255.254",
"10.0.0.1",
"172.16.0.1",
"172.31.255.255",
"192.168.1.1",
"169.254.169.254",
"169.254.0.1",
"100.64.0.1",
"100.127.255.255",
"192.0.0.8",
"192.0.2.1",
"198.51.100.7",
"203.0.113.9",
"198.18.0.1",
"198.19.255.255",
"224.0.0.1",
"239.255.255.250",
"240.0.0.1",
"255.255.255.255",
"::",
"::1",
"::ffff:127.0.0.1",
"::ffff:0:7f00:1",
"::ffff:0:a9fe:a9fe",
"64:ff9b:1::a00:1",
"2001:0:4136:e378:8000:63bf:3fff:fdd2",
"168.63.129.16",
"::ffff:10.0.0.1",
"::ffff:169.254.169.254",
"::127.0.0.1",
"64:ff9b::7f00:1",
"64:ff9b::a9fe:a9fe",
"2002:7f00:1::",
"2002:c0a8:101::1",
"fc00::1",
"fd00::1",
"fd00:ec2::254",
"fe80::1",
"febf::1",
"fec0::1",
"ff02::1",
"2001:db8::1",
"100::1",
];
for s in blocked {
assert!(!is_public(ip(s)), "{s} should be blocked");
}
let public = [
"1.1.1.1",
"8.8.8.8",
"93.184.216.34",
"100.63.255.255",
"100.128.0.1",
"172.15.255.255",
"172.32.0.1",
"192.169.0.1",
"169.253.0.1",
"2606:4700:4700::1111",
"2001:4860:4860::8888",
"::ffff:8.8.8.8",
"64:ff9b::808:808",
"2002:808:808::",
];
for s in public {
assert!(is_public(ip(s)), "{s} should be public");
}
}
#[test]
fn literal_urls_are_checked() {
let p = EgressPolicy::default();
let check = |u: &str| p.check_url(&Url::parse(u).unwrap());
assert!(check("http://127.0.0.1/").is_err());
assert!(check("http://[::1]:8080/").is_err());
assert!(check("http://[::ffff:7f00:1]/").is_err());
assert!(check("http://2130706433/").is_err());
assert!(check("http://0x7f.1/").is_err());
assert!(check("http://0177.0.0.1/").is_err());
assert!(check("http://169.254.169.254/latest/meta-data").is_err());
assert!(check("ftp://example.com/").is_err());
assert!(check("file:///etc/passwd").is_err());
assert!(check("https://example.com/").is_ok());
assert!(check("http://8.8.8.8/").is_ok());
let open = EgressPolicy::trusted();
assert!(open.check_url(&Url::parse("http://127.0.0.1/").unwrap()).is_ok());
}
#[test]
fn host_lists() {
let p = EgressPolicy {
allowed_hosts: vec!["*.example.com".into(), "api.other.org".into()],
denied_hosts: vec!["evil.example.com".into()],
..EgressPolicy::default()
};
assert!(p.check_host_name("example.com").is_ok());
assert!(p.check_host_name("a.b.example.com").is_ok());
assert!(p.check_host_name("API.other.org.").is_ok());
assert!(p.check_host_name("evil.example.com").is_err());
assert!(p.check_host_name("other.org").is_err());
assert!(p.check_host_name("notexample.com").is_err());
}
}