mirror of
https://github.com/eduardogsilva/wireguard_webadmin.git
synced 2026-11-22 04:43:18 +01:00
harden auth gateway
This commit is contained in:
@@ -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")
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user