/Traefik Real IP

Traefik Real IP

25
v0.4.0

Traefik Real IP

A Traefik middleware plugin that extracts the real client IP address from various HTTP headers.

Traefik Plugin Version License: MIT

Overview

Traefik Real IP extracts and validates the actual client IP address from commonly used headers such as X-Forwarded-For, X-Real-IP, and Cf-Connecting-Ip. This plugin is particularly useful when Traefik is behind a CDN, proxy, or load balancer like Cloudflare.

Features

  • Extracts real IP from Cf-Connecting-Ip, Eo-Connecting-Ip, X-Real-IP, and X-Forwarded-For headers
  • Validates whether the source IP is trusted before accepting header values
  • Built-in support for Cloudflare IP ranges
  • Optional support for EdgeOne IP ranges
  • Supports local/private IP ranges
  • Custom trusted IP configuration
  • Configurable logging level

Installation

From Traefik Pilot

The easiest way to install this plugin is through the Traefik Plugin Catalog.

Manual Installation

Add the plugin to your Traefik static configuration:

experimental:
plugins:
traefik-real-ip:
moduleName: github.com/zekihan/traefik-real-ip
version: v0.4.0

Configuration

Static Configuration Example

# Static configuration
experimental:
plugins:
traefik-real-ip:
moduleName: github.com/zekihan/traefik-real-ip
version: v0.4.0

Middleware Configuration

# Dynamic configuration
http:
middlewares:
traefik-real-ip:
plugin:
traefik-real-ip:
trustLocal: true
trustCloudFlare: true
trustEdgeOne: false
trustedIPs:
- "1.2.3.4/32"
- "10.0.0.0/8"
logLevel: info
denyUntrusted: false
xForwardedForMode: append

Configuration Options

OptionTypeDefaultDescription
trustLocalbooleantrueTrust local and private IP ranges
trustCloudFlarebooleantrueTrust Cloudflare IP ranges
trustEdgeOnebooleanfalseTrust EdgeOne IP ranges
trustedIPsarray of strings[]Additional IP ranges to trust in CIDR notation
logLevelstringinfoLog level (debug, info, warn, error)
denyUntrustedbooleanfalseDeny requests from untrusted IPs with 403 Forbidden
panicPolicystringlegacy-retryPanic handling: legacy-retry preserves retries; propagate prevents middleware replay (see below)
xForwardedForModestringappendHow to write X-Forwarded-For: append preserves proxy hops; replace writes only the resolved client IP
scopedTrustbooleanfalsePer-header trust and identity-header stripping (see Scoped trust)
forwardedTrustedIPsarray of strings[]Scoped mode: peers allowed to send X-Real-IP / X-Forwarded-For
cloudflareTrustedIPsarray of strings[]Scoped mode: extra peers (for example cloudflared) allowed to send Cf-Connecting-Ip
cloudflareAuthHeaderstring""Scoped mode: header carrying the Cloudflare edge secret
cloudflareAuthSecretFilestring""Scoped mode: file holding the edge secret (one per line, current and previous)

The former thrustLocal, thrustCloudFlare, and thrustEdgeOne keys remain accepted for compatibility and emit a deprecation warning. Use the trust* spellings for new configurations.

Remote providers must return valid, nonempty CIDR lists from every required URL before the plugin can initialize. Each Cloudflare feed must contain only ranges for its advertised address family. If an enabled provider fails, New returns an error, even when local or custom trusted ranges are configured. Failed loads do not populate the process cache: a later middleware initialization can retry without a process restart. Successful lists are cached for the process lifetime; there is no periodic refresh or persisted fallback.

Each remote response is limited to 1 MiB after HTTP decompression, lines shorter than 4 KiB, and 4,096 CIDR entries (counting duplicates). Canonical duplicate ranges are removed within and across provider URLs, and a provider snapshot can contain at most 4,096 unique ranges. Empty, malformed, oversized, or default-route lists are rejected in full, including 0.0.0.0/0, ::/0, and IPv4-mapped equivalents such as ::ffff:0:0/96. These validation limits apply to remote providers; custom trustedIPs retain their existing behavior.

How It Works

  1. The plugin extracts the source IP from the incoming request
  2. It checks if the source IP is in the trusted IPs list
  3. If denyUntrusted is enabled and the source IP is not trusted, it returns a 403 Forbidden response
  4. If trusted, it looks for the real IP in headers in this order: Cf-Connecting-Ip, Eo-Connecting-Ip, X-Real-IP, then X-Forwarded-For. A private or link-local X-Real-IP is skipped; see below.
  5. It updates the request headers with the discovered real IP
  6. Adds an X-Is-Trusted: yes|no header indicating if the source was trusted

Panic Handling

Set panicPolicy: propagate to prevent this middleware from invoking downstream again after a panic:

http:
middlewares:
traefik-real-ip:
plugin:
traefik-real-ip:
panicPolicy: propagate

This policy rethrows the original panic to the enclosing HTTP server or recovery middleware. It does not rewind request bodies, retry canceled requests, append a replacement response, or manufacture a success response. http.ErrAbortHandler remains an abort signal. Already committed downstream actions and response bytes cannot be undone. An outer recovery middleware can still choose a different response or retry policy.

The default, legacy-retry (also selected by an omitted or empty value), preserves the existing behavior, including possible duplicate downstream actions and retries with consumed bodies. Abort retries reuse the initially resolved client IP rather than resolving identity again from rewritten headers. Unknown values fail initialization. The default still permits downstream replay; OPS-16 is not fully resolved by adding this opt-in. Preserving compatibility avoids silently removing existing abort retries, at the cost of retaining that risk until a policy is agreed. Changing the default or removing deliberate abort retries requires maintainer agreement under OPS-16. This opt-in does not establish that agreement or change a live configuration. See synthetic replay results and the operator migration checklist for response semantics, the proposed policy, and remaining acceptance work.

Forwarded Identity Trust Boundary

X-Forwarded-For resolution starts at the socket peer (RemoteAddr). Headers from an untrusted peer are ignored. For a trusted peer, the plugin validates the entire XFF field, then walks from right to left through the contiguous suffix of addresses in the configured trusted ranges. The first untrusted hop is the client boundary, even when that address is private. It never skips an untrusted hop to select a public address further left.

For example, with only 192.0.2.0/24 trusted, a peer at 192.0.2.1 and XFF 198.51.100.66, 203.0.113.10, 192.0.2.2 resolve to 203.0.113.10. The socket peer and the rightmost hop are inside that range; the leftmost address cannot override that boundary. A trusted socket peer is sufficient when there are no additional trusted proxies in the header: 198.51.100.66, 203.0.113.10 still resolves to 203.0.113.10.

When XFF is selected, repeated header fields, empty or malformed entries, more than 32 hops, and values over 4,096 bytes return HTTP 400. If every parsed address is trusted, the plugin selects the first (leftmost) address after validating the complete chain. This supports home networks where clients and proxies all use trusted local addresses. Mixed chains still select the first untrusted hop from the right. Malformed entries are never silently dropped.

Trust only proxy ranges controlled by your deployment. Every trusted proxy must remove or sanitize client-supplied identity headers and accurately append its observed upstream peer to XFF (or replace the chain with a verified client address). The existing trustLocal default trusts broad private ranges; operators must review whether those ranges contain untrusted clients. No trust configuration is changed automatically.

Header priority remains Cf-Connecting-Ip, Eo-Connecting-Ip, X-Real-IP, then XFF; a valid higher-priority header bypasses XFF resolution, except a private or link-local X-Real-IP. That skip covers loopback, RFC 1918, IPv6 unique-local, and link-local unicast and multicast, including IPv4-mapped forms of those addresses. It does not cover other non-routable space such as 100.64.0.0/10. Resolution then continues with XFF, or uses the socket peer when XFF is absent. Cf-Connecting-Ip and Eo-Connecting-Ip are accepted even when the address is private. Trusted proxies must strip or overwrite those headers as well. xForwardedForMode only controls the outgoing header. append retains incoming entries, including an untrusted prefix; downstream consumers must not treat every retained entry as authoritative. Use replace when a downstream consumer requires a single resolved client address.

Malformed identity headers return a fixed response without echoing their values. Validation diagnostics are emitted only at debug level, contain header lengths rather than raw values, and do not include stack traces. Single-address identity headers are limited to 45 bytes.

Private-network trust and migration

A trusted address means authorized to assert another host's identity, not simply permitted to connect. The plugin cannot distinguish a private client from a private proxy by address syntax. trustLocal: true includes RFC1918, loopback, IPv6 unique-local and link-local ranges. The defaults are unchanged: trusting these networks intentionally allows hosts within them to assert client identity.

An existing middleware configuration illustrates this private-network preference:

trustLocal: true
trustCloudFlare: true
trustedIPs: []
xForwardedForMode: append

For a synthetic example, peer 10.0.0.1 with XFF 10.20.0.10, 10.0.0.2 resolves to 10.20.0.10 under broad local trust. A single trusted hop 10.20.0.10 also resolves to that address. IPv6 works the same way: peer fd00::1 with fd20::10, fd00::2 resolves to fd20::10. An all-trusted chain is not rejected solely for lacking an untrusted hop.

The leftmost address does not independently prove the actual origin. For example, a trusted host can prepend 10.99.0.66 to the IPv4 chain above, and the resulting all-trusted chain resolves to that asserted address. A trusted host can also forward a fabricated public address: 203.0.113.66, 10.20.0.10, 10.0.0.2 resolves to 203.0.113.66 as the first untrusted hop from the right. This is the authority granted by broad private-network trust. By contrast, 10.99.0.66, 203.0.113.10, 10.0.0.2 resolves to 203.0.113.10; the untrusted boundary prevents a further-left prefix from overriding it.

Operators who prefer to separate clients from proxies can evaluate trustLocal: false and trust only verified proxy hosts or dedicated proxy subnets in an isolated environment. With only 10.0.0.1/32 and 10.0.0.2/32 trusted, the chain 203.0.113.66, 10.20.0.10, 10.0.0.2 resolves to private client 10.20.0.10. The equivalent IPv6 fixture trusts fd00::1/128, fd00::2/128 with client fd20::10. These are synthetic examples, not selected deployment ranges. Any operator policy change affects all identity headers and can affect denyUntrusted; review enabled provider ranges and test both direct and proxied traffic. No default or live trust settings are changed by this PR.

xForwardedForMode only changes the outgoing header; it does not change identity selection. Trusted proxies must sanitize identity headers according to the authority their operators intend to grant. Synthetic tests cover the existing broad-trust configuration, precise proxy ranges, accepted all-trusted assertions, and mixed-chain boundaries with offline fixtures.

Scoped trust

scopedTrust: true replaces the single trusted list with one list per header, for deployments where each listener has a known kind of peer:

HeaderAccepted only from
Cf-Connecting-IpCloudflare ranges (trustCloudFlare) or cloudflareTrustedIPs, and with a valid edge secret when cloudflareAuthHeader is set
Eo-Connecting-IpEdgeOne ranges (trustEdgeOne)
X-Real-IP, X-Forwarded-ForforwardedTrustedIPs

A private or link-local X-Real-IP from a forwarded peer is skipped, as in the default mode. Resolution then uses X-Forwarded-For, or the socket peer when that header is absent.

Every other peer is its own client address. After resolution the plugin removes every identity assertion (Cf-Connecting-Ip, Cf-Connecting-Ipv6, Cf-Pseudo-Ipv4, Eo-Connecting-Ip, True-Client-Ip, X-Client-Ip, X-Cluster-Client-Ip, X-Original-Forwarded-For, Fastly-Client-Ip, Forwarded, X-Is-Trusted and the edge-secret header) and writes the resolved address as the only X-Real-IP and X-Forwarded-For value. trustLocal is ignored and trustedIPs is rejected in this mode.

Cloudflare publishes one set of edge addresses for all customers, so any Cloudflare zone can send Cf-Connecting-Ip to your public address. To accept only your own zone, add the secret at the edge (for example with a request header Transform Rule) and configure the same value here:

http:
middlewares:
traefik-real-ip:
plugin:
traefik-real-ip:
scopedTrust: true
trustCloudFlare: false
cloudflareTrustedIPs: ["10.42.0.0/16"] # cloudflared pods
cloudflareAuthHeader: X-Edge-Auth
cloudflareAuthSecretFile: /etc/traefik/secrets/EDGE_AUTH

When cloudflareAuthHeader is set, a Cloudflare peer is refused with 403 unless the request carries exactly one matching secret and a Cf-Connecting-Ip header. A valid secret without that header is also refused. Peers outside the Cloudflare ranges are unaffected, including when the secret file is missing or invalid. The file may hold two non-empty lines (current and previous secret, each at least 16 bytes) so rotation has no gap; it is re-read within ten seconds of changing. A missing or invalid file does not stop the middleware from loading: requests that need the secret are refused and the error is logged.

Scoped mode trusts addresses, not connections. Pair each listener with network controls that guarantee which peers can reach it.

Protecting Against Direct Access

If your server has a public IP but uses a WAF/CDN like Cloudflare, you may want to ensure that traffic can only reach your server through the WAF/CDN. Enable the denyUntrusted option to reject any traffic that doesn't come from trusted IP ranges (such as Cloudflare IPs).

http:
middlewares:
traefik-real-ip:
plugin:
traefik-real-ip:
trustCloudFlare: true
denyUntrusted: true

With this configuration, requests that bypass Cloudflare and reach your server directly will receive a 403 Forbidden response.

Development

Testing Locally

A Docker Compose setup is provided in the testing folder to test the plugin locally:

cd testing
docker compose up -d

Running Tests

make test

Tests serve checked-in provider snapshots and use loopback HTTP fixtures; external service requests are blocked. Run make lint and go build ./... for the other local checks. Actual proxy append/sanitization behavior and Traefik/Yaegi integration still require an isolated acceptance environment before deployment.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Publishing and manual recovery: Publishing.