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/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/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 2c4c47135..2f33240fe 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 @@ -50,6 +51,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 +85,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 +117,118 @@ 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 + + +@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_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 = [] + + 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( + "setting, peer, client_ip, trusted", + [ + ("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, setting, peer, client_ip, trusted): + monkeypatch.setenv("AIKIDO_TRUST_PROXY", setting) + request = dict( + basic_wsgi_req, REMOTE_ADDR=peer, HTTP_X_FORWARDED_FOR="9.9.9.9, 8.8.8.8" + ) + context = context_behind_proxy_fix(request, x_for=2) + assert context.remote_address == client_ip + assert context.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 +250,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..f79d33597 100644 --- a/aikido_zen/context/wsgi/__init__.py +++ b/aikido_zen/context/wsgi/__init__.py @@ -3,6 +3,11 @@ 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 ( + BooleanTrustProxy, + 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 @@ -23,8 +28,18 @@ def set_wsgi_attributes_on_context(context, environ): context.cookies = {} context.url = build_url_from_wsgi(environ) context.query = parse_qs(environ["QUERY_STRING"]) + 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 remote_addr + ) + context.is_behind_trusted_proxy = is_trusted_proxy_request(connection_ip) + # 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( - environ["REMOTE_ADDR"], context.headers + 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 : diff --git a/aikido_zen/helpers/get_ip_from_request.py b/aikido_zen/helpers/get_ip_from_request.py index 73de267ab..58c6a4325 100644 --- a/aikido_zen/helpers/get_ip_from_request.py +++ b/aikido_zen/helpers/get_ip_from_request.py @@ -8,17 +8,24 @@ from aikido_zen.helpers.headers import Headers 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]: """ 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(): + 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): @@ -31,32 +38,36 @@ 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 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 + 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 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..d994bf329 100644 --- a/aikido_zen/helpers/get_ip_from_request_test.py +++ b/aikido_zen/helpers/get_ip_from_request_test.py @@ -1,10 +1,17 @@ +import sys +import threading + 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, is_ip, get_client_ip_from_header, ) from .headers import Headers +from .ip_matcher import IPMatcher +from .trust_proxy import is_trusted_proxy_request, parse_trust_proxy @pytest.fixture(autouse=True) @@ -87,7 +94,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 +106,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 +145,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 +179,173 @@ 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 + + +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", + [ + ("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", + ), + ("::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): + 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 +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", + [ + ( + "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(setting) + + assert caplog.text.count(warning) == 1 + + +@pytest.mark.parametrize( + "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_supported_values(caplog, setting): + parse_trust_proxy.cache_clear() + + parse_trust_proxy(setting) + + assert caplog.text == "" + + +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): + 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() + first = threading.Thread(target=trust_proxy.get_trust_proxy_config) + first.start() + first_inside.wait() + + trust_proxy.get_trust_proxy_config() + second_done.set() + first.join() + + assert second_finished_in_time == [True] + + +@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/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(): diff --git a/aikido_zen/helpers/trust_proxy.py b/aikido_zen/helpers/trust_proxy.py new file mode 100644 index 000000000..a22063d02 --- /dev/null +++ b/aikido_zen/helpers/trust_proxy.py @@ -0,0 +1,77 @@ +import ipaddress +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 +from aikido_zen.helpers.logging import logger + + +@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: + value = (value or "").strip() + 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: + 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)) + if value.lower() not in ("false", "0", "no", "n", "off"): + logger.warning("Ignoring an invalid trusted proxy setting.") + 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): + return config.value + if isinstance(config, CIDRTrustProxy): + return bool(remote_address) and config.matcher.has(remote_address) + return True 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 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/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..1180428d1 100644 --- a/docs/proxy.md +++ b/docs/proxy.md @@ -1,12 +1,64 @@ # 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 +``` + +## 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. + +## 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 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.