Any application that reads a client IP address from X-Forwarded-For without knowing which proxy wrote each entry is letting the client choose its own IP address. That one mistake turns IP allowlists into suggestions, lets abusers rotate past rate limits, and fills audit logs with addresses nobody can rely on in an investigation. This guide explains how forwarding headers are built, why the leftmost entry is untrustworthy, and the trust model that works: count or list your own proxies, then read from the right. It is written for web developers, platform engineers and application security teams, and stays framework neutral, with configuration examples from common servers and frameworks to show the pattern.
Key takeaways
- The header is client-writable. RFC 7239 states that forwarding headers cannot be relied upon to be correct, because any node on the path, including the client, can modify them.
- Read from the right, stop at the first untrusted address. Only entries appended by proxies you control are trustworthy; the first address to the left of your last trusted proxy is the client for security purposes.
- Direct reachability voids the model. MDN warns that if the server can be reached directly from the internet, no part of the list can be trusted for security uses, even when a reverse proxy also sits in front.
- Trust is configured per hop. Each layer (CDN, load balancer, ingress, application) needs an explicit trusted-proxy list or hop count; a single
trust allsetting anywhere re-opens spoofing. - Log both addresses. Record the TCP peer and the derived client IP separately so investigations can see what was claimed and what was proven.
How proxy headers work
When a request passes through a reverse proxy, the TCP connection the application sees comes from the proxy, not the user. To preserve the original address, proxies add headers. X-Forwarded-For is the de facto standard; MDN describes its syntax as a comma-separated list, <client>, <proxy1>, ..., <proxyN>, where each proxy appends the address it received the connection from. The rightmost entry is therefore written by the most recent proxy, and the leftmost entry is the original client only if every hop behaved.
| Header | Carries | Defined by | Typical consumer |
|---|---|---|---|
X-Forwarded-For | Chain of client and proxy addresses | De facto convention | Client IP for logging, rate limits, allowlists |
X-Forwarded-Proto | Original scheme (http or https) | De facto convention | Redirects, secure cookie flags, HSTS |
X-Forwarded-Host | Original Host header | De facto convention | Absolute URL and link generation |
X-Real-IP | Single client address | Proxy convention, common with nginx | Simple single-hop deployments |
Forwarded | for, by, host, proto per hop | RFC 7239 (Proposed Standard) | Structured forwarding information |
| PROXY protocol | Client address at the TCP layer, before HTTP | HAProxy specification | TCP load balancers in front of HTTP servers |
Two details trip up custom parsers. First, MDN notes a request may carry several X-Forwarded-For headers, which must be treated as one list in order; reading only one is insufficient. Second, entries may carry ports (AWS Application Load Balancer can add the client port when routing.http.xff_client_port.enabled is set) and IPv6 addresses, so parse with a real IP library rather than string splitting alone.
Spoofing and allowlist bypass
The client can send any X-Forwarded-For value it likes. A proxy configured to append will add the real peer address to the right of the forged values, so the forged entries end up on the left. Any code that takes the first entry, or a framework setting that trusts every hop, hands control of the client IP to the client. This is the textbook example for CWE-348 Use of Less Trusted Source, whose demonstrative example is an IP allowlist that trusts X-Forwarded-For when present. When the derived address is used to authenticate or authorise, the weakness is also CWE-290 Authentication Bypass by Spoofing, with CWE-291 Reliance on IP Address for Authentication as a child.
| Where the client IP is used | Impact of a spoofed value | Control |
|---|---|---|
| Admin or internal-only allowlists | Access control bypass from the internet | Derive IP from trusted hops only; better, require authentication and do not rely on IP alone |
| Rate limiting and brute-force lockout | Attacker rotates fake addresses to avoid limits; or names a victim's IP to get it blocked | Key limits on the trusted client IP plus account or token identifiers |
| Audit and security logs | Investigations chase forged addresses; attribution fails | Log peer address and derived client IP as separate fields |
| Geo-blocking and fraud scoring | Location checks evaded | Use the trusted client IP; treat leftmost values as hints only |
Host and scheme headers (X-Forwarded-Host, -Proto) | Poisoned password-reset links, redirect loops, cookies issued without Secure | Trust these only from known proxies; restrict allowed hosts |
MDN lists the consequences of using untrustworthy values as rate-limiter avoidance, access-control bypass, memory exhaustion and other availability problems, and states that leftmost values must only be used where spoofing has no negative impact, for example analytics. AWS gives the same warning in its load balancer documentation: an entry is trustworthy only if a system you control added it.
The parsing rule
MDN describes two safe ways to select a security-relevant address. Both read the combined list from the right.
- Trusted proxy count: configure the number of reverse proxies between the internet and the application. With one proxy, the rightmost entry is the client; with three, the last two entries are internal and the third from the right is the client.
- Trusted proxy list: configure the addresses or CIDR ranges of your proxies. Walk from the right, skipping entries that match the list; the first non-matching address is the client.
The list method copes better with paths of different lengths. The count method breaks if any route reaches the application in fewer hops than configured: Express's documentation warns that a client able to take a shorter path can then spoof any value. In both methods, the first step is to check the TCP peer itself: if the connection did not come from a trusted proxy, ignore the header entirely. MDN adds a useful caveat: the address you select may belong to an untrusted intermediate proxy (a corporate egress proxy, for example) rather than the end user, but it is the only address suitable for security decisions.
Configuring trusted proxies
Every common server and framework implements the right-to-left rule if you configure it. The examples below are listed alphabetically and show each product's own setting names, taken from its documentation; the pattern, not the product, is the point.
| Product | Trusted proxy setting | Behaviour once set | Watch for |
|---|---|---|---|
Apache HTTP Server (mod_remoteip) | RemoteIPHeader X-Forwarded-For with RemoteIPTrustedProxy or RemoteIPInternalProxy | Processes right to left and halts at the first address not trusted to present the preceding one | The documentation states that without trusted proxy directives the module trusts all hosts presenting the header |
| ASP.NET Core (Forwarded Headers Middleware) | ForwardedHeadersOptions: ForwardedHeaders, KnownProxies, KnownNetworks, ForwardLimit (default 1) | Accepts headers only from known proxies, consumes entries right to left, keeps the previous address in X-Original-For | Clearing the known lists accepts headers from any peer; set AllowedHosts for X-Forwarded-Host |
| AWS Application Load Balancer | routing.http.xff_header_processing.mode: append (default), preserve, remove | Append adds the client IP to the right of any existing value | Targets must still read from the right and trust only the load balancer's addresses |
| Express (Node.js) | trust proxy: subnet names, addresses, hop count or function | Walks X-Forwarded-For right to left to the first untrusted address for req.ip | true takes the leftmost entry, so the last trusted proxy must overwrite the header |
nginx (ngx_http_realip_module) | set_real_ip_from CIDRs, real_ip_header X-Forwarded-For, real_ip_recursive on | With recursive on, uses the last non-trusted address in the header | Module is not built by default; with recursive off it takes the last address after a trusted peer |
Choosing a trust design
- Single reverse proxy on a private network: trust that proxy's address, take the rightmost entry, and block direct access to the application port.
- CDN, then load balancer, then application: trust a list, not a count: the CDN's published egress ranges plus your load balancer subnet. Refresh CDN ranges automatically, since providers change them.
- Edge proxy you fully control: configure it to overwrite, not append, the header with the peer address, so downstream services receive a single trusted value. Express's documentation describes exactly this requirement when
trust proxyistrue. - TCP load balancer without HTTP awareness: use PROXY protocol between the balancer and the HTTP server, and accept it only from the balancer.
- Small teams: one proxy and a framework trusted-proxy setting covers most cases. Large estates should define the trust chain once, as code, and test it in every environment because hop counts differ between staging and production.
The Forwarded header (RFC 7239)
RFC 7239, published in June 2014 as a Proposed Standard, defines Forwarded as a structured replacement for the X-Forwarded-* family. Each hop adds an element with up to four parameters: for (the client-facing address), by (the proxy's own interface), host (the original Host) and proto (the scheme). Its main advance is that values from one hop stay together, which the RFC notes is impossible with separate X-Forwarded headers.
- Same trust problem: section 8.1 states the header cannot be relied upon to be correct. Structure does not make it trustworthy; you still read from the right and trust only your proxies.
- IPv6 syntax: addresses must be bracketed and quoted, for example
for="[2001:db8:cafe::17]", because the colon is not allowed in a token. Parsers that do not handle quoting will mis-read entries. - Obfuscated identifiers: section 6.3 allows identifiers beginning with an underscore, such as
for=_hidden, to hide internal addresses while keeping traceability. - Information leakage: section 8.2 says origin servers should never copy the header into responses, as it can reveal internal network structure.
- Conversion: section 7.4 describes converting
X-Forwarded-Forby prefixing entries withfor=, and warns conversion may be impossible when severalX-Forwardedheaders are present because their order relative to each other is unknown.
In practice, support for Forwarded is uneven across proxies and frameworks, and many deployments emit both. Pick one header as authoritative per hop, configure every proxy to strip the other from inbound client requests, and test that a client-supplied value of either never reaches the application unchallenged.
Logging the right client IP
Logs are where a wrong trust model does quiet, long-term damage. An incident responder asking "which address made this request" needs to know what the network proved and what a header claimed.
- Two fields, always: log the TCP peer address and the derived client IP. Apache's
mod_remoteipdocuments this directly:%alogs the overridden client address and%{c}athe underlying connection address. nginx exposes the original peer as$realip_remote_addr, and ASP.NET Core keeps it inX-Original-For. - Keep the raw header: store the full
X-Forwarded-Forvalue in security logs (subject to retention rules), so a mis-configured trust setting can be corrected after the fact. - Treat it as personal data: MDN and RFC 7239 both flag client IP addresses as privacy-sensitive; apply your logging retention and minimisation rules.
- Consistency across layers: CDN, load balancer, WAF and application logs should resolve the same client IP for the same request; mismatches point to a trust gap.
Detection and metrics
- Header from untrusted peers: count requests where a forwarding header arrives from a peer outside the trusted list (ASP.NET Core logs unknown proxies); in a correct design this should be near zero at the application tier.
- Leftmost and derived mismatch: track the share of requests where the leftmost entry differs from the derived client IP; sudden spikes from one peer suggest spoofing attempts.
- Private or loopback client IPs: derived client addresses in
127.0.0.0/8or RFC 1918 space at an internet-facing tier usually mean a trust misconfiguration. - Direct-access attempts: connections to application ports from addresses that are not your proxies, which should be blocked at the network layer.
- Test coverage: percentage of internet-facing services with an automated test that sends a forged header and asserts the derived IP is unchanged.
Implementation plan
- Map the chain: for each internet-facing service, list every hop (CDN, WAF, load balancer, ingress, sidecar) with its addresses and whether it appends, overwrites or passes the header.
- Close direct paths: restrict application ports so only the last trusted proxy can connect; without this step, nothing else holds.
- Configure each hop: set trusted proxy lists in servers and frameworks, prefer lists to counts, and set the edge to overwrite where possible.
- Test in staging: send requests with forged
X-Forwarded-For,X-Forwarded-HostandForwardedvalues and confirm the derived IP, host and scheme match the real path. Repeat in production with harmless requests. - Move security decisions: key rate limits and lockouts on the derived IP plus user or token identifiers; review every IP allowlist and add authentication behind it.
- Update logging: add peer and derived IP fields and the raw header; update SIEM parsers.
- Roll back safely: if a new trust list breaks legitimate traffic, revert to the previous configuration while fixing the list, but do not fall back to trusting all peers.
Framework mapping
| Framework | Reference | Relevance |
|---|---|---|
| MITRE CWE | CWE-348 Use of Less Trusted Source | Choosing the client-supplied header over the verified peer |
| MITRE CWE | CWE-290 Authentication Bypass by Spoofing; CWE-291 Reliance on IP Address for Authentication | IP allowlists used as authentication |
| NIST SP 800-53 Rev 5 | AC-3 Access Enforcement; SI-10 Information Input Validation | Treat headers as untrusted input before use in decisions |
| NIST SP 800-53 Rev 5 | AU-3 Content of Audit Records; SC-5 Denial-of-service Protection | Accurate source in logs; rate limits that cannot be evaded |
| NIST CSF 2.0 | PR.PS-04, DE.AE-02 | Log records fit for monitoring and analysis |
Practitioner checklist
- Document the proxy chain for every internet-facing service, including which hops append or overwrite.
- Block direct network access to application ports from anything except the last trusted proxy.
- Configure trusted proxy lists (preferred) or exact hop counts in every server and framework; never trust all peers.
- Read
X-Forwarded-Forfrom the right, combining multiple headers into one list, and stop at the first untrusted address. - Strip or overwrite client-supplied forwarding headers at the edge.
- Trust
X-Forwarded-HostandX-Forwarded-Protoonly from known proxies and restrict allowed hosts. - Key rate limits on derived IP plus account or token, and put authentication behind IP allowlists.
- Log peer address, derived client IP and the raw header as separate fields.
- Add an automated forged-header test to each service's pipeline.
Standards and references
- IETF: RFC 7239 Forwarded HTTP Extension
- MITRE: CWE-348 Use of Less Trusted Source
- MDN: X-Forwarded-For
- Apache Software Foundation: mod_remoteip
- Microsoft: Configure ASP.NET Core to work with proxy servers and load balancers
- AWS: HTTP headers and Application Load Balancers
- Express: Express behind proxies
- nginx: Module ngx_http_realip_module
Related NHI Mgmt Group resources: Proxies and Forward vs Reverse Proxy Security Guide · Rate Limiting and API Abuse Guide · API Gateway vs Reverse Proxy · Secure Logging Vocabulary and Application Security Events Guide