Skip to main content

tuwunel_core/config/
ip_source.rs

1//! Defines sources for trusted client IP extraction.
2//!
3//! [`IpSource`] enumerates the TCP peer address and supported forwarding
4//! headers. The default uses the TCP peer address without trusting a proxy.
5
6use std::net::{IpAddr, Ipv4Addr, SocketAddr};
7
8use serde::Deserialize;
9
10use crate::implement;
11
12/// Selects the source used to determine the connecting client's IP
13/// address.
14#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
15#[serde(rename_all = "snake_case")]
16pub enum IpSource {
17	/// TCP peer address. Safe default; no proxy required.
18	#[default]
19	ConnectInfo,
20
21	/// Rightmost value of `X-Forwarded-For`.
22	RightmostXForwardedFor,
23
24	/// Rightmost value of RFC 7239 `Forwarded`.
25	RightmostForwarded,
26
27	/// `X-Real-IP` header (nginx).
28	XRealIp,
29
30	/// `CF-Connecting-IP` (Cloudflare / cloudflared).
31	CfConnectingIp,
32
33	/// `True-Client-IP` (Akamai, Cloudflare Enterprise).
34	TrueClientIp,
35
36	/// `Fly-Client-IP` (Fly.io).
37	FlyClientIp,
38
39	/// `CloudFront-Viewer-Address` (AWS CloudFront).
40	#[serde(rename = "cloudfront_viewer_address")]
41	CloudFrontViewerAddress,
42}
43
44/// The stand-in peer address the Unix listener reports for every client.
45///
46/// It is loopback so that socket clients take the loopback-peer rules: the
47/// general client IP extractor bypasses a configured source for them, and
48/// [`IpSource::identifies_client`] exempts them from the per-address password
49/// limit.
50pub const UNIX_SOCKET_PEER: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
51
52/// Whether an address taken from this source identifies a single client.
53///
54/// A loopback TCP peer may be a local reverse proxy, the Unix listener's
55/// [`UNIX_SOCKET_PEER`] or a local client, so it can stand for many clients at
56/// once. A forwarding header names the client itself, loopback or not.
57#[implement(IpSource)]
58#[inline]
59#[must_use]
60pub fn identifies_client(self, address: IpAddr) -> bool {
61	self.is_header() || !address.to_canonical().is_loopback()
62}
63
64/// Whether this source reads a forwarding header rather than the TCP peer.
65///
66/// Every variant but `ConnectInfo` reads a header, which only a trusted reverse
67/// proxy can vouch for.
68#[implement(IpSource)]
69#[inline]
70#[must_use]
71pub fn is_header(self) -> bool { !matches!(self, Self::ConnectInfo) }