Sign out
+Sign this browser out of Pipelines.
+ +diff --git a/scripts/manage.py b/scripts/manage.py index 9f958559..ebd1a99f 100644 --- a/scripts/manage.py +++ b/scripts/manage.py @@ -416,6 +416,10 @@ def supervise(config): PIPELINES_NTFY_PUBLIC_URL=config["public_url"], PIPELINES_NTFY_TOKEN_FILE=str(root / "secrets/publisher-token")) env.pop("PIPELINES_NTFY_TOKEN", None) + if config.get("web"): + # The server verifies step-up re-authentication against the + # web sign-in password file (read-only). + env["PIPELINES_WEB_AUTH_FILE"] = config["web"]["auth_file"] server_command = [str(root / "bin/pipelines-server"), "-addr", server_address(config), "-db", str(root / "data/pipelines.db")] if config.get("allow_authoring") is True: diff --git a/scripts/password.py b/scripts/password.py index 9c2b854a..d8232cb9 100644 --- a/scripts/password.py +++ b/scripts/password.py @@ -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__": diff --git a/scripts/setup-native.py b/scripts/setup-native.py index 7ed9bdde..7a5e7153 100644 --- a/scripts/setup-native.py +++ b/scripts/setup-native.py @@ -44,6 +44,7 @@ lan = module("lan_address", "lan-address.py") release_lookup = module("resolve_releases", "resolve-releases.py") tokens = module("save_ntfy_token", "save-ntfy-token.py") app_build = module("app_build", "app_build.py") +web_password = module("pipelines_password", "password.py") DEFAULT_PREFIX = Path.home() / ".local/share/pipelines" MARKER = "pipelines-install.json" @@ -348,16 +349,17 @@ class Setup: or Path.home() / ".config/pipelines/web-auth.json").expanduser().resolve() if auth.exists(): data = json.loads(auth.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 web_password.valid_auth(data): raise ValueError(f"Invalid existing web auth file; retained unchanged: {auth}") if auth.stat().st_mode & 0o077: raise ValueError(f"Web auth file must be private (chmod 600): {auth}") else: password = self.choose_password() + self.chosen_web_password = password auth.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - self._write_atomic(auth, (json.dumps({"password": password, + # Only a scrypt hash is stored (see scripts/password.py). + self._write_atomic(auth, (json.dumps({"password_hash": web_password.hash_password(password), + "password_weak": False, "generation": 0, "secret": secrets.token_urlsafe(48)}) + "\n").encode(), 0o600) target = prefix / "lib/web" shutil.copytree(Path(__file__).resolve().parents[1] / "web", target, dirs_exist_ok=True, @@ -374,17 +376,20 @@ class Setup: PIPELINES_WEB_PASSWORD answers it without a terminal (automation).""" given = self.environ.get("PIPELINES_WEB_PASSWORD") if given is not None: - if len(given) < 8: - raise ValueError("PIPELINES_WEB_PASSWORD must be at least 8 characters") + problem = web_password.password_problem(given) + if problem: + raise ValueError(f"PIPELINES_WEB_PASSWORD is too weak. {problem}") return given if not sys.stdin.isatty(): raise ValueError("Choose the web sign-in password: rerun ./install in a terminal, " - "or set PIPELINES_WEB_PASSWORD (at least 8 characters)") + "or set PIPELINES_WEB_PASSWORD. " + web_password.PASSWORD_RULE) print("This computer has no web sign-in yet. Choose the password for the web app and phone.") + print(web_password.PASSWORD_RULE) while True: - first = getpass.getpass("Web password (at least 8 characters): ") - if len(first) < 8: - print("Too short; use at least 8 characters.") + first = getpass.getpass("Web password: ") + problem = web_password.password_problem(first) + if problem: + print(problem) continue if getpass.getpass("Repeat the password: ") != first: print("The passwords did not match; try again.") @@ -673,6 +678,17 @@ class Setup: process.kill() process.wait() + def reader_password(self, web): + """The phone's ntfy password, which matches the web password: the one + chosen during this install, else a not yet migrated plaintext file. A + hashed file has no plaintext; an existing ntfy account keeps its own + password and a new one is asked for on the terminal.""" + chosen = getattr(self, "chosen_web_password", None) + if chosen is not None: + return chosen + legacy = json.loads(Path(web["auth_file"]).read_text()).get("password") + return legacy if isinstance(legacy, str) else None + def bootstrap_ntfy(self, prefix, config_path, reader_password=None): def run_ntfy(args, capture=False, interactive=False, password=None): return self.ntfy(prefix, config_path, list(args), capture=capture, password=password) @@ -856,7 +872,7 @@ class Setup: else: self.migrate_docker(prefix, args.replace_data) self.bootstrap_ntfy(prefix, config_path, - reader_password=json.loads(Path(web["auth_file"]).read_text())["password"]) + reader_password=self.reader_password(web)) timezone = args.timezone if not timezone: try: diff --git a/scripts/test_password.py b/scripts/test_password.py index 5383109b..15684a62 100644 --- a/scripts/test_password.py +++ b/scripts/test_password.py @@ -12,6 +12,9 @@ password = importlib.util.module_from_spec(spec) spec.loader.exec_module(password) +NEW = "tulip orbit canyon ember" + + class PasswordTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory(prefix="pipelines-password-test-") @@ -36,12 +39,61 @@ class PasswordTests(unittest.TestCase): self.assertEqual(password.auth_path(home=self.home, prefix=prefix, environ={"PIPELINES_WEB_AUTH_FILE": str(self.auth)}), self.auth) - def test_change_preserves_cookie_secret_metadata_and_private_permissions(self): - password.change_password(self.auth, "new password") + def test_change_stores_a_hash_rotates_sessions_and_keeps_metadata(self): + password.change_password(self.auth, NEW) result = json.loads(self.auth.read_text()) - self.assertEqual(result, dict(self.original, password="new password")) + self.assertNotIn("password", result) + self.assertNotIn(NEW, self.auth.read_text()) + self.assertTrue(result["password_hash"].startswith("scrypt$32768$8$1$")) + self.assertTrue(password.verify_password(result["password_hash"], NEW)) + self.assertFalse(password.verify_password(result["password_hash"], "old password")) + self.assertIs(result["password_weak"], False) + self.assertNotEqual(result["secret"], self.original["secret"]) + self.assertGreaterEqual(len(result["secret"]), 32) + self.assertEqual(result["generation"], 1) + self.assertEqual(result["other"], "preserve") self.assertEqual(self.auth.stat().st_mode & 0o777, 0o600) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) + password.change_password(self.auth, "k7#Rv9!qLm2@Xz4s") + self.assertEqual(json.loads(self.auth.read_text())["generation"], 2) + + def test_revoke_all_rotates_secret_and_generation_but_keeps_password(self): + password.change_password(self.auth, NEW) + before = json.loads(self.auth.read_text()) + password.revoke_all(self.auth) + after = json.loads(self.auth.read_text()) + self.assertEqual(after["password_hash"], before["password_hash"]) + self.assertEqual(after["generation"], before["generation"] + 1) + self.assertNotEqual(after["secret"], before["secret"]) + + def test_revoke_all_cli_needs_no_terminal_and_prints_no_secret(self): + output = io.StringIO() + with patch.object(password.sys, "argv", ["password", "--revoke-all"]), \ + patch.object(password, "auth_path", return_value=self.auth), \ + patch.object(password.sys.stdin, "isatty", return_value=False), \ + patch.object(password.sys, "stdout", output): + password.main() + result = json.loads(self.auth.read_text()) + self.assertEqual(result["generation"], 1) + self.assertEqual(result["password"], "old password") # unchanged, still the proxy's to migrate + self.assertIn("signed out", output.getvalue()) + for value in ("old password", result["secret"], self.original["secret"]): + self.assertNotIn(value, output.getvalue()) + + def test_strength_rule(self): + for strong in (NEW, "correct horse battery staple", "k7#Rv9!qLm2@Xz4s", "cat dog sun red"): + self.assertIsNone(password.password_problem(strong), strong) + for weak in ("short", "old password", "J8m!x2Lq0#vR9tZ", "password password password", + "a" * 20, "Password12345678!", "qwertyuiop1234567890", "password welcome admin letmein", + "dog dog dog dog dog"): + self.assertIsNotNone(password.password_problem(weak), weak) + + def test_hash_matches_rfc7914_scrypt_and_rejects_garbage(self): + stored = password.hash_password("pleaseletmein", n=16384) + self.assertTrue(password.verify_password(stored, "pleaseletmein")) + self.assertFalse(password.verify_password(stored, "pleaseletmeim")) + self.assertFalse(password.verify_password("scrypt$x", "pleaseletmein")) + self.assertFalse(password.verify_password("plain$1$1$1$a$b", "pleaseletmein")) def test_short_password_does_not_modify_auth(self): with self.assertRaises(ValueError): @@ -52,25 +104,25 @@ class PasswordTests(unittest.TestCase): link = self.home / "link.json" link.symlink_to(self.auth) with self.assertRaises(ValueError): - password.change_password(link, "new password") + password.change_password(link, NEW) self.assertEqual(json.loads(self.auth.read_text()), self.original) self.assertTrue(link.is_symlink()) def test_public_or_malformed_auth_is_not_replaced(self): self.auth.chmod(0o644) with self.assertRaisesRegex(ValueError, "private"): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) self.auth.chmod(0o600) self.auth.write_text("{broken") with self.assertRaises(ValueError): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) self.assertEqual(self.auth.read_text(), "{broken") def test_replacement_failure_preserves_original_and_cleans_staging(self): before = self.auth.read_bytes() with patch.object(password.os, "replace", side_effect=OSError("fixture failure")): with self.assertRaises(OSError): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) self.assertEqual(self.auth.read_bytes(), before) self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) @@ -82,7 +134,7 @@ class PasswordTests(unittest.TestCase): self.assertEqual(Path(source).parent, self.auth.parent) return replace(source, target) with patch.object(password.os, "replace", side_effect=checked_replace): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) self.assertEqual(len(calls), 1) def test_file_changed_during_update_is_not_overwritten(self): @@ -92,10 +144,24 @@ class PasswordTests(unittest.TestCase): return replace(descriptor) with patch.object(password.os, "fsync", side_effect=external_update): with self.assertRaisesRegex(ValueError, "changed during"): - password.change_password(self.auth, "new password") + password.change_password(self.auth, NEW) self.assertEqual(json.loads(self.auth.read_text())["password"], "changed elsewhere") self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) + def test_cli_warns_once_about_a_weak_current_password(self): + self.auth.write_text(json.dumps(dict(self.original, password_weak=True))) + errors = io.StringIO() + with patch.object(password.sys, "argv", ["password"]), \ + patch.object(password, "auth_path", return_value=self.auth), \ + patch.object(password.sys.stdin, "isatty", return_value=True), \ + patch.object(password.getpass, "getpass", side_effect=[NEW, NEW]), \ + patch.object(password.sys, "stdout", io.StringIO()), \ + patch.object(password.sys, "stderr", errors): + password.main() + self.assertEqual(errors.getvalue().count("weak"), 1) + self.assertIs(json.loads(self.auth.read_text())["password_weak"], False) + self.assertEqual(list(self.auth.parent.glob(".pipelines-password-*")), []) + def test_cli_retries_mismatch_and_does_not_print_password(self): output = io.StringIO() errors = io.StringIO() @@ -103,14 +169,16 @@ class PasswordTests(unittest.TestCase): patch.object(password, "auth_path", return_value=self.auth), \ patch.object(password.sys.stdin, "isatty", return_value=True), \ patch.object(password.getpass, "getpass", side_effect=[ - "first password", "wrong confirmation", "new password", "new password"]), \ + "tiny9", "first strong password here", "wrong confirmation", NEW, NEW]), \ patch.object(password.sys, "stdout", output), \ patch.object(password.sys, "stderr", errors): password.main() - self.assertEqual(json.loads(self.auth.read_text())["password"], "new password") + self.assertTrue(password.verify_password(json.loads(self.auth.read_text())["password_hash"], NEW)) self.assertIn("do not match", errors.getvalue()) + self.assertIn("Too short", errors.getvalue()) self.assertIn("No service restart", output.getvalue()) - for value in ("first password", "wrong confirmation", "new password", "old password"): + self.assertIn("signed out", output.getvalue()) + for value in ("tiny9", "first strong password here", "wrong confirmation", NEW, "old password"): self.assertNotIn(value, output.getvalue() + errors.getvalue()) def test_cli_refuses_non_tty_before_prompting(self): diff --git a/scripts/test_setup_native.py b/scripts/test_setup_native.py index 8a74f682..409091cb 100644 --- a/scripts/test_setup_native.py +++ b/scripts/test_setup_native.py @@ -140,7 +140,7 @@ class SetupNativeTests(unittest.TestCase): return setup_native.Setup(directory, prefix=Path(directory) / "prefix", runner=recorder, resolver=resolution, popen=fake_ntfy_serve, environ={"XDG_CONFIG_HOME": str(Path(directory) / "config"), - "PIPELINES_WEB_PASSWORD": "chosen-password"}) + "PIPELINES_WEB_PASSWORD": "chosen tulip orbit canyon"}) @staticmethod def which_all(opencode="/usr/bin/opencode", pi=None, cc="/usr/bin/cc"): @@ -247,7 +247,10 @@ class SetupNativeTests(unittest.TestCase): installer.configure_web(prefix, setup_native.arguments([])) self.assertEqual(auth.read_bytes(), before) self.assertEqual(auth.stat().st_mode & 0o777, 0o600) - self.assertEqual(json.loads(before)["password"], "chosen-password") + stored = json.loads(before) + self.assertNotIn("password", stored) + self.assertNotIn(b"chosen tulip", before) + self.assertTrue(setup_native.web_password.verify_password(stored["password_hash"], "chosen tulip orbit canyon")) self.assertTrue(Path(web["script"]).is_file()) # The web app is built in Docker once and installed for the proxy. self.assertTrue(installer.runner.has("docker", "run", "pipelines-app-build", "web")) @@ -269,16 +272,17 @@ class SetupNativeTests(unittest.TestCase): installer.configure_web(prefix, setup_native.arguments([])) installer.environ["PIPELINES_WEB_PASSWORD"] = "short" with patch.object(setup_native.shutil, "which", side_effect=self.which_all()): - with self.assertRaisesRegex(ValueError, "at least 8"): + with self.assertRaisesRegex(ValueError, "too weak"): installer.configure_web(prefix, setup_native.arguments([])) installer.environ.pop("PIPELINES_WEB_PASSWORD") with patch.object(setup_native.shutil, "which", side_effect=self.which_all()), \ patch.object(setup_native.sys.stdin, "isatty", return_value=True), \ patch.object(setup_native.getpass, "getpass", - side_effect=["short", "typed-password", "other-password", - "typed-password", "typed-password"]): + side_effect=["short", "typed tulip orbit canyon", "other tulip orbit canyon", + "typed tulip orbit canyon", "typed tulip orbit canyon"]): web = installer.configure_web(prefix, setup_native.arguments([])) - self.assertEqual(json.loads(Path(web["auth_file"]).read_text())["password"], "typed-password") + stored = json.loads(Path(web["auth_file"]).read_text())["password_hash"] + self.assertTrue(setup_native.web_password.verify_password(stored, "typed tulip orbit canyon")) def test_fresh_install_skips_docker_migration(self): args = setup_native.arguments(["--fresh"]) diff --git a/scripts/uninstall.py b/scripts/uninstall.py index 90da20a8..4f47164b 100644 --- a/scripts/uninstall.py +++ b/scripts/uninstall.py @@ -73,9 +73,12 @@ class Uninstall: # A custom credential file must actually be a Pipelines login store. if path.exists(): data = json.loads(path.read_text()) - if not isinstance(data, dict) or not isinstance(data.get("password"), str) or not isinstance(data.get("secret"), str): + if not isinstance(data, dict) or not isinstance(data.get("password", data.get("password_hash")), str) \ + or not isinstance(data.get("secret"), str): raise ValueError("Custom web credentials are not a Pipelines password file") roots.add(path) + # The proxy's signed-out session list beside it (web/serve.mjs). + roots.add(self.safe(path.with_name(path.name + ".sessions.json"))) return {self.safe(path) for path in roots} def preflight(self): diff --git a/web/serve.mjs b/web/serve.mjs index 1f8e316d..4485f271 100644 --- a/web/serve.mjs +++ b/web/serve.mjs @@ -18,14 +18,27 @@ // // The default host is 127.0.0.1. Use --host 0.0.0.0 only on a trusted LAN/VPN. import { createServer, request } from "node:http"; -import { createHmac, timingSafeEqual, randomBytes } from "node:crypto"; -import { createReadStream, readFileSync } from "node:fs"; +import { createReadStream } from "node:fs"; import { homedir } from "node:os"; import { readFile, stat } from "node:fs/promises"; import { extname, join, normalize, resolve, sep } from "node:path"; import { fileURLToPath } from "node:url"; import net from "node:net"; import { sameOriginUpgrade } from "./src/proxySecurity.js"; +import { AuthStore, verifyPassword } from "./src/authStore.js"; +import { LoginLimiter, clientKey } from "./src/loginLimiter.js"; +import { PASSWORD_RULE } from "./src/passwordPolicy.js"; +import { SessionSockets } from "./src/sessionSockets.js"; +import { + HOST_SESSION_COOKIE, + SESSION_COOKIE, + applySecurityHeaders, + isHttps, + pageHeaders, + safeNext, + sameOriginRequest, + sessionCookieName, +} from "./src/webSecurity.js"; import { PeerRelay, proxyDiscovery } from "./src/peerRelay.js"; // The proxy's own directory holds the sign-in page's icons. @@ -46,20 +59,12 @@ const UPDATES = flag(process.argv, "--updates", "") ? resolve(flag(process.argv, const AUTH_DISABLED = process.env.PIPELINES_WEB_AUTH === "disabled"; const AUTH_FILE = process.env.PIPELINES_WEB_AUTH_FILE ?? join(homedir(), ".config", "pipelines", "web-auth.json"); -const SESSION_COOKIE = "pipelines_session"; +const store = AUTH_DISABLED ? null : new AuthStore(AUTH_FILE); function loadAuth(fatal = true) { if (AUTH_DISABLED) return null; try { - const parsed = JSON.parse(readFileSync(AUTH_FILE, "utf8")); - if ( - typeof parsed.password === "string" && - parsed.password.length >= 8 && - typeof parsed.secret === "string" && - parsed.secret.length >= 32 - ) { - return { password: parsed.password, secret: parsed.secret }; - } + return store.load(); } catch { // Fall through to the refusal below. } @@ -69,7 +74,41 @@ function loadAuth(fatal = true) { } let auth = loadAuth(); -function refreshAuth() { auth = loadAuth(false); } +// Every upgraded browser socket remembers its session token, so a sign-out, +// a password change or an expiry closes it (on the event, and on a timer). +const sockets = new SessionSockets(); +function sweepSockets() { + sockets.sweep((token) => { + try { + return store.check(token) !== null; + } catch { + return false; + } + }); +} + +/** Reloads the credential; a new password or secret closes every socket. */ +function refreshAuth() { + const previous = auth; + try { + auth = loadAuth(false); + } catch (error) { + // Fail closed: an unusable credential file ends every open connection. + sockets.sweep(() => false); + throw error; + } + if (previous && auth && (previous.secret !== auth.secret || previous.generation !== auth.generation)) sweepSockets(); +} + +const SWEEP_MS = Math.max(200, Number(process.env.PIPELINES_WEB_SWEEP_MS) || 5000); +if (!AUTH_DISABLED) { + setInterval(() => { + try { + refreshAuth(); + sweepSockets(); + } catch {} + }, SWEEP_MS).unref(); +} function cookieValue(req, name) { for (const part of String(req.headers.cookie ?? "").split(";")) { @@ -86,47 +125,44 @@ function cookieValue(req, name) { return ""; } -function signSession(expires) { - const payload = `${expires}.${randomBytes(18).toString("base64url")}`; - return `${payload}.${createHmac("sha256", auth.secret).update(payload).digest("base64url")}`; +/** The request's session token (the https cookie name first). */ +function sessionValue(req) { + return cookieValue(req, HOST_SESSION_COOKIE) || cookieValue(req, SESSION_COOKIE); } const SESSION_LONG_SECONDS = 30 * 24 * 60 * 60; const SESSION_SHORT_SECONDS = 12 * 60 * 60; -function sessionToken(remember = false) { - const ttl = remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS; - return signSession(Math.floor(Date.now() / 1000) + ttl); -} - -function validSession(value) { - if (!auth || typeof value !== "string") return false; - const parts = value.split("."); - if (parts.length !== 2 && parts.length !== 3) return false; - const expires = parts[0], signature = parts.at(-1); - if (!/^\d+$/.test(expires) || !signature) return false; - const expected = createHmac("sha256", auth.secret).update(parts.slice(0, -1).join(".")).digest(); - let given; +/** The request's live session, or null. */ +function session(req) { + if (!auth) return null; try { - given = Buffer.from(signature, "base64url"); + return store.check(sessionValue(req)); } catch { - return false; + return null; } - if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false; - return Number(expires) > Math.floor(Date.now() / 1000); } function isAuthed(req) { - return !auth || validSession(cookieValue(req, SESSION_COOKIE)); + return !auth || session(req) !== null; } -const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : cookieValue(req, SESSION_COOKIE)); +const peerRelay = new PeerRelay((req) => AUTH_DISABLED ? "test-auth-disabled" : sessionValue(req)); -function passwordOk(candidate) { +// Password checks are scrypt (32 MiB each); a few run at once and the rest +// are answered 429 rather than queued without bound. +const VERIFY_LIMIT = 4; +let verifying = 0; +async function passwordOk(candidate) { if (!auth) return true; - const given = Buffer.from(String(candidate ?? "")); - const expected = Buffer.from(auth.password); - return given.length === expected.length && timingSafeEqual(given, expected); + const value = String(candidate ?? ""); + if (value.length > 4096) return false; + verifying++; + try { + return await verifyPassword(auth.hash, value); + } finally { + verifying--; + } } function sessionCookie(req, remember = false) { @@ -134,40 +170,65 @@ function sessionCookie(req, remember = false) { // a top-level navigation, and a Strict cookie is withheld on that first // request, which made a remembered session look forgotten. Lax still keeps // the cookie off cross-site subresource and POST requests. - const bits = [`${SESSION_COOKIE}=${sessionToken(remember)}`, "Path=/", "HttpOnly", "SameSite=Lax"]; + const { token } = store.issue(remember ? SESSION_LONG_SECONDS : SESSION_SHORT_SECONDS); + const bits = [`${sessionCookieName(req)}=${token}`, "Path=/", "HttpOnly", "SameSite=Lax"]; // Remember me persists the cookie; otherwise it is a browser-session cookie // (and the signed token itself expires after 12 hours). if (remember) { const expires = new Date(Date.now() + SESSION_LONG_SECONDS * 1000).toUTCString(); bits.push(`Max-Age=${SESSION_LONG_SECONDS}`, `Expires=${expires}`); } - // Tailscale terminates TLS and usually forwards the scheme; when it does, the - // cookie is Secure. A direct plain-http LAN visit still works without it. - const forwarded = String(req.headers["x-forwarded-proto"] ?? "").split(",")[0].trim(); - if (forwarded === "https") bits.push("Secure"); + // Tailscale terminates TLS and forwards the scheme; then the cookie is + // Secure and host-locked (__Host-). A plain-http LAN visit keeps the plain name. + if (isHttps(req)) bits.push("Secure"); return bits.join("; "); } -/** Small per-address brake on password guessing. */ -const loginFailures = new Map(); -function loginBlocked(address) { - const entry = loginFailures.get(address); - return Boolean(entry && entry.until > Date.now()); -} -function noteLoginFailure(address) { - const now = Date.now(); - const entry = loginFailures.get(address) ?? { count: 0, until: 0 }; - entry.count += 1; - if (entry.count >= 8) { - entry.count = 0; - entry.until = now + 30_000; - } - loginFailures.set(address, entry); +/** Set-Cookie values that clear both session cookie names. */ +function clearedCookies(req) { + const cleared = [`${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`]; + if (isHttps(req)) cleared.push(`${HOST_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Secure; Max-Age=0`); + return cleared; } -function safeNext(value) { - const next = String(value ?? ""); - return next.startsWith("/") && !next.startsWith("//") ? next : "/"; +/** Ends one session: server-side revocation, its relayed peers and sockets. */ +function signOut(req) { + const token = sessionValue(req); + peerRelay.forget(req); + try { + store.revoke(token); + } catch {} + sweepSockets(); +} + +const limiter = new LoginLimiter(); + +function logoutPage() { + return ` + +
+ + + +Sign this browser out of Pipelines.
+ +Sign in to reach this server.