aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg
diff options
context:
space:
mode:
authorDennis Fink2026-10-31 19:33:49 +0100
committerDennis Fink2026-10-31 19:33:49 +0100
commit3a3284abe23e143cbb638877f47958c82afa3367 (patch)
tree5409bb940d252756f502d545cc145b382f06a3a0 /webmentions_ssg
parent40bdba0f2aa132f47326d2591e83039249ae2121 (diff)
downloadwebmentions-ssg-3a3284abe23e143cbb638877f47958c82afa3367.tar.gz
webmentions-ssg-3a3284abe23e143cbb638877f47958c82afa3367.zip
fix(core): harden login rate limiting behind proxies
Trust forwarded client addresses only for an explicitly configured number of reverse-proxy hops so per-IP limits cannot be bypassed or collapsed in proxied deployments. Add a separate hashed per-username login limit across IPs to reduce distributed credential-guessing attempts without storing raw usernames in limiter keys.
Diffstat (limited to '')
-rw-r--r--webmentions_ssg/__init__.py9
-rw-r--r--webmentions_ssg/config.py6
-rw-r--r--webmentions_ssg/views.py18
3 files changed, 33 insertions, 0 deletions
diff --git a/webmentions_ssg/__init__.py b/webmentions_ssg/__init__.py
index 4c185c7..f8fd8f1 100644
--- a/webmentions_ssg/__init__.py
+++ b/webmentions_ssg/__init__.py
@@ -19,6 +19,7 @@ from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from sqlalchemy.orm import DeclarativeBase
+from werkzeug.middleware.proxy_fix import ProxyFix
from webmentions_ssg.config import (
DefaultConfig,
@@ -100,6 +101,14 @@ def create_app(config_class: type[DefaultConfig] | None = None) -> Flask:
app.config["IGNORED_HOSTNAMES"] = normalize_ignored_hostnames(
app.config["IGNORED_HOSTNAMES"]
)
+ proxy_hops = app.config["PROXY_FIX_TRUSTED_HOPS"]
+ if type(proxy_hops) is not int or proxy_hops < 0:
+ raise ValueError("PROXY_FIX_TRUSTED_HOPS must be a non-negative integer.")
+ if proxy_hops:
+ # Trust only the configured number of proxies; never trust forwarded
+ # host, port or URL prefix headers for rate limiting.
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=proxy_hops, x_proto=proxy_hops)
+
for key in (
"MAX_CONTENT_LENGTH",
"MAX_WEBMENTION_URL_BYTES",
diff --git a/webmentions_ssg/config.py b/webmentions_ssg/config.py
index b1d588b..8a3e58d 100644
--- a/webmentions_ssg/config.py
+++ b/webmentions_ssg/config.py
@@ -98,6 +98,10 @@ class DefaultConfig:
MAIL_PASSWORD = None
MAIL_DEFAULT_SENDER = None
+ # Number of trusted reverse-proxy hops for X-Forwarded-For/Proto.
+ # 0 (default) means forwarded headers are not trusted.
+ PROXY_FIX_TRUSTED_HOPS = 0
+
RATELIMIT_STORAGE_URI = "memory://"
RATELIMIT_HEADERS_ENABLED = True
@@ -106,6 +110,8 @@ class DefaultConfig:
ENDPOINT_REVERIFY_COOLDOWN_SECONDS = 600
LOGIN_RATE_LIMIT = "5/minute;30/hour"
+ # Separate cross-IP limit for each submitted username (hashed in storage).
+ LOGIN_USERNAME_RATE_LIMIT = "20/minute;100/hour"
class DevelopmentConfig(DefaultConfig):
diff --git a/webmentions_ssg/views.py b/webmentions_ssg/views.py
index 0836869..5b563f0 100644
--- a/webmentions_ssg/views.py
+++ b/webmentions_ssg/views.py
@@ -4,6 +4,7 @@
"""Provide routes for authentication and Webmention administration."""
+import hashlib
import secrets
import uuid
from datetime import UTC, datetime, timedelta
@@ -23,6 +24,7 @@ from flask import (
url_for,
)
from flask.typing import ResponseReturnValue
+from flask_limiter.util import get_remote_address
from flask_login import current_user, login_required, login_user, logout_user
from sqlalchemy.engine import CursorResult
from sqlalchemy.orm import selectinload
@@ -42,6 +44,16 @@ DUMMY_USER = User(username=secrets.token_urlsafe())
DUMMY_USER.password = secrets.token_urlsafe()
+def login_username_limit_key() -> str:
+ """Group submitted usernames across IPs without storing raw account names."""
+ username = request.form.get("username", "").strip().casefold()
+ if not username:
+ # A missing username must not put all clients into one global bucket.
+ return f"missing-username:{get_remote_address()}"
+ digest = hashlib.sha256(username.encode("utf-8")).hexdigest()
+ return f"username:{digest}"
+
+
@root_page.route("/")
def index() -> ResponseReturnValue:
"""
@@ -54,6 +66,12 @@ def index() -> ResponseReturnValue:
@root_page.route("/login", methods=["GET", "POST"])
@LIMITER.limit(
+ lambda: current_app.config["LOGIN_USERNAME_RATE_LIMIT"],
+ key_func=login_username_limit_key,
+ methods=["POST"],
+ error_message="Too many login attempts. Please try again later.",
+)
+@LIMITER.limit(
lambda: current_app.config["LOGIN_RATE_LIMIT"],
methods=["POST"],
error_message="Too many login attempts. Please try again later.",