forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

client_ip.rs124 lines, 4.1 KiBHistoryRawDownload
1//! The client address of a request, for throttling and for the audit log.
2//!
3//! The TCP peer is the client, unless the peer is in `trusted_proxies`. Only then is
4//! `X-Forwarded-For` read: from the right, skipping trusted hops, the first untrusted address is the
5//! client. Any unusable header falls back to the peer, so a spoofed header from an untrusted peer is
6//! never believed. IPv6 is bucketed by /64 for throttling, so one client holding a /64 cannot
7//! multiply its attempt budget.
8
9use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
10
11use topcoat::context::{Cx, app_context};
12use topcoat::router::IpNet;
13use topcoat::router::request::{headers, remote_addr};
14
15use crate::state::AppState;
16
17/// The header a trusted proxy appends the client address to.
18const FORWARDED_FOR: &str = "x-forwarded-for";
19
20/// The client address for throttling: the exact address, with IPv6 bucketed by /64.
21pub fn client_ip(cx: &Cx) -> IpAddr {
22 bucket(client_addr(cx))
23}
24
25/// The exact client address of this request, normalised but not bucketed. Used for the audit log
26/// and the session list. A request without a peer address (not possible over TCP) maps to the
27/// unspecified address.
28pub fn client_addr(cx: &Cx) -> IpAddr {
29 let trusted = &app_context::<AppState>(cx).config.trusted_proxies;
30 let peer = remote_addr(cx).map(|addr| addr.ip());
31 let forwarded = headers(cx)
32 .get_all(FORWARDED_FOR)
33 .iter()
34 .filter_map(|value| value.to_str().ok())
35 .collect::<Vec<_>>()
36 .join(",");
37 resolve_addr(peer, &forwarded, trusted)
38}
39
40/// Pure form of [`client_addr`]. `forwarded` is the combined `X-Forwarded-For` value, or empty.
41pub fn resolve_addr(peer: Option<IpAddr>, forwarded: &str, trusted: &[IpNet]) -> IpAddr {
42 let Some(peer) = peer.map(normalize) else {
43 return IpAddr::V4(Ipv4Addr::UNSPECIFIED);
44 };
45 if !is_trusted(peer, trusted) {
46 return peer;
47 }
48 for entry in forwarded.rsplit(',') {
49 let Ok(ip) = entry.trim().parse::<IpAddr>() else {
50 return peer;
51 };
52 let ip = normalize(ip);
53 if !is_trusted(ip, trusted) {
54 return ip;
55 }
56 }
57 peer
58}
59
60fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool {
61 trusted.iter().any(|net| net.contains(&ip))
62}
63
64/// IPv4-mapped IPv6 addresses are reported as the IPv4 address they carry.
65fn normalize(ip: IpAddr) -> IpAddr {
66 match ip {
67 IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
68 IpAddr::V4(_) => ip,
69 }
70}
71
72/// Clears the host half of an IPv6 address, so every address of a /64 shares one bucket.
73fn bucket(ip: IpAddr) -> IpAddr {
74 match ip {
75 IpAddr::V4(_) => ip,
76 IpAddr::V6(v6) => {
77 let mut octets = v6.octets();
78 octets[8..].fill(0);
79 IpAddr::V6(Ipv6Addr::from(octets))
80 }
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 fn ip(text: &str) -> IpAddr {
89 text.parse().unwrap()
90 }
91
92 #[test]
93 fn forwarded_for_counts_only_from_a_trusted_peer() {
94 let trusted: [IpNet; 1] = ["127.0.0.0/8".parse().unwrap()];
95 // An untrusted peer's header is ignored. 127.0.0.0/8 is the trusted proxy range.
96 assert_eq!(
97 resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted),
98 ip("203.0.113.9")
99 );
100 // A trusted proxy's header names the client, skipping trusted hops from the right.
101 assert_eq!(
102 resolve_addr(
103 Some(ip("127.0.0.1")),
104 "1.2.3.4, 198.51.100.7, 127.0.0.2",
105 &trusted
106 ),
107 ip("198.51.100.7")
108 );
109 // An unusable header falls back to the peer.
110 assert_eq!(
111 resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted),
112 ip("127.0.0.1")
113 );
114 }
115
116 #[test]
117 fn ipv6_is_bucketed_by_slash_64_and_mapped_addresses_are_ipv4() {
118 let a = bucket(ip("2001:db8:1:2:aaaa::1"));
119 assert_eq!(a, bucket(ip("2001:db8:1:2:bbbb::9")));
120 assert_ne!(a, bucket(ip("2001:db8:1:3::1")));
121 assert_eq!(a, ip("2001:db8:1:2::"));
122 assert_eq!(normalize(ip("::ffff:192.0.2.5")), ip("192.0.2.5"));
123 }
124}