//! The client's address, behind a reverse proxy or not.
//!
//! The server is served with `ConnectInfo<SocketAddr>`, so the TCP peer is
//! known. Behind nginx `proxy_pass` or the cluster ingress that peer is the
//! proxy; the client is in `X-Forwarded-For`, which each proxy appends to.
//! Only a peer inside `TRUSTED_PROXIES` (the name angler uses) is believed,
//! and only for the rightmost address that isn't itself a trusted proxy:
//! everything left of that is whatever the client chose to send. With an
//! untrusted peer, headers are ignored and the peer is the client
//! (angler's `AnglerWeb.Plugs.RemoteIp`, gitgud's `GITGUD_TRUSTED_PROXIES`).
//!
//! [`layer`] resolves it once per request into a [`ClientIp`] extension.
use std::net::{IpAddr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use axum::extract::{ConnectInfo, FromRequestParts, Request, State};
use axum::http::{request::Parts, HeaderMap};
use axum::middleware::Next;
use axum::response::Response;
/// An address range, `10.0.0.0/8` or `fc00::/7`; a bare address is a /32
/// (/128).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Cidr {
addr: IpAddr,
prefix: u8,
}
impl Cidr {
pub fn contains(&self, ip: IpAddr) -> bool {
match (self.addr, canonical(ip)) {
(IpAddr::V4(net), IpAddr::V4(ip)) => {
let mask = if self.prefix == 0 { 0 } else { u32::MAX << (32 - self.prefix) };
(u32::from(net) & mask) == (u32::from(ip) & mask)
}
(IpAddr::V6(net), IpAddr::V6(ip)) => {
let mask = if self.prefix == 0 { 0 } else { u128::MAX << (128 - self.prefix) };
(u128::from(net) & mask) == (u128::from(ip) & mask)
}
_ => false,
}
}
/// The network `ip` sits in at this prefix length (`/24`, `/64`).
pub fn network_of(ip: IpAddr, prefix: u8) -> Cidr {
let ip = canonical(ip);
let addr = match ip {
IpAddr::V4(v4) => {
let p = prefix.min(32);
let mask = if p == 0 { 0 } else { u32::MAX << (32 - p) };
IpAddr::V4((u32::from(v4) & mask).into())
}
IpAddr::V6(v6) => {
let p = prefix.min(128);
let mask = if p == 0 { 0 } else { u128::MAX << (128 - p) };
IpAddr::V6((u128::from(v6) & mask).into())
}
};
let prefix = if ip.is_ipv4() { prefix.min(32) } else { prefix.min(128) };
Cidr { addr, prefix }
}
}
impl std::fmt::Display for Cidr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.addr, self.prefix)
}
}
impl FromStr for Cidr {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
let (addr, prefix) = match s.split_once('/') {
Some((a, p)) => (a, Some(p)),
None => (s, None),
};
let addr: IpAddr = addr.parse().map_err(|_| format!("{s}: not an address"))?;
let max = if addr.is_ipv4() { 32 } else { 128 };
let prefix = match prefix {
Some(p) => p.parse::<u8>().ok().filter(|p| *p <= max).ok_or(format!("{s}: bad prefix length"))?,
None => max,
};
Ok(Cidr { addr: canonical(addr), prefix })
}
}
/// IPv4-mapped IPv6 (`::ffff:1.2.3.4`, from a dual-stack listener) as IPv4.
pub fn canonical(ip: IpAddr) -> IpAddr {
match ip {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(ip),
v4 => v4,
}
}
/// `TRUSTED_PROXIES`: comma-separated CIDRs. Empty (the default) trusts
/// nothing: forwarding headers are ignored and the peer is the client.
#[derive(Debug, Clone, Default)]
pub struct TrustedProxies(pub Vec<Cidr>);
impl TrustedProxies {
pub fn parse(s: &str) -> Result<Self, String> {
s.split(',').map(str::trim).filter(|p| !p.is_empty()).map(Cidr::from_str).collect::<Result<_, _>>().map(Self)
}
pub fn trusts(&self, ip: IpAddr) -> bool {
self.0.iter().any(|c| c.contains(ip))
}
/// The client for a request from `peer` carrying `headers`.
pub fn resolve(&self, peer: Option<IpAddr>, headers: &HeaderMap) -> Option<IpAddr> {
let peer = peer.map(canonical)?;
if !self.trusts(peer) {
return Some(peer);
}
// Every X-Forwarded-For value in order, each comma-separated; walk
// right to left, skipping our own proxies. Unparsable entries are
// skipped rather than believed.
let forwarded: Vec<&str> = headers
.get_all("x-forwarded-for")
.iter()
.filter_map(|v| v.to_str().ok())
.flat_map(|v| v.split(','))
.collect();
if let Some(ip) = forwarded.iter().rev().filter_map(|e| parse_entry(e)).find(|ip| !self.trusts(*ip)) {
return Some(ip);
}
let real_ip = || headers.get("x-real-ip").and_then(|v| v.to_str().ok()).and_then(parse_entry);
match forwarded.is_empty() {
true => real_ip().or(Some(peer)),
false => Some(peer),
}
}
}
/// `1.2.3.4`, `1.2.3.4:567`, `[::1]:80` or `::1`.
fn parse_entry(e: &str) -> Option<IpAddr> {
let e = e.trim();
if let Ok(ip) = e.parse::<IpAddr>() {
return Some(canonical(ip));
}
e.parse::<SocketAddr>().ok().map(|s| canonical(s.ip()))
}
/// The resolved client address of this request (None only when the server
/// wasn't served with connect info, e.g. in-process tests that don't set it).
#[derive(Debug, Clone, Copy, Default)]
pub struct ClientIp(pub Option<IpAddr>);
impl ClientIp {
pub fn text(&self) -> Option<String> {
self.0.map(|ip| ip.to_string())
}
}
impl<S: Send + Sync> FromRequestParts<S> for ClientIp {
type Rejection = std::convert::Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(parts.extensions.get::<ClientIp>().copied().unwrap_or_default())
}
}
/// Internal request header carrying the resolved client address to code that
/// only has the headers (the anonymous view throttle). [`layer`] always
/// removes any copy a client sent before setting it, so it can't be forged.
pub const RESOLVED_HEADER: &str = "x-recourse-client-ip";
/// Resolve the client once and attach it ([`ClientIp`], and
/// [`RESOLVED_HEADER`]). Outermost, so the auth middlewares see it too.
pub async fn layer(State(trusted): State<Arc<TrustedProxies>>, mut request: Request, next: Next) -> Response {
let peer = request.extensions().get::<ConnectInfo<SocketAddr>>().map(|c| c.0.ip());
let ip = trusted.resolve(peer, request.headers());
stamp(request.headers_mut(), ip);
request.extensions_mut().insert(ClientIp(ip));
next.run(request).await
}
/// Replace whatever the client sent as [`RESOLVED_HEADER`] with the resolved
/// address (or nothing).
fn stamp(headers: &mut axum::http::HeaderMap, ip: Option<IpAddr>) {
headers.remove(RESOLVED_HEADER);
if let Some(v) = ip.and_then(|ip| axum::http::HeaderValue::from_str(&ip.to_string()).ok()) {
headers.insert(RESOLVED_HEADER, v);
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
#[test]
fn the_resolved_header_cannot_be_forged() {
let mut m = HeaderMap::new();
m.insert(RESOLVED_HEADER, HeaderValue::from_static("6.6.6.6"));
stamp(&mut m, Some("203.0.113.7".parse().unwrap()));
assert_eq!(m.get_all(RESOLVED_HEADER).iter().count(), 1);
assert_eq!(m.get(RESOLVED_HEADER).unwrap(), "203.0.113.7");
// Unknown client: the forged value is still dropped.
let mut m = HeaderMap::new();
m.insert(RESOLVED_HEADER, HeaderValue::from_static("6.6.6.6"));
stamp(&mut m, None);
assert!(m.get(RESOLVED_HEADER).is_none());
}
fn h(pairs: &[(&'static str, &str)]) -> HeaderMap {
let mut m = HeaderMap::new();
for (k, v) in pairs {
m.append(*k, HeaderValue::from_str(v).unwrap());
}
m
}
fn ip(s: &str) -> Option<IpAddr> {
Some(s.parse().unwrap())
}
#[test]
fn cidrs_parse_and_match() {
let t = TrustedProxies::parse("10.0.0.0/8, 127.0.0.1/32,fc00::/7").unwrap();
assert!(t.trusts("10.42.1.7".parse().unwrap()));
assert!(t.trusts("127.0.0.1".parse().unwrap()));
assert!(!t.trusts("127.0.0.2".parse().unwrap()));
assert!(t.trusts("fd12::1".parse().unwrap()));
assert!(t.trusts("::ffff:10.1.2.3".parse().unwrap()), "v4-mapped v6 is the v4 address");
assert!(!t.trusts("11.0.0.1".parse().unwrap()));
assert!(TrustedProxies::parse("").unwrap().0.is_empty());
assert!(TrustedProxies::parse("10.0.0.0/33").is_err());
assert!(TrustedProxies::parse("nope").is_err());
assert_eq!(Cidr::network_of("203.0.113.77".parse().unwrap(), 24).to_string(), "203.0.113.0/24");
assert_eq!(Cidr::network_of("2001:db8:1:2:3::9".parse().unwrap(), 64).to_string(), "2001:db8:1:2::/64");
}
#[test]
fn nothing_trusted_means_the_peer_whatever_the_headers_say() {
let t = TrustedProxies::default();
let headers = h(&[("x-forwarded-for", "6.6.6.6"), ("x-real-ip", "6.6.6.6")]);
assert_eq!(t.resolve(ip("203.0.113.5"), &headers), ip("203.0.113.5"));
}
#[test]
fn an_untrusted_peer_cannot_spoof() {
let t = TrustedProxies::parse("10.0.0.0/8").unwrap();
let headers = h(&[("x-forwarded-for", "1.1.1.1, 10.0.0.9")]);
assert_eq!(t.resolve(ip("198.51.100.4"), &headers), ip("198.51.100.4"));
}
#[test]
fn behind_a_trusted_proxy_the_rightmost_untrusted_hop_is_the_client() {
let t = TrustedProxies::parse("10.0.0.0/8,127.0.0.1/32").unwrap();
// nginx -> ingress -> app: each proxy appended the address it saw.
let headers = h(&[("x-forwarded-for", "203.0.113.9, 10.1.0.4")]);
assert_eq!(t.resolve(ip("10.1.0.5"), &headers), ip("203.0.113.9"));
// A forged leftmost entry from the client is passed over.
let headers = h(&[("x-forwarded-for", "6.6.6.6, 203.0.113.9")]);
assert_eq!(t.resolve(ip("127.0.0.1"), &headers), ip("203.0.113.9"));
// Several header lines are one list, in order.
let mut headers = h(&[("x-forwarded-for", "6.6.6.6")]);
headers.append("x-forwarded-for", HeaderValue::from_static("198.51.100.1, 10.9.9.9"));
assert_eq!(t.resolve(ip("10.0.0.1"), &headers), ip("198.51.100.1"));
// Garbage entries are skipped, ports stripped.
let headers = h(&[("x-forwarded-for", "203.0.113.9:4431, garbage")]);
assert_eq!(t.resolve(ip("10.0.0.1"), &headers), ip("203.0.113.9"));
let headers = h(&[("x-forwarded-for", "[2001:db8::7]:443")]);
assert_eq!(t.resolve(ip("10.0.0.1"), &headers), ip("2001:db8::7"));
}
#[test]
fn x_real_ip_only_without_x_forwarded_for_and_only_from_a_trusted_peer() {
let t = TrustedProxies::parse("127.0.0.1/32").unwrap();
assert_eq!(t.resolve(ip("127.0.0.1"), &h(&[("x-real-ip", "203.0.113.2")])), ip("203.0.113.2"));
assert_eq!(t.resolve(ip("192.0.2.1"), &h(&[("x-real-ip", "203.0.113.2")])), ip("192.0.2.1"));
// All hops trusted: the peer (nothing better to go on).
assert_eq!(t.resolve(ip("127.0.0.1"), &h(&[("x-forwarded-for", "127.0.0.1")])), ip("127.0.0.1"));
assert_eq!(t.resolve(None, &h(&[])), None);
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
11.3 KiB · text
History
4fa4298