aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDennis Fink2026-10-29 18:57:32 +0100
committerDennis Fink2026-10-29 18:57:32 +0100
commitaa59080c78a815a7c2e4509c9a8fe73edc93f6c2 (patch)
tree500802f1d421a5418f978a60f28401be93b9f830
parent8fb010e7ae781e94eefe20fe713a98905b031a8f (diff)
downloadwebmentions-ssg-aa59080c78a815a7c2e4509c9a8fe73edc93f6c2.tar.gz
webmentions-ssg-aa59080c78a815a7c2e4509c9a8fe73edc93f6c2.zip
fix(core): prevent unsafe login redirects
Validate post-login redirect targets as local paths and reject backslashes, scheme-relative URLs, and malformed paths that browsers may interpret as external destinations. Add regression coverage for safe local redirects and open redirect variants.
-rw-r--r--tests/test_url_security.py31
-rw-r--r--tests/test_views.py47
-rw-r--r--webmentions_ssg/url_security.py20
-rw-r--r--webmentions_ssg/views.py10
4 files changed, 96 insertions, 12 deletions
diff --git a/tests/test_url_security.py b/tests/test_url_security.py
index dee38dd..80b45e9 100644
--- a/tests/test_url_security.py
+++ b/tests/test_url_security.py
@@ -11,6 +11,7 @@ from webmentions_ssg.url_security import (
AddressResolutionError,
is_http_url,
is_public_url,
+ is_safe_next_url,
)
@@ -35,6 +36,36 @@ def test_is_http_url(url: str, expected: bool) -> None:
assert is_http_url(url) is expected
+@pytest.mark.parametrize(
+ ("next_url", "expected"),
+ [
+ pytest.param("/", True, id="root"),
+ pytest.param("/received", True, id="local-path"),
+ pytest.param("/received?page=2", True, id="query-string"),
+ pytest.param("/received#details", True, id="fragment"),
+ pytest.param(
+ "/sent?next=https://evil.example", True, id="external-url-in-query"
+ ),
+ pytest.param("/foo//bar", True, id="double-slash-within-path"),
+ pytest.param("", False, id="empty"),
+ pytest.param("received", False, id="relative-path"),
+ pytest.param(" /received", False, id="leading-space"),
+ pytest.param("https://evil.example/phishing", False, id="absolute-https"),
+ pytest.param("http://evil.example", False, id="absolute-http"),
+ pytest.param("javascript:alert(1)", False, id="non-http-scheme"),
+ pytest.param("//evil.example/phishing", False, id="scheme-relative"),
+ pytest.param("///evil.example/phishing", False, id="triple-slash"),
+ pytest.param("////evil.example", False, id="four-slashes"),
+ pytest.param("//", False, id="two-slashes"),
+ pytest.param(r"/\evil.example", False, id="slash-backslash-host"),
+ pytest.param(r"/received\evil.example", False, id="backslash-in-path"),
+ pytest.param(r"\/evil.example", False, id="backslash-slash-host"),
+ ],
+)
+def test_is_safe_next_url(next_url: str, expected: bool) -> None:
+ assert is_safe_next_url(next_url) is expected
+
+
@patch("webmentions_ssg.url_security.dns.resolver.resolve_name")
@pytest.mark.parametrize(
("url", "resolved_addresses"),
diff --git a/tests/test_views.py b/tests/test_views.py
index 3de4c3d..c7f86d2 100644
--- a/tests/test_views.py
+++ b/tests/test_views.py
@@ -404,11 +404,21 @@ def test_login_rejects_invalid_credentials(
assert ("danger", "Invalid username or password") in session["_flashes"]
+@pytest.mark.parametrize(
+ "next_url",
+ [
+ pytest.param("/", id="root"),
+ pytest.param("/received", id="local-path"),
+ pytest.param("/received?page=2", id="query-string"),
+ pytest.param("/received#details", id="fragment"),
+ ],
+)
def test_login_redirects_to_local_next_page(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
+ next_url: str,
) -> None:
with app.app_context():
user = User(username="admin", password="test")
@@ -418,32 +428,55 @@ def test_login_redirects_to_local_next_page(
mock_login_form(views_module, monkeypatch, valid=True)
- response = client.post("/login?next=/received?page=2")
+ response = client.post("/login", query_string={"next": next_url})
assert response.status_code == 302
- assert response.headers["Location"].endswith("/received?page=2")
+ assert response.headers["Location"] == next_url
with client.session_transaction() as session:
assert session["_user_id"] == str(user_id)
-def test_login_rejects_external_next_page(
+@pytest.mark.parametrize(
+ "next_url",
+ [
+ pytest.param(None, id="missing"),
+ pytest.param("", id="empty"),
+ pytest.param("received", id="relative-path"),
+ pytest.param("https://evil.example/phishing", id="absolute-https"),
+ pytest.param("http://evil.example", id="absolute-http"),
+ pytest.param("javascript:alert(1)", id="non-http-scheme"),
+ pytest.param("//evil.example/phishing", id="scheme-relative"),
+ pytest.param("///evil.example/phishing", id="triple-slash"),
+ pytest.param("////evil.example", id="four-slashes"),
+ pytest.param(r"/\evil.example", id="slash-backslash-host"),
+ pytest.param(r"/received\evil.example", id="backslash-in-path"),
+ pytest.param(r"\/evil.example", id="backslash-slash-host"),
+ ],
+)
+def test_login_rejects_unsafe_next_page(
app: Flask,
client: FlaskClient,
views_module: ModuleType,
monkeypatch: pytest.MonkeyPatch,
+ next_url: str | None,
) -> None:
with app.app_context():
- db.session.add(User(username="admin", password="test"))
+ user = User(username="admin", password="test")
+ db.session.add(user)
db.session.commit()
+ user_id = user.id
mock_login_form(views_module, monkeypatch, valid=True)
- response = client.post("/login?next=https://evil.example/phishing")
+ query_string = {} if next_url is None else {"next": next_url}
+ response = client.post("/login", query_string=query_string)
assert response.status_code == 302
- assert response.headers["Location"].endswith("/")
- assert "evil.example" not in response.headers["Location"]
+ assert response.headers["Location"] == "/"
+
+ with client.session_transaction() as session:
+ assert session["_user_id"] == str(user_id)
def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> None:
diff --git a/webmentions_ssg/url_security.py b/webmentions_ssg/url_security.py
index a963635..ade64d6 100644
--- a/webmentions_ssg/url_security.py
+++ b/webmentions_ssg/url_security.py
@@ -56,3 +56,23 @@ def is_http_url(url: str) -> bool:
return False
return parsed.scheme.lower() in {"http", "https"} and parsed.hostname is not None
+
+
+def is_safe_next_url(next_url: str) -> bool:
+ """Allow redirects only to paths on this site."""
+ # Check the original string too: urlsplit("///evil.example").path is
+ # "/evil.example", even though browsers can treat the original as external.
+ if "\\" in next_url or not next_url.startswith("/") or next_url.startswith("//"):
+ return False
+
+ try:
+ target = urlsplit(next_url)
+ except ValueError:
+ return False
+
+ return (
+ not target.scheme
+ and not target.netloc
+ and target.path.startswith("/")
+ and not target.path.startswith("//")
+ )
diff --git a/webmentions_ssg/views.py b/webmentions_ssg/views.py
index d411296..cef81fc 100644
--- a/webmentions_ssg/views.py
+++ b/webmentions_ssg/views.py
@@ -6,7 +6,6 @@
import uuid
from typing import cast
-from urllib.parse import urlsplit
import sqlalchemy as sa
import sqlalchemy.exc as sa_exc
@@ -30,6 +29,7 @@ from .models import ReceivedWebmention, SentWebmention, Source, User
from .tasks.receiver import verify_webmention
from .tasks.scanner import manual_scan_sources
from .tasks.sender import send_webmention
+from .url_security import is_safe_next_url
root_page = Blueprint("root", __name__)
@@ -72,10 +72,10 @@ def login() -> ResponseReturnValue:
login_user(user)
- next_page = request.args.get("next")
- if not next_page or urlsplit(next_page).netloc != "":
- next_page = url_for("root.index")
- return redirect(next_page)
+ next_url = request.args.get("next")
+ if not next_url or not is_safe_next_url(next_url):
+ next_url = url_for("root.index")
+ return redirect(next_url)
return render_template("login.html", form=form)