|
3 | 3 | //! This module provides secure extraction of client IP addresses from HTTP requests, |
4 | 4 | //! with protection against header spoofing attacks that attempt to bypass localhost checks. |
5 | 5 |
|
| 6 | +use actix_web::http::header::{HeaderMap, HeaderValue}; |
6 | 7 | use actix_web::HttpRequest; |
| 8 | +use ipnet::IpNet; |
7 | 9 | use kalamdb_commons::models::ConnectionInfo; |
8 | 10 | use log::warn; |
| 11 | +use once_cell::sync::Lazy; |
| 12 | +use std::net::IpAddr; |
| 13 | +use std::sync::RwLock; |
| 14 | + |
| 15 | +static TRUSTED_PROXY_RANGES: Lazy<RwLock<Vec<IpNet>>> = Lazy::new(|| RwLock::new(Vec::new())); |
9 | 16 |
|
10 | 17 | /// Extract client IP address with security checks against header spoofing |
11 | 18 | /// |
@@ -34,36 +41,80 @@ use log::warn; |
34 | 41 | /// println!("Client IP: {:?}", client_ip); |
35 | 42 | /// } |
36 | 43 | /// ``` |
| 44 | +pub fn init_trusted_proxy_ranges(entries: &[String]) -> anyhow::Result<()> { |
| 45 | + let parsed = kalamdb_configs::parse_trusted_proxy_entries(entries)?; |
| 46 | + *TRUSTED_PROXY_RANGES |
| 47 | + .write() |
| 48 | + .expect("trusted proxy ranges lock poisoned") = parsed; |
| 49 | + Ok(()) |
| 50 | +} |
| 51 | + |
| 52 | +pub fn extract_client_ip_addr_secure(peer_addr: Option<IpAddr>, headers: &HeaderMap) -> Option<IpAddr> { |
| 53 | + let trusted_proxy_ranges = TRUSTED_PROXY_RANGES |
| 54 | + .read() |
| 55 | + .expect("trusted proxy ranges lock poisoned"); |
| 56 | + extract_client_ip_addr_with_trusted_ranges(peer_addr, headers, &trusted_proxy_ranges) |
| 57 | +} |
| 58 | + |
37 | 59 | pub fn extract_client_ip_secure(req: &HttpRequest) -> ConnectionInfo { |
38 | | - let peer_addr = req.peer_addr().map(|addr| addr.ip()); |
39 | | - |
40 | | - // Trust X-Forwarded-For only when the direct peer is loopback (trusted local reverse proxy). |
41 | | - if peer_addr.is_some_and(|ip| ip.is_loopback()) { |
42 | | - if let Some(forwarded_for) = req.headers().get("X-Forwarded-For") { |
43 | | - if let Ok(header_value) = forwarded_for.to_str() { |
44 | | - // Take first IP in comma-separated list (original client) |
45 | | - let first_ip = header_value.split(',').next().unwrap_or("").trim(); |
46 | | - |
47 | | - // Security check: Reject localhost values in X-Forwarded-For |
48 | | - // This prevents bypass attempts like: X-Forwarded-For: 127.0.0.1 |
49 | | - if is_localhost_address(first_ip) { |
50 | | - warn!( |
51 | | - "Security: Rejected localhost value in trusted X-Forwarded-For header: '{}'. Using peer_addr instead.", |
52 | | - first_ip |
53 | | - ); |
54 | | - } else if !first_ip.is_empty() { |
55 | | - return ConnectionInfo::new(Some(first_ip.to_string())); |
56 | | - } |
57 | | - } |
| 60 | + extract_client_ip_addr_secure(req.peer_addr().map(|addr| addr.ip()), req.headers()) |
| 61 | + .map(|ip| ConnectionInfo::new(Some(ip.to_string()))) |
| 62 | + .unwrap_or_else(|| ConnectionInfo::new(None)) |
| 63 | +} |
| 64 | + |
| 65 | +fn extract_client_ip_addr_with_trusted_ranges( |
| 66 | + peer_addr: Option<IpAddr>, |
| 67 | + headers: &HeaderMap, |
| 68 | + trusted_proxy_ranges: &[IpNet], |
| 69 | +) -> Option<IpAddr> { |
| 70 | + if peer_addr.is_some_and(|ip| is_trusted_proxy_peer(ip, trusted_proxy_ranges)) { |
| 71 | + if let Some(ip) = extract_proxy_header_ip(headers.get("X-Forwarded-For"), true, "X-Forwarded-For") { |
| 72 | + return Some(ip); |
| 73 | + } |
| 74 | + |
| 75 | + if let Some(ip) = extract_proxy_header_ip(headers.get("X-Real-IP"), false, "X-Real-IP") { |
| 76 | + return Some(ip); |
58 | 77 | } |
59 | | - } else if req.headers().contains_key("X-Forwarded-For") { |
60 | | - warn!("Security: Ignoring X-Forwarded-For from non-loopback peer {:?}", peer_addr); |
| 78 | + } else if headers.contains_key("X-Forwarded-For") || headers.contains_key("X-Real-IP") { |
| 79 | + warn!( |
| 80 | + "Security: Ignoring proxy headers from untrusted peer {:?}", |
| 81 | + peer_addr |
| 82 | + ); |
61 | 83 | } |
62 | 84 |
|
63 | | - // Fallback to peer address (direct TCP connection) |
64 | 85 | peer_addr |
65 | | - .map(|ip| ConnectionInfo::new(Some(ip.to_string()))) |
66 | | - .unwrap_or_else(|| ConnectionInfo::new(None)) |
| 86 | +} |
| 87 | + |
| 88 | +fn is_trusted_proxy_peer(peer_addr: IpAddr, trusted_proxy_ranges: &[IpNet]) -> bool { |
| 89 | + peer_addr.is_loopback() || trusted_proxy_ranges.iter().any(|range| range.contains(&peer_addr)) |
| 90 | +} |
| 91 | + |
| 92 | +fn extract_proxy_header_ip( |
| 93 | + header: Option<&HeaderValue>, |
| 94 | + first_csv_value: bool, |
| 95 | + header_name: &str, |
| 96 | +) -> Option<IpAddr> { |
| 97 | + let header_value = header?.to_str().ok()?; |
| 98 | + let candidate = if first_csv_value { |
| 99 | + header_value.split(',').next().unwrap_or("").trim() |
| 100 | + } else { |
| 101 | + header_value.trim() |
| 102 | + }; |
| 103 | + |
| 104 | + if candidate.is_empty() { |
| 105 | + return None; |
| 106 | + } |
| 107 | + |
| 108 | + if is_localhost_address(candidate) { |
| 109 | + warn!( |
| 110 | + "Security: Rejected localhost value in trusted {} header: '{}'. Using peer_addr instead.", |
| 111 | + header_name, |
| 112 | + candidate |
| 113 | + ); |
| 114 | + return None; |
| 115 | + } |
| 116 | + |
| 117 | + candidate.parse::<IpAddr>().ok() |
67 | 118 | } |
68 | 119 |
|
69 | 120 | /// Check if an IP address string represents localhost |
@@ -94,6 +145,7 @@ pub fn is_localhost_address(ip: &str) -> bool { |
94 | 145 | #[cfg(test)] |
95 | 146 | mod tests { |
96 | 147 | use super::*; |
| 148 | + use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue}; |
97 | 149 |
|
98 | 150 | #[test] |
99 | 151 | fn test_is_localhost_address() { |
@@ -138,4 +190,80 @@ mod tests { |
138 | 190 | ); |
139 | 191 | } |
140 | 192 | } |
| 193 | + |
| 194 | + #[test] |
| 195 | + fn test_loopback_proxy_headers_are_trusted() { |
| 196 | + let mut headers = HeaderMap::new(); |
| 197 | + headers.insert( |
| 198 | + HeaderName::from_static("x-forwarded-for"), |
| 199 | + HeaderValue::from_static("203.0.113.8, 10.0.0.1"), |
| 200 | + ); |
| 201 | + |
| 202 | + let ip = extract_client_ip_addr_with_trusted_ranges( |
| 203 | + Some("127.0.0.1".parse().unwrap()), |
| 204 | + &headers, |
| 205 | + &[], |
| 206 | + ); |
| 207 | + |
| 208 | + assert_eq!(ip, Some("203.0.113.8".parse().unwrap())); |
| 209 | + } |
| 210 | + |
| 211 | + #[test] |
| 212 | + fn test_trusted_proxy_range_allows_forwarded_headers() { |
| 213 | + let mut headers = HeaderMap::new(); |
| 214 | + headers.insert( |
| 215 | + HeaderName::from_static("x-forwarded-for"), |
| 216 | + HeaderValue::from_static("203.0.113.8"), |
| 217 | + ); |
| 218 | + let trusted_ranges = kalamdb_configs::parse_trusted_proxy_entries(&[ |
| 219 | + "10.0.0.0/8".to_string(), |
| 220 | + ]) |
| 221 | + .unwrap(); |
| 222 | + |
| 223 | + let ip = extract_client_ip_addr_with_trusted_ranges( |
| 224 | + Some("10.0.1.9".parse().unwrap()), |
| 225 | + &headers, |
| 226 | + &trusted_ranges, |
| 227 | + ); |
| 228 | + |
| 229 | + assert_eq!(ip, Some("203.0.113.8".parse().unwrap())); |
| 230 | + } |
| 231 | + |
| 232 | + #[test] |
| 233 | + fn test_untrusted_proxy_headers_are_ignored() { |
| 234 | + let mut headers = HeaderMap::new(); |
| 235 | + headers.insert( |
| 236 | + HeaderName::from_static("x-forwarded-for"), |
| 237 | + HeaderValue::from_static("203.0.113.8"), |
| 238 | + ); |
| 239 | + |
| 240 | + let ip = extract_client_ip_addr_with_trusted_ranges( |
| 241 | + Some("10.0.1.9".parse().unwrap()), |
| 242 | + &headers, |
| 243 | + &[], |
| 244 | + ); |
| 245 | + |
| 246 | + assert_eq!(ip, Some("10.0.1.9".parse().unwrap())); |
| 247 | + } |
| 248 | + |
| 249 | + #[test] |
| 250 | + fn test_localhost_spoofing_is_rejected_even_for_trusted_proxy() { |
| 251 | + let mut headers = HeaderMap::new(); |
| 252 | + headers.insert( |
| 253 | + HeaderName::from_static("x-forwarded-for"), |
| 254 | + HeaderValue::from_static("127.0.0.1"), |
| 255 | + ); |
| 256 | + let trusted_ranges = kalamdb_configs::parse_trusted_proxy_entries(&[ |
| 257 | + "10.0.0.0/8".to_string(), |
| 258 | + ]) |
| 259 | + .unwrap(); |
| 260 | + |
| 261 | + let ip = extract_client_ip_addr_with_trusted_ranges( |
| 262 | + Some("10.0.1.9".parse().unwrap()), |
| 263 | + &headers, |
| 264 | + &trusted_ranges, |
| 265 | + ); |
| 266 | + |
| 267 | + assert_eq!(ip, Some("10.0.1.9".parse().unwrap())); |
| 268 | + } |
141 | 269 | } |
0 commit comments