use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Class {
Private,
Loopback,
Own,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Denial {
pub class: Class,
pub why: &'static str,
}
const V4: &[([u8; 4], u8, &str, Class)] = &[
([0, 0, 0, 0], 8, "\"this network\"", Class::Other),
([10, 0, 0, 0], 8, "private network", Class::Private),
(
[100, 64, 0, 0],
10,
"shared address space (carrier NAT)",
Class::Private,
),
([127, 0, 0, 0], 8, "loopback", Class::Loopback),
(
[169, 254, 0, 0],
16,
"link-local (cloud metadata lives here)",
Class::Other,
),
([172, 16, 0, 0], 12, "private network", Class::Private),
(
[192, 0, 0, 0],
24,
"IETF protocol assignments",
Class::Other,
),
([192, 0, 2, 0], 24, "documentation", Class::Other),
([192, 88, 99, 0], 24, "deprecated 6to4 relay", Class::Other),
([192, 168, 0, 0], 16, "private network", Class::Private),
([198, 18, 0, 0], 15, "benchmarking", Class::Other),
([198, 51, 100, 0], 24, "documentation", Class::Other),
([203, 0, 113, 0], 24, "documentation", Class::Other),
([224, 0, 0, 0], 4, "multicast", Class::Other),
([240, 0, 0, 0], 4, "reserved", Class::Other),
(
[168, 63, 129, 16],
32,
"Azure platform service",
Class::Other,
),
];
const V6: &[([u16; 8], u8, &str, Class)] = &[
([0, 0, 0, 0, 0, 0, 0, 0], 128, "unspecified", Class::Other),
([0, 0, 0, 0, 0, 0, 0, 1], 128, "loopback", Class::Loopback),
(
[0x64, 0xff9b, 0, 0, 0, 0, 0, 0],
96,
"NAT64 (could reach private IPv4)",
Class::Other,
),
(
[0x64, 0xff9b, 1, 0, 0, 0, 0, 0],
48,
"local NAT64",
Class::Other,
),
(
[0x100, 0, 0, 0, 0, 0, 0, 0],
64,
"discard-only",
Class::Other,
),
(
[0x100, 0, 0, 1, 0, 0, 0, 0],
64,
"dummy prefix",
Class::Other,
),
(
[0x2001, 0, 0, 0, 0, 0, 0, 0],
23,
"IETF protocol assignments (Teredo, benchmarking, ...)",
Class::Other,
),
(
[0x2001, 0xdb8, 0, 0, 0, 0, 0, 0],
32,
"documentation",
Class::Other,
),
(
[0x2002, 0, 0, 0, 0, 0, 0, 0],
16,
"6to4 (embeds any IPv4)",
Class::Other,
),
(
[0x3fff, 0, 0, 0, 0, 0, 0, 0],
20,
"documentation",
Class::Other,
),
(
[0x5f00, 0, 0, 0, 0, 0, 0, 0],
16,
"segment routing",
Class::Other,
),
(
[0xfc00, 0, 0, 0, 0, 0, 0, 0],
7,
"unique-local (private network)",
Class::Private,
),
(
[0xfe80, 0, 0, 0, 0, 0, 0, 0],
10,
"link-local",
Class::Other,
),
(
[0xfec0, 0, 0, 0, 0, 0, 0, 0],
10,
"site-local (deprecated)",
Class::Other,
),
([0xff00, 0, 0, 0, 0, 0, 0, 0], 8, "multicast", Class::Other),
];
fn in_v4(ip: Ipv4Addr, net: [u8; 4], len: u8) -> bool {
let mask = u32::MAX.checked_shl(32 - u32::from(len)).unwrap_or(0);
u32::from(ip) & mask == u32::from(Ipv4Addr::from(net)) & mask
}
fn in_v6(ip: Ipv6Addr, net: [u16; 8], len: u8) -> bool {
let mask = u128::MAX.checked_shl(128 - u32::from(len)).unwrap_or(0);
u128::from(ip) & mask == u128::from(Ipv6Addr::from(net)) & mask
}
pub fn denied(ip: IpAddr, own: &[IpAddr]) -> Option<Denial> {
let row = |why, class| Denial { class, why };
if own.contains(&ip) {
return Some(row("an address of this machine", Class::Own));
}
match ip {
IpAddr::V4(v4) => V4
.iter()
.find(|(n, l, ..)| in_v4(v4, *n, *l))
.map(|b| row(b.2, b.3)),
IpAddr::V6(v6) => {
if let Some(v4) = v6.to_ipv4_mapped() {
return denied(IpAddr::V4(v4), own).or(Some(row("IPv4-mapped IPv6", Class::Other)));
}
V6.iter()
.find(|(n, l, ..)| in_v6(v6, *n, *l))
.map(|b| row(b.2, b.3))
}
}
}
pub fn own_addresses() -> Vec<IpAddr> {
let v4 = std::fs::read_to_string("/proc/net/fib_trie").unwrap_or_default();
let v6 = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
let mut out = parse_fib_trie(&v4);
out.extend(parse_if_inet6(&v6));
out.sort();
out.dedup();
out
}
fn parse_fib_trie(text: &str) -> Vec<IpAddr> {
let mut out = Vec::new();
let mut last: Option<Ipv4Addr> = None;
for line in text.lines() {
let t = line.trim_start_matches([' ', '|', '-', '+']).trim();
if let Ok(ip) = t.parse::<Ipv4Addr>() {
last = Some(ip);
} else if t == "/32 host LOCAL"
&& let Some(ip) = last
{
out.push(IpAddr::V4(ip));
}
}
out
}
fn parse_if_inet6(text: &str) -> Vec<IpAddr> {
text.lines()
.filter_map(|l| l.split_whitespace().next())
.filter_map(|hex| {
u128::from_str_radix(hex, 16)
.ok()
.filter(|_| hex.len() == 32)
})
.map(|n| IpAddr::V6(Ipv6Addr::from(n)))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn d(s: &str) -> Option<&'static str> {
denied(s.parse().expect("ip"), &[]).map(|d| d.why)
}
#[test]
fn refusals_have_a_class() {
let class = |s: &str, own: &[IpAddr]| denied(s.parse().expect("ip"), own).map(|d| d.class);
for ip in [
"10.1.2.3",
"172.16.0.1",
"192.168.1.1",
"100.64.0.1",
"fd00::1",
"::ffff:10.0.0.1",
] {
assert_eq!(class(ip, &[]), Some(Class::Private), "{ip}");
}
for ip in ["127.0.0.1", "::1", "::ffff:127.0.0.1"] {
assert_eq!(class(ip, &[]), Some(Class::Loopback), "{ip}");
}
for ip in [
"169.254.169.254",
"fe80::1",
"224.0.0.1",
"::ffff:192.0.2.1",
"64:ff9b::a00:1",
] {
assert_eq!(class(ip, &[]), Some(Class::Other), "{ip}");
}
let me: IpAddr = "203.0.114.7".parse().expect("ip");
assert_eq!(class("203.0.114.7", &[me]), Some(Class::Own));
assert_eq!(class("1.1.1.1", &[]), None);
}
#[test]
fn special_purpose_blocks_are_refused() {
for ip in [
"0.0.0.0",
"0.1.2.3",
"10.1.2.3",
"100.64.0.1",
"100.127.255.255",
"127.0.0.1",
"127.255.0.1",
"169.254.169.254",
"172.16.0.1",
"172.31.255.255",
"192.0.0.9",
"192.0.2.1",
"192.88.99.1",
"192.168.1.1",
"198.18.0.1",
"198.19.255.255",
"198.51.100.1",
"203.0.113.1",
"224.0.0.1",
"239.1.1.1",
"240.0.0.1",
"255.255.255.255",
"168.63.129.16",
"::",
"::1",
"64:ff9b::a00:1",
"64:ff9b:1::1",
"100::1",
"100:0:0:1::1",
"2001::1",
"2001:1::1",
"2001:2::1",
"2001:db8::1",
"2002:c0a8:101::1",
"3fff::1",
"5f00::1",
"fc00::1",
"fd00:ec2::254",
"fe80::1",
"fec0::1",
"ff02::1",
"::ffff:10.0.0.1",
"::ffff:127.0.0.1",
] {
assert!(d(ip).is_some(), "{ip} must be refused");
}
assert_eq!(d("::ffff:8.8.8.8"), Some("IPv4-mapped IPv6"));
}
#[test]
fn public_addresses_pass() {
for ip in [
"1.1.1.1",
"8.8.8.8",
"100.63.255.255",
"100.128.0.0",
"172.15.255.255",
"172.32.0.0",
"192.0.1.1",
"192.169.0.1",
"198.17.255.255",
"198.20.0.0",
"223.255.255.255",
"140.82.112.3",
"2606:4700::6810:84e5",
"2a00:1450::200e",
"2001:4860:4860::8888",
] {
assert_eq!(d(ip), None, "{ip} is public");
}
}
#[test]
fn this_machine_is_refused_too() {
let own: Vec<IpAddr> = vec!["203.0.114.7".parse().expect("ip")];
assert_eq!(
denied(own[0], &own).map(|d| d.why),
Some("an address of this machine")
);
assert_eq!(denied("203.0.114.8".parse().expect("ip"), &own), None);
}
#[test]
fn own_addresses_from_proc() {
let trie = "Main:\n +-- 0.0.0.0/0 3 0 5\n |-- 0.0.0.0\n /0 universe UNICAST\n \
|-- 192.168.139.54\n /32 host LOCAL\n |-- 192.168.139.255\n \
/32 link BROADCAST\n |-- 127.0.0.1\n /32 host LOCAL\n";
assert_eq!(
parse_fib_trie(trie),
[
"192.168.139.54".parse::<IpAddr>().expect("ip"),
"127.0.0.1".parse().expect("ip")
]
);
let inet6 = "00000000000000000000000000000001 01 80 10 80 lo\n\
fe80000000000000021c42fffe0a1b2c 02 40 20 80 eth0\nnot-hex\n";
assert_eq!(
parse_if_inet6(inet6),
[
"::1".parse::<IpAddr>().expect("ip"),
"fe80::21c:42ff:fe0a:1b2c".parse().expect("ip")
]
);
let _ = own_addresses();
}
}