1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Class {
15 Private,
17 Loopback,
19 Own,
21 Other,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub struct Denial {
28 pub class: Class,
29 pub why: &'static str,
30}
31
32const V4: &[([u8; 4], u8, &str, Class)] = &[
33 ([0, 0, 0, 0], 8, "\"this network\"", Class::Other),
34 ([10, 0, 0, 0], 8, "private network", Class::Private),
35 (
36 [100, 64, 0, 0],
37 10,
38 "shared address space (carrier NAT)",
39 Class::Private,
40 ),
41 ([127, 0, 0, 0], 8, "loopback", Class::Loopback),
42 (
43 [169, 254, 0, 0],
44 16,
45 "link-local (cloud metadata lives here)",
46 Class::Other,
47 ),
48 ([172, 16, 0, 0], 12, "private network", Class::Private),
49 (
50 [192, 0, 0, 0],
51 24,
52 "IETF protocol assignments",
53 Class::Other,
54 ),
55 ([192, 0, 2, 0], 24, "documentation", Class::Other),
56 ([192, 88, 99, 0], 24, "deprecated 6to4 relay", Class::Other),
57 ([192, 168, 0, 0], 16, "private network", Class::Private),
58 ([198, 18, 0, 0], 15, "benchmarking", Class::Other),
59 ([198, 51, 100, 0], 24, "documentation", Class::Other),
60 ([203, 0, 113, 0], 24, "documentation", Class::Other),
61 ([224, 0, 0, 0], 4, "multicast", Class::Other),
62 ([240, 0, 0, 0], 4, "reserved", Class::Other),
63 (
65 [168, 63, 129, 16],
66 32,
67 "Azure platform service",
68 Class::Other,
69 ),
70];
71
72const V6: &[([u16; 8], u8, &str, Class)] = &[
74 ([0, 0, 0, 0, 0, 0, 0, 0], 128, "unspecified", Class::Other),
75 ([0, 0, 0, 0, 0, 0, 0, 1], 128, "loopback", Class::Loopback),
76 (
77 [0x64, 0xff9b, 0, 0, 0, 0, 0, 0],
78 96,
79 "NAT64 (could reach private IPv4)",
80 Class::Other,
81 ),
82 (
83 [0x64, 0xff9b, 1, 0, 0, 0, 0, 0],
84 48,
85 "local NAT64",
86 Class::Other,
87 ),
88 (
89 [0x100, 0, 0, 0, 0, 0, 0, 0],
90 64,
91 "discard-only",
92 Class::Other,
93 ),
94 (
95 [0x100, 0, 0, 1, 0, 0, 0, 0],
96 64,
97 "dummy prefix",
98 Class::Other,
99 ),
100 (
101 [0x2001, 0, 0, 0, 0, 0, 0, 0],
102 23,
103 "IETF protocol assignments (Teredo, benchmarking, ...)",
104 Class::Other,
105 ),
106 (
107 [0x2001, 0xdb8, 0, 0, 0, 0, 0, 0],
108 32,
109 "documentation",
110 Class::Other,
111 ),
112 (
113 [0x2002, 0, 0, 0, 0, 0, 0, 0],
114 16,
115 "6to4 (embeds any IPv4)",
116 Class::Other,
117 ),
118 (
119 [0x3fff, 0, 0, 0, 0, 0, 0, 0],
120 20,
121 "documentation",
122 Class::Other,
123 ),
124 (
125 [0x5f00, 0, 0, 0, 0, 0, 0, 0],
126 16,
127 "segment routing",
128 Class::Other,
129 ),
130 (
131 [0xfc00, 0, 0, 0, 0, 0, 0, 0],
132 7,
133 "unique-local (private network)",
134 Class::Private,
135 ),
136 (
137 [0xfe80, 0, 0, 0, 0, 0, 0, 0],
138 10,
139 "link-local",
140 Class::Other,
141 ),
142 (
143 [0xfec0, 0, 0, 0, 0, 0, 0, 0],
144 10,
145 "site-local (deprecated)",
146 Class::Other,
147 ),
148 ([0xff00, 0, 0, 0, 0, 0, 0, 0], 8, "multicast", Class::Other),
149];
150
151fn in_v4(ip: Ipv4Addr, net: [u8; 4], len: u8) -> bool {
152 let mask = u32::MAX.checked_shl(32 - u32::from(len)).unwrap_or(0);
154 u32::from(ip) & mask == u32::from(Ipv4Addr::from(net)) & mask
155}
156
157fn in_v6(ip: Ipv6Addr, net: [u16; 8], len: u8) -> bool {
158 let mask = u128::MAX.checked_shl(128 - u32::from(len)).unwrap_or(0);
159 u128::from(ip) & mask == u128::from(Ipv6Addr::from(net)) & mask
160}
161
162pub fn denied(ip: IpAddr, own: &[IpAddr]) -> Option<Denial> {
164 let row = |why, class| Denial { class, why };
165 if own.contains(&ip) {
166 return Some(row("an address of this machine", Class::Own));
167 }
168 match ip {
169 IpAddr::V4(v4) => V4
170 .iter()
171 .find(|(n, l, ..)| in_v4(v4, *n, *l))
172 .map(|b| row(b.2, b.3)),
173 IpAddr::V6(v6) => {
174 if let Some(v4) = v6.to_ipv4_mapped() {
175 return denied(IpAddr::V4(v4), own).or(Some(row("IPv4-mapped IPv6", Class::Other)));
176 }
177 V6.iter()
178 .find(|(n, l, ..)| in_v6(v6, *n, *l))
179 .map(|b| row(b.2, b.3))
180 }
181 }
182}
183
184pub fn own_addresses() -> Vec<IpAddr> {
187 let v4 = std::fs::read_to_string("/proc/net/fib_trie").unwrap_or_default();
188 let v6 = std::fs::read_to_string("/proc/net/if_inet6").unwrap_or_default();
189 let mut out = parse_fib_trie(&v4);
190 out.extend(parse_if_inet6(&v6));
191 out.sort();
192 out.dedup();
193 out
194}
195
196fn parse_fib_trie(text: &str) -> Vec<IpAddr> {
198 let mut out = Vec::new();
199 let mut last: Option<Ipv4Addr> = None;
200 for line in text.lines() {
201 let t = line.trim_start_matches([' ', '|', '-', '+']).trim();
202 if let Ok(ip) = t.parse::<Ipv4Addr>() {
203 last = Some(ip);
204 } else if t == "/32 host LOCAL"
205 && let Some(ip) = last
206 {
207 out.push(IpAddr::V4(ip));
208 }
209 }
210 out
211}
212
213fn parse_if_inet6(text: &str) -> Vec<IpAddr> {
215 text.lines()
216 .filter_map(|l| l.split_whitespace().next())
217 .filter_map(|hex| {
218 u128::from_str_radix(hex, 16)
219 .ok()
220 .filter(|_| hex.len() == 32)
221 })
222 .map(|n| IpAddr::V6(Ipv6Addr::from(n)))
223 .collect()
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 fn d(s: &str) -> Option<&'static str> {
231 denied(s.parse().expect("ip"), &[]).map(|d| d.why)
232 }
233
234 #[test]
235 fn refusals_have_a_class() {
236 let class = |s: &str, own: &[IpAddr]| denied(s.parse().expect("ip"), own).map(|d| d.class);
237 for ip in [
238 "10.1.2.3",
239 "172.16.0.1",
240 "192.168.1.1",
241 "100.64.0.1",
242 "fd00::1",
243 "::ffff:10.0.0.1",
244 ] {
245 assert_eq!(class(ip, &[]), Some(Class::Private), "{ip}");
246 }
247 for ip in ["127.0.0.1", "::1", "::ffff:127.0.0.1"] {
248 assert_eq!(class(ip, &[]), Some(Class::Loopback), "{ip}");
249 }
250 for ip in [
251 "169.254.169.254",
252 "fe80::1",
253 "224.0.0.1",
254 "::ffff:192.0.2.1",
255 "64:ff9b::a00:1",
256 ] {
257 assert_eq!(class(ip, &[]), Some(Class::Other), "{ip}");
258 }
259 let me: IpAddr = "203.0.114.7".parse().expect("ip");
260 assert_eq!(class("203.0.114.7", &[me]), Some(Class::Own));
261 assert_eq!(class("1.1.1.1", &[]), None);
262 }
263
264 #[test]
265 fn special_purpose_blocks_are_refused() {
266 for ip in [
267 "0.0.0.0",
268 "0.1.2.3",
269 "10.1.2.3",
270 "100.64.0.1",
271 "100.127.255.255",
272 "127.0.0.1",
273 "127.255.0.1",
274 "169.254.169.254",
275 "172.16.0.1",
276 "172.31.255.255",
277 "192.0.0.9",
278 "192.0.2.1",
279 "192.88.99.1",
280 "192.168.1.1",
281 "198.18.0.1",
282 "198.19.255.255",
283 "198.51.100.1",
284 "203.0.113.1",
285 "224.0.0.1",
286 "239.1.1.1",
287 "240.0.0.1",
288 "255.255.255.255",
289 "168.63.129.16",
290 "::",
291 "::1",
292 "64:ff9b::a00:1",
293 "64:ff9b:1::1",
294 "100::1",
295 "100:0:0:1::1",
296 "2001::1",
297 "2001:1::1",
298 "2001:2::1",
299 "2001:db8::1",
300 "2002:c0a8:101::1",
301 "3fff::1",
302 "5f00::1",
303 "fc00::1",
304 "fd00:ec2::254",
305 "fe80::1",
306 "fec0::1",
307 "ff02::1",
308 "::ffff:10.0.0.1",
309 "::ffff:127.0.0.1",
310 ] {
311 assert!(d(ip).is_some(), "{ip} must be refused");
312 }
313 assert_eq!(d("::ffff:8.8.8.8"), Some("IPv4-mapped IPv6"));
314 }
315
316 #[test]
317 fn public_addresses_pass() {
318 for ip in [
319 "1.1.1.1",
320 "8.8.8.8",
321 "100.63.255.255",
322 "100.128.0.0",
323 "172.15.255.255",
324 "172.32.0.0",
325 "192.0.1.1",
326 "192.169.0.1",
327 "198.17.255.255",
328 "198.20.0.0",
329 "223.255.255.255",
330 "140.82.112.3",
331 "2606:4700::6810:84e5",
332 "2a00:1450::200e",
333 "2001:4860:4860::8888",
334 ] {
335 assert_eq!(d(ip), None, "{ip} is public");
336 }
337 }
338
339 #[test]
340 fn this_machine_is_refused_too() {
341 let own: Vec<IpAddr> = vec!["203.0.114.7".parse().expect("ip")];
342 assert_eq!(
343 denied(own[0], &own).map(|d| d.why),
344 Some("an address of this machine")
345 );
346 assert_eq!(denied("203.0.114.8".parse().expect("ip"), &own), None);
347 }
348
349 #[test]
350 fn own_addresses_from_proc() {
351 let trie = "Main:\n +-- 0.0.0.0/0 3 0 5\n |-- 0.0.0.0\n /0 universe UNICAST\n \
352 |-- 192.168.139.54\n /32 host LOCAL\n |-- 192.168.139.255\n \
353 /32 link BROADCAST\n |-- 127.0.0.1\n /32 host LOCAL\n";
354 assert_eq!(
355 parse_fib_trie(trie),
356 [
357 "192.168.139.54".parse::<IpAddr>().expect("ip"),
358 "127.0.0.1".parse().expect("ip")
359 ]
360 );
361 let inet6 = "00000000000000000000000000000001 01 80 10 80 lo\n\
362 fe80000000000000021c42fffe0a1b2c 02 40 20 80 eth0\nnot-hex\n";
363 assert_eq!(
364 parse_if_inet6(inet6),
365 [
366 "::1".parse::<IpAddr>().expect("ip"),
367 "fe80::21c:42ff:fe0a:1b2c".parse().expect("ip")
368 ]
369 );
370 let _ = own_addresses();
372 }
373}