223 lines
6.9 KiB
Python
223 lines
6.9 KiB
Python
"""The admin account and the sessions.
|
|
|
|
The sessions table of docs/spec.md section 4 has no column for a CSRF secret, so
|
|
the secret is derived from the session token instead: the server sends it in a
|
|
script-readable cookie and recomputes it from the stored session on every
|
|
mutating request. It cannot be turned back into the session token.
|
|
"""
|
|
|
|
import hashlib
|
|
import hmac
|
|
import secrets
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import database
|
|
|
|
MIN_PASSWORD_LENGTH = 12
|
|
SALT_BYTES = 16
|
|
ITERATIONS = 200_000
|
|
SESSION_BYTES = 32
|
|
SESSION_TTL_SECONDS = 30 * 24 * 60 * 60
|
|
|
|
SESSION_COOKIE = "skuld_session"
|
|
CSRF_COOKIE = "skuld_csrf"
|
|
|
|
|
|
def _now():
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def _stamp(moment):
|
|
return moment.isoformat(timespec="seconds")
|
|
|
|
|
|
def _hash_password(password, salt_hex, iterations):
|
|
return hashlib.pbkdf2_hmac(
|
|
"sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), iterations
|
|
).hex()
|
|
|
|
|
|
def _hash_token(token):
|
|
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def csrf_secret(token):
|
|
"""Return the CSRF secret that belongs to a session token."""
|
|
return hashlib.sha256(("csrf:" + token).encode("utf-8")).hexdigest()
|
|
|
|
|
|
def admin_exists(conn=None):
|
|
"""Return True when the admin account has been created."""
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
row = conn.execute("SELECT 1 FROM admin WHERE id = 1").fetchone()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
return row is not None
|
|
|
|
|
|
def create_admin(username, password, conn=None):
|
|
"""Create the single admin account. Refuses a short password or a second admin."""
|
|
username = (username or "").strip()
|
|
if not username:
|
|
raise ValueError("username is required")
|
|
if len(password or "") < MIN_PASSWORD_LENGTH:
|
|
raise ValueError("password must be at least %d characters" % MIN_PASSWORD_LENGTH)
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
if admin_exists(conn):
|
|
raise ValueError("an admin already exists")
|
|
salt = secrets.token_hex(SALT_BYTES)
|
|
now = _stamp(_now())
|
|
conn.execute(
|
|
"INSERT INTO admin (id, username, password_hash, salt, iterations,"
|
|
" created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?)",
|
|
(username, _hash_password(password, salt, ITERATIONS), salt, ITERATIONS, now, now),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
|
|
|
|
def reset_password(password, username=None, conn=None):
|
|
"""Set the admin password without knowing the current one.
|
|
|
|
Creates the admin account when there is none. Used by the
|
|
`set-admin-password` action, which generates the password in the container.
|
|
Returns the stored username.
|
|
"""
|
|
if len(password or "") < MIN_PASSWORD_LENGTH:
|
|
raise ValueError("password must be at least %d characters" % MIN_PASSWORD_LENGTH)
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
row = conn.execute("SELECT username FROM admin WHERE id = 1").fetchone()
|
|
name = (username or "").strip() or (row["username"] if row else "admin")
|
|
salt = secrets.token_hex(SALT_BYTES)
|
|
digest = _hash_password(password, salt, ITERATIONS)
|
|
now = _stamp(_now())
|
|
if row is None:
|
|
conn.execute(
|
|
"INSERT INTO admin (id, username, password_hash, salt, iterations,"
|
|
" created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?)",
|
|
(name, digest, salt, ITERATIONS, now, now),
|
|
)
|
|
else:
|
|
conn.execute(
|
|
"UPDATE admin SET username = ?, password_hash = ?, salt = ?,"
|
|
" iterations = ?, updated_at = ? WHERE id = 1",
|
|
(name, digest, salt, ITERATIONS, now),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
return name
|
|
|
|
|
|
def verify_login(username, password, conn=None):
|
|
"""Return True when the username and password match the admin account."""
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT username, password_hash, salt, iterations FROM admin WHERE id = 1"
|
|
).fetchone()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
if row is None:
|
|
return False
|
|
if not hmac.compare_digest((username or "").strip(), row["username"]):
|
|
return False
|
|
expected = _hash_password(password or "", row["salt"], row["iterations"])
|
|
return hmac.compare_digest(expected, row["password_hash"])
|
|
|
|
|
|
def create_session(conn=None):
|
|
"""Create a session and return its raw token."""
|
|
token = secrets.token_urlsafe(SESSION_BYTES)
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
now = _now()
|
|
conn.execute(
|
|
"INSERT INTO sessions (token_hash, created_at, expires_at) VALUES (?, ?, ?)",
|
|
(
|
|
_hash_token(token),
|
|
_stamp(now),
|
|
_stamp(now + timedelta(seconds=SESSION_TTL_SECONDS)),
|
|
),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
return token
|
|
|
|
|
|
def session_valid(token):
|
|
"""Return True when the token names a live session. Expired rows are deleted."""
|
|
if not token:
|
|
return False
|
|
conn = database.connect()
|
|
try:
|
|
conn.execute("DELETE FROM sessions WHERE expires_at <= ?", (_stamp(_now()),))
|
|
conn.commit()
|
|
row = conn.execute(
|
|
"SELECT 1 FROM sessions WHERE token_hash = ?", (_hash_token(token),)
|
|
).fetchone()
|
|
finally:
|
|
conn.close()
|
|
return row is not None
|
|
|
|
|
|
def delete_session(token):
|
|
"""Remove one session."""
|
|
if not token:
|
|
return
|
|
conn = database.connect()
|
|
try:
|
|
conn.execute("DELETE FROM sessions WHERE token_hash = ?", (_hash_token(token),))
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def change_password(current, new, conn=None):
|
|
"""Replace the admin password. Returns False when the current one is wrong."""
|
|
if len(new or "") < MIN_PASSWORD_LENGTH:
|
|
raise ValueError("password must be at least %d characters" % MIN_PASSWORD_LENGTH)
|
|
own = conn is None
|
|
if own:
|
|
conn = database.connect()
|
|
try:
|
|
row = conn.execute(
|
|
"SELECT password_hash, salt, iterations FROM admin WHERE id = 1"
|
|
).fetchone()
|
|
if row is None:
|
|
return False
|
|
expected = _hash_password(current or "", row["salt"], row["iterations"])
|
|
if not hmac.compare_digest(expected, row["password_hash"]):
|
|
return False
|
|
salt = secrets.token_hex(SALT_BYTES)
|
|
conn.execute(
|
|
"UPDATE admin SET password_hash = ?, salt = ?, iterations = ?, updated_at = ?"
|
|
" WHERE id = 1",
|
|
(_hash_password(new, salt, ITERATIONS), salt, ITERATIONS, _stamp(_now())),
|
|
)
|
|
conn.commit()
|
|
finally:
|
|
if own:
|
|
conn.close()
|
|
return True
|