Files
imeai-aKode/akode-rs/web-tools/src/net.rs

238 lines
8.0 KiB
Rust

//! Address classification and DNS resolution used for SSRF protection.
use std::future::Future;
use std::io;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::net::Ipv6Addr;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
/// Future returned by [`HostResolver::resolve`].
pub type ResolveFuture<'a> = Pin<Box<dyn Future<Output = io::Result<Vec<SocketAddr>>> + Send + 'a>>;
/// Resolves a host name to socket addresses. The fetcher resolves names
/// itself, vets every address, and then connects only to the vetted ones.
/// Injectable so tests can simulate arbitrary DNS answers.
pub trait HostResolver: Send + Sync {
fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a>;
}
/// Resolver backed by the operating system (`getaddrinfo` via tokio).
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemResolver;
impl HostResolver for SystemResolver {
fn resolve<'a>(&'a self, host: &'a str, port: u16) -> ResolveFuture<'a> {
Box::pin(async move { Ok(tokio::net::lookup_host((host, port)).await?.collect()) })
}
}
/// IPv4 ranges that must never be reached by the fetcher.
const BLOCKED_V4: &[([u8; 4], u32)] = &[
([0, 0, 0, 0], 8), // "this network", incl. 0.0.0.0
([10, 0, 0, 0], 8), // private
([100, 64, 0, 0], 10), // CGNAT
([127, 0, 0, 0], 8), // loopback
([169, 254, 0, 0], 16), // link-local, incl. cloud metadata 169.254.169.254
([172, 16, 0, 0], 12), // private
([192, 0, 0, 0], 24), // IETF protocol assignments
([192, 0, 2, 0], 24), // TEST-NET-1
([192, 88, 99, 0], 24), // 6to4 relay anycast
([192, 168, 0, 0], 16), // private
([198, 18, 0, 0], 15), // benchmarking
([198, 51, 100, 0], 24), // TEST-NET-2
([203, 0, 113, 0], 24), // TEST-NET-3
([224, 0, 0, 0], 4), // multicast
([240, 0, 0, 0], 4), // reserved, incl. broadcast 255.255.255.255
];
fn in_v4_net(ip: Ipv4Addr, net: [u8; 4], prefix: u32) -> bool {
let mask = if prefix == 0 {
0
} else {
u32::MAX << (32 - prefix)
};
(u32::from(ip) & mask) == (u32::from(Ipv4Addr::from(net)) & mask)
}
fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
BLOCKED_V4
.iter()
.any(|(net, prefix)| in_v4_net(ip, *net, *prefix))
}
fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
let s = ip.segments();
// IPv4-mapped (::ffff:a.b.c.d): judge the embedded IPv4 address.
if let Some(v4) = ip.to_ipv4_mapped() {
return is_blocked_ipv4(v4);
}
// NAT64 well-known prefix 64:ff9b::/96: judge the embedded IPv4 address.
if s[..6] == [0x64, 0xff9b, 0, 0, 0, 0] {
let low = u128::from(ip) as u32;
return is_blocked_ipv4(Ipv4Addr::from(low));
}
// 6to4 2002::/16 embeds an IPv4 address in bits 16..48.
if s[0] == 0x2002 {
let v4 = Ipv4Addr::new((s[1] >> 8) as u8, s[1] as u8, (s[2] >> 8) as u8, s[2] as u8);
return is_blocked_ipv4(v4);
}
// Only global unicast 2000::/3 is reachable. This rules out ::, ::1,
// IPv4-compatible ::a.b.c.d, IPv4-translated, 64:ff9b:1::/48, 100::/64,
// fc00::/7 (ULA), fe80::/10 (link-local), fec0::/10 and ff00::/8.
if s[0] & 0xe000 != 0x2000 {
return true;
}
// 2001::/23 IETF protocol assignments (Teredo, benchmarking, ORCHID, ...).
if s[0] == 0x2001 && s[1] < 0x0200 {
return true;
}
// 2001:db8::/32 and 3fff::/20 documentation.
if s[0] == 0x2001 && s[1] == 0x0db8 {
return true;
}
s[0] == 0x3fff && s[1] & 0xf000 == 0
}
/// Returns true when `ip` is loopback, private, link-local, CGNAT,
/// unspecified, multicast, broadcast, documentation/benchmark or otherwise
/// reserved, including IPv4-mapped, NAT64 and 6to4 forms of those.
pub fn is_blocked_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(v4) => is_blocked_ipv4(v4),
IpAddr::V6(v6) => is_blocked_ipv6(v6),
}
}
/// An address is acceptable if it is public, or if it is exactly one of the
/// explicitly allowlisted socket addresses (same IP and same port).
pub(crate) fn is_addr_allowed(addr: SocketAddr, allowlist: &[SocketAddr]) -> bool {
allowlist.contains(&addr) || !is_blocked_ip(addr.ip())
}
/// `localhost` and `*.localhost` always mean loopback (RFC 6761); they are
/// answered locally instead of trusting DNS.
pub(crate) fn is_localhost_name(host: &str) -> bool {
let host = host.trim_end_matches('.').to_ascii_lowercase();
host == "localhost" || host.ends_with(".localhost")
}
/// reqwest resolver that only ever returns the addresses vetted for the
/// current hop, so a second DNS lookup (DNS rebinding) cannot change the
/// destination and the system resolver is never consulted.
pub(crate) struct PinnedResolver {
host: String,
addrs: Vec<SocketAddr>,
}
impl PinnedResolver {
pub(crate) fn new(host: String, addrs: Vec<SocketAddr>) -> Arc<Self> {
Arc::new(Self { host, addrs })
}
}
impl reqwest::dns::Resolve for PinnedResolver {
fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
let result: Result<reqwest::dns::Addrs, Box<dyn std::error::Error + Send + Sync>> =
if name.as_str().eq_ignore_ascii_case(&self.host) && !self.addrs.is_empty() {
Ok(Box::new(self.addrs.clone().into_iter()))
} else {
Err(format!("host `{}` was not vetted for this request", name.as_str()).into())
};
Box::pin(async move { result })
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn classifies_addresses() {
let blocked = [
"0.0.0.0",
"10.1.2.3",
"100.64.0.1",
"100.127.255.254",
"127.0.0.1",
"127.255.255.255",
"169.254.169.254",
"172.16.0.1",
"172.31.255.255",
"192.0.0.8",
"192.0.2.1",
"192.168.1.1",
"198.18.0.1",
"198.51.100.7",
"203.0.113.9",
"224.0.0.1",
"239.255.255.250",
"240.0.0.1",
"255.255.255.255",
"::",
"::1",
"::127.0.0.1",
"::ffff:127.0.0.1",
"::ffff:10.0.0.1",
"::ffff:169.254.169.254",
"64:ff9b::7f00:1",
"64:ff9b::a9fe:a9fe",
"64:ff9b:1::1",
"100::1",
"2001::1",
"2001:db8::1",
"2002:7f00:1::1",
"2002:c0a8:101::1",
"3fff::1",
"fc00::1",
"fd12:3456::1",
"fe80::1",
"fec0::1",
"ff02::1",
];
for ip in blocked {
let parsed: IpAddr = ip.parse().unwrap();
assert_eq!(is_blocked_ip(parsed), true, "{ip} should be blocked");
}
let allowed = [
"1.1.1.1",
"8.8.8.8",
"93.184.216.34",
"100.63.255.255",
"100.128.0.0",
"172.15.255.255",
"172.32.0.0",
"::ffff:8.8.8.8",
"64:ff9b::808:808",
"2002:808:808::1",
"2606:4700:4700::1111",
"2a00:1450:4001::200e",
];
for ip in allowed {
let parsed: IpAddr = ip.parse().unwrap();
assert_eq!(is_blocked_ip(parsed), false, "{ip} should be allowed");
}
}
#[test]
fn allowlist_is_exact_socket_address() {
let allowed: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let list = [allowed];
assert!(is_addr_allowed(allowed, &list));
assert!(!is_addr_allowed("127.0.0.1:8081".parse().unwrap(), &list));
assert!(!is_addr_allowed("127.0.0.2:8080".parse().unwrap(), &list));
assert!(is_addr_allowed("8.8.8.8:443".parse().unwrap(), &[]));
}
#[test]
fn localhost_names() {
assert!(is_localhost_name("localhost"));
assert!(is_localhost_name("LOCALHOST."));
assert!(is_localhost_name("foo.localhost"));
assert!(!is_localhost_name("localhost.example.com"));
}
}