From 3494eab1208dc18478485e02c61e292556502fa6 Mon Sep 17 00:00:00 2001 From: Dennis Fink Date: Sat, 31 Oct 2026 16:42:44 +0100 Subject: fix(core): harden session and credential security Require persistent non-placeholder signing keys outside local development and bind login sessions to the current password hash so password changes revoke existing cookies. Enforce a minimal password policy for user administration while preserving long Unicode passphrases without arbitrary composition limits. --- webmentions_ssg/security.py | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 webmentions_ssg/security.py (limited to 'webmentions_ssg/security.py') diff --git a/webmentions_ssg/security.py b/webmentions_ssg/security.py new file mode 100644 index 0000000..f4841a4 --- /dev/null +++ b/webmentions_ssg/security.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2026 Dennis Fink +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Validate persistent signing keys and administrator passwords.""" + +MIN_PASSWORD_LENGTH = 8 +MIN_SECRET_KEY_LENGTH = 32 + + +def validate_secret_key(value: object) -> None: + """Require a non-placeholder, sufficiently long deployment signing key.""" + if not isinstance(value, (str, bytes)): + raise TypeError( + "Configure a persistent SECRET_KEY of at least 32 random bytes " + "before starting." + ) + + # Flask accepts either text or bytes as its signing key. Reject common + # example/development values even when their lengths look sufficient. + key = value.encode("utf-8") if isinstance(value, str) else value + if len(key) < MIN_SECRET_KEY_LENGTH or not key.strip(): + raise RuntimeError( + "Configure a persistent SECRET_KEY of at least 32 random bytes " + "before starting." + ) + + normalized = key.strip().lower() + if normalized.startswith( + (b"replace_with", b"changeme", b"change_me", b"your_", b"insecure_") + ): + raise RuntimeError( + "SECRET_KEY is an example/development placeholder; " + "generate and configure a real random key." + ) + + +def validate_password(password: str) -> None: + """Validate newly chosen passwords without arbitrary composition rules. + + Allow Unicode, whitespace-only passwords, and arbitrarily long passphrases, + but reject empty passwords and control characters. + """ + if not password: + raise ValueError("Password must not be empty.") + if len(password) < MIN_PASSWORD_LENGTH: + raise ValueError( + f"Password must be at least {MIN_PASSWORD_LENGTH} characters long." + ) + if any(ord(char) < 32 or ord(char) == 127 for char in password): + raise ValueError("Password must not contain control characters.") -- cgit v1.3.1