Skip to content

Commit 1fd8dec

Browse files
MaiAdityaFarhanAliRazamasenf
authored
fix: validate the trusted X-Forwarded-For entry as client_ip (#7880)
* fix: validate the trusted X-Forwarded-For entry as client_ip With trusted_proxy_hops set, the selected X-Forwarded-For entry became router.session.client_ip verbatim, so values with a port or that were not addresses at all were passed through. Normalize the entry with ipaddress.ip_address after dropping a port and IPv6 brackets, and fall back to the peer address (logging at debug level) when it is not a valid address. Fixes #7854 * fix: reject malformed brackets and ports in X-Forwarded-For entries An unclosed bracket, text after the closing bracket or a non-numeric port now falls back to the peer address instead of being trimmed away. The log test only looks at the reflex.app debug records. * fix: reject IPv6 zone indexes in X-Forwarded-For entries ipaddress keeps the text after % without validating it, so a client could still choose its own client_ip through it. A zone only means something on the proxy's own host, so such entries now fall back to the peer address. * fix: unmap IPv4-mapped X-Forwarded-For entries and reject out-of-range ports A dual-stack proxy writes an IPv4 client as ::ffff:a.b.c.d, which gave the same client a second client_ip. A port above 65535 is malformed like the other rejected forms; the length cap also keeps int() under Python's integer-string conversion limit. --------- Co-authored-by: Farhan <www.mfarvirus@gmail.com> Co-authored-by: Masen Furer <m_github@0x26.net>
1 parent 27297ec commit 1fd8dec

4 files changed

Lines changed: 94 additions & 2 deletions

File tree

‎docs/advanced_onboarding/configuration.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ config = rx.Config(
151151
)
152152
```
153153

154-
For example, `trusted_proxy_hops=1` uses the rightmost `X-Forwarded-For` entry; `2` uses the second entry from the right. The same entry of `X-Forwarded-Host` and `X-Forwarded-Proto` is used when the backend checks the origin of a WebSocket connection (see [CORS](#cors)). Proxies usually set these two headers instead of appending to them, so when one has fewer entries than `trusted_proxy_hops`, its leftmost entry is used. The default is `0`. Do not enable forwarded-header trust if untrusted clients can connect directly to the backend or bypass the trusted proxy chain. The setting can also be provided as `REFLEX_TRUSTED_PROXY_HOPS`.
154+
For example, `trusted_proxy_hops=1` uses the rightmost `X-Forwarded-For` entry; `2` uses the second entry from the right. The entry is normalized to an IP address after dropping any port and IPv6 brackets, and an IPv4-mapped IPv6 address such as `::ffff:203.0.113.7` becomes its IPv4 address; if it is not a valid address, it is ignored and the connection's peer address is used. The same entry of `X-Forwarded-Host` and `X-Forwarded-Proto` is used when the backend checks the origin of a WebSocket connection (see [CORS](#cors)). Proxies usually set these two headers instead of appending to them, so when one has fewer entries than `trusted_proxy_hops`, its leftmost entry is used. The default is `0`. Do not enable forwarded-header trust if untrusted clients can connect directly to the backend or bypass the trusted proxy chain. The setting can also be provided as `REFLEX_TRUSTED_PROXY_HOPS`.
155155

156156
## Plugins
157157

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`router.session.client_ip` now normalizes the `X-Forwarded-For` entry selected by `trusted_proxy_hops` to an IP address, dropping any port and IPv6 brackets and unmapping IPv4-mapped IPv6 addresses, and falls back to the connection's peer address when the entry is not a valid address.

‎reflex/app.py‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import functools
1010
import importlib
1111
import inspect
12+
import ipaddress
1213
import json
1314
import logging
1415
import operator
@@ -658,6 +659,50 @@ def _trusted_forwarded_value(
658659
return None if appended or not entries else entries[0]
659660

660661

662+
def _is_port(text: str) -> bool:
663+
"""Return whether text is a port number.
664+
665+
Args:
666+
text: The text after the ``:`` of an address.
667+
668+
Returns:
669+
Whether the text is ASCII digits for a number from 0 to 65535.
670+
"""
671+
return len(text) <= 5 and text.isascii() and text.isdigit() and int(text) < 65536
672+
673+
674+
def _forwarded_client_ip(entry: str) -> str | None:
675+
"""Normalize an ``X-Forwarded-For`` entry to an IP address.
676+
677+
Args:
678+
entry: The entry, an IP address with an optional port and IPv6 brackets.
679+
680+
Returns:
681+
The normalized address, or None when the entry is not an IP address.
682+
"""
683+
if entry.startswith("["):
684+
entry, closed, rest = entry[1:].partition("]")
685+
port_ok = not rest or (rest.startswith(":") and _is_port(rest[1:]))
686+
if not closed or not port_ok:
687+
return None
688+
elif entry.count(":") == 1:
689+
entry, _, port = entry.partition(":")
690+
if not _is_port(port):
691+
return None
692+
if "%" in entry:
693+
# A zone index only means something on the proxy's own host, and
694+
# ``ipaddress`` keeps it without validating it.
695+
return None
696+
try:
697+
ip = ipaddress.ip_address(entry)
698+
except ValueError:
699+
return None
700+
# A dual-stack proxy writes an IPv4 client as ``::ffff:a.b.c.d``.
701+
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
702+
ip = ip.ipv4_mapped
703+
return str(ip)
704+
705+
661706
def _origin_matches_request(
662707
origin: str, hosts: Iterable[str | None], forwarded_proto: str | None
663708
) -> bool:
@@ -2774,7 +2819,13 @@ def _build_static_router_data(self, sid: str, environ: dict) -> dict[str, Any]:
27742819
headers.get("x-forwarded-for", ""), get_config().trusted_proxy_hops
27752820
)
27762821
if forwarded_ip is not None:
2777-
client_ip = forwarded_ip
2822+
if (normalized_ip := _forwarded_client_ip(forwarded_ip)) is not None:
2823+
client_ip = normalized_ip
2824+
else:
2825+
logger.debug(
2826+
f"Ignoring X-Forwarded-For entry {_clip(forwarded_ip)}: "
2827+
"not an IP address."
2828+
)
27782829
return {
27792830
constants.RouteVar.SESSION_ID: sid,
27802831
constants.RouteVar.HEADERS: headers,

‎tests/units/test_app.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5113,6 +5113,22 @@ def test_static_router_data_keeps_every_repeated_header_field(
51135113
(1, "203.0.113.7", "10.0.0.2", "203.0.113.7"),
51145114
(2, "6.6.6.6, 203.0.113.7, 10.0.0.2", "127.0.0.1", "203.0.113.7"),
51155115
(2, "203.0.113.7", "10.0.0.2", "10.0.0.2"),
5116+
(1, "203.0.113.7:51234", "10.0.0.2", "203.0.113.7"),
5117+
(1, "[2001:db8::1]:443", "10.0.0.2", "2001:db8::1"),
5118+
(1, "[2001:db8::1]", "10.0.0.2", "2001:db8::1"),
5119+
(1, "2001:db8:0:0:0:0:0:1", "10.0.0.2", "2001:db8::1"),
5120+
(1, "6.6.6.6, not an ip <script>", "10.0.0.2", "10.0.0.2"),
5121+
(1, "[2001:db8::1", "10.0.0.2", "10.0.0.2"),
5122+
(1, "[2001:db8::1]junk", "10.0.0.2", "10.0.0.2"),
5123+
(1, "[2001:db8::1]:", "10.0.0.2", "10.0.0.2"),
5124+
(1, "203.0.113.7:garbage", "10.0.0.2", "10.0.0.2"),
5125+
(1, "203.0.113.7:", "10.0.0.2", "10.0.0.2"),
5126+
(1, "203.0.113.7:65536", "10.0.0.2", "10.0.0.2"),
5127+
(1, "[2001:db8::1]:100000", "10.0.0.2", "10.0.0.2"),
5128+
(1, "::ffff:203.0.113.7", "10.0.0.2", "203.0.113.7"),
5129+
(1, "[::ffff:203.0.113.7]:443", "10.0.0.2", "203.0.113.7"),
5130+
(1, "fe80::1%not an ip <script>", "10.0.0.2", "10.0.0.2"),
5131+
(1, "[fe80::1%eth0]:443", "10.0.0.2", "10.0.0.2"),
51165132
],
51175133
)
51185134
def test_static_router_data_resolves_client_ip_from_trusted_proxy_hops(
@@ -5140,6 +5156,30 @@ def test_static_router_data_resolves_client_ip_from_trusted_proxy_hops(
51405156
assert router_data[constants.RouteVar.CLIENT_IP] == expected_ip
51415157

51425158

5159+
def test_static_router_data_logs_ignored_forwarded_client_ip(
5160+
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
5161+
):
5162+
"""A forwarded entry that is not an IP address is logged and ignored."""
5163+
monkeypatch.setattr("reflex.app.get_config", lambda: Mock(trusted_proxy_hops=1))
5164+
with caplog.at_level(logging.DEBUG, logger="reflex.app"):
5165+
router_data = EventNamespace("/event", Mock())._build_static_router_data(
5166+
"sid1",
5167+
{
5168+
"asgi.scope": {
5169+
"headers": [(b"x-forwarded-for", b"not an ip <script>")],
5170+
"client": ("10.0.0.2", 1234),
5171+
}
5172+
},
5173+
)
5174+
5175+
assert router_data[constants.RouteVar.CLIENT_IP] == "10.0.0.2"
5176+
assert [
5177+
record.getMessage()
5178+
for record in caplog.records
5179+
if record.name == "reflex.app" and record.levelno == logging.DEBUG
5180+
] == ["Ignoring X-Forwarded-For entry 'not an ip <script>': not an IP address."]
5181+
5182+
51435183
def test_call_ignores_stale_marker_without_dev_backend_reload(
51445184
compilable_app: tuple[App, Path],
51455185
mocker: MockerFixture,

0 commit comments

Comments
 (0)