use reqwest::Url;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::time::Duration;
fn v4_block_reason(ip: Ipv4Addr) -> Option<&'static str> {
let [a, b, c, _] = ip.octets();
Some(match (a, b, c) {
(0, ..) if ip.is_unspecified() => "unspecified address",
(0, ..) => "\"this network\" address (0.0.0.0/8)",
(127, ..) => "loopback address",
(10, ..) => "private address (10.0.0.0/8)",
(172, 16..=31, _) => "private address (172.16.0.0/12)",
(192, 168, _) => "private address (192.168.0.0/16)",
(169, 254, _) => "link-local address",
(100, 64..=127, _) => "carrier-grade NAT address (100.64.0.0/10)",
(192, 0, 0) => "IETF protocol assignment (192.0.0.0/24)",
(192, 0, 2) | (198, 51, 100) | (203, 0, 113) => "documentation address",
(198, 18..=19, _) => "benchmarking address (198.18.0.0/15)",
(224..=239, ..) => "multicast address",
(240..=255, ..) => "reserved or broadcast address",
_ => return None,
})
}
fn v6_block_reason(ip: Ipv6Addr) -> Option<&'static str> {
if ip.is_unspecified() {
return Some("unspecified address");
}
if ip.is_loopback() {
return Some("loopback address");
}
let s = ip.segments();
if let Some(v4) = ip.to_ipv4_mapped() {
return Some(v4_block_reason(v4).unwrap_or("IPv4-mapped IPv6 address"));
}
Some(match s {
[0, 0, 0, 0, 0, 0, ..] => "IPv4-compatible IPv6 address (::/96)",
[0x64, 0xff9b, 0, 0, 0, 0, ..] => "NAT64 address (64:ff9b::/96)",
[0x64, 0xff9b, 1, ..] => "local-use NAT64 address (64:ff9b:1::/48)",
[0x2002, ..] => "6to4 address (2002::/16)",
[0x2001, 0, ..] => "Teredo address (2001::/32)",
[0x2001, 0xdb8, ..] => "documentation address (2001:db8::/32)",
[0x3fff, hi, ..] if hi < 0x1000 => "documentation address (3fff::/20)",
[first, ..] if first & 0xfe00 == 0xfc00 => "unique local address (fc00::/7)",
[first, ..] if first & 0xffc0 == 0xfe80 => "link-local address (fe80::/10)",
[first, ..] if first & 0xffc0 == 0xfec0 => "site-local address (fec0::/10)",
[first, ..] if first & 0xff00 == 0xff00 => "multicast address",
_ => return None,
})
}
pub fn blocked_reason(ip: IpAddr) -> Option<&'static str> {
match ip {
IpAddr::V4(v4) => v4_block_reason(v4),
IpAddr::V6(v6) => v6_block_reason(v6),
}
}
pub fn check_resolved(host: &str, addrs: &[IpAddr]) -> Result<(), String> {
if addrs.is_empty() {
return Err(format!("`{host}` did not resolve to any address"));
}
for ip in addrs {
if let Some(why) = blocked_reason(*ip) {
return Err(format!(
"blocked: `{host}` resolves to {ip}, a {why}; fetch only reaches public hosts"
));
}
}
Ok(())
}
pub fn check_url_host(url: &Url) -> Result<String, String> {
use url::Host;
match url.host() {
None => Err("blocked: URL has no host".into()),
Some(Host::Ipv4(ip)) => Err(format!(
"blocked: IP literal {ip} is not allowed; use a public host name"
)),
Some(Host::Ipv6(ip)) => Err(format!(
"blocked: IP literal {ip} is not allowed; use a public host name"
)),
Some(Host::Domain(d)) => {
let name = d.trim_end_matches('.').to_ascii_lowercase();
if name == "localhost" || name.ends_with(".localhost") {
Err(format!("blocked: `{d}` is a localhost name"))
} else {
Ok(name)
}
}
}
}
pub async fn resolve_public(
host: &str,
port: u16,
timeout: Duration,
) -> Result<Vec<SocketAddr>, String> {
let lookup = tokio::net::lookup_host((host, port));
let addrs: Vec<SocketAddr> = tokio::time::timeout(timeout, lookup)
.await
.map_err(|_| format!("DNS lookup for `{host}` timed out"))?
.map_err(|e| format!("DNS lookup for `{host}` failed: {e}"))?
.collect();
let ips: Vec<IpAddr> = addrs.iter().map(SocketAddr::ip).collect();
check_resolved(host, &ips)?;
Ok(addrs)
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn loopback_private_linklocal_and_unspecified_are_blocked() {
for s in [
"127.0.0.1",
"127.255.255.254",
"::1",
"10.0.0.1",
"10.255.255.255",
"172.16.0.1",
"172.31.255.255",
"192.168.1.1",
"169.254.169.254",
"fe80::1",
"febf::1",
"0.0.0.0",
"::",
"fc00::1",
"fd12:3456::1",
] {
assert!(blocked_reason(ip(s)).is_some(), "{s} should be blocked");
}
}
#[test]
fn cgnat_documentation_and_translation_ranges_are_blocked() {
for s in [
"100.64.0.1",
"100.127.255.255",
"192.0.2.1",
"198.51.100.7",
"203.0.113.9",
"2001:db8::1",
"64:ff9b::7f00:1",
"64:ff9b::808:808",
"64:ff9b:1::1",
"::ffff:127.0.0.1",
"::ffff:8.8.8.8",
"2002:7f00:1::1",
"ff02::1",
"224.0.0.1",
"255.255.255.255",
] {
assert!(blocked_reason(ip(s)).is_some(), "{s} should be blocked");
}
}
#[test]
fn public_addresses_and_range_edges_pass() {
for s in [
"8.8.8.8",
"1.1.1.1",
"172.15.255.255",
"172.32.0.1",
"100.63.255.255",
"100.128.0.1",
"192.169.0.1",
"198.17.0.1",
"198.20.0.1",
"203.0.114.1",
"2606:4700:4700::1111",
"2a00:1450:4001:81b::200e",
"fe00::1",
] {
assert_eq!(blocked_reason(ip(s)), None, "{s} should be allowed");
}
}
#[test]
fn resolved_set_is_blocked_if_any_answer_is_internal() {
assert!(check_resolved("a.example", &[ip("8.8.8.8"), ip("2606:4700::1")]).is_ok());
let err = check_resolved("a.example", &[ip("8.8.8.8"), ip("10.0.0.5")]).unwrap_err();
assert!(err.contains("10.0.0.5") && err.contains("private"), "{err}");
assert!(check_resolved("a.example", &[]).is_err());
}
#[test]
fn url_hosts_literals_and_localhost_names_are_rejected() {
let host = |u: &str| check_url_host(&Url::parse(u).unwrap());
assert_eq!(host("https://Example.COM./x").unwrap(), "example.com");
for u in [
"http://127.0.0.1/",
"http://8.8.8.8/",
"http://[::1]:8080/",
"http://[::ffff:8.8.8.8]/",
"http://[::ffff:7f00:1]/",
"http://2130706433/",
"http://0x7f.1/",
"http://localhost/",
"http://LOCALHOST:3000/",
"http://localhost./",
"http://foo.localhost/",
"http://a.b.LOCALHOST./",
] {
assert!(host(u).is_err(), "{u} should be rejected");
}
assert!(host("http://notlocalhost.example/").is_ok());
assert!(host("http://localhost.example/").is_ok());
}
}