//! The client address of a request, for throttling and for the audit log. //! //! The TCP peer is the client, unless the peer is in `trusted_proxies`. Only then is //! `X-Forwarded-For` read: from the right, skipping trusted hops, the first untrusted address is the //! client. Any unusable header falls back to the peer, so a spoofed header from an untrusted peer is //! never believed. IPv6 is bucketed by /64 for throttling, so one client holding a /64 cannot //! multiply its attempt budget. use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use topcoat::context::{Cx, app_context}; use topcoat::router::IpNet; use topcoat::router::request::{headers, remote_addr}; use crate::state::AppState; /// The header a trusted proxy appends the client address to. const FORWARDED_FOR: &str = "x-forwarded-for"; /// The client address for throttling: the exact address, with IPv6 bucketed by /64. pub fn client_ip(cx: &Cx) -> IpAddr { bucket(client_addr(cx)) } /// The exact client address of this request, normalised but not bucketed. Used for the audit log /// and the session list. A request without a peer address (not possible over TCP) maps to the /// unspecified address. pub fn client_addr(cx: &Cx) -> IpAddr { let trusted = &app_context::(cx).config.trusted_proxies; let peer = remote_addr(cx).map(|addr| addr.ip()); let forwarded = headers(cx) .get_all(FORWARDED_FOR) .iter() .filter_map(|value| value.to_str().ok()) .collect::>() .join(","); resolve_addr(peer, &forwarded, trusted) } /// Pure form of [`client_addr`]. `forwarded` is the combined `X-Forwarded-For` value, or empty. pub fn resolve_addr(peer: Option, forwarded: &str, trusted: &[IpNet]) -> IpAddr { let Some(peer) = peer.map(normalize) else { return IpAddr::V4(Ipv4Addr::UNSPECIFIED); }; if !is_trusted(peer, trusted) { return peer; } for entry in forwarded.rsplit(',') { let Ok(ip) = entry.trim().parse::() else { return peer; }; let ip = normalize(ip); if !is_trusted(ip, trusted) { return ip; } } peer } fn is_trusted(ip: IpAddr, trusted: &[IpNet]) -> bool { trusted.iter().any(|net| net.contains(&ip)) } /// IPv4-mapped IPv6 addresses are reported as the IPv4 address they carry. fn normalize(ip: IpAddr) -> IpAddr { match ip { IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4), IpAddr::V4(_) => ip, } } /// Clears the host half of an IPv6 address, so every address of a /64 shares one bucket. fn bucket(ip: IpAddr) -> IpAddr { match ip { IpAddr::V4(_) => ip, IpAddr::V6(v6) => { let mut octets = v6.octets(); octets[8..].fill(0); IpAddr::V6(Ipv6Addr::from(octets)) } } } #[cfg(test)] mod tests { use super::*; fn ip(text: &str) -> IpAddr { text.parse().unwrap() } #[test] fn forwarded_for_counts_only_from_a_trusted_peer() { let trusted: [IpNet; 1] = ["127.0.0.0/8".parse().unwrap()]; // An untrusted peer's header is ignored. 127.0.0.0/8 is the trusted proxy range. assert_eq!( resolve_addr(Some(ip("203.0.113.9")), "198.51.100.7", &trusted), ip("203.0.113.9") ); // A trusted proxy's header names the client, skipping trusted hops from the right. assert_eq!( resolve_addr( Some(ip("127.0.0.1")), "1.2.3.4, 198.51.100.7, 127.0.0.2", &trusted ), ip("198.51.100.7") ); // An unusable header falls back to the peer. assert_eq!( resolve_addr(Some(ip("127.0.0.1")), "garbage", &trusted), ip("127.0.0.1") ); } #[test] fn ipv6_is_bucketed_by_slash_64_and_mapped_addresses_are_ipv4() { let a = bucket(ip("2001:db8:1:2:aaaa::1")); assert_eq!(a, bucket(ip("2001:db8:1:2:bbbb::9"))); assert_ne!(a, bucket(ip("2001:db8:1:3::1"))); assert_eq!(a, ip("2001:db8:1:2::")); assert_eq!(normalize(ip("::ffff:192.0.2.5")), ip("192.0.2.5")); } }