Hash the web password and revoke sessions server-side
Store a scrypt hash (migrating a plaintext password without changing it), sign sessions with a generation that ./password and --revoke-all rotate, make logout a same-origin POST that revokes the token, add sign out everywhere, and close proxied websockets whose session ends. Enforce a strength rule for new passwords, back off logins per client and server-wide, check Origin on login, tighten next, add security headers and a __Host- cookie over https.
This commit is contained in:
+164
-12
@@ -1,15 +1,119 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Change the local Pipelines web sign-in password without restarting services."""
|
||||
"""Change the local Pipelines web sign-in password, or sign out every device.
|
||||
|
||||
The password is stored only as a scrypt hash. Every change (and --revoke-all)
|
||||
rotates the cookie secret and the session generation, so each signed-in
|
||||
browser and device must sign in again; open connections are closed within a
|
||||
few seconds. No service restart is needed.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import fcntl
|
||||
import getpass
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import stat
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# scrypt cost: 32 MiB and roughly a tenth of a second per check. The hash
|
||||
# records its parameters, so they can be raised later without a migration.
|
||||
SCRYPT_N, SCRYPT_R, SCRYPT_P, SCRYPT_KEY = 1 << 15, 8, 1, 32
|
||||
SCRYPT_MAXMEM = 64 * 1024 * 1024
|
||||
|
||||
PASSWORD_RULE = ("Use at least 16 characters, or a passphrase of 4 or more random words "
|
||||
"separated by spaces or dashes (15 characters or more in all). Common words, "
|
||||
"keyboard runs and repeated characters do not count towards the length.")
|
||||
|
||||
# Kept in step with web/src/passwordPolicy.js.
|
||||
COMMON = ("password", "passwort", "pipelines", "pipeline", "qwerty", "azerty", "letmein",
|
||||
"welcome", "admin", "administrator", "iloveyou", "monkey", "dragon", "master",
|
||||
"secret", "login", "changeme", "default", "football", "baseball", "sunshine",
|
||||
"princess", "shadow", "trustno", "superman", "hello", "test", "guest", "root")
|
||||
SEPARATORS = re.compile(r"[\s\-_.,;:+/]+")
|
||||
|
||||
|
||||
def _runs(text):
|
||||
"""Remove runs of 3+ repeated characters and 4+ consecutive characters."""
|
||||
out, i = [], 0
|
||||
while i < len(text):
|
||||
j = i + 1
|
||||
while j < len(text) and text[j] == text[i]:
|
||||
j += 1
|
||||
if j - i >= 3:
|
||||
i = j
|
||||
continue
|
||||
for step in (1, -1):
|
||||
j = i + 1
|
||||
while j < len(text) and ord(text[j]) - ord(text[j - 1]) == step:
|
||||
j += 1
|
||||
if j - i >= 4:
|
||||
break
|
||||
else:
|
||||
out.append(text[i])
|
||||
i += 1
|
||||
continue
|
||||
i = j
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _substance(password):
|
||||
"""The characters left once common words, runs and separators are removed."""
|
||||
text = password.lower()
|
||||
for word in sorted(COMMON, key=len, reverse=True):
|
||||
text = text.replace(word, "")
|
||||
for row in ("qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"):
|
||||
for size in range(len(row), 3, -1):
|
||||
for start in range(len(row) - size + 1):
|
||||
text = text.replace(row[start:start + size], "")
|
||||
return SEPARATORS.sub("", _runs(text))
|
||||
|
||||
|
||||
def password_problem(password):
|
||||
"""Why a new password is too weak, or None. See PASSWORD_RULE."""
|
||||
if len(password) > 1024:
|
||||
return "Choose a password of at most 1024 characters."
|
||||
words = [word.lower() for word in SEPARATORS.split(password) if word]
|
||||
passphrase = (len(words) >= 4 and len(set(words)) >= 4 and all(len(word) >= 3 for word in words)
|
||||
and len(password) >= 15 and len(_substance(password)) >= 12)
|
||||
if passphrase:
|
||||
return None
|
||||
if len(password) < 16:
|
||||
return "Too short. " + PASSWORD_RULE
|
||||
if len(set(password)) < 8 or len(_substance(password)) < 12:
|
||||
return "Too predictable. " + PASSWORD_RULE
|
||||
return None
|
||||
|
||||
|
||||
def _b64(raw):
|
||||
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def hash_password(password, *, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P):
|
||||
salt = secrets.token_bytes(16)
|
||||
key = hashlib.scrypt(password.encode(), salt=salt, n=n, r=r, p=p, maxmem=SCRYPT_MAXMEM, dklen=SCRYPT_KEY)
|
||||
return f"scrypt${n}${r}${p}${_b64(salt)}${_b64(key)}"
|
||||
|
||||
|
||||
def verify_password(stored, candidate):
|
||||
"""Constant-time check of candidate against a stored scrypt hash."""
|
||||
try:
|
||||
scheme, n, r, p, salt, key = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
pad = lambda value: base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||
expected = pad(key)
|
||||
derived = hashlib.scrypt(candidate.encode(), salt=pad(salt), n=int(n), r=int(r), p=int(p),
|
||||
maxmem=SCRYPT_MAXMEM, dklen=len(expected))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(derived, expected)
|
||||
|
||||
|
||||
def auth_path(*, prefix=None, home=None, environ=None):
|
||||
home = Path(home or Path.home())
|
||||
@@ -31,6 +135,17 @@ def auth_path(*, prefix=None, home=None, environ=None):
|
||||
return home / ".config/pipelines/web-auth.json"
|
||||
|
||||
|
||||
def valid_auth(data):
|
||||
"""Whether data is a usable web auth file: a scrypt hash (or a legacy
|
||||
plaintext password the proxy has not migrated yet) and a cookie secret."""
|
||||
if not isinstance(data, dict) or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32:
|
||||
return False
|
||||
stored = data.get("password_hash")
|
||||
if isinstance(stored, str):
|
||||
return stored.startswith("scrypt$") and stored.count("$") == 5
|
||||
return isinstance(data.get("password"), str) and len(data["password"]) >= 8
|
||||
|
||||
|
||||
def read_auth(path):
|
||||
path = Path(path)
|
||||
info = path.lstat()
|
||||
@@ -39,21 +154,27 @@ def read_auth(path):
|
||||
if info.st_mode & 0o077:
|
||||
raise ValueError(f"Password file must be private: chmod 600 '{path}'")
|
||||
data = json.loads(path.read_text())
|
||||
if not isinstance(data, dict) or not isinstance(data.get("password"), str) or len(data["password"]) < 8 or not isinstance(data.get("secret"), str) or len(data["secret"]) < 32:
|
||||
if not valid_auth(data):
|
||||
raise ValueError("Invalid Pipelines password file; it was retained unchanged")
|
||||
return data, info
|
||||
|
||||
|
||||
def change_password(path, password):
|
||||
if len(password) < 8:
|
||||
raise ValueError("Choose a password of at least 8 characters")
|
||||
def _rotate(data):
|
||||
"""Invalidate every session: a new cookie secret and session generation."""
|
||||
generation = data.get("generation")
|
||||
data["generation"] = (generation if isinstance(generation, int) and generation >= 0 else 0) + 1
|
||||
data["secret"] = secrets.token_urlsafe(48)
|
||||
|
||||
|
||||
def update_auth(path, mutate):
|
||||
"""Apply mutate to the auth file atomically, under a directory lock."""
|
||||
path = Path(path)
|
||||
# Lock the directory inode, which remains stable across atomic file replaces.
|
||||
directory = os.open(path.parent, os.O_RDONLY)
|
||||
try:
|
||||
fcntl.flock(directory, fcntl.LOCK_EX)
|
||||
data, original = read_auth(path)
|
||||
data["password"] = password
|
||||
mutate(data)
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".pipelines-password-", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w") as output:
|
||||
@@ -72,26 +193,57 @@ def change_password(path, password):
|
||||
os.close(directory)
|
||||
|
||||
|
||||
def change_password(path, password):
|
||||
problem = password_problem(password)
|
||||
if problem:
|
||||
raise ValueError(problem)
|
||||
stored = hash_password(password)
|
||||
|
||||
def mutate(data):
|
||||
data.pop("password", None)
|
||||
data["password_hash"] = stored
|
||||
data["password_weak"] = False
|
||||
_rotate(data)
|
||||
|
||||
update_auth(path, mutate)
|
||||
|
||||
|
||||
def revoke_all(path):
|
||||
update_auth(path, _rotate)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--prefix", type=Path, help="Installation prefix (or PIPELINES_PREFIX)")
|
||||
parser.add_argument("--revoke-all", action="store_true",
|
||||
help="Sign out every browser and device without changing the password")
|
||||
args = parser.parse_args()
|
||||
path = auth_path(prefix=args.prefix)
|
||||
read_auth(path)
|
||||
data, _ = read_auth(path)
|
||||
if args.revoke_all:
|
||||
revoke_all(path)
|
||||
print("Every browser and device was signed out; sign in again with the same password.")
|
||||
return
|
||||
if not sys.stdin.isatty():
|
||||
raise ValueError("Run ./password in an interactive terminal (SSH with a TTY is supported)")
|
||||
if data.get("password_weak") is True:
|
||||
print("Warning: the current web password is weak. " + PASSWORD_RULE, file=sys.stderr)
|
||||
print(PASSWORD_RULE)
|
||||
while True:
|
||||
password = getpass.getpass("New Pipelines password: ")
|
||||
problem = password_problem(password)
|
||||
if problem:
|
||||
print(problem, file=sys.stderr)
|
||||
continue
|
||||
confirmation = getpass.getpass("Confirm new password: ")
|
||||
if len(password) < 8:
|
||||
print("Choose a password of at least 8 characters.", file=sys.stderr)
|
||||
elif password != confirmation:
|
||||
if password != confirmation:
|
||||
print("Passwords do not match. Try again.", file=sys.stderr)
|
||||
else:
|
||||
break
|
||||
change_password(path, password)
|
||||
print("Web sign-in password changed. No service restart is needed.")
|
||||
print("Existing sessions remain signed in. The notification password is unchanged.")
|
||||
print("Every browser and device was signed out and must sign in with the new password.")
|
||||
print("The notification password is unchanged.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user