From 7fd1a4fbc3774205e4f3ee843934d3816ebb4855 Mon Sep 17 00:00:00 2001 From: Eduardo Silva Date: Sat, 21 Nov 2026 12:26:28 -0300 Subject: [PATCH] harden auth gateway --- .../auth-gateway/auth_gateway/limiter.py | 32 +++++++- .../services/challenge_service.py | 19 ++++- .../auth_gateway/services/oidc_service.py | 6 +- .../auth_gateway/services/password_service.py | 14 ++-- .../auth_gateway/services/resolver.py | 19 +++-- .../auth_gateway/services/totp_service.py | 29 ++++++- .../templates/login_password.html | 4 +- .../auth_gateway/web/auth_routes.py | 11 ++- .../auth_gateway/web/dependencies.py | 39 +++++++++- .../auth_gateway/web/login_routes.py | 76 ++++++++++++------- containers/auth-gateway/entrypoint.sh | 2 +- containers/caddy/process_config.py | 4 +- 12 files changed, 195 insertions(+), 60 deletions(-) diff --git a/containers/auth-gateway/auth_gateway/limiter.py b/containers/auth-gateway/auth_gateway/limiter.py index d3e1fda..65b00eb 100644 --- a/containers/auth-gateway/auth_gateway/limiter.py +++ b/containers/auth-gateway/auth_gateway/limiter.py @@ -1,14 +1,40 @@ +import ipaddress + from fastapi import Request from slowapi import Limiter AUTH_RATE_LIMIT = "5/minute" +def _is_trusted_proxy(peer: str) -> bool: + """Caddy reaches the gateway over a Docker network, so only private and loopback peers can forward the client.""" + try: + address = ipaddress.ip_address(peer) + except ValueError: + return False + return address.is_private or address.is_loopback + + def get_real_client_ip(request: Request) -> str: + peer = request.client.host if request.client else "" forwarded_for = request.headers.get("x-forwarded-for", "") - if forwarded_for: + if forwarded_for and _is_trusted_proxy(peer): return forwarded_for.split(",")[0].strip() - return request.client.host if request.client else "unknown" + return peer or "unknown" -limiter = Limiter(key_func=get_real_client_ip) +def get_rate_limit_key(request: Request) -> str: + """Client address used by the rate limit. IPv6 clients usually own a whole /64, so it counts as one address.""" + client = get_real_client_ip(request) + try: + address = ipaddress.ip_address(client) + except ValueError: + return client + if address.version == 6: + if address.ipv4_mapped: + return str(address.ipv4_mapped) + return str(ipaddress.ip_network(f"{address}/64", strict=False)) + return str(address) + + +limiter = Limiter(key_func=get_rate_limit_key) diff --git a/containers/auth-gateway/auth_gateway/services/challenge_service.py b/containers/auth-gateway/auth_gateway/services/challenge_service.py index 3340a5c..e5c1b0f 100644 --- a/containers/auth-gateway/auth_gateway/services/challenge_service.py +++ b/containers/auth-gateway/auth_gateway/services/challenge_service.py @@ -8,6 +8,8 @@ import time ALTCHA_MAX_NUMBER = 1_000_000 CHALLENGE_TTL_SECONDS = 300 # 5 minutes CHALLENGE_COOKIE_NAME = "auth_gateway_challenge" +# Nonces of challenge cookies revoked after a failed login: a script keeping the old cookie must solve a new challenge +_revoked_nonces: dict[str, float] = {} def generate_altcha_challenge(hmac_key: str) -> dict: @@ -63,7 +65,20 @@ def verify_challenge_cookie(cookie_value: str, secret: str) -> bool: expected_sig = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() if not hmac.compare_digest(expected_sig, sig): return False - timestamp = int(message.split(".")[0]) - return (time.time() - timestamp) < CHALLENGE_TTL_SECONDS + timestamp, nonce = message.split(".") + if nonce in _revoked_nonces: + return False + return (time.time() - int(timestamp)) < CHALLENGE_TTL_SECONDS except Exception: return False + + +def revoke_challenge_cookie(cookie_value: str | None) -> None: + """Make a challenge cookie invalid before it expires.""" + now = time.time() + for nonce, revoked_at in list(_revoked_nonces.items()): + if now - revoked_at > CHALLENGE_TTL_SECONDS: + del _revoked_nonces[nonce] + parts = (cookie_value or "").split(".") + if len(parts) == 3 and parts[1]: + _revoked_nonces[parts[1]] = now diff --git a/containers/auth-gateway/auth_gateway/services/oidc_service.py b/containers/auth-gateway/auth_gateway/services/oidc_service.py index 54ba6ab..1b82ff4 100644 --- a/containers/auth-gateway/auth_gateway/services/oidc_service.py +++ b/containers/auth-gateway/auth_gateway/services/oidc_service.py @@ -1,8 +1,9 @@ from dataclasses import dataclass -from auth_gateway.models.auth import OIDCMethodModel from authlib.integrations.starlette_client import OAuth +from auth_gateway.models.auth import OIDCMethodModel + @dataclass class OIDCIdentity: @@ -45,6 +46,9 @@ class OIDCService: if "userinfo" in token and isinstance(token["userinfo"], dict): claims.update(token["userinfo"]) email = claims.get("email") + # An email the provider did not verify can be set by the user, so it must not pass the allowlists + if str(claims.get("email_verified", True)).lower() == "false": + email = None subject = claims.get("sub") return OIDCIdentity(subject=subject, email=email, claims=claims) diff --git a/containers/auth-gateway/auth_gateway/services/password_service.py b/containers/auth-gateway/auth_gateway/services/password_service.py index 3ba9dae..a8074d8 100644 --- a/containers/auth-gateway/auth_gateway/services/password_service.py +++ b/containers/auth-gateway/auth_gateway/services/password_service.py @@ -1,10 +1,11 @@ from argon2 import PasswordHasher -from argon2.exceptions import VerifyMismatchError +from argon2.exceptions import InvalidHashError, VerifyMismatchError from auth_gateway.models.auth import UserModel - password_hasher = PasswordHasher() +# Checked when the user does not exist, so the response time does not reveal which usernames exist +DUMMY_PASSWORD_HASH = password_hasher.hash("unused-password") MAX_PASSWORD_LENGTH = 1024 @@ -14,10 +15,9 @@ def verify_user_password(username: str, password: str, users: dict[str, UserMode if not password or len(password) > MAX_PASSWORD_LENGTH: return None user = users.get(username) - if not user or not user.password_hash: - return None + password_hash = user.password_hash if user and user.password_hash else DUMMY_PASSWORD_HASH try: - password_hasher.verify(user.password_hash, password) - except VerifyMismatchError: + password_hasher.verify(password_hash, password) + except (VerifyMismatchError, InvalidHashError): return None - return user + return user if password_hash is not DUMMY_PASSWORD_HASH else None diff --git a/containers/auth-gateway/auth_gateway/services/resolver.py b/containers/auth-gateway/auth_gateway/services/resolver.py index 76340ac..0a9c5a5 100644 --- a/containers/auth-gateway/auth_gateway/services/resolver.py +++ b/containers/auth-gateway/auth_gateway/services/resolver.py @@ -1,6 +1,7 @@ import posixpath +import re from dataclasses import dataclass -from urllib.parse import unquote, urlsplit +from urllib.parse import unquote from auth_gateway.models.applications import ApplicationModel from auth_gateway.models.routes import AppRoutesModel, RoutePolicyBindingModel @@ -21,16 +22,22 @@ def normalize_host(raw_host: str) -> str: def normalize_path(raw_uri: str) -> str: - parsed = urlsplit(raw_uri or "/") - path = unquote(parsed.path or "/") + """ + Path used to pick the policy, normalized the same way Caddy matches routes: repeated slashes are merged and + . and .. segments are resolved. The value is a request URI, never a full URL, so a leading // is part of the + path and not a network location. + """ + path = re.split(r"[?#]", raw_uri or "/", maxsplit=1)[0] + path = unquote(path) or "/" path = path if path.startswith("/") else f"/{path}" - # Resolve any .. or . segments to prevent path traversal bypasses + path = re.sub(r"/{2,}", "/", path) return posixpath.normpath(path) def _path_matches(path: str, prefix: str) -> bool: - """Check path boundary correctly — prevents /admin matching /administrator.""" - prefix = prefix.rstrip("/") + """Check path boundary correctly — prevents /admin matching /administrator. Case-insensitive, like Caddy.""" + path = path.lower() + prefix = prefix.rstrip("/").lower() return path == prefix or path.startswith(prefix + "/") diff --git a/containers/auth-gateway/auth_gateway/services/totp_service.py b/containers/auth-gateway/auth_gateway/services/totp_service.py index 65d9dc4..32e07e6 100644 --- a/containers/auth-gateway/auth_gateway/services/totp_service.py +++ b/containers/auth-gateway/auth_gateway/services/totp_service.py @@ -1,9 +1,23 @@ +import hashlib import logging +import time +from datetime import datetime import pyotp logger = logging.getLogger("uvicorn.error") +VALID_WINDOW = 1 +# (secret hash, time step) of codes already accepted, so a code cannot be used twice +_used_codes: dict[tuple[str, int], float] = {} + + +def _forget_expired_codes(now: float, interval: int) -> None: + oldest = now - interval * (2 * VALID_WINDOW + 2) + for key, used_at in list(_used_codes.items()): + if used_at < oldest: + del _used_codes[key] + def verify_totp(secret: str, token: str) -> bool: normalized_secret = secret.strip() @@ -15,4 +29,17 @@ def verify_totp(secret: str, token: str) -> bool: except ValueError as error: logger.warning("TOTP secret rejected (%s) — generate a new secret with at least 24 Base32 characters.", error) return False - return totp.verify(normalized_token, valid_window=1) + + now = time.time() + _forget_expired_codes(now, totp.interval) + secret_hash = hashlib.sha256(normalized_secret.encode()).hexdigest() + current_step = totp.timecode(datetime.fromtimestamp(now)) + for offset in range(-VALID_WINDOW, VALID_WINDOW + 1): + step = current_step + offset + if pyotp.utils.strings_equal(normalized_token, totp.generate_otp(step)): + if (secret_hash, step) in _used_codes: + logger.warning("TOTP code reuse rejected.") + return False + _used_codes[(secret_hash, step)] = now + return True + return False diff --git a/containers/auth-gateway/auth_gateway/templates/login_password.html b/containers/auth-gateway/auth_gateway/templates/login_password.html index 2ec7031..f9aad40 100644 --- a/containers/auth-gateway/auth_gateway/templates/login_password.html +++ b/containers/auth-gateway/auth_gateway/templates/login_password.html @@ -11,11 +11,11 @@ diff --git a/containers/auth-gateway/auth_gateway/web/auth_routes.py b/containers/auth-gateway/auth_gateway/web/auth_routes.py index 33f0c82..efb0bf1 100644 --- a/containers/auth-gateway/auth_gateway/web/auth_routes.py +++ b/containers/auth-gateway/auth_gateway/web/auth_routes.py @@ -1,5 +1,9 @@ import re +from fastapi import APIRouter, Request, Response +from fastapi.responses import PlainTextResponse, RedirectResponse + +from auth_gateway.limiter import get_real_client_ip from auth_gateway.services.policy_engine import evaluate_ip_access, extract_client_ip from auth_gateway.services.resolver import resolve_request_context from auth_gateway.web.dependencies import ( @@ -7,10 +11,9 @@ from auth_gateway.web.dependencies import ( get_effective_policy, get_runtime_config, get_session, + get_session_factors, session_is_allowed, ) -from fastapi import APIRouter, Request, Response -from fastapi.responses import PlainTextResponse, RedirectResponse router = APIRouter() @@ -32,7 +35,7 @@ async def auth_check(request: Request): if effective_policy.mode == "bypass": return PlainTextResponse("OK", status_code=200) - client_ip = extract_client_ip(request.headers.get("x-forwarded-for", "")) + client_ip = extract_client_ip(get_real_client_ip(request)) ip_allowed = evaluate_ip_access(runtime_config, effective_policy, client_ip) if effective_policy.ip_method_names and not ip_allowed: return PlainTextResponse("Access denied for this IP address.", status_code=403) @@ -44,7 +47,7 @@ async def auth_check(request: Request): login_url = build_external_url(request, "/login", next=context.path) return RedirectResponse(login_url, status_code=302) - current_factors = set(session.auth_factors if session else []) + current_factors = get_session_factors(session, effective_policy) if ip_allowed: current_factors.add("ip") diff --git a/containers/auth-gateway/auth_gateway/web/dependencies.py b/containers/auth-gateway/auth_gateway/web/dependencies.py index faeb906..95ed916 100644 --- a/containers/auth-gateway/auth_gateway/web/dependencies.py +++ b/containers/auth-gateway/auth_gateway/web/dependencies.py @@ -1,14 +1,15 @@ from secrets import token_urlsafe from urllib.parse import urlencode +from fastapi import HTTPException, Request +from fastapi.responses import Response + from auth_gateway.config_loader import RuntimeConfigStore from auth_gateway.models.auth import OIDCMethodModel, TotpMethodModel from auth_gateway.models.runtime import RuntimeConfig from auth_gateway.models.session import SessionRecord from auth_gateway.services.policy_engine import EffectivePolicy, build_effective_policy from auth_gateway.services.resolver import RequestContext, normalize_host, normalize_path, resolve_request_context -from fastapi import HTTPException, Request -from fastapi.responses import Response def get_runtime_config(request: Request) -> RuntimeConfig: @@ -64,6 +65,31 @@ def session_is_allowed(session: SessionRecord | None, effective_policy: Effectiv return session.username in effective_policy.allowed_users +def get_session_factors(session: SessionRecord | None, effective_policy: EffectivePolicy) -> set[str]: + """ + Factors of the session that count for the policy. OIDC and TOTP only count when they were completed with one + of the methods of the policy: each method has its own allowlists or secret. + """ + if not session: + return set() + factors = set(session.auth_factors) + factor_methods = session.metadata.get("factor_methods", {}) + for factor, method_names in (("oidc", effective_policy.oidc_method_names), ("totp", effective_policy.totp_method_names)): + if factor in factors and not set(factor_methods.get(factor, [])) & set(method_names): + factors.discard(factor) + return factors + + +def factor_method_metadata(session: SessionRecord | None, factor: str, method_name: str) -> dict: + """Session metadata recording that the factor was completed with the given method.""" + current = session.metadata.get("factor_methods", {}) if session else {} + factor_methods = {name: list(methods) for name, methods in current.items()} + method_names = factor_methods.setdefault(factor, []) + if method_name not in method_names: + method_names.append(method_name) + return {"factor_methods": factor_methods} + + def get_totp_method(runtime_config: RuntimeConfig, effective_policy: EffectivePolicy) -> tuple[str, TotpMethodModel] | tuple[None, None]: for method_name in effective_policy.totp_method_names: method = runtime_config.auth_methods[method_name] @@ -120,9 +146,14 @@ def challenge_is_valid(request: Request) -> bool: return verify_challenge_cookie(cookie, request.app.state.settings.challenge_secret) -def build_challenge_url(request: Request, login_route: str, next_url: str) -> str: +def build_challenge_url(request: Request, login_route: str, next_url: str, error: str | None = None) -> str: external_path = request.app.state.settings.external_path.rstrip("/") login_path = f"{external_path}{login_route}" + params = {} if next_url and next_url != "/": - login_path = f"{login_path}?{urlencode({'next': next_url})}" + params["next"] = next_url + if error: + params["error"] = error + if params: + login_path = f"{login_path}?{urlencode(params)}" return build_external_url(request, "/challenge", next=login_path) diff --git a/containers/auth-gateway/auth_gateway/web/login_routes.py b/containers/auth-gateway/auth_gateway/web/login_routes.py index a5906e4..ab92fe5 100644 --- a/containers/auth-gateway/auth_gateway/web/login_routes.py +++ b/containers/auth-gateway/auth_gateway/web/login_routes.py @@ -5,6 +5,7 @@ from auth_gateway.models.auth import OIDCMethodModel logger = logging.getLogger("uvicorn.error") from auth_gateway.services.oidc_service import is_oidc_identity_allowed from auth_gateway.services.password_service import verify_user_password +from auth_gateway.services.challenge_service import CHALLENGE_COOKIE_NAME, revoke_challenge_cookie from auth_gateway.services.policy_engine import evaluate_ip_access, extract_client_ip from auth_gateway.services.resolver import normalize_host from auth_gateway.services.totp_service import verify_totp @@ -12,24 +13,32 @@ from auth_gateway.web.dependencies import ( build_challenge_url, build_external_url, challenge_is_valid, + factor_method_metadata, get_effective_expiration, get_effective_policy, get_oidc_method, get_or_create_csrf_token, get_runtime_config, get_session, + get_session_factors, get_totp_method, resolve_context_from_request, set_csrf_cookie, session_is_allowed, validate_csrf, ) -from auth_gateway.limiter import AUTH_RATE_LIMIT, limiter +from auth_gateway.limiter import AUTH_RATE_LIMIT, get_real_client_ip, limiter from fastapi import APIRouter, Form, HTTPException, Request from fastapi.responses import HTMLResponse, RedirectResponse router = APIRouter() +LOGIN_USERNAME_COOKIE_NAME = "auth_gateway_login_user" +LOGIN_ERRORS = { + "invalid_password": "Invalid username or password.", + "invalid_totp": "Invalid verification code.", +} + def _render(request: Request, template_name: str, status_code: int = 200, **context): templates = request.app.state.templates @@ -72,6 +81,28 @@ def _create_authenticated_session(request: Request, *, username=None, email=None ) +def _failed_login_redirect(request: Request, login_route: str, next_path: str, error: str, username: str | None = None): + """ + After a failed attempt the challenge must be solved again: the current challenge cookie is revoked and the + browser goes through the challenge back to the form, which shows the error. + """ + revoke_challenge_cookie(request.cookies.get(CHALLENGE_COOKIE_NAME)) + response = RedirectResponse(build_challenge_url(request, login_route, next_path, error=error), status_code=303) + response.delete_cookie(CHALLENGE_COOKIE_NAME, path="/") + if username: + # Kept out of the URL so the username does not end up in logs and browser history + response.set_cookie( + key=LOGIN_USERNAME_COOKIE_NAME, + value=username, + max_age=300, + httponly=True, + secure=request.app.state.settings.secure_cookies, + samesite="strict", + path="/", + ) + return response + + def _csrf_error(request: Request, next_path: str, application_name: str | None = None): return _render( request, @@ -108,9 +139,9 @@ async def login_page(request: Request, next: str = "/"): return RedirectResponse(context.path, status_code=303) if session and session_is_allowed(session, effective_policy): - current_factors = set(session.auth_factors) + current_factors = get_session_factors(session, effective_policy) if effective_policy.ip_method_names: - client_ip = extract_client_ip(request.headers.get("x-forwarded-for", "")) + client_ip = extract_client_ip(get_real_client_ip(request)) if evaluate_ip_access(runtime_config, effective_policy, client_ip): current_factors.add("ip") missing_factors = [factor for factor in effective_policy.required_factors if factor not in current_factors] @@ -155,14 +186,17 @@ async def login_password_page(request: Request, next: str = "/"): effective_policy = get_effective_policy(runtime_config, context.policy_name) if not effective_policy.password_method_names: return _render(request, "error.html", status_code=400, title="Password login unavailable", message="The selected policy does not require a password step.") - return _render( + response = _render( request, "login_password.html", next=next, application_name=context.application.name, - error=None, + error=LOGIN_ERRORS.get(request.query_params.get("error", "")), + username=request.cookies.get(LOGIN_USERNAME_COOKIE_NAME, ""), csrf_token=get_or_create_csrf_token(request), ) + response.delete_cookie(LOGIN_USERNAME_COOKIE_NAME, path="/") + return response @router.post("/login/password") @@ -187,15 +221,7 @@ async def login_password_submit( if not user: logger.warning("AUTH password failed for '%s' (policy: %s)", username, context.policy_name) - return _render( - request, - "login_password.html", - status_code=401, - next=next, - application_name=context.application.name, - error="Invalid username or password.", - csrf_token=get_or_create_csrf_token(request), - ) + return _failed_login_redirect(request, "/login/password", next, "invalid_password", username=username) if effective_policy.allowed_users and username not in effective_policy.allowed_users: logger.warning("AUTH password denied for '%s' — not in allowed_users (policy: %s)", username, context.policy_name) return _render( @@ -247,7 +273,7 @@ async def login_totp_page(request: Request, next: str = "/"): "login_totp.html", next=next, application_name=context.application.name, - error=None, + error=LOGIN_ERRORS.get(request.query_params.get("error", "")), csrf_token=get_or_create_csrf_token(request), ) @@ -268,7 +294,7 @@ async def login_totp_submit(request: Request, next: str = Form("/"), token: str if effective_policy.password_method_names and (not session or "password" not in session.auth_factors): return RedirectResponse(build_external_url(request, "/login/password", next=next), status_code=303) - if effective_policy.oidc_method_names and (not session or "oidc" not in session.auth_factors): + if effective_policy.oidc_method_names and "oidc" not in get_session_factors(session, effective_policy): return RedirectResponse(build_external_url(request, "/login/oidc/start", next=next), status_code=303) method_name, method = get_totp_method(runtime_config, effective_policy) @@ -283,20 +309,13 @@ async def login_totp_submit(request: Request, next: str = Form("/"), token: str if not verify_totp(secret, token): logger.warning("AUTH totp failed for '%s' (policy: %s)", session.username if session else "?", context.policy_name) - return _render( - request, - "login_totp.html", - status_code=401, - next=next, - application_name=context.application.name, - error="Invalid verification code.", - csrf_token=get_or_create_csrf_token(request), - ) + return _failed_login_redirect(request, "/login/totp", next, "invalid_totp") session_service = request.app.state.session_service refreshed_session = session_service.issue_session( existing_session=session, add_factors=["totp"], + metadata=factor_method_metadata(session, "totp", method_name), expires_in_minutes=get_effective_expiration(request, effective_policy, ["totp"]), ) logger.info("AUTH login ok for '%s' via password+totp (policy: %s)", refreshed_session.username, context.policy_name) @@ -352,7 +371,7 @@ async def login_oidc_callback(request: Request, state: str): request, email=identity.email, subject=identity.subject, - metadata={"oidc_claims": identity.claims}, + metadata={"oidc_claims": identity.claims, **factor_method_metadata(None, "oidc", oidc_state.method_name)}, factors=["oidc"], expires_in_minutes=get_effective_expiration(request, effective_policy, ["oidc"]), ) @@ -382,8 +401,9 @@ def _do_logout(request: Request, next_url: str = "/") -> RedirectResponse: @router.get("/logout") -async def logout_get(request: Request, next: str = "/"): - return _do_logout(request, next) +async def logout_get(request: Request): + # A link must not be able to end the session: the session page asks for the confirmation (POST with CSRF) + return RedirectResponse(build_external_url(request, "/"), status_code=303) @router.post("/logout") diff --git a/containers/auth-gateway/entrypoint.sh b/containers/auth-gateway/entrypoint.sh index 866a739..d251319 100644 --- a/containers/auth-gateway/entrypoint.sh +++ b/containers/auth-gateway/entrypoint.sh @@ -2,4 +2,4 @@ set -eu -exec uvicorn auth_gateway.main:app --host 0.0.0.0 --port 9091 --no-access-log --proxy-headers --forwarded-allow-ips="*" +exec uvicorn auth_gateway.main:app --host 0.0.0.0 --port 9091 --no-access-log --no-proxy-headers diff --git a/containers/caddy/process_config.py b/containers/caddy/process_config.py index 9daa6f9..b574f08 100644 --- a/containers/caddy/process_config.py +++ b/containers/caddy/process_config.py @@ -218,8 +218,10 @@ def build_caddyfile(apps, auth_policies, routes, tls_data=None): # Caddy's path matcher does not decode percent-encoding, so /%2fadmin would # NOT match path /admin and would fall through to the default (potentially # bypass) handler even though some upstreams decode it to /admin. + # Path parameters (;, also encoded as %3b) are rejected for the same reason: /admin;x does not match the + # /admin route, but Java upstreams (Tomcat, Spring) serve it as /admin. lines.append(" @encoded_slash {") - lines.append(" path_regexp (?i)%(?:25)*2f") + lines.append(" path_regexp (?i)%(?:25)*2f|;|%(?:25)*3b") lines.append(" }") lines.append(" handle @encoded_slash {") lines.append(" respond 400")