From aa59080c78a815a7c2e4509c9a8fe73edc93f6c2 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Thu, 29 Oct 2026 18:57:32 +0100 Subject: 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. --- webmentions_ssg/url_security.py | 20 ++++++++++++++++++++ webmentions_ssg/views.py | 10 +++++----- 2 files changed, 25 insertions(+), 5 deletions(-) (limited to 'webmentions_ssg') 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) -- cgit v1.3.1