Python
fix(auth): validate loopback origins as IP addresses (#90)
u7-u74dbf7b6ed2cb
diff --git a/memhub/apps/core/src/one_memory/auth.py b/memhub/apps/core/src/one_memory/auth.pyindex b91918f..f7f8450 100644--- a/memhub/apps/core/src/one_memory/auth.py+++ b/memhub/apps/core/src/one_memory/auth.py@@ -1,4 +1,5 @@import hmac+import ipaddressfrom collections.abc import Callablefrom urllib.parse import urlsplit@@ -35,7 +36,15 @@ def is_loopback_origin(origin: str) -> bool:host = parsed.hostnameif not host:return False- return host in LOOPBACK_HOSTNAMES or host.startswith("127.")+ if host in LOOPBACK_HOSTNAMES:+ return True+ # A prefix check is not enough: "127.attacker.example" is a perfectly valid+ # DNS name that resolves wherever its owner wants (including 127.0.0.1 via+ # DNS rebinding). Parse the address and ask the standard library.+ try:+ return ipaddress.ip_address(host).is_loopback+ except ValueError:+ return Falsedef local_api_guard(diff --git a/memhub/apps/core/tests/test_loopback_origin_write.py b/memhub/apps/core/tests/test_loopback_origin_write.pyindex fe1f889..d4d9726 100644--- a/memhub/apps/core/tests/test_loopback_origin_write.py+++ b/memhub/apps/core/tests/test_loopback_origin_write.py@@ -61,3 +61,19 @@ def test_a_page_from_anywhere_else_is_still_refused() -> None:"http://10.0.0.7:8765",]) == [403, 403, 403]+++def test_dns_names_that_only_start_with_127_are_refused() -> None:+ # A prefix check treated any "127.*" hostname as loopback. These are+ # ordinary DNS names an attacker can point at 127.0.0.1 (DNS rebinding).+ assert _statuses(+ [+ "http://127.0.0.1.attacker.example:8765",+ "https://127.attacker.example",+ "http://127.0.0.1.nip.io:8765",+ ]+ ) == [403, 403, 403]+++def test_ipv6_loopback_is_still_accepted() -> None:+ assert _statuses(["http://[::1]:8765"]) == [200]