389 lines
13 KiB
Python
389 lines
13 KiB
Python
"""Admin authentication: credential storage, throttling and session lifecycle.
|
|
|
|
There is a single admin account. Its password is stored as a salted hash in the
|
|
``settings`` table, so it can be rotated from a shell without rebuilding the
|
|
container or editing environment variables::
|
|
|
|
python -m blog.manage set-password
|
|
|
|
``BLOG_ADMIN_PASSWORD`` is only a *bootstrap* value: on the first run (when no
|
|
hash is stored yet) it is hashed into the database. After that it is ignored;
|
|
use the CLI to change the password. Changing the password invalidates every
|
|
existing admin session, because sessions remember the password stamp.
|
|
"""
|
|
|
|
import os
|
|
import secrets
|
|
import sys
|
|
import time
|
|
|
|
from flask import session
|
|
from werkzeug.security import check_password_hash, generate_password_hash
|
|
|
|
from .db import get_db
|
|
|
|
PASSWORD_HASH_KEY = "admin_password_hash"
|
|
PASSWORD_SET_AT_KEY = "admin_password_set_at"
|
|
SESSION_SECRET_KEY = "session_secret"
|
|
|
|
MIN_PASSWORD_LENGTH = 12
|
|
# Anything longer than this is almost certainly a malicious payload, and running
|
|
# a deliberately slow KDF over megabytes is a cheap CPU-exhaustion vector.
|
|
MAX_PASSWORD_LENGTH = 1024
|
|
|
|
# Placeholder / well-known passwords that must never be accepted. The values on
|
|
# the right are matched case-insensitively.
|
|
WEAK_PASSWORDS = {
|
|
"admin",
|
|
"administrator",
|
|
"change-me",
|
|
"change-me-in-production",
|
|
"changeme",
|
|
"letmein",
|
|
"password",
|
|
"please-change-this-to-a-long-random-string",
|
|
"please-change-me",
|
|
"secret",
|
|
"test",
|
|
"welcome",
|
|
"123456",
|
|
"12345678",
|
|
"123456789",
|
|
"qwerty",
|
|
}
|
|
|
|
# Secret-key values that used to ship with the project. They are public, so a
|
|
# session signed with one can be forged: never use them.
|
|
PLACEHOLDER_SECRETS = {
|
|
"please-change-me",
|
|
"dev-insecure-secret",
|
|
"please-change-this-to-a-long-random-string",
|
|
"change-me",
|
|
"changeme",
|
|
"secret",
|
|
}
|
|
|
|
# --- Failed-login throttling ------------------------------------------------ #
|
|
# Exponential backoff per client IP: the first MAX_FAILED_ATTEMPTS attempts are
|
|
# free, then the lock doubles from LOCKOUT_BASE_SECONDS up to LOCKOUT_MAX_SECONDS.
|
|
MAX_FAILED_ATTEMPTS = 5
|
|
LOCKOUT_BASE_SECONDS = 30
|
|
LOCKOUT_MAX_SECONDS = 15 * 60
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# settings table helpers
|
|
# --------------------------------------------------------------------------- #
|
|
def get_setting(key, default=""):
|
|
row = get_db().execute(
|
|
"SELECT value FROM settings WHERE key = ?", (key,)
|
|
).fetchone()
|
|
if row is None or row[0] is None:
|
|
return default
|
|
return row[0]
|
|
|
|
|
|
def set_setting(key, value):
|
|
db = get_db()
|
|
db.execute(
|
|
"INSERT INTO settings (key, value) VALUES (?, ?) "
|
|
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
(key, value),
|
|
)
|
|
db.commit()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Passwords
|
|
# --------------------------------------------------------------------------- #
|
|
def generate_temporary_password():
|
|
"""A random, hard-to-guess password shown once when none is configured."""
|
|
return secrets.token_urlsafe(18)
|
|
|
|
|
|
def password_problem(password):
|
|
"""Return a human-readable reason the password is unacceptable, or None."""
|
|
if not password:
|
|
return "the password is empty"
|
|
if len(password) < MIN_PASSWORD_LENGTH:
|
|
return "the password must be at least %d characters" % MIN_PASSWORD_LENGTH
|
|
if len(password) > MAX_PASSWORD_LENGTH:
|
|
return "the password is too long"
|
|
if password.strip().lower() in WEAK_PASSWORDS:
|
|
return "that password is a well-known default"
|
|
return None
|
|
|
|
|
|
def set_admin_password(password):
|
|
"""Hash and store a new admin password; returns its stamp.
|
|
|
|
The returned stamp travels inside sessions so every active login becomes
|
|
invalid as soon as the password changes.
|
|
"""
|
|
problem = password_problem(password)
|
|
if problem:
|
|
raise ValueError(problem)
|
|
stamp = str(int(time.time()))
|
|
set_setting(PASSWORD_HASH_KEY, generate_password_hash(password))
|
|
set_setting(PASSWORD_SET_AT_KEY, stamp)
|
|
clear_login_attempts()
|
|
return stamp
|
|
|
|
|
|
def password_stamp():
|
|
"""Identity of the current password (empty when none is configured)."""
|
|
return get_setting(PASSWORD_SET_AT_KEY, "")
|
|
|
|
|
|
def verify_admin_password(password):
|
|
"""Check a candidate password against the stored hash.
|
|
|
|
The hash comparison always runs (even for an empty/oversized input) so the
|
|
response time does not reveal whether a password was supplied.
|
|
"""
|
|
stored = get_setting(PASSWORD_HASH_KEY, "")
|
|
if not stored:
|
|
return False
|
|
if not isinstance(password, str) or not password or len(password) > MAX_PASSWORD_LENGTH:
|
|
# Burn the same KDF work a real comparison would do.
|
|
check_password_hash(stored, secrets.token_hex(16))
|
|
return False
|
|
try:
|
|
return check_password_hash(stored, password)
|
|
except (ValueError, TypeError):
|
|
# A corrupt hash in the DB must fail closed, never raise.
|
|
return False
|
|
|
|
|
|
def ensure_admin_credentials(app):
|
|
"""Seed the stored password from the environment on first run.
|
|
|
|
- No stored hash + a strong ``BLOG_ADMIN_PASSWORD`` -> hash it into the DB.
|
|
- No stored hash + nothing usable -> generate a random password and print it
|
|
once, so the site never comes up with a guessable default.
|
|
- A stored hash always wins; the env var is only a bootstrap value.
|
|
"""
|
|
stored = get_setting(PASSWORD_HASH_KEY, "")
|
|
env_password = os.environ.get("BLOG_ADMIN_PASSWORD") or ""
|
|
|
|
if not stored:
|
|
if not password_problem(env_password):
|
|
set_admin_password(env_password)
|
|
app.logger.info("Admin password initialised from BLOG_ADMIN_PASSWORD.")
|
|
return
|
|
temporary = generate_temporary_password()
|
|
set_admin_password(temporary)
|
|
if env_password:
|
|
print(
|
|
"WARNING: BLOG_ADMIN_PASSWORD is a weak/default value and was "
|
|
"rejected. Change the password with: python -m blog.manage "
|
|
"set-password",
|
|
file=sys.stderr,
|
|
)
|
|
print(
|
|
"\n"
|
|
" ============================================================\n"
|
|
" No admin password was configured, so a temporary one was\n"
|
|
" generated. Sign in with it and change it right away:\n"
|
|
"\n"
|
|
" password: %s\n"
|
|
"\n"
|
|
" Change it with:\n"
|
|
" python -m blog.manage set-password\n"
|
|
" ============================================================\n"
|
|
% temporary,
|
|
file=sys.stderr,
|
|
flush=True,
|
|
)
|
|
return
|
|
|
|
# A hash is stored; warn if the environment still claims to control it.
|
|
if env_password and not verify_admin_password(env_password):
|
|
app.logger.warning(
|
|
"BLOG_ADMIN_PASSWORD is set but no longer controls the admin login "
|
|
"(a password is already stored in the database). Use "
|
|
"'python -m blog.manage set-password' to change it."
|
|
)
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Session secret
|
|
# --------------------------------------------------------------------------- #
|
|
def ensure_session_secret(app):
|
|
"""Configure a strong SECRET_KEY, preferring the environment.
|
|
|
|
A placeholder/absent ``BLOG_SESSION_SECRET`` falls back to a random secret
|
|
generated once and stored in the database, so sessions survive restarts but
|
|
are never signed with a publicly known key.
|
|
"""
|
|
env_secret = (os.environ.get("BLOG_SESSION_SECRET") or "").strip()
|
|
if (
|
|
len(env_secret) >= 32
|
|
and env_secret.lower() not in PLACEHOLDER_SECRETS
|
|
):
|
|
app.config["SECRET_KEY"] = env_secret
|
|
return
|
|
|
|
stored = get_setting(SESSION_SECRET_KEY, "")
|
|
if len(stored) < 32:
|
|
stored = secrets.token_hex(32)
|
|
set_setting(SESSION_SECRET_KEY, stored)
|
|
app.logger.warning(
|
|
"BLOG_SESSION_SECRET is missing or a known placeholder; generated "
|
|
"and stored a new session secret."
|
|
)
|
|
app.config["SECRET_KEY"] = stored
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Sessions
|
|
# --------------------------------------------------------------------------- #
|
|
def session_absolute_seconds():
|
|
try:
|
|
hours = int(os.environ.get("BLOG_SESSION_HOURS", "12"))
|
|
except ValueError:
|
|
hours = 12
|
|
return max(1, hours) * 3600
|
|
|
|
|
|
def session_idle_seconds():
|
|
try:
|
|
minutes = int(os.environ.get("BLOG_SESSION_IDLE_MINUTES", "120"))
|
|
except ValueError:
|
|
minutes = 120
|
|
return max(1, minutes) * 60
|
|
|
|
|
|
def is_logged_in():
|
|
"""True when the session is a live, current admin login."""
|
|
if session.get("logged_in") is not True:
|
|
return False
|
|
login_at = session.get("login_at")
|
|
last_seen = session.get("last_seen")
|
|
if not isinstance(login_at, int) or not isinstance(last_seen, int):
|
|
# Pre-upgrade sessions had no timestamps: treat them as expired.
|
|
return False
|
|
now = int(time.time())
|
|
if now - login_at > session_absolute_seconds():
|
|
return False
|
|
if now - last_seen > session_idle_seconds():
|
|
return False
|
|
if session.get("pwd_stamp") != password_stamp():
|
|
return False
|
|
return True
|
|
|
|
|
|
def login_admin(username):
|
|
"""Start a fresh admin session (clears anything already in the session)."""
|
|
session.clear()
|
|
now = int(time.time())
|
|
session.permanent = True
|
|
session["logged_in"] = True
|
|
session["username"] = username
|
|
session["login_at"] = now
|
|
session["last_seen"] = now
|
|
session["pwd_stamp"] = password_stamp()
|
|
# Rotate the CSRF token on privilege change (session fixation defence).
|
|
session["csrf_token"] = secrets.token_hex(32)
|
|
|
|
|
|
def logout_admin():
|
|
session.clear()
|
|
|
|
|
|
def refresh_session():
|
|
"""Expire stale sessions and slide the idle window.
|
|
|
|
Called once per request. Writing ``last_seen`` on every asset request would
|
|
churn cookies, so it is only refreshed about once a minute.
|
|
"""
|
|
if session.get("logged_in") is None:
|
|
return
|
|
if not is_logged_in():
|
|
session.clear()
|
|
return
|
|
now = int(time.time())
|
|
if now - int(session.get("last_seen", 0)) >= 60:
|
|
session["last_seen"] = now
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# Login throttling
|
|
# --------------------------------------------------------------------------- #
|
|
def _attempt_key(ip):
|
|
return (ip or "unknown").strip() or "unknown"
|
|
|
|
|
|
def lockout_remaining(ip):
|
|
"""Seconds the given client is still locked out for (0 when not locked)."""
|
|
row = get_db().execute(
|
|
"SELECT locked_until FROM login_attempts WHERE key = ?",
|
|
(_attempt_key(ip),),
|
|
).fetchone()
|
|
if row is None or not row[0]:
|
|
return 0
|
|
return max(0, int(float(row[0]) - time.time()))
|
|
|
|
|
|
def record_failed_login(ip):
|
|
"""Count a failed attempt and apply exponential backoff.
|
|
|
|
Returns the number of seconds the client is now locked out for (0 if it
|
|
still has attempts left).
|
|
"""
|
|
db = get_db()
|
|
key = _attempt_key(ip)
|
|
now = time.time()
|
|
row = db.execute(
|
|
"SELECT failures FROM login_attempts WHERE key = ?", (key,)
|
|
).fetchone()
|
|
failures = (row[0] if row else 0) + 1
|
|
|
|
locked_until = 0.0
|
|
if failures >= MAX_FAILED_ATTEMPTS:
|
|
overage = failures - MAX_FAILED_ATTEMPTS
|
|
delay = min(LOCKOUT_BASE_SECONDS * (2 ** overage), LOCKOUT_MAX_SECONDS)
|
|
locked_until = now + delay
|
|
|
|
db.execute(
|
|
"INSERT INTO login_attempts (key, failures, last_failure, locked_until) "
|
|
"VALUES (?, ?, ?, ?) "
|
|
"ON CONFLICT(key) DO UPDATE SET failures = excluded.failures, "
|
|
"last_failure = excluded.last_failure, locked_until = excluded.locked_until",
|
|
(key, failures, now, locked_until),
|
|
)
|
|
# Opportunistic cleanup so the table cannot grow without bound.
|
|
db.execute(
|
|
"DELETE FROM login_attempts WHERE locked_until = 0 AND last_failure < ?",
|
|
(now - 24 * 3600,),
|
|
)
|
|
db.commit()
|
|
return max(0, int(locked_until - now))
|
|
|
|
|
|
def clear_login_attempts(ip=None):
|
|
"""Clear the failure history for one client, or for everyone."""
|
|
db = get_db()
|
|
if ip is None:
|
|
cur = db.execute("DELETE FROM login_attempts")
|
|
else:
|
|
cur = db.execute(
|
|
"DELETE FROM login_attempts WHERE key = ?", (_attempt_key(ip),)
|
|
)
|
|
db.commit()
|
|
return cur.rowcount if cur.rowcount and cur.rowcount > 0 else 0
|
|
|
|
|
|
def locked_clients():
|
|
"""Currently locked-out client keys, for the CLI status command."""
|
|
now = time.time()
|
|
rows = get_db().execute(
|
|
"SELECT key, failures, locked_until FROM login_attempts "
|
|
"WHERE locked_until > ? ORDER BY locked_until DESC",
|
|
(now,),
|
|
).fetchall()
|
|
return [
|
|
{"key": r[0], "failures": r[1], "remaining": int(float(r[2]) - now)}
|
|
for r in rows
|
|
]
|