Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions aikido_zen/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=""):
Expand Down Expand Up @@ -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()
2 changes: 2 additions & 0 deletions aikido_zen/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions aikido_zen/context/asgi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
18 changes: 18 additions & 0 deletions aikido_zen/context/asgi/init_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
4 changes: 2 additions & 2 deletions aikido_zen/context/asgi/normalize_asgi_headers.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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]
116 changes: 116 additions & 0 deletions aikido_zen/context/init_test.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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")
Expand All @@ -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 == {
Expand Down
17 changes: 16 additions & 1 deletion aikido_zen/context/wsgi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 :
Expand Down
63 changes: 37 additions & 26 deletions aikido_zen/helpers/get_ip_from_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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():
Expand Down
Loading
Loading