- removing a passkey ends every session it opened (sessions record the id); - an open Chrome view on the internet address re-checks its session every 5 s and closes when it ends (sign-out, passkey removed, access off); - Sign out there always ends the owner's session unless the guest cookie beside it is a live impersonation — a cookie a guest's *.gabvdl.xyz site planted can no longer turn it into a no-op; - the passkey link and "back on" need Authelia on the admin host, not just "not the internet address": the host token / loopback (what a run started from a stolen session can call) are refused; making a link now pushes; - switching internet access off cancels an open link; - ceremony tickets capped per address (10) so one address can't drain them; - docs: what the off switch can't undo (the owner is a shell). - 13 regression tests (test_remote_access: 51). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
165 lines
6.6 KiB
Python
165 lines
6.6 KiB
Python
"""
|
|
The security log and its switches — see docs/security.md.
|
|
|
|
* ``/data/security-log.jsonl`` — one event per line, append-only: guest
|
|
sign-ins and link requests, guest runs, the guard hook's hits, sandbox
|
|
denials, anonymous edge requests on the admin host, the owner's lock/stop
|
|
actions. Past ``MAX_BYTES`` the older half is dropped.
|
|
* ``/data/security.json`` — ``{guestsLocked, lockedAt, pushKinds, devices}``:
|
|
the *Lock guests* switch, which kinds push the owner, and the devices
|
|
(IP + user agent) each guest has signed in from, so a new one stands out.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import secrets
|
|
import threading
|
|
|
|
from users.store import _JsonFile
|
|
|
|
MAX_BYTES = int(os.environ.get("SECURITY_LOG_MAX_BYTES", str(8 * 1024 * 1024)))
|
|
# What pushes the owner by default (Gabriel's picks, form 2026-11-01): a run
|
|
# the guard stopped, an owner run that tripped a rule (allowed, but he hears
|
|
# of it), a guest signing in from a new device, a burst of sandbox denials —
|
|
# plus the edge tripwire (someone trying what made them the owner until then).
|
|
DEFAULT_PUSH_KINDS = ("guard_block", "guard_owner", "new_device", "sandbox_burst",
|
|
"edge_anonymous", "cross_site", "owner_login",
|
|
"remote_passkey_added", "remote_passkey_invited")
|
|
# Defaults that postdate the first security.json: offered once (see __init__).
|
|
NEW_DEFAULT_KINDS = ("cross_site", "owner_login", "remote_passkey_added",
|
|
"remote_passkey_invited")
|
|
DEVICES_PER_USER = 20
|
|
|
|
|
|
def _now_iso() -> str:
|
|
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
class SecurityState(_JsonFile):
|
|
def __init__(self, path: str):
|
|
super().__init__(path, {"guestsLocked": False, "lockedAt": None,
|
|
"pushKinds": list(DEFAULT_PUSH_KINDS), "devices": {}})
|
|
# A default added after this file was written (``cross_site``,
|
|
# 2026-11-15) is switched on once; unticking it afterwards sticks.
|
|
with self._lock:
|
|
offered = set(self._data.get("offered") or ())
|
|
fresh = [k for k in NEW_DEFAULT_KINDS if k not in offered]
|
|
if fresh:
|
|
kinds = set(self._data.get("pushKinds") or ()) | set(fresh)
|
|
self._data["pushKinds"] = sorted(kinds)
|
|
self._data["offered"] = sorted(offered | set(NEW_DEFAULT_KINDS))
|
|
try:
|
|
self._save()
|
|
except OSError:
|
|
pass
|
|
|
|
def get(self) -> dict:
|
|
with self._lock:
|
|
return {"guestsLocked": bool(self._data.get("guestsLocked")),
|
|
"lockedAt": self._data.get("lockedAt"),
|
|
"remoteLocked": bool(self._data.get("remoteLocked")),
|
|
"remoteLockedAt": self._data.get("remoteLockedAt"),
|
|
"pushKinds": list(self._data.get("pushKinds") or [])}
|
|
|
|
def guests_locked(self) -> bool:
|
|
with self._lock:
|
|
return bool(self._data.get("guestsLocked"))
|
|
|
|
def remote_locked(self) -> bool:
|
|
"""*Internet access* switched off: nobody signs in as the owner on the
|
|
internet address (``OWNER_HOSTS``) — the admin host is unaffected."""
|
|
with self._lock:
|
|
return bool(self._data.get("remoteLocked"))
|
|
|
|
def set_remote_locked(self, locked: bool) -> None:
|
|
with self._lock:
|
|
self._data["remoteLocked"] = bool(locked)
|
|
self._data["remoteLockedAt"] = _now_iso() if locked else None
|
|
self._save()
|
|
|
|
def set_locked(self, locked: bool) -> dict:
|
|
with self._lock:
|
|
self._data["guestsLocked"] = bool(locked)
|
|
self._data["lockedAt"] = _now_iso() if locked else None
|
|
self._save()
|
|
return self.get()
|
|
|
|
def set_push_kinds(self, kinds: list[str]) -> dict:
|
|
with self._lock:
|
|
self._data["pushKinds"] = sorted({str(k) for k in kinds})
|
|
self._save()
|
|
return self.get()
|
|
|
|
def see_device(self, uid: str, ip: str, ua: str) -> dict:
|
|
"""Record that ``uid`` signed in from ``ip`` with ``ua``; which of the
|
|
two is new for them (``{"ip": bool, "ua": bool, "first": bool}``)."""
|
|
ua_key = hashlib.sha256((ua or "").encode()).hexdigest()[:16]
|
|
with self._lock:
|
|
seen = self._data.setdefault("devices", {}).setdefault(uid, [])
|
|
first = not seen
|
|
new_ip = bool(ip) and all(d.get("ip") != ip for d in seen)
|
|
new_ua = all(d.get("ua") != ua_key for d in seen)
|
|
seen.append({"ip": ip, "ua": ua_key, "at": _now_iso()})
|
|
del seen[:-DEVICES_PER_USER]
|
|
self._save()
|
|
return {"ip": new_ip, "ua": new_ua, "first": first}
|
|
|
|
|
|
class SecurityLog:
|
|
def __init__(self, path: str):
|
|
self.path = pathlib.Path(path)
|
|
self._lock = threading.Lock()
|
|
|
|
def append(self, event: dict) -> dict:
|
|
ev = {"id": f"sec_{secrets.token_hex(6)}", "at": _now_iso(), **event}
|
|
line = json.dumps(ev, separators=(",", ":"), ensure_ascii=False) + "\n"
|
|
with self._lock:
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
with os.fdopen(fd, "a", encoding="utf-8") as f:
|
|
f.write(line)
|
|
self._rotate()
|
|
return ev
|
|
|
|
def _rotate(self) -> None:
|
|
try:
|
|
if self.path.stat().st_size <= MAX_BYTES:
|
|
return
|
|
lines = self.path.read_text(encoding="utf-8").splitlines(keepends=True)
|
|
except OSError:
|
|
return
|
|
tmp = self.path.with_suffix(".tmp")
|
|
tmp.write_text("".join(lines[len(lines) // 2:]), encoding="utf-8")
|
|
os.chmod(tmp, 0o600)
|
|
os.replace(tmp, self.path)
|
|
|
|
def events(self, *, kinds: set[str] | None = None, who: str | None = None,
|
|
since: str | None = None, limit: int = 200) -> list[dict]:
|
|
"""Newest first."""
|
|
try:
|
|
with self._lock:
|
|
lines = self.path.read_text(encoding="utf-8").splitlines()
|
|
except OSError:
|
|
return []
|
|
out: list[dict] = []
|
|
for line in reversed(lines):
|
|
try:
|
|
ev = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if since and (ev.get("at") or "") < since:
|
|
break
|
|
if kinds and ev.get("kind") not in kinds:
|
|
continue
|
|
if who and ev.get("who") != who:
|
|
continue
|
|
out.append(ev)
|
|
if len(out) >= limit:
|
|
break
|
|
return out
|