From 9bbfbc82231b390ae776d2c96446eb1eaa708162 Mon Sep 17 00:00:00 2001 From: Hans Ott Date: Sat, 14 Nov 2026 13:25:10 +0100 Subject: [PATCH 01/15] Add proxy CIDR and hop trust with right-to-left IP selection --- aikido_zen/context/__init__.py | 2 + aikido_zen/context/asgi/__init__.py | 2 + aikido_zen/context/init_test.py | 47 +++++++ aikido_zen/context/wsgi/__init__.py | 7 +- aikido_zen/helpers/get_ip_from_request.py | 65 +++++---- .../helpers/get_ip_from_request_test.py | 126 +++++++++++++----- aikido_zen/helpers/trust_proxy.py | 57 ++++++++ .../ssrf/find_hostname_in_context.py | 4 +- .../ssrf/is_request_to_itself.py | 7 +- .../ssrf/is_request_to_itself_test.py | 91 +++++-------- docs/proxy.md | 46 ++++++- 11 files changed, 326 insertions(+), 128 deletions(-) create mode 100644 aikido_zen/helpers/trust_proxy.py diff --git a/aikido_zen/context/__init__.py b/aikido_zen/context/__init__.py index 81b1dff5c..2eb47d515 100644 --- a/aikido_zen/context/__init__.py +++ b/aikido_zen/context/__init__.py @@ -58,6 +58,7 @@ def __init__(self, context_obj=None, body=None, req=None, source=None): # Parse WSGI/ASGI/... request : self.method = self.remote_address = self.url = None + self.is_behind_trusted_proxy = False if source in WSGI_SOURCES: set_wsgi_attributes_on_context(self, req) elif source in ASGI_SOURCES: @@ -79,6 +80,7 @@ def __reduce__(self): { "method": self.method, "remote_address": self.remote_address, + "is_behind_trusted_proxy": self.is_behind_trusted_proxy, "url": self.url, "body": self.body, "headers": self.headers, diff --git a/aikido_zen/context/asgi/__init__.py b/aikido_zen/context/asgi/__init__.py index 71f047a4b..aa9dd0e58 100644 --- a/aikido_zen/context/asgi/__init__.py +++ b/aikido_zen/context/asgi/__init__.py @@ -3,6 +3,7 @@ from urllib.parse import parse_qs from aikido_zen.helpers.get_ip_from_request import get_ip_from_request from aikido_zen.helpers.logging import logger +from aikido_zen.helpers.trust_proxy import is_trusted_proxy_request from ..parse_cookies import parse_cookies from .normalize_asgi_headers import normalize_asgi_headers from .build_url_from_asgi import build_url_from_asgi @@ -25,3 +26,4 @@ def set_asgi_attributes_on_context(context, scope): raw_ip = scope["client"][0] if scope["client"] else "" context.remote_address = get_ip_from_request(raw_ip, context.headers) + context.is_behind_trusted_proxy = is_trusted_proxy_request(raw_ip) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index 2c4c47135..ce0507109 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -50,6 +50,7 @@ def test_wsgi_context_1(): } context = Context(req=wsgi_request, body=123, source="django") assert context.__dict__ == { + "is_behind_trusted_proxy": True, "source": "django", "method": "POST", "headers": { @@ -83,6 +84,7 @@ def test_wsgi_context_1(): def test_wsgi_context_2(): context = Context(req=basic_wsgi_req, body={"test": True}, source="flask") assert context.__dict__ == { + "is_behind_trusted_proxy": True, "source": "flask", "method": "GET", "headers": { @@ -114,6 +116,50 @@ def test_wsgi_context_2(): assert context.get_user_agent() == "Mozilla/5.0" +@pytest.mark.parametrize("source", ["flask", "starlette"]) +@pytest.mark.parametrize( + "setting, peer, trusted, client_ip", + [ + ("1.2.3.0/24", "1.2.3.4", True, "9.9.9.9"), + ("1.2.3.0/24", "8.8.8.8", False, "8.8.8.8"), + ("false", "1.2.3.4", False, "1.2.3.4"), + ("2", "1.2.3.4", True, "9.9.9.9"), + ], +) +def test_proxy_trust_in_request_context( + monkeypatch, source, setting, peer, trusted, client_ip +): + from aikido_zen.vulnerabilities.ssrf.find_hostname_in_context import ( + find_hostname_in_context, + ) + + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) + if source == "flask": + request = dict(basic_wsgi_req) + request["REMOTE_ADDR"] = peer + request["HTTP_X_FORWARDED_FOR"] = "9.9.9.9, 1.2.3.5" + else: + request = { + "method": "GET", + "headers": [ + (b"host", b"localhost:8080"), + (b"x-forwarded-for", b"9.9.9.9, 1.2.3.5"), + ], + "query_string": b"", + "client": (peer, 1234), + "server": ("localhost", 8080), + "scheme": "http", + "root_path": "", + "path": "/hello", + } + context = Context(req=request, body={"url": "http://localhost:8080"}, source=source) + assert context.remote_address == client_ip + assert context.is_behind_trusted_proxy is trusted + assert (find_hostname_in_context("localhost", context, 8080) is None) is trusted + restored = pickle.loads(pickle.dumps(context)) + assert restored.is_behind_trusted_proxy is trusted + + def test_set_as_current_context(mocker): # Test set_as_current_context() method context = Context(req=basic_wsgi_req, body=12, source="flask") @@ -135,6 +181,7 @@ def test_context_is_picklable(mocker): assert unpickled_obj.source == "flask" assert unpickled_obj.method == "GET" assert unpickled_obj.remote_address == "198.51.100.23" + assert unpickled_obj.is_behind_trusted_proxy is True assert unpickled_obj.url == "http://localhost:8080/hello" assert unpickled_obj.body == 123 assert unpickled_obj.headers == { diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index f90a47369..71479629e 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -3,6 +3,7 @@ from urllib.parse import parse_qs from aikido_zen.helpers.get_ip_from_request import get_ip_from_request from aikido_zen.helpers.logging import logger +from aikido_zen.helpers.trust_proxy import is_trusted_proxy_request from .extract_wsgi_headers import extract_wsgi_headers from .build_url_from_wsgi import build_url_from_wsgi from ..parse_cookies import parse_cookies @@ -23,9 +24,9 @@ def set_wsgi_attributes_on_context(context, environ): context.cookies = {} context.url = build_url_from_wsgi(environ) context.query = parse_qs(environ["QUERY_STRING"]) - context.remote_address = get_ip_from_request( - environ["REMOTE_ADDR"], context.headers - ) + raw_ip = environ["REMOTE_ADDR"] + context.remote_address = get_ip_from_request(raw_ip, context.headers) + context.is_behind_trusted_proxy = is_trusted_proxy_request(raw_ip) # Content type is generally not included as a header, do include this as a header to simplify : if "CONTENT_TYPE" in environ: diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index 73de267ab..816a6f2a5 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -7,7 +7,15 @@ from typing import Optional from aikido_zen.helpers.headers import Headers +from aikido_zen.helpers.ip_matcher import preparse from aikido_zen.helpers.logging import logger +from aikido_zen.helpers.net.is_private_ip import is_private_ip +from aikido_zen.helpers.trust_proxy import ( + CIDRTrustProxy, + CountTrustProxy, + get_trust_proxy_config, + is_trusted_proxy_request, +) def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: @@ -15,7 +23,7 @@ def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: Tries and get the IP address from the request, checking for x-forwarded-for """ ip_header = headers.get_header(get_ip_header_name()) - if ip_header and trust_proxy(): + if ip_header and is_trusted_proxy_request(remote_address): ip_header_value = get_client_ip_from_header(ip_header) if ip_header_value and is_ip(ip_header_value): @@ -31,32 +39,41 @@ def get_client_ip_from_header(value): """ Fetches the IP out of the X-Forwarder-For headers """ - forwarded_ips = [ip.strip() for ip in value.split(",")] - - for ip in forwarded_ips: - if ":" in ip: - parts = ip.split(":") - if len(parts) == 2: - return parts[0] - - for ip in forwarded_ips: - if is_ip(ip): - return ip - + config = get_trust_proxy_config() + forwarded_ips = value.split(",") + if isinstance(config, CountTrustProxy): + index = len(forwarded_ips) - config.value + if index < 0: + return None + ip = normalize_ip(forwarded_ips[index].strip()) + return ip if is_ip(ip) else None + + for index in range(len(forwarded_ips) - 1, -1, -1): + ip = normalize_ip(forwarded_ips[index].strip()) + if not is_ip(ip): + continue + normalized_ip = preparse(ip) + if is_private_ip(normalized_ip): + continue + if isinstance(config, CIDRTrustProxy) and config.matcher.has(normalized_ip): + continue + return ip return None -def trust_proxy(): - """ - Checks the environment variables for `AIKIDO_TRUST_PROXY`, Defaults to true. - """ - trust_proxy_env = os.getenv("AIKIDO_TRUST_PROXY") - if not trust_proxy_env: - return True # default to trusting proxy - - if trust_proxy_env.lower() in ["0", "false"]: - return False - return True +def normalize_ip(ip: str) -> str: + if is_ip(ip): + return ip + if ip.startswith("["): + if ip.endswith("]"): + return ip[1:-1] + closing_bracket = ip.find("]:") + if closing_bracket > 0: + return ip[1:closing_bracket] + parts = ip.split(":") + if len(parts) == 2: + return parts[0] + return ip def get_ip_header_name(): diff --git a/aikido_zen/helpers/get_ip_from_request_test.py b/aikido_zen/helpers/get_ip_from_request_test.py index d34404ddc..da7cf73f2 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -1,3 +1,5 @@ +import sys + import pytest from .get_ip_from_request import ( get_ip_from_request, @@ -5,6 +7,7 @@ get_client_ip_from_header, ) from .headers import Headers +from .trust_proxy import is_trusted_proxy_request @pytest.fixture(autouse=True) @@ -87,7 +90,7 @@ def test_x_forwarded_for_with_trust_proxy_multiple_ips(): # Test case 10: x-forwarded-for with trust proxy and multiple IPs headers = Headers() headers.store_header("x-forwarded-for", "9.9.9.9, 8.8.8.8, 7.7.7.7") - assert get_ip_from_request("1.2.3.4", headers) == "9.9.9.9" + assert get_ip_from_request("1.2.3.4", headers) == "7.7.7.7" def test_x_forwarded_for_with_trust_proxy_multiple_ips_ipv6(): @@ -99,7 +102,7 @@ def test_x_forwarded_for_with_trust_proxy_multiple_ips_ipv6(): ) assert ( get_ip_from_request("df89:84af:85e0:c55f:960c:341a:2cc6:734d", headers) - == "a3ad:8f95:d2a8:454b:cf19:be6e:73c6:f880" + == "791d:967e:428a:90b9:8f6f:4fcc:5d88:015d" ) @@ -138,7 +141,7 @@ def test_get_ip_from_different_header(monkeypatch): headers = Headers() headers.store_header("x-forwarded-for", "5.6.7.8, 192.168.0.1") headers.store_header("connecting-ip", "9.9.9.9") - assert get_ip_from_request("1.2.3.4", headers) == "5.6.7.8" + assert get_ip_from_request("1.2.3.4", headers) == "192.168.0.1" # Test case 6: Valid client ip header, but trust proxy 0 monkeypatch.setenv("AIKIDO_CLIENT_IP_HEADER", "connecting-ip") @@ -172,37 +175,90 @@ def test_invalid_ipv6(): assert not is_ip("::g") # Invalid IPv6 -# Test `get_client_ip_from_header` function : -def test_get_client_ip_from_header(): - # Test cases with valid IPs - assert get_client_ip_from_header("192.168.1.1") == "192.168.1.1" - assert get_client_ip_from_header("192.168.1.1, 10.0.0.1") == "192.168.1.1" - assert get_client_ip_from_header("10.0.0.1, 192.168.1.1") == "10.0.0.1" - assert ( - get_client_ip_from_header("2001:0db8:85a3:0000:0000:8a2e:0370:7334") - == "2001:0db8:85a3:0000:0000:8a2e:0370:7334" - ) - assert ( - get_client_ip_from_header( - "2001:0db8:85a3:0000:0000:8a2e:0370:7334, 192.168.1.1" - ) - == "2001:0db8:85a3:0000:0000:8a2e:0370:7334" - ) +@pytest.mark.parametrize( + "value, expected", + [ + ("192.168.1.1", None), + ("192.168.1.1, 10.0.0.1", None), + ("9.9.9.9, 8.8.8.8, 10.0.0.1, ::1", "8.8.8.8"), + ("9.9.9.9, invalid:8080, 256.256.256.256", "9.9.9.9"), + ("9.9.9.9:8080, 8.8.8.8:443", "8.8.8.8"), + ("9.9.9.9, [2606:4700::1111]:443", "2606:4700::1111"), + ("[2606:4700::1111], 192.168.1.1", "2606:4700::1111"), + ("::1, 2606:4700::1111", "2606:4700::1111"), + ("9.9.9.9, ::ffff:192.168.1.1", "9.9.9.9"), + ("abc.def.ghi.jkl, 256.256.256.256", None), + ("", None), + ], +) +def test_get_client_ip_from_header(value, expected): + assert get_client_ip_from_header(value) == expected + + +@pytest.mark.parametrize( + "setting, remote_address, value, expected", + [ + ("true", "1.2.3.4", "10.0.0.1, ::1", "1.2.3.4"), + ("false", "1.2.3.4", "9.9.9.9", "1.2.3.4"), + ("unknown", "1.2.3.4", "9.9.9.9", "1.2.3.4"), + ("YES", "1.2.3.4", "9.9.9.9", "9.9.9.9"), + ("2", "1.2.3.4", "9.9.9.9, 8.8.8.8, 7.7.7.7", "8.8.8.8"), + ("2", "1.2.3.4", "9.9.9.9, 10.0.0.1, 7.7.7.7", "10.0.0.1"), + ("2", "1.2.3.4", "9.9.9.9, ::1, 7.7.7.7", "::1"), + ( + "2", + "1.2.3.4", + "9.9.9.9, ::ffff:192.168.0.1, 7.7.7.7", + "::ffff:192.168.0.1", + ), + ("2", "1.2.3.4", "9.9.9.9, 10.0.0.1:1234, 7.7.7.7", "10.0.0.1"), + ("2", "1.2.3.4", "9.9.9.9, invalid, 7.7.7.7", "1.2.3.4"), + ("2", "1.2.3.4", "9.9.9.9, , 7.7.7.7", "1.2.3.4"), + ("4", "1.2.3.4", "9.9.9.9, 8.8.8.8", "1.2.3.4"), + ("1.2.3.0/24", "1.2.3.4", "9.9.9.9, 1.2.3.5", "9.9.9.9"), + ("1.2.3.0/24", "8.8.8.8", "9.9.9.9", "8.8.8.8"), + ("1.2.3.0/24", None, "9.9.9.9", None), + ("1.2.3.0/24", "1.2.3.4", "1.2.3.5, 10.0.0.1", "1.2.3.4"), + ("1.2.3.4", "1.2.3.4", "9.9.9.9, 1.2.3.4", "9.9.9.9"), + ( + " 1.2.3.0/24, 8.8.8.0/24, ", + "1.2.3.4", + "9.9.9.9, 8.8.8.8, 1.2.3.5", + "9.9.9.9", + ), + ( + "2606:4700::/32", + "2606:4700::1111", + "9.9.9.9, [2606:4700::1001]:443", + "9.9.9.9", + ), + ( + "1.2.3.0/24", + "::ffff:1.2.3.4", + "9.9.9.9, ::ffff:1.2.3.5", + "9.9.9.9", + ), + ("invalid.ip", "1.2.3.4", "9.9.9.9", "1.2.3.4"), + ], +) +def test_proxy_trust_modes(monkeypatch, setting, remote_address, value, expected): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) + headers = Headers() + headers.store_header("x-forwarded-for", value) + assert get_ip_from_request(remote_address, headers) == expected - # Test cases with mixed valid and invalid IPs - assert ( - get_client_ip_from_header("256.256.256.256, 192.168.1.1") == "192.168.1.1" - ) # Invalid IPv4 ignored - assert ( - get_client_ip_from_header("192.168.1.1, abc.def.ghi.jkl") == "192.168.1.1" - ) # Invalid IPv4 ignored - assert ( - get_client_ip_from_header("::1, 2001:0db8:85a3:0000:0000:8a2e:0370:7334") - == "::1" - ) # Valid IPv6 preferred - # Test cases with only invalid IPs - assert ( - get_client_ip_from_header("abc.def.ghi.jkl, 256.256.256.256") is None - ) # All invalid - assert get_client_ip_from_header("") is None # Empty string +@pytest.mark.skipif( + not hasattr(sys, "get_int_max_str_digits"), reason="No integer conversion limit" +) +def test_oversized_proxy_count_disables_trust(monkeypatch): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "9" * 5000) + original_limit = sys.get_int_max_str_digits() + try: + sys.set_int_max_str_digits(4300) + assert not is_trusted_proxy_request("1.2.3.4") + headers = Headers() + headers.store_header("x-forwarded-for", "9.9.9.9") + assert get_ip_from_request("1.2.3.4", headers) == "1.2.3.4" + finally: + sys.set_int_max_str_digits(original_limit) diff --git a/aikido_zen/helpers/trust_proxy.py b/aikido_zen/helpers/trust_proxy.py new file mode 100644 index 000000000..cc53840c4 --- /dev/null +++ b/aikido_zen/helpers/trust_proxy.py @@ -0,0 +1,57 @@ +import os +import re +from dataclasses import dataclass +from functools import lru_cache +from typing import Optional, Union + +from aikido_zen.helpers.ip_matcher import IPMatcher, preparse + + +@dataclass(frozen=True) +class BooleanTrustProxy: + value: bool + + +@dataclass(frozen=True) +class CountTrustProxy: + value: int + + +@dataclass(frozen=True) +class CIDRTrustProxy: + matcher: IPMatcher + + +TrustProxyConfig = Union[BooleanTrustProxy, CountTrustProxy, CIDRTrustProxy] + + +def get_trust_proxy_config() -> TrustProxyConfig: + return parse_trust_proxy(os.getenv("AIKIDO_TRUST_PROXY")) + + +@lru_cache(maxsize=1) +def parse_trust_proxy(value: Optional[str]) -> TrustProxyConfig: + if not value: + return BooleanTrustProxy(True) + if re.fullmatch(r"[0-9]+", value): + try: + count = int(value) + except ValueError: + return BooleanTrustProxy(False) + if count > 0: + return CountTrustProxy(count) + if value.lower() in ("true", "1", "yes", "y", "on"): + return BooleanTrustProxy(True) + if "." in value or ":" in value: + ranges = [entry.strip() for entry in value.split(",") if entry.strip()] + return CIDRTrustProxy(IPMatcher(ranges)) + return BooleanTrustProxy(False) + + +def is_trusted_proxy_request(remote_address: Optional[str]) -> bool: + config = get_trust_proxy_config() + if isinstance(config, BooleanTrustProxy): + return config.value + if isinstance(config, CIDRTrustProxy): + return bool(remote_address) and config.matcher.has(preparse(remote_address)) + return True diff --git a/aikido_zen/vulnerabilities/ssrf/find_hostname_in_context.py b/aikido_zen/vulnerabilities/ssrf/find_hostname_in_context.py index 19091a7d2..af58f6678 100644 --- a/aikido_zen/vulnerabilities/ssrf/find_hostname_in_context.py +++ b/aikido_zen/vulnerabilities/ssrf/find_hostname_in_context.py @@ -17,7 +17,9 @@ def find_hostname_in_context(hostname, context: Context, port): # We don't want to block outgoing requests to the same host as the server # (often happens that we have a match on headers like `Host`, `Origin`, `Referer`, etc.) - if is_request_to_itself(context.url, hostname, port): + if is_request_to_itself( + context.url, hostname, port, context.is_behind_trusted_proxy + ): return None # Gets the different hostname options: with/without punycode, with/without brackets for IPv6 diff --git a/aikido_zen/vulnerabilities/ssrf/is_request_to_itself.py b/aikido_zen/vulnerabilities/ssrf/is_request_to_itself.py index a3676c75c..523416808 100644 --- a/aikido_zen/vulnerabilities/ssrf/is_request_to_itself.py +++ b/aikido_zen/vulnerabilities/ssrf/is_request_to_itself.py @@ -1,9 +1,10 @@ -from aikido_zen.helpers.get_ip_from_request import trust_proxy from aikido_zen.helpers.get_port_from_url import get_port_from_url from aikido_zen.helpers.try_parse_url import try_parse_url -def is_request_to_itself(server_url, outbound_hostname, outbound_port): +def is_request_to_itself( + server_url, outbound_hostname, outbound_port, is_behind_trusted_proxy +): """ We don't want to block outgoing requests to the same host as the server (often happens that we have a match on headers like `Host`, `Origin`, `Referer`, etc.) @@ -13,7 +14,7 @@ def is_request_to_itself(server_url, outbound_hostname, outbound_port): # When the app is not behind a reverse proxy, we can't trust the hostname inside `server_url` # The hostname in `server_url` is built from the request headers # The headers can be manipulated by the client if the app is directly exposed to the internet - if not trust_proxy(): + if not is_behind_trusted_proxy: return False base_url = try_parse_url(server_url) diff --git a/aikido_zen/vulnerabilities/ssrf/is_request_to_itself_test.py b/aikido_zen/vulnerabilities/ssrf/is_request_to_itself_test.py index 5049c2a79..e1f998cd0 100644 --- a/aikido_zen/vulnerabilities/ssrf/is_request_to_itself_test.py +++ b/aikido_zen/vulnerabilities/ssrf/is_request_to_itself_test.py @@ -1,63 +1,38 @@ -import os import pytest from aikido_zen.vulnerabilities.ssrf.is_request_to_itself import is_request_to_itself -@pytest.fixture(autouse=True) -def clear_environment(): - # Clear the environment variable before each test - os.environ.pop("AIKIDO_TRUST_PROXY", None) - - -def test_returns_false_if_server_url_is_empty(): - assert not is_request_to_itself("", "aikido.dev", 80) - - -def test_returns_false_if_server_url_is_invalid(): - assert not is_request_to_itself("http://", "aikido.dev", 80) - - -def test_returns_false_if_port_is_different(): - assert not is_request_to_itself("http://aikido.dev:4000", "aikido.dev", 80) - assert not is_request_to_itself("https://aikido.dev:4000", "aikido.dev", 443) - - -def test_returns_false_if_hostname_is_different(): - assert not is_request_to_itself("http://aikido.dev", "google.com", 80) - assert not is_request_to_itself("http://aikido.dev:4000", "google.com", 4000) - assert not is_request_to_itself("https://aikido.dev", "google.com", 443) - assert not is_request_to_itself("https://aikido.dev:4000", "google.com", 443) - - -def test_returns_true_if_server_does_request_to_itself(): - assert is_request_to_itself("https://aikido.dev", "aikido.dev", 443) - assert is_request_to_itself("http://aikido.dev:4000", "aikido.dev", 4000) - assert is_request_to_itself("http://aikido.dev", "aikido.dev", 80) - assert is_request_to_itself("https://aikido.dev:4000", "aikido.dev", 4000) - - -def test_returns_true_for_special_case_http_to_https(): - assert is_request_to_itself("http://aikido.dev", "aikido.dev", 443) - assert is_request_to_itself("https://aikido.dev", "aikido.dev", 80) - - -def test_returns_false_if_trust_proxy_is_false(monkeypatch): - monkeypatch.setenv("AIKIDO_TRUST_PROXY", "false") - assert not is_request_to_itself("https://aikido.dev", "aikido.dev", 443) - assert not is_request_to_itself("http://aikido.dev", "aikido.dev", 80) - - -def test_returns_false_if_server_url_is_null(): - assert not is_request_to_itself(None, "aikido.dev", 80) - assert not is_request_to_itself(None, "aikido.dev", 443) - - -def test_returns_false_if_hostname_is_null(): - assert not is_request_to_itself("http://aikido.dev:4000", None, 80) - assert not is_request_to_itself("https://aikido.dev:4000", None, 443) - - -def test_returns_false_if_both_are_null(): - assert not is_request_to_itself(None, None, 80) - assert not is_request_to_itself(None, None, 443) +@pytest.mark.parametrize( + "server_url, hostname, port, expected", + [ + ("", "aikido.dev", 80, False), + ("http://", "aikido.dev", 80, False), + ("http://aikido.dev:4000", "aikido.dev", 80, False), + ("https://aikido.dev:4000", "aikido.dev", 443, False), + ("http://aikido.dev", "google.com", 80, False), + ("http://aikido.dev:4000", "google.com", 4000, False), + ("https://aikido.dev", "google.com", 443, False), + ("https://aikido.dev:4000", "google.com", 443, False), + ("https://aikido.dev", "aikido.dev", 443, True), + ("http://aikido.dev:4000", "aikido.dev", 4000, True), + ("http://aikido.dev", "aikido.dev", 80, True), + ("https://aikido.dev:4000", "aikido.dev", 4000, True), + ("http://aikido.dev", "aikido.dev", 443, True), + ("https://aikido.dev", "aikido.dev", 80, True), + (None, "aikido.dev", 80, False), + (None, "aikido.dev", 443, False), + ("http://aikido.dev:4000", None, 80, False), + ("https://aikido.dev:4000", None, 443, False), + (None, None, 80, False), + (None, None, 443, False), + ], +) +def test_request_to_itself(server_url, hostname, port, expected): + assert is_request_to_itself(server_url, hostname, port, True) is expected + + +@pytest.mark.parametrize("trusted", [False, None]) +def test_untrusted_request_cannot_bypass_ssrf(trusted): + assert not is_request_to_itself("https://aikido.dev", "aikido.dev", 443, trusted) + assert not is_request_to_itself("http://aikido.dev", "aikido.dev", 80, trusted) diff --git a/docs/proxy.md b/docs/proxy.md index 876d3c093..8d5dfd170 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -1,12 +1,50 @@ # Proxy settings -We'll automatically use the `x-forwarded-for` header to determine the client's IP address when behind a proxy. - -If you're publicly exposing your server without a load balancer in front of it, you should set the `AIKIDO_TRUST_PROXY` env var to `false` to ensure that the correct IP address is used. Otherwise, someone could potentially spoof their IP address by adding the above header and thus bypassing the rate limiting. +Zen automatically reads the `x-forwarded-for` header to determine the client's IP address when running behind a proxy. If you're publicly exposing your server without a load balancer in front of it, you should set the `AIKIDO_TRUST_PROXY` env var to `false` to ensure that the correct IP address is used. Otherwise, someone could potentially spoof their IP address by adding the above header and thus bypassing the rate limiting. If you need to use a different header to determine the client's IP address, you can set the `AIKIDO_CLIENT_IP_HEADER` environment variable to the name of that header. This will override the default `x-forwarded-for` header. ```bash # For DigitalOcean App Platform -AIKIDO_CLIENT_IP_HEADER=do-connecting-ip flask --app app run +AIKIDO_CLIENT_IP_HEADER=do-connecting-ip flask --app app run +``` + +## Advanced proxy trust configuration + +The `AIKIDO_TRUST_PROXY` environment variable controls whether Zen reads the IP header at all, and how it selects the client IP from it. + +| Value | Behavior | +| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| _(not set)_ or `true` | **Default.** Trust the header and use the first non-private IP found, scanning from right to left. Suitable for most deployments behind a reverse proxy. | +| `false` | Ignore the header entirely and always use the remote address of the request socket. Use this when your server is directly exposed to the internet without a proxy in front of it. | +| `1.2.3.4/32, …` _(CIDR notation)_ | Only trusted if the request's remote address matches one of the specified CIDR ranges; otherwise the header is ignored and the remote address is used. When trusted, use the first non-private IP that does not belong to any of the specified CIDR ranges, scanning from right to left. Multiple ranges can be separated by commas. Use this when your proxies have known public IP addresses. | +| `1`, `2`, … _(positive integer n)_ | Trust the header and use the _n_-th IP from the right (1 = rightmost). Use this when a fixed number of trusted proxies are in front of your server. Private IPs are not skipped. | + +> [!WARNING] +> In the default mode (`true` or not set), Zen picks the rightmost **non-private** IP in the header. This only works if all proxies in front of your app communicate over private networks and use private IP addresses. If there is a proxy with a public IP in the chain (e.g. a CDN like Cloudflare in front of your load balancer), Zen will treat that proxy's IP as the client IP. In this case, use the CIDR or number-of-proxies mode below. If your server is directly exposed to the internet, set `AIKIDO_TRUST_PROXY=false`. + +## How the client IP is selected + +Each proxy appends the address it received the connection from to `x-forwarded-for`. Everything to the left of the last trusted proxy's entry can be spoofed by the client, so Zen scans from right to left and stops at the first IP that is not part of your own infrastructure. + +## Choosing a mode + +You can use the following flowchart to determine which mode is appropriate for your deployment: + +```mermaid +flowchart TD + A{"Can clients connect to your app
directly, without a proxy?"} + A -->|Yes| F["AIKIDO_TRUST_PROXY=false"] + A -->|No| B{"Do all proxies in front of your app communicate
over private networks with private IPs
(VPC, Docker network, cluster network)?"} + B -->|Yes| D["Leave AIKIDO_TRUST_PROXY unset"] + B -->|No| C{"Do you know the IP addresses or
ranges of your proxies?"} + C -->|Yes| G["AIKIDO_TRUST_PROXY=192.0.2.0/24
(CIDR ranges or single IPs, comma separated)"] + C -->|No| H["AIKIDO_TRUST_PROXY=2
(number of proxies in front of your app)"] + + classDef node_ stroke:#6551f3,stroke-width:1.5px + classDef default_ stroke:#6551f3,stroke-width:4px + class A,B,C,F,G,H node_ + class D default_ + linkStyle default stroke:#6551f3,stroke-width:1.5px + linkStyle 1,2 stroke:#6551f3,stroke-width:3px ``` From 5aaba8214014dc1dcef8b551ed1a08a6656955b5 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 12:08:13 +0200 Subject: [PATCH 02/15] Leave IP normalization to the IP matcher --- aikido_zen/helpers/get_ip_from_request.py | 6 ++---- aikido_zen/helpers/trust_proxy.py | 4 ++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index 816a6f2a5..013e1f1ec 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -7,7 +7,6 @@ from typing import Optional from aikido_zen.helpers.headers import Headers -from aikido_zen.helpers.ip_matcher import preparse from aikido_zen.helpers.logging import logger from aikido_zen.helpers.net.is_private_ip import is_private_ip from aikido_zen.helpers.trust_proxy import ( @@ -52,10 +51,9 @@ def get_client_ip_from_header(value): ip = normalize_ip(forwarded_ips[index].strip()) if not is_ip(ip): continue - normalized_ip = preparse(ip) - if is_private_ip(normalized_ip): + if is_private_ip(ip): continue - if isinstance(config, CIDRTrustProxy) and config.matcher.has(normalized_ip): + if isinstance(config, CIDRTrustProxy) and config.matcher.has(ip): continue return ip return None diff --git a/aikido_zen/helpers/trust_proxy.py b/aikido_zen/helpers/trust_proxy.py index cc53840c4..8d9309cca 100644 --- a/aikido_zen/helpers/trust_proxy.py +++ b/aikido_zen/helpers/trust_proxy.py @@ -4,7 +4,7 @@ from functools import lru_cache from typing import Optional, Union -from aikido_zen.helpers.ip_matcher import IPMatcher, preparse +from aikido_zen.helpers.ip_matcher import IPMatcher @dataclass(frozen=True) @@ -53,5 +53,5 @@ def is_trusted_proxy_request(remote_address: Optional[str]) -> bool: if isinstance(config, BooleanTrustProxy): return config.value if isinstance(config, CIDRTrustProxy): - return bool(remote_address) and config.matcher.has(preparse(remote_address)) + return bool(remote_address) and config.matcher.has(remote_address) return True From d8b2bec91132e92bd94ba8f362f238e59c41a253 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 15:23:34 +0200 Subject: [PATCH 03/15] Validate AIKIDO_TRUST_PROXY and store mapped proxy ranges as IPv4 --- .../helpers/get_ip_from_request_test.py | 59 ++++++++++++++++++- aikido_zen/helpers/trust_proxy.py | 28 ++++++++- 2 files changed, 84 insertions(+), 3 deletions(-) diff --git a/aikido_zen/helpers/get_ip_from_request_test.py b/aikido_zen/helpers/get_ip_from_request_test.py index da7cf73f2..46f97c363 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -1,13 +1,17 @@ import sys +import threading +import time import pytest +from . import trust_proxy from .get_ip_from_request import ( get_ip_from_request, is_ip, get_client_ip_from_header, ) from .headers import Headers -from .trust_proxy import is_trusted_proxy_request +from .ip_matcher import IPMatcher +from .trust_proxy import is_trusted_proxy_request, parse_trust_proxy @pytest.fixture(autouse=True) @@ -238,7 +242,13 @@ def test_get_client_ip_from_header(value, expected): "9.9.9.9, ::ffff:1.2.3.5", "9.9.9.9", ), + ("::ffff:1.2.3.0/120", "1.2.3.4", "9.9.9.9, 1.2.3.5", "9.9.9.9"), + ("::ffff:1.2.3.4", "1.2.3.4", "9.9.9.9, 1.2.3.4", "9.9.9.9"), ("invalid.ip", "1.2.3.4", "9.9.9.9", "1.2.3.4"), + ("1.2.3.0/2 4", "9.9.9.9", "77.77.77.77", "9.9.9.9"), + ("1.2.3.0/24oops, 8.8.8.0/24", "1.2.3.4", "9.9.9.9", "1.2.3.4"), + ("1.2.3.0/24oops, 8.8.8.0/24", "8.8.8.8", "9.9.9.9, 8.8.8.9", "9.9.9.9"), + (" 2 ", "1.2.3.4", "9.9.9.9, 8.8.8.8, 7.7.7.7", "8.8.8.8"), ], ) def test_proxy_trust_modes(monkeypatch, setting, remote_address, value, expected): @@ -248,6 +258,53 @@ def test_proxy_trust_modes(monkeypatch, setting, remote_address, value, expected assert get_ip_from_request(remote_address, headers) == expected +def test_proxy_trust_warns_once_about_invalid_ranges(caplog): + parse_trust_proxy.cache_clear() + + parse_trust_proxy("1.2.3.0/2 4, 8.8.8.0/24, oops.example") + + assert [record.getMessage() for record in caplog.records] == [ + "Ignoring invalid trusted proxy ranges." + ] + + +@pytest.mark.parametrize( + "setting", ["true", "false", "unknown", "2", "8.8.8.0/24, ::1", "1.2.3.0/24, "] +) +def test_proxy_trust_does_not_warn_about_other_values(caplog, setting): + parse_trust_proxy.cache_clear() + + parse_trust_proxy(setting) + + assert caplog.records == [] + + +def test_concurrent_first_requests_parse_the_setting_once(monkeypatch): + built = [] + + def slow_matcher(ranges): + built.append(ranges) + time.sleep(0.05) + return IPMatcher(ranges) + + monkeypatch.setattr(trust_proxy, "IPMatcher", slow_matcher) + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "8.8.8.0/24") + parse_trust_proxy.cache_clear() + start = threading.Barrier(8) + + def first_request(): + start.wait() + is_trusted_proxy_request("8.8.8.8") + + threads = [threading.Thread(target=first_request) for _ in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert built == [["8.8.8.0/24"]] + + @pytest.mark.skipif( not hasattr(sys, "get_int_max_str_digits"), reason="No integer conversion limit" ) diff --git a/aikido_zen/helpers/trust_proxy.py b/aikido_zen/helpers/trust_proxy.py index 8d9309cca..6cb4ef073 100644 --- a/aikido_zen/helpers/trust_proxy.py +++ b/aikido_zen/helpers/trust_proxy.py @@ -1,10 +1,13 @@ +import ipaddress import os import re +import threading from dataclasses import dataclass from functools import lru_cache from typing import Optional, Union from aikido_zen.helpers.ip_matcher import IPMatcher +from aikido_zen.helpers.logging import logger @dataclass(frozen=True) @@ -25,12 +28,18 @@ class CIDRTrustProxy: TrustProxyConfig = Union[BooleanTrustProxy, CountTrustProxy, CIDRTrustProxy] +# Without the lock, requests that arrive together all parse the setting and warn. +_parse_lock = threading.Lock() + + def get_trust_proxy_config() -> TrustProxyConfig: - return parse_trust_proxy(os.getenv("AIKIDO_TRUST_PROXY")) + with _parse_lock: + return parse_trust_proxy(os.getenv("AIKIDO_TRUST_PROXY")) @lru_cache(maxsize=1) def parse_trust_proxy(value: Optional[str]) -> TrustProxyConfig: + value = (value or "").strip() if not value: return BooleanTrustProxy(True) if re.fullmatch(r"[0-9]+", value): @@ -43,11 +52,26 @@ def parse_trust_proxy(value: Optional[str]) -> TrustProxyConfig: if value.lower() in ("true", "1", "yes", "y", "on"): return BooleanTrustProxy(True) if "." in value or ":" in value: - ranges = [entry.strip() for entry in value.split(",") if entry.strip()] + entries = [entry for entry in map(str.strip, value.split(",")) if entry] + ranges = [r for r in map(_proxy_range, entries) if r] + if len(ranges) < len(entries): + logger.warning("Ignoring invalid trusted proxy ranges.") return CIDRTrustProxy(IPMatcher(ranges)) return BooleanTrustProxy(False) +def _proxy_range(entry: str) -> Optional[str]: + try: + network = ipaddress.ip_network(entry.strip("[]"), strict=False) + except ValueError: + return None + # Stored as IPv4 so the proxy also matches when it connects over IPv4. + mapped = getattr(network.network_address, "ipv4_mapped", None) + if mapped is not None and network.prefixlen >= 96: + return f"{mapped}/{network.prefixlen - 96}" + return str(network) + + def is_trusted_proxy_request(remote_address: Optional[str]) -> bool: config = get_trust_proxy_config() if isinstance(config, BooleanTrustProxy): From 8ad461be0ca7d25e183fd5a15eb38b29bc739c30 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 15:38:22 +0200 Subject: [PATCH 04/15] Check each forwarded IP once --- aikido_zen/helpers/get_ip_from_request.py | 2 -- aikido_zen/helpers/get_ip_from_request_test.py | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index 013e1f1ec..b65aa146a 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -60,8 +60,6 @@ def get_client_ip_from_header(value): def normalize_ip(ip: str) -> str: - if is_ip(ip): - return ip if ip.startswith("["): if ip.endswith("]"): return ip[1:-1] diff --git a/aikido_zen/helpers/get_ip_from_request_test.py b/aikido_zen/helpers/get_ip_from_request_test.py index 46f97c363..feef287b9 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -3,6 +3,7 @@ import time import pytest +from . import get_ip_from_request as get_ip_module from . import trust_proxy from .get_ip_from_request import ( get_ip_from_request, @@ -199,6 +200,20 @@ def test_get_client_ip_from_header(value, expected): assert get_client_ip_from_header(value) == expected +def test_each_forwarded_entry_is_checked_once(monkeypatch): + checked = [] + + def counting_is_ip(value): + checked.append(value) + return is_ip(value) + + monkeypatch.setattr(get_ip_module, "is_ip", counting_is_ip) + + get_client_ip_from_header("junk, 10.0.0.1, [::1]:443, x") + + assert checked == ["x", "::1", "10.0.0.1", "junk"] + + @pytest.mark.parametrize( "setting, remote_address, value, expected", [ From 7277a0ce78ed662a609580da5b5904b52d18ff89 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 17:15:59 +0200 Subject: [PATCH 05/15] Parse AIKIDO_TRUST_PROXY at startup and drop the lock --- aikido_zen/__init__.py | 2 + .../helpers/get_ip_from_request_test.py | 55 +++++++++++-------- aikido_zen/helpers/trust_proxy.py | 10 +--- aikido_zen/init_test.py | 10 ++++ 4 files changed, 46 insertions(+), 31 deletions(-) diff --git a/aikido_zen/__init__.py b/aikido_zen/__init__.py index 723a1401d..a3a0b9ed8 100644 --- a/aikido_zen/__init__.py +++ b/aikido_zen/__init__.py @@ -53,6 +53,7 @@ def lazy_imports_filter(importer, name, fromlist): # Load environment variables and constants from aikido_zen.config import PKG_VERSION from aikido_zen.helpers.aikido_disabled_flag_active import aikido_disabled_flag_active +from aikido_zen.helpers.trust_proxy import get_trust_proxy_config def protect(mode="daemon", token=""): @@ -130,3 +131,4 @@ def protect(mode="daemon", token=""): import aikido_zen.sinks.botocore logger.info("Zen by Aikido v%s starting.", PKG_VERSION) + get_trust_proxy_config() diff --git a/aikido_zen/helpers/get_ip_from_request_test.py b/aikido_zen/helpers/get_ip_from_request_test.py index feef287b9..cf6b46540 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -1,6 +1,5 @@ import sys import threading -import time import pytest from . import get_ip_from_request as get_ip_module @@ -273,51 +272,59 @@ def test_proxy_trust_modes(monkeypatch, setting, remote_address, value, expected assert get_ip_from_request(remote_address, headers) == expected -def test_proxy_trust_warns_once_about_invalid_ranges(caplog): +@pytest.mark.parametrize( + "setting, warning", + [ + ( + "1.2.3.0/2 4, 8.8.8.0/24, oops.example", + "Ignoring invalid trusted proxy ranges.", + ), + ("unknown", "Ignoring an invalid trusted proxy setting."), + ("-1", "Ignoring an invalid trusted proxy setting."), + ], +) +def test_proxy_trust_warns_once_about_invalid_settings(caplog, setting, warning): parse_trust_proxy.cache_clear() - parse_trust_proxy("1.2.3.0/2 4, 8.8.8.0/24, oops.example") + parse_trust_proxy(setting) - assert [record.getMessage() for record in caplog.records] == [ - "Ignoring invalid trusted proxy ranges." - ] + assert caplog.text.count(warning) == 1 @pytest.mark.parametrize( - "setting", ["true", "false", "unknown", "2", "8.8.8.0/24, ::1", "1.2.3.0/24, "] + "setting", ["true", "false", "0", "off", "2", "8.8.8.0/24, ::1", "1.2.3.0/24, "] ) -def test_proxy_trust_does_not_warn_about_other_values(caplog, setting): +def test_proxy_trust_does_not_warn_about_supported_values(caplog, setting): parse_trust_proxy.cache_clear() parse_trust_proxy(setting) - assert caplog.records == [] + assert caplog.text == "" -def test_concurrent_first_requests_parse_the_setting_once(monkeypatch): - built = [] +def test_reading_the_setting_does_not_wait_for_another_thread(monkeypatch): + first_inside = threading.Event() + second_done = threading.Event() + second_finished_in_time = [] def slow_matcher(ranges): - built.append(ranges) - time.sleep(0.05) + if not first_inside.is_set(): + first_inside.set() + second_finished_in_time.append(second_done.wait(timeout=5)) return IPMatcher(ranges) monkeypatch.setattr(trust_proxy, "IPMatcher", slow_matcher) monkeypatch.setenv("AIKIDO_TRUST_PROXY", "8.8.8.0/24") parse_trust_proxy.cache_clear() - start = threading.Barrier(8) - - def first_request(): - start.wait() - is_trusted_proxy_request("8.8.8.8") + first = threading.Thread(target=trust_proxy.get_trust_proxy_config) + first.start() + first_inside.wait() - threads = [threading.Thread(target=first_request) for _ in range(8)] - for thread in threads: - thread.start() - for thread in threads: - thread.join() + trust_proxy.get_trust_proxy_config() + second_done.set() + first.join() - assert built == [["8.8.8.0/24"]] + assert second_finished_in_time == [True] @pytest.mark.skipif( diff --git a/aikido_zen/helpers/trust_proxy.py b/aikido_zen/helpers/trust_proxy.py index 6cb4ef073..a22063d02 100644 --- a/aikido_zen/helpers/trust_proxy.py +++ b/aikido_zen/helpers/trust_proxy.py @@ -1,7 +1,6 @@ import ipaddress import os import re -import threading from dataclasses import dataclass from functools import lru_cache from typing import Optional, Union @@ -28,13 +27,8 @@ class CIDRTrustProxy: TrustProxyConfig = Union[BooleanTrustProxy, CountTrustProxy, CIDRTrustProxy] -# Without the lock, requests that arrive together all parse the setting and warn. -_parse_lock = threading.Lock() - - def get_trust_proxy_config() -> TrustProxyConfig: - with _parse_lock: - return parse_trust_proxy(os.getenv("AIKIDO_TRUST_PROXY")) + return parse_trust_proxy(os.getenv("AIKIDO_TRUST_PROXY")) @lru_cache(maxsize=1) @@ -57,6 +51,8 @@ def parse_trust_proxy(value: Optional[str]) -> TrustProxyConfig: if len(ranges) < len(entries): logger.warning("Ignoring invalid trusted proxy ranges.") return CIDRTrustProxy(IPMatcher(ranges)) + if value.lower() not in ("false", "0", "no", "n", "off"): + logger.warning("Ignoring an invalid trusted proxy setting.") return BooleanTrustProxy(False) diff --git a/aikido_zen/init_test.py b/aikido_zen/init_test.py index 00a805003..59711b594 100644 --- a/aikido_zen/init_test.py +++ b/aikido_zen/init_test.py @@ -10,6 +10,7 @@ from aikido_zen import protect from aikido_zen.background_process.ipc import IPCClient from aikido_zen.helpers.token import get_token_from_env +from aikido_zen.helpers.trust_proxy import parse_trust_proxy def test_protect_with_django(monkeypatch, caplog): @@ -37,6 +38,15 @@ def test_protect_does_not_start_without_gil(monkeypatch): start_background_process.assert_not_called() +def test_protect_reports_an_invalid_trust_proxy_setting(monkeypatch, caplog): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "unknown") + parse_trust_proxy.cache_clear() + + protect(mode="daemon_disabled") + + assert "Ignoring an invalid trusted proxy setting." in caplog.text + + class FakeLazyImports: def __init__(self, current_filter): self.current_filter = current_filter From fff6c91452be262e46fc37be686133896cc397cc Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 17:37:45 +0200 Subject: [PATCH 06/15] Read every X-Forwarded-For line on ASGI --- aikido_zen/context/init_test.py | 20 +++++++++++++++++++ aikido_zen/helpers/get_ip_from_request.py | 2 +- .../helpers/get_ip_from_request_test.py | 8 ++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index ce0507109..f052ba5c6 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -160,6 +160,26 @@ def test_proxy_trust_in_request_context( assert restored.is_behind_trusted_proxy is trusted +@pytest.mark.parametrize("setting", ["true", "2"]) +def test_client_ip_is_read_from_every_forwarded_header_line(monkeypatch, setting): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) + request = { + "method": "GET", + "headers": [ + (b"x-forwarded-for", b"9.9.9.9"), + (b"x-forwarded-for", b"10.0.0.2"), + ], + "query_string": b"", + "client": ("10.0.0.3", 1234), + "server": ("localhost", 8080), + "scheme": "http", + "root_path": "", + "path": "/hello", + } + context = Context(req=request, source="starlette") + assert context.remote_address == "9.9.9.9" + + def test_set_as_current_context(mocker): # Test set_as_current_context() method context = Context(req=basic_wsgi_req, body=12, source="flask") diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index b65aa146a..dbe673a9a 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -21,7 +21,7 @@ def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: """ Tries and get the IP address from the request, checking for x-forwarded-for """ - ip_header = headers.get_header(get_ip_header_name()) + ip_header = ", ".join(headers.get(get_ip_header_name(), [])) if ip_header and is_trusted_proxy_request(remote_address): ip_header_value = get_client_ip_from_header(ip_header) diff --git a/aikido_zen/helpers/get_ip_from_request_test.py b/aikido_zen/helpers/get_ip_from_request_test.py index cf6b46540..d994bf329 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -272,6 +272,14 @@ def test_proxy_trust_modes(monkeypatch, setting, remote_address, value, expected assert get_ip_from_request(remote_address, headers) == expected +def test_forwarded_header_lines_are_counted_in_arrival_order(monkeypatch): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "2") + headers = Headers() + headers.store_header("x-forwarded-for", "9.9.9.9") + headers.store_header("x-forwarded-for", "10.0.0.2") + assert get_ip_from_request("10.0.0.3", headers) == "9.9.9.9" + + @pytest.mark.parametrize( "setting, warning", [ From 14615b1b621678f63826624f0be477045dab2265 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Tue, 24 Nov 2026 18:20:19 +0200 Subject: [PATCH 07/15] Check the connection address behind Werkzeug's ProxyFix --- aikido_zen/context/init_test.py | 22 ++++++++++++++++++++++ aikido_zen/context/wsgi/__init__.py | 9 +++++++-- aikido_zen/helpers/get_ip_from_request.py | 6 ++++-- docs/proxy.md | 4 ++++ 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index f052ba5c6..8d32da132 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -1,6 +1,7 @@ import pytest import pickle import json +from werkzeug.middleware.proxy_fix import ProxyFix from aikido_zen.context import Context, get_current_context, current_context LEVELS_TOO_DEEP_TO_PARSE = 1_000_000 @@ -180,6 +181,27 @@ def test_client_ip_is_read_from_every_forwarded_header_line(monkeypatch, setting assert context.remote_address == "9.9.9.9" +@pytest.mark.parametrize("forwarded", ["9.9.9.9", "9.9.9.9:1234"]) +def test_proxy_trust_checks_the_connection_address_behind_proxy_fix( + monkeypatch, forwarded +): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "1.2.3.0/24") + environs = [] + + def app(environ, start_response): + environs.append(environ) + return [] + + request = dict( + basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR=forwarded + ) + ProxyFix(app)(request, None) + + context = Context(req=environs[0], source="flask") + assert context.remote_address == "9.9.9.9" + assert context.is_behind_trusted_proxy is True + + def test_set_as_current_context(mocker): # Test set_as_current_context() method context = Context(req=basic_wsgi_req, body=12, source="flask") diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index 71479629e..a0089dcef 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -25,8 +25,13 @@ def set_wsgi_attributes_on_context(context, environ): context.url = build_url_from_wsgi(environ) context.query = parse_qs(environ["QUERY_STRING"]) raw_ip = environ["REMOTE_ADDR"] - context.remote_address = get_ip_from_request(raw_ip, context.headers) - context.is_behind_trusted_proxy = is_trusted_proxy_request(raw_ip) + # Werkzeug's ProxyFix replaces REMOTE_ADDR with the forwarded client address and keeps + # the connection address here, which is the address the trusted proxy check needs. + connection_ip = ( + environ.get("werkzeug.proxy_fix.orig", {}).get("REMOTE_ADDR") or raw_ip + ) + context.remote_address = get_ip_from_request(raw_ip, context.headers, connection_ip) + context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) # Content type is generally not included as a header, do include this as a header to simplify : if "CONTENT_TYPE" in environ: diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index dbe673a9a..24afed029 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -17,12 +17,14 @@ ) -def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: +def get_ip_from_request( + remote_address: str, headers: Headers, connection_ip=None +) -> Optional[str]: """ Tries and get the IP address from the request, checking for x-forwarded-for """ ip_header = ", ".join(headers.get(get_ip_header_name(), [])) - if ip_header and is_trusted_proxy_request(remote_address): + if ip_header and is_trusted_proxy_request(connection_ip or remote_address): ip_header_value = get_client_ip_from_header(ip_header) if ip_header_value and is_ip(ip_header_value): diff --git a/docs/proxy.md b/docs/proxy.md index 8d5dfd170..46fa06530 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -48,3 +48,7 @@ flowchart TD linkStyle default stroke:#6551f3,stroke-width:1.5px linkStyle 1,2 stroke:#6551f3,stroke-width:3px ``` + +## Servers that rewrite the client address + +With CIDR ranges, Zen checks the address of the connection against them. Some ASGI servers replace that address with one from `x-forwarded-for` before Zen sees the request: Uvicorn does this for the proxies in `--forwarded-allow-ips` (by default `127.0.0.1` and `::1`), and Hypercorn does it with `ProxyFixMiddleware`. Turn this off (`uvicorn --no-proxy-headers`, or remove `ProxyFixMiddleware`), or use the number-of-proxies mode instead of CIDR ranges. From 8d6eed5cd3e7c07905ff511644734c7902005ac6 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Wed, 25 Nov 2026 00:11:53 +0200 Subject: [PATCH 08/15] Use the client address that ProxyFix chose --- aikido_zen/context/init_test.py | 39 +++++++++++++++++------ aikido_zen/context/wsgi/__init__.py | 17 +++++++--- aikido_zen/helpers/get_ip_from_request.py | 6 ++-- docs/proxy.md | 4 +-- 4 files changed, 47 insertions(+), 19 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index 8d32da132..a91736638 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -181,27 +181,48 @@ def test_client_ip_is_read_from_every_forwarded_header_line(monkeypatch, setting assert context.remote_address == "9.9.9.9" -@pytest.mark.parametrize("forwarded", ["9.9.9.9", "9.9.9.9:1234"]) -def test_proxy_trust_checks_the_connection_address_behind_proxy_fix( - monkeypatch, forwarded -): - monkeypatch.setenv("AIKIDO_TRUST_PROXY", "1.2.3.0/24") +def context_behind_proxy_fix(request, **proxy_fix_args): environs = [] def app(environ, start_response): environs.append(environ) return [] + ProxyFix(app, **proxy_fix_args)(request, None) + return Context(req=environs[0], source="flask") + + +@pytest.mark.parametrize( + "x_for, forwarded, client_ip", + [ + (1, "9.9.9.9", "9.9.9.9"), + (1, "9.9.9.9:1234", "9.9.9.9"), + (2, "9.9.9.9, 8.8.8.8", "9.9.9.9"), + (0, "9.9.9.9", "9.9.9.9"), + (1, "unknown", None), + ], +) +def test_client_ip_behind_proxy_fix(monkeypatch, x_for, forwarded, client_ip): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "1.2.3.0/24") request = dict( basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR=forwarded ) - ProxyFix(app)(request, None) - - context = Context(req=environs[0], source="flask") - assert context.remote_address == "9.9.9.9" + context = context_behind_proxy_fix(request, x_for=x_for) + assert context.remote_address == client_ip assert context.is_behind_trusted_proxy is True +def test_custom_client_ip_header_is_read_behind_proxy_fix(monkeypatch): + monkeypatch.setenv("AIKIDO_CLIENT_IP_HEADER", "do-connecting-ip") + request = dict( + basic_wsgi_req, + REMOTE_ADDR="1.2.3.4", + HTTP_X_FORWARDED_FOR="8.8.8.8", + HTTP_DO_CONNECTING_IP="9.9.9.9", + ) + assert context_behind_proxy_fix(request).remote_address == "9.9.9.9" + + def test_set_as_current_context(mocker): # Test set_as_current_context() method context = Context(req=basic_wsgi_req, body=12, source="flask") diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index a0089dcef..c42467487 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -1,7 +1,12 @@ """Exports set_wsgi_attributes_on_context""" from urllib.parse import parse_qs -from aikido_zen.helpers.get_ip_from_request import get_ip_from_request +from aikido_zen.helpers.get_ip_from_request import ( + get_ip_from_request, + get_ip_header_name, + is_ip, + normalize_ip, +) from aikido_zen.helpers.logging import logger from aikido_zen.helpers.trust_proxy import is_trusted_proxy_request from .extract_wsgi_headers import extract_wsgi_headers @@ -25,12 +30,16 @@ def set_wsgi_attributes_on_context(context, environ): context.url = build_url_from_wsgi(environ) context.query = parse_qs(environ["QUERY_STRING"]) raw_ip = environ["REMOTE_ADDR"] - # Werkzeug's ProxyFix replaces REMOTE_ADDR with the forwarded client address and keeps - # the connection address here, which is the address the trusted proxy check needs. + # Werkzeug's ProxyFix keeps the connection address here. A different REMOTE_ADDR is + # the client ProxyFix chose, which Zen uses instead of parsing the header again. connection_ip = ( environ.get("werkzeug.proxy_fix.orig", {}).get("REMOTE_ADDR") or raw_ip ) - context.remote_address = get_ip_from_request(raw_ip, context.headers, connection_ip) + if connection_ip != raw_ip and get_ip_header_name() == "X_FORWARDED_FOR": + client_ip = normalize_ip(raw_ip) + context.remote_address = client_ip if is_ip(client_ip) else None + else: + context.remote_address = get_ip_from_request(raw_ip, context.headers) context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) # Content type is generally not included as a header, do include this as a header to simplify : diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index 24afed029..dbe673a9a 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -17,14 +17,12 @@ ) -def get_ip_from_request( - remote_address: str, headers: Headers, connection_ip=None -) -> Optional[str]: +def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: """ Tries and get the IP address from the request, checking for x-forwarded-for """ ip_header = ", ".join(headers.get(get_ip_header_name(), [])) - if ip_header and is_trusted_proxy_request(connection_ip or remote_address): + if ip_header and is_trusted_proxy_request(remote_address): ip_header_value = get_client_ip_from_header(ip_header) if ip_header_value and is_ip(ip_header_value): diff --git a/docs/proxy.md b/docs/proxy.md index 46fa06530..087f0ba8c 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -49,6 +49,6 @@ flowchart TD linkStyle 1,2 stroke:#6551f3,stroke-width:3px ``` -## Servers that rewrite the client address +## Servers that resolve the client IP -With CIDR ranges, Zen checks the address of the connection against them. Some ASGI servers replace that address with one from `x-forwarded-for` before Zen sees the request: Uvicorn does this for the proxies in `--forwarded-allow-ips` (by default `127.0.0.1` and `::1`), and Hypercorn does it with `ProxyFixMiddleware`. Turn this off (`uvicorn --no-proxy-headers`, or remove `ProxyFixMiddleware`), or use the number-of-proxies mode instead of CIDR ranges. +If Uvicorn (`--forwarded-allow-ips`, by default `127.0.0.1`) or Hypercorn's `ProxyFixMiddleware` resolves the client IP, set `AIKIDO_TRUST_PROXY=false` so that Zen uses that IP, and configure it to trust only your own proxies. Behind Werkzeug's `ProxyFix`, Zen uses the IP that `ProxyFix` chose, so set the number of proxies there. From 09c210387caaec328855e343dbe91bdecc787274 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Wed, 25 Nov 2026 11:38:17 +0200 Subject: [PATCH 09/15] Use the connection address for unlisted connections behind ProxyFix --- aikido_zen/context/init_test.py | 15 +++++++++++++++ aikido_zen/context/wsgi/__init__.py | 12 ++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index a91736638..c1103b660 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -223,6 +223,21 @@ def test_custom_client_ip_header_is_read_behind_proxy_fix(monkeypatch): assert context_behind_proxy_fix(request).remote_address == "9.9.9.9" +@pytest.mark.parametrize( + "setting, client_ip", [("1.2.3.0/24", "5.5.5.5"), ("false", "6.6.6.6")] +) +def test_connection_from_an_unlisted_address_behind_proxy_fix( + monkeypatch, setting, client_ip +): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) + request = dict( + basic_wsgi_req, REMOTE_ADDR="5.5.5.5", HTTP_X_FORWARDED_FOR="6.6.6.6" + ) + context = context_behind_proxy_fix(request) + assert context.remote_address == client_ip + assert context.is_behind_trusted_proxy is False + + def test_set_as_current_context(mocker): # Test set_as_current_context() method context = Context(req=basic_wsgi_req, body=12, source="flask") diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index c42467487..d9838598e 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -8,7 +8,11 @@ normalize_ip, ) from aikido_zen.helpers.logging import logger -from aikido_zen.helpers.trust_proxy import is_trusted_proxy_request +from aikido_zen.helpers.trust_proxy import ( + CIDRTrustProxy, + get_trust_proxy_config, + is_trusted_proxy_request, +) from .extract_wsgi_headers import extract_wsgi_headers from .build_url_from_wsgi import build_url_from_wsgi from ..parse_cookies import parse_cookies @@ -35,12 +39,16 @@ def set_wsgi_attributes_on_context(context, environ): connection_ip = ( environ.get("werkzeug.proxy_fix.orig", {}).get("REMOTE_ADDR") or raw_ip ) + context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) if connection_ip != raw_ip and get_ip_header_name() == "X_FORWARDED_FOR": client_ip = normalize_ip(raw_ip) + cidr_mode = isinstance(get_trust_proxy_config(), CIDRTrustProxy) + if cidr_mode and not context.is_behind_trusted_proxy: + # In CIDR mode, an unlisted connection is the client, as without ProxyFix. + client_ip = connection_ip context.remote_address = client_ip if is_ip(client_ip) else None else: context.remote_address = get_ip_from_request(raw_ip, context.headers) - context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) # Content type is generally not included as a header, do include this as a header to simplify : if "CONTENT_TYPE" in environ: From 7ffad4f5d18cb3d85973252347ef5e91ccb74f43 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Wed, 25 Nov 2026 13:14:18 +0200 Subject: [PATCH 10/15] Check the connection address with a custom client IP header behind ProxyFix --- aikido_zen/context/init_test.py | 18 +++++++++++++++--- aikido_zen/context/wsgi/__init__.py | 2 +- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index c1103b660..11d995e75 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -212,15 +212,27 @@ def test_client_ip_behind_proxy_fix(monkeypatch, x_for, forwarded, client_ip): assert context.is_behind_trusted_proxy is True -def test_custom_client_ip_header_is_read_behind_proxy_fix(monkeypatch): +@pytest.mark.parametrize( + "setting, custom_header, client_ip", + [ + ("true", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "9.9.9.9"), + ("1.2.3.0/24", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "9.9.9.9"), + ("true", {}, "1.2.3.4"), + ("false", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "1.2.3.4"), + ], +) +def test_custom_client_ip_header_behind_proxy_fix( + monkeypatch, setting, custom_header, client_ip +): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) monkeypatch.setenv("AIKIDO_CLIENT_IP_HEADER", "do-connecting-ip") request = dict( basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR="8.8.8.8", - HTTP_DO_CONNECTING_IP="9.9.9.9", + **custom_header, ) - assert context_behind_proxy_fix(request).remote_address == "9.9.9.9" + assert context_behind_proxy_fix(request).remote_address == client_ip @pytest.mark.parametrize( diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index d9838598e..9872323b7 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -48,7 +48,7 @@ def set_wsgi_attributes_on_context(context, environ): client_ip = connection_ip context.remote_address = client_ip if is_ip(client_ip) else None else: - context.remote_address = get_ip_from_request(raw_ip, context.headers) + context.remote_address = get_ip_from_request(connection_ip, context.headers) # Content type is generally not included as a header, do include this as a header to simplify : if "CONTENT_TYPE" in environ: From 3a7f51e1275083d56eeb9a4496acd3b0ee7a26e2 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Wed, 25 Nov 2026 13:14:18 +0200 Subject: [PATCH 11/15] Fall back to the connection when ProxyFix's choice is not an IP As without ProxyFix, and as the spec's fallback rule says, use the connection address when the address ProxyFix chose is not an IP. Narrow the docs sentence to the X-Forwarded-For case. --- aikido_zen/context/init_test.py | 2 +- aikido_zen/context/wsgi/__init__.py | 4 ++-- docs/proxy.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index 11d995e75..eb18264c2 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -199,7 +199,7 @@ def app(environ, start_response): (1, "9.9.9.9:1234", "9.9.9.9"), (2, "9.9.9.9, 8.8.8.8", "9.9.9.9"), (0, "9.9.9.9", "9.9.9.9"), - (1, "unknown", None), + (1, "unknown", "1.2.3.4"), ], ) def test_client_ip_behind_proxy_fix(monkeypatch, x_for, forwarded, client_ip): diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index 9872323b7..0287b8be5 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -43,8 +43,8 @@ def set_wsgi_attributes_on_context(context, environ): if connection_ip != raw_ip and get_ip_header_name() == "X_FORWARDED_FOR": client_ip = normalize_ip(raw_ip) cidr_mode = isinstance(get_trust_proxy_config(), CIDRTrustProxy) - if cidr_mode and not context.is_behind_trusted_proxy: - # In CIDR mode, an unlisted connection is the client, as without ProxyFix. + # The same fallbacks as without ProxyFix. + if not is_ip(client_ip) or (cidr_mode and not context.is_behind_trusted_proxy): client_ip = connection_ip context.remote_address = client_ip if is_ip(client_ip) else None else: diff --git a/docs/proxy.md b/docs/proxy.md index 087f0ba8c..bac7753b6 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -51,4 +51,4 @@ flowchart TD ## Servers that resolve the client IP -If Uvicorn (`--forwarded-allow-ips`, by default `127.0.0.1`) or Hypercorn's `ProxyFixMiddleware` resolves the client IP, set `AIKIDO_TRUST_PROXY=false` so that Zen uses that IP, and configure it to trust only your own proxies. Behind Werkzeug's `ProxyFix`, Zen uses the IP that `ProxyFix` chose, so set the number of proxies there. +If Uvicorn (`--forwarded-allow-ips`, by default `127.0.0.1`) or Hypercorn's `ProxyFixMiddleware` resolves the client IP, set `AIKIDO_TRUST_PROXY=false` so that Zen uses that IP, and configure the server to trust only your own proxies. When Zen reads `x-forwarded-for` behind Werkzeug's `ProxyFix`, it uses the IP that `ProxyFix` chose, so set the number of proxies there. From ae6594da00b48f4deccc0b85e1d75659f833cd6b Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Wed, 25 Nov 2026 13:24:41 +0200 Subject: [PATCH 12/15] Name the unlisted-connection condition behind ProxyFix --- aikido_zen/context/wsgi/__init__.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index 0287b8be5..2934e0d76 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -43,8 +43,9 @@ def set_wsgi_attributes_on_context(context, environ): if connection_ip != raw_ip and get_ip_header_name() == "X_FORWARDED_FOR": client_ip = normalize_ip(raw_ip) cidr_mode = isinstance(get_trust_proxy_config(), CIDRTrustProxy) + unlisted_connection = cidr_mode and not context.is_behind_trusted_proxy # The same fallbacks as without ProxyFix. - if not is_ip(client_ip) or (cidr_mode and not context.is_behind_trusted_proxy): + if unlisted_connection or not is_ip(client_ip): client_ip = connection_ip context.remote_address = client_ip if is_ip(client_ip) else None else: From 6e26e778b8724e9e63846a07c54c6decc7a6389b Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Thu, 26 Nov 2026 16:50:26 +0200 Subject: [PATCH 13/15] Count each ASGI header line once when selecting the client IP The UTF-8 reading of a non-ASCII line is still scanned, but it no longer shifts the hop count. The selector only returns valid IPs, so the caller does not check them again. --- aikido_zen/context/asgi/init_test.py | 18 ++++++++++++++++++ .../context/asgi/normalize_asgi_headers.py | 4 ++-- aikido_zen/context/init_test.py | 19 +++++++++++++++++++ aikido_zen/helpers/get_ip_from_request.py | 12 +++++------- aikido_zen/helpers/headers.py | 7 +++++++ 5 files changed, 51 insertions(+), 9 deletions(-) diff --git a/aikido_zen/context/asgi/init_test.py b/aikido_zen/context/asgi/init_test.py index d4af745ae..f79d4fc23 100644 --- a/aikido_zen/context/asgi/init_test.py +++ b/aikido_zen/context/asgi/init_test.py @@ -258,6 +258,24 @@ def test_sql_injection_in_any_cookie_value_the_app_can_read_is_detected( ) +@pytest.mark.parametrize("app_value", ["café' OR '1'='1", "café' OR '1'='1"]) +def test_sql_injection_in_either_decoding_of_a_header_is_detected(app_value): + scope = { + "type": "http", + "method": "GET", + "headers": [(b"x-dog-name", "café' OR '1'='1".encode())], + "query_string": b"", + "client": ["6.6.6.6"], + "server": ["192.168.0.6", 80], + "scheme": "http", + "root_path": "", + "path": "/users", + } + context = ZenContext(req=scope, source="starlette") + query = f"SELECT * FROM users WHERE name = '{app_value}'" + assert context_contains_sql_injection(query, "select", context, "sqlite") + + def test_valid_utf8_query_matches_strict_decode(): raw = "q=café' OR 1=1 --&b=d".encode("utf-8") scope = { diff --git a/aikido_zen/context/asgi/normalize_asgi_headers.py b/aikido_zen/context/asgi/normalize_asgi_headers.py index 2418ed507..549cbcc69 100644 --- a/aikido_zen/context/asgi/normalize_asgi_headers.py +++ b/aikido_zen/context/asgi/normalize_asgi_headers.py @@ -1,6 +1,6 @@ """Mainly exports normalize_asgi_headers""" -from aikido_zen.helpers.headers import Headers +from aikido_zen.helpers.headers import AlternateReading, Headers def normalize_asgi_headers(headers) -> Headers: @@ -27,4 +27,4 @@ def decoded_header_values(raw): return [as_framework] if as_utf8 == as_framework: return [as_framework] - return [as_utf8, as_framework] + return [AlternateReading(as_utf8), as_framework] diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index eb18264c2..8f7533818 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -181,6 +181,25 @@ def test_client_ip_is_read_from_every_forwarded_header_line(monkeypatch, setting assert context.remote_address == "9.9.9.9" +def test_hop_count_counts_a_non_ascii_forwarded_line_once(monkeypatch): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "3") + request = { + "method": "GET", + "headers": [ + (b"x-forwarded-for", b"9.9.9.9"), + (b"x-forwarded-for", "café, 8.8.8.8".encode()), + ], + "query_string": b"", + "client": ("10.0.0.3", 1234), + "server": ("localhost", 8080), + "scheme": "http", + "root_path": "", + "path": "/hello", + } + context = Context(req=request, source="starlette") + assert context.remote_address == "9.9.9.9" + + def context_behind_proxy_fix(request, **proxy_fix_args): environs = [] diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index dbe673a9a..58c6a4325 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -21,11 +21,11 @@ def get_ip_from_request(remote_address: str, headers: Headers) -> Optional[str]: """ Tries and get the IP address from the request, checking for x-forwarded-for """ - ip_header = ", ".join(headers.get(get_ip_header_name(), [])) + ip_header = ", ".join(headers.get_fields(get_ip_header_name())) if ip_header and is_trusted_proxy_request(remote_address): ip_header_value = get_client_ip_from_header(ip_header) - if ip_header_value and is_ip(ip_header_value): + if ip_header_value: return ip_header_value if remote_address and is_ip(remote_address): @@ -47,11 +47,9 @@ def get_client_ip_from_header(value): ip = normalize_ip(forwarded_ips[index].strip()) return ip if is_ip(ip) else None - for index in range(len(forwarded_ips) - 1, -1, -1): - ip = normalize_ip(forwarded_ips[index].strip()) - if not is_ip(ip): - continue - if is_private_ip(ip): + for entry in reversed(forwarded_ips): + ip = normalize_ip(entry.strip()) + if not is_ip(ip) or is_private_ip(ip): continue if isinstance(config, CIDRTrustProxy) and config.matcher.has(ip): continue diff --git a/aikido_zen/helpers/headers.py b/aikido_zen/helpers/headers.py index 1bea4b350..9091a3dd9 100644 --- a/aikido_zen/helpers/headers.py +++ b/aikido_zen/helpers/headers.py @@ -1,6 +1,10 @@ from typing import List, Optional +class AlternateReading(str): + """A second decoding of the same header field. get_fields skips it.""" + + class Headers(dict): def store_headers(self, key: str, values: List[str]): normalized_key = self.normalize_header_key(key) @@ -18,6 +22,9 @@ def get_header(self, key: str) -> Optional[str]: return self.get(key)[-1] return None + def get_fields(self, key: str) -> List[str]: + return [v for v in self.get(key, []) if not isinstance(v, AlternateReading)] + @staticmethod def validate_header_key(key: str): if not key.isupper(): From b519e4c567710110335530f792587421d715b0dc Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Thu, 26 Nov 2026 16:51:28 +0200 Subject: [PATCH 14/15] Document ProxyFix with a matching hop count Zen reads the client IP before a ProxyFix inside app.wsgi_app runs, so AIKIDO_TRUST_PROXY must equal x_for for both to select the same client. --- aikido_zen/context/init_test.py | 8 ++++++++ aikido_zen/sources/flask/flask_test.py | 28 ++++++++++++++++++++++++++ docs/proxy.md | 12 ++++++++++- 3 files changed, 47 insertions(+), 1 deletion(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index 8f7533818..8b0d49ec0 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -231,6 +231,14 @@ def test_client_ip_behind_proxy_fix(monkeypatch, x_for, forwarded, client_ip): assert context.is_behind_trusted_proxy is True +def test_fewer_forwarded_entries_than_x_for_behind_proxy_fix(monkeypatch): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "2") + request = dict( + basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR="9.9.9.9" + ) + assert context_behind_proxy_fix(request, x_for=2).remote_address == "1.2.3.4" + + @pytest.mark.parametrize( "setting, custom_header, client_ip", [ diff --git a/aikido_zen/sources/flask/flask_test.py b/aikido_zen/sources/flask/flask_test.py index 1b6522196..1ed55b994 100644 --- a/aikido_zen/sources/flask/flask_test.py +++ b/aikido_zen/sources/flask/flask_test.py @@ -323,6 +323,34 @@ def start_response(status, headers): assert request_ref() is None +def test_ip_checks_use_the_proxy_fix_client_ip_with_a_matching_hop_count( + body_app, monkeypatch +): + from flask import request + from werkzeug.middleware.proxy_fix import ProxyFix + + monkeypatch.setenv("AIKIDO_TRUST_PROXY", "2") + body_app.wsgi_app = ProxyFix(body_app.wsgi_app, x_for=2) + checked_ips = [] + + def should_block(): + checked_ips.append(get_current_context().remote_address) + + monkeypatch.setattr(aikido_zen.sources.flask, "should_block", should_block) + + @body_app.get("/") + def view(): + return request.remote_addr + + response = body_app.test_client().get( + "/", + headers={"X-Forwarded-For": "6.6.6.6, 8.8.8.8, 1.1.1.1"}, + environ_overrides={"REMOTE_ADDR": "192.0.2.10"}, + ) + assert response.get_data(as_text=True) == "8.8.8.8" + assert checked_ips == ["8.8.8.8"] + + def test_streaming_response_keeps_flask_context_and_body(body_app): from flask import request, stream_with_context diff --git a/docs/proxy.md b/docs/proxy.md index bac7753b6..ef06eb5dc 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -51,4 +51,14 @@ flowchart TD ## Servers that resolve the client IP -If Uvicorn (`--forwarded-allow-ips`, by default `127.0.0.1`) or Hypercorn's `ProxyFixMiddleware` resolves the client IP, set `AIKIDO_TRUST_PROXY=false` so that Zen uses that IP, and configure the server to trust only your own proxies. When Zen reads `x-forwarded-for` behind Werkzeug's `ProxyFix`, it uses the IP that `ProxyFix` chose, so set the number of proxies there. +If Uvicorn (`--forwarded-allow-ips`, by default `127.0.0.1`) or Hypercorn's `ProxyFixMiddleware` resolves the client IP, set `AIKIDO_TRUST_PROXY=false` so that Zen uses that IP, and configure the server to trust only your own proxies. + +## Flask and Werkzeug's `ProxyFix` + +If you use [Werkzeug's `ProxyFix`](https://werkzeug.palletsprojects.com/en/stable/middleware/proxy_fix/), set `AIKIDO_TRUST_PROXY` to the same number as its `x_for` (`1` by default): + +```python +app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2) # with AIKIDO_TRUST_PROXY=2 +``` + +Zen reads the client IP before a `ProxyFix` inside `app.wsgi_app` runs, so it selects the IP from the header itself. The same number makes Zen select the same entry as `ProxyFix`, and use the remote address of the request socket when the header has fewer entries. Use the same setting when `ProxyFix` wraps the whole app. From d5cc70b4ac042612e9b0055ef1b010eb1a6cade7 Mon Sep 17 00:00:00 2001 From: Daniel Iulian Iacob Date: Thu, 26 Nov 2026 18:58:54 +0200 Subject: [PATCH 15/15] Apply Zen's proxy settings behind ProxyFix With proxy trust on, Zen applies its setting to the connection address that ProxyFix keeps. With it off, Zen uses the address the app sees, as .NET does. This replaces the special cases for the address ProxyFix chose. --- aikido_zen/context/init_test.py | 64 ++++------------------------- aikido_zen/context/wsgi/__init__.py | 33 ++++++--------- docs/proxy.md | 2 +- 3 files changed, 21 insertions(+), 78 deletions(-) diff --git a/aikido_zen/context/init_test.py b/aikido_zen/context/init_test.py index 8b0d49ec0..2f33240fe 100644 --- a/aikido_zen/context/init_test.py +++ b/aikido_zen/context/init_test.py @@ -212,69 +212,21 @@ def app(environ, start_response): @pytest.mark.parametrize( - "x_for, forwarded, client_ip", + "setting, peer, client_ip, trusted", [ - (1, "9.9.9.9", "9.9.9.9"), - (1, "9.9.9.9:1234", "9.9.9.9"), - (2, "9.9.9.9, 8.8.8.8", "9.9.9.9"), - (0, "9.9.9.9", "9.9.9.9"), - (1, "unknown", "1.2.3.4"), + ("1.2.3.0/24", "1.2.3.4", "8.8.8.8", True), + ("1.2.3.0/24", "5.5.5.5", "5.5.5.5", False), + ("false", "1.2.3.4", "9.9.9.9", False), ], ) -def test_client_ip_behind_proxy_fix(monkeypatch, x_for, forwarded, client_ip): - monkeypatch.setenv("AIKIDO_TRUST_PROXY", "1.2.3.0/24") - request = dict( - basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR=forwarded - ) - context = context_behind_proxy_fix(request, x_for=x_for) - assert context.remote_address == client_ip - assert context.is_behind_trusted_proxy is True - - -def test_fewer_forwarded_entries_than_x_for_behind_proxy_fix(monkeypatch): - monkeypatch.setenv("AIKIDO_TRUST_PROXY", "2") - request = dict( - basic_wsgi_req, REMOTE_ADDR="1.2.3.4", HTTP_X_FORWARDED_FOR="9.9.9.9" - ) - assert context_behind_proxy_fix(request, x_for=2).remote_address == "1.2.3.4" - - -@pytest.mark.parametrize( - "setting, custom_header, client_ip", - [ - ("true", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "9.9.9.9"), - ("1.2.3.0/24", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "9.9.9.9"), - ("true", {}, "1.2.3.4"), - ("false", {"HTTP_DO_CONNECTING_IP": "9.9.9.9"}, "1.2.3.4"), - ], -) -def test_custom_client_ip_header_behind_proxy_fix( - monkeypatch, setting, custom_header, client_ip -): +def test_client_ip_behind_proxy_fix(monkeypatch, setting, peer, client_ip, trusted): monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) - monkeypatch.setenv("AIKIDO_CLIENT_IP_HEADER", "do-connecting-ip") request = dict( - basic_wsgi_req, - REMOTE_ADDR="1.2.3.4", - HTTP_X_FORWARDED_FOR="8.8.8.8", - **custom_header, + basic_wsgi_req, REMOTE_ADDR=peer, HTTP_X_FORWARDED_FOR="9.9.9.9, 8.8.8.8" ) - assert context_behind_proxy_fix(request).remote_address == client_ip - - -@pytest.mark.parametrize( - "setting, client_ip", [("1.2.3.0/24", "5.5.5.5"), ("false", "6.6.6.6")] -) -def test_connection_from_an_unlisted_address_behind_proxy_fix( - monkeypatch, setting, client_ip -): - monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) - request = dict( - basic_wsgi_req, REMOTE_ADDR="5.5.5.5", HTTP_X_FORWARDED_FOR="6.6.6.6" - ) - context = context_behind_proxy_fix(request) + context = context_behind_proxy_fix(request, x_for=2) assert context.remote_address == client_ip - assert context.is_behind_trusted_proxy is False + assert context.is_behind_trusted_proxy is trusted def test_set_as_current_context(mocker): diff --git a/aikido_zen/context/wsgi/__init__.py b/aikido_zen/context/wsgi/__init__.py index 2934e0d76..f79d33597 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -1,15 +1,10 @@ """Exports set_wsgi_attributes_on_context""" from urllib.parse import parse_qs -from aikido_zen.helpers.get_ip_from_request import ( - get_ip_from_request, - get_ip_header_name, - is_ip, - normalize_ip, -) +from aikido_zen.helpers.get_ip_from_request import get_ip_from_request from aikido_zen.helpers.logging import logger from aikido_zen.helpers.trust_proxy import ( - CIDRTrustProxy, + BooleanTrustProxy, get_trust_proxy_config, is_trusted_proxy_request, ) @@ -33,23 +28,19 @@ def set_wsgi_attributes_on_context(context, environ): context.cookies = {} context.url = build_url_from_wsgi(environ) context.query = parse_qs(environ["QUERY_STRING"]) - raw_ip = environ["REMOTE_ADDR"] - # Werkzeug's ProxyFix keeps the connection address here. A different REMOTE_ADDR is - # the client ProxyFix chose, which Zen uses instead of parsing the header again. + remote_addr = environ["REMOTE_ADDR"] + # A ProxyFix around the app keeps the connection address here. connection_ip = ( - environ.get("werkzeug.proxy_fix.orig", {}).get("REMOTE_ADDR") or raw_ip + environ.get("werkzeug.proxy_fix.orig", {}).get("REMOTE_ADDR") or remote_addr ) context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) - if connection_ip != raw_ip and get_ip_header_name() == "X_FORWARDED_FOR": - client_ip = normalize_ip(raw_ip) - cidr_mode = isinstance(get_trust_proxy_config(), CIDRTrustProxy) - unlisted_connection = cidr_mode and not context.is_behind_trusted_proxy - # The same fallbacks as without ProxyFix. - if unlisted_connection or not is_ip(client_ip): - client_ip = connection_ip - context.remote_address = client_ip if is_ip(client_ip) else None - else: - context.remote_address = get_ip_from_request(connection_ip, context.headers) + # Only an untrusted request can have proxy trust off, so read the setting only then. + trust_off = not context.is_behind_trusted_proxy and ( + get_trust_proxy_config() == BooleanTrustProxy(False) + ) + context.remote_address = get_ip_from_request( + remote_addr if trust_off else connection_ip, context.headers + ) # Content type is generally not included as a header, do include this as a header to simplify : if "CONTENT_TYPE" in environ: diff --git a/docs/proxy.md b/docs/proxy.md index ef06eb5dc..1180428d1 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -61,4 +61,4 @@ If you use [Werkzeug's `ProxyFix`](https://werkzeug.palletsprojects.com/en/stabl app.wsgi_app = ProxyFix(app.wsgi_app, x_for=2) # with AIKIDO_TRUST_PROXY=2 ``` -Zen reads the client IP before a `ProxyFix` inside `app.wsgi_app` runs, so it selects the IP from the header itself. The same number makes Zen select the same entry as `ProxyFix`, and use the remote address of the request socket when the header has fewer entries. Use the same setting when `ProxyFix` wraps the whole app. +Zen selects the client IP from the header itself, also when `ProxyFix` wraps the whole app. The same number makes Zen select the same entry as `ProxyFix`, and use the remote address of the request socket when the header has fewer entries.