aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDennis Fink2026-10-31 19:33:49 +0100
committerDennis Fink2026-10-31 19:33:49 +0100
commit3a3284abe23e143cbb638877f47958c82afa3367 (patch)
tree5409bb940d252756f502d545cc145b382f06a3a0
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--contrib/webmentions-ssg.example.cfg15
-rw-r--r--tests/test_config.py84
-rw-r--r--tests/test_views.py119
-rw-r--r--webmentions_ssg/__init__.py9
-rw-r--r--webmentions_ssg/config.py6
-rw-r--r--webmentions_ssg/views.py18
6 files changed, 250 insertions, 1 deletions
diff --git a/contrib/webmentions-ssg.example.cfg b/contrib/webmentions-ssg.example.cfg
index 577eeef..a5dbaf9 100644
--- a/contrib/webmentions-ssg.example.cfg
+++ b/contrib/webmentions-ssg.example.cfg
@@ -26,6 +26,14 @@ BOOTSTRAP_SERVE_LOCAL = True
# Upgrading to password-bound sessions also requires users to sign in again once.
SECRET_KEY = "REPLACE_WITH_A_LONG_RANDOM_SECRET"
+# When deployed behind a trusted reverse proxy, set this to the EXACT number
+# of trusted hops that set X-Forwarded-For and X-Forwarded-Proto. Use 1 for a
+# single nginx instance directly in front of the application; 0 (default)
+# ignores forwarded headers. Do not enable this if the backend is reachable
+# directly or if the proxy fails to overwrite untrusted forwarded headers.
+# See README.md for an nginx example and multi-proxy caveats.
+PROXY_FIX_TRUSTED_HOPS = 0
+
# ---------------------------------------------------------------------------
# Database and logging
# ---------------------------------------------------------------------------
@@ -100,8 +108,13 @@ ENDPOINT_GLOBAL_RATE_LIMIT = "1000/hour"
# Minimum seconds between verifications of the same source/target pair.
ENDPOINT_REVERIFY_COOLDOWN_SECONDS = 600
-# Limit login POST attempts per client.
+# Limit login POST attempts per client IP, and separately for each submitted
+# username across IPs (case-folded and hashed before being used as a key).
+# Both limits apply to POSTs, even unsuccessful validation attempts. A per-user
+# bucket can be deliberately exhausted to temporarily deny that account login;
+# keep its allowance higher than the per-IP limit and monitor for abuse.
LOGIN_RATE_LIMIT = "5/minute;30/hour"
+LOGIN_USERNAME_RATE_LIMIT = "20/minute;100/hour"
# ---------------------------------------------------------------------------
# Sending Webmentions from a statically generated site
diff --git a/tests/test_config.py b/tests/test_config.py
index aae7cce..c483ee7 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -6,6 +6,9 @@
from pathlib import Path
+from flask import request
+from flask_limiter.util import get_remote_address
+
import pytest
from wtforms import Field, ValidationError
from wtforms.form import BaseForm
@@ -288,3 +291,84 @@ def test_invalid_resource_limits_fail_at_startup(
setattr(InvalidResourceLimit, key, value)
with pytest.raises(ValueError, match=key):
create_app(InvalidResourceLimit)
+
+
+def test_proxy_fix_disabled_by_default(tmp_path: Path) -> None:
+ class DirectConfig(TestingConfig):
+ LOG_FILE = str(tmp_path / "direct.log")
+
+ app = create_app(DirectConfig)
+
+ @app.get("/_proxy-check")
+ def proxy_check() -> dict[str, str]:
+ return {
+ "ip": get_remote_address(),
+ "scheme": request.scheme,
+ "host": request.host,
+ }
+
+ response = app.test_client().get(
+ "/_proxy-check",
+ environ_overrides={"REMOTE_ADDR": "192.0.2.50"},
+ headers={
+ "X-Forwarded-For": "198.51.100.99",
+ "X-Forwarded-Proto": "https",
+ "X-Forwarded-Host": "attacker.example",
+ },
+ )
+ assert response.json == {"ip": "192.0.2.50", "scheme": "http", "host": "localhost"}
+
+
+def test_proxy_fix_trusts_only_configured_proxy_hops(tmp_path: Path) -> None:
+ class TwoProxyConfig(TestingConfig):
+ LOG_FILE = str(tmp_path / "proxy.log")
+ PROXY_FIX_TRUSTED_HOPS = 2
+
+ app = create_app(TwoProxyConfig)
+
+ @app.get("/_proxy-check")
+ def proxy_check() -> dict[str, str]:
+ return {
+ "ip": get_remote_address(),
+ "scheme": request.scheme,
+ "host": request.host,
+ }
+
+ response = app.test_client().get(
+ "/_proxy-check",
+ environ_overrides={"REMOTE_ADDR": "192.0.2.50"},
+ headers={
+ "X-Forwarded-For": "198.51.100.99, 203.0.113.4, 192.0.2.10",
+ "X-Forwarded-Proto": "http, https",
+ "X-Forwarded-Host": "attacker.example",
+ },
+ )
+ assert response.json == {"ip": "203.0.113.4", "scheme": "http", "host": "localhost"}
+
+
+@pytest.mark.parametrize("hops", [-1, True, False, None, "1", 1.5])
+def test_invalid_proxy_fix_hop_counts_fail_at_startup(
+ tmp_path: Path, hops: object
+) -> None:
+ class InvalidProxyConfig(TestingConfig):
+ LOG_FILE = str(tmp_path / "invalid-proxy.log")
+ PROXY_FIX_TRUSTED_HOPS = hops
+
+ with pytest.raises(ValueError, match="PROXY_FIX_TRUSTED_HOPS"):
+ create_app(InvalidProxyConfig)
+
+
+def test_proxy_fix_can_be_configured_via_environment(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ config_path = tmp_path / "development.cfg"
+ config_path.write_text("# proxy configuration supplied by environment\n")
+ monkeypatch.setenv("WEBMENTIONS_SSG_PROXY_FIX_TRUSTED_HOPS", "1")
+
+ class EnvProxyConfig(DevelopmentConfig):
+ CONFIG_FILE = str(config_path)
+ LOG_FILE = str(tmp_path / "development.log")
+
+ app = create_app(EnvProxyConfig)
+ assert app.config["PROXY_FIX_TRUSTED_HOPS"] == 1
+ assert app.wsgi_app.__class__.__name__ == "ProxyFix"
diff --git a/tests/test_views.py b/tests/test_views.py
index 2108b38..129bdbf 100644
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -835,6 +835,32 @@ def test_endpoint_rate_limits_requests_per_ip(
assert count == 2
+def test_endpoint_rate_limit_distinguishes_clients_behind_trusted_proxy(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from werkzeug.middleware.proxy_fix import ProxyFix
+
+ app.config["ENDPOINT_RATE_LIMIT"] = "1/minute"
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
+ form = mock_endpoint_form(views_module, monkeypatch, valid=True)
+ monkeypatch.setattr(views_module, "verify_webmention", Mock())
+
+ def attempt(client_ip: str, index: int) -> int:
+ form.source.data = f"https://source.example/proxy-post-{index}"
+ return client.post(
+ "/endpoint",
+ environ_overrides={"REMOTE_ADDR": "192.0.2.200"},
+ headers={"X-Forwarded-For": client_ip},
+ ).status_code
+
+ assert attempt("198.51.100.11", 0) == 201
+ assert attempt("198.51.100.11", 1) == 429
+ assert attempt("198.51.100.12", 2) == 201
+
+
def test_endpoint_global_rate_limit(
app: Flask,
client: FlaskClient,
@@ -1040,6 +1066,99 @@ def test_login_rate_limit_is_independent_per_ip(
assert attempt("192.0.2.11") == 429
+def test_login_rate_limit_uses_forwarded_client_ip_when_proxy_is_trusted(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from werkzeug.middleware.proxy_fix import ProxyFix
+
+ app.config["LOGIN_RATE_LIMIT"] = "1/minute"
+ app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1)
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(client_ip: str) -> int:
+ response = client.post(
+ "/login",
+ environ_overrides={"REMOTE_ADDR": "192.0.2.200"},
+ headers={"X-Forwarded-For": client_ip},
+ )
+ return response.status_code
+
+ assert attempt("198.51.100.11") == 302
+ # A forged earlier X-Forwarded-For entry cannot change the client bucket.
+ assert attempt("203.0.113.99, 198.51.100.11") == 429
+ assert attempt("198.51.100.12") == 302
+
+
+def test_login_username_limit_throttles_across_ips(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "100/minute"
+ app.config["LOGIN_USERNAME_RATE_LIMIT"] = "2/minute"
+
+ with monkeypatch.context() as patcher:
+ mock_login_form(
+ views_module,
+ patcher,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(ip: str, username: str) -> int:
+ return client.post(
+ "/login",
+ data={"username": username, "password": "wrong-password"},
+ environ_overrides={"REMOTE_ADDR": ip},
+ ).status_code
+
+ assert attempt("192.0.2.10", "Admin") == 302
+ assert attempt("192.0.2.11", " admin ") == 302
+ assert attempt("192.0.2.12", "ADMIN") == 429
+ # An unrelated username is not locked by attempts against Admin.
+ assert attempt("192.0.2.12", "another-user") == 302
+
+ # Restore the real form: the POST-only limits must not block a GET,
+ # even from the client IP that submitted the throttled attempt.
+ response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.12"})
+ assert response.status_code == 200
+
+
+def test_login_missing_username_uses_per_ip_bucket(
+ app: Flask,
+ client: FlaskClient,
+ views_module: ModuleType,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app.config["LOGIN_RATE_LIMIT"] = "100/minute"
+ app.config["LOGIN_USERNAME_RATE_LIMIT"] = "1/minute"
+ mock_login_form(
+ views_module,
+ monkeypatch,
+ valid=True,
+ username="unknown-user",
+ password="wrong-password",
+ )
+
+ def attempt(ip: str) -> int:
+ return client.post("/login", environ_overrides={"REMOTE_ADDR": ip}).status_code
+
+ assert attempt("192.0.2.10") == 302
+ assert attempt("192.0.2.10") == 429
+ assert attempt("192.0.2.11") == 302
+
+
def test_login_rate_limits_requests_per_ip(
app: Flask,
client: FlaskClient,
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.",