validate proxy header authentication by checking loopback addresses

This commit is contained in:
duan_j committed 2026-06-10 10:24:28 +02:00
1 parent 11a56addee
commit 4c0c86b8ec
1 file changed
+17 -3
+17 -3
View File
@@ -1,4 +1,5 @@
import grp
import ipaddress
import os
import pwd
import re
@@ -80,14 +81,27 @@ def authenticate_from_apache_log() -> str:
)
def _is_loopback(host: str | None) -> bool:
if host is None:
return False
try:
addr = ipaddress.ip_address(host)
# Unwrap IPv4-mapped IPv6 (e.g. ::ffff:127.0.0.1) before checking
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
return addr.ipv4_mapped.is_loopback
return addr.is_loopback
except ValueError:
return False
def authenticate_from_proxy_header(request: Request) -> str:
"""
Extract the pre-authenticated username from the trusted Apache proxy header.
Only trust this header when the request originates from localhost (127.0.0.1 / ::1),
meaning only the Apache proxy running on the same host can supply it.
Only trust this header when the request originates from localhost, meaning
only the Apache proxy running on the same host can supply it.
"""
client_host = request.client.host if request.client else None
if client_host not in ("127.0.0.1", "::1"):
if not _is_loopback(client_host):
raise AuthenticationException(
message="X-Remote-User header is only trusted from the localhost proxy",
status_code=401,