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:
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 + "/")
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user