"""Local break-glass accounts.
These exist for one purpose: administering the backup server when Microsoft
365 sign-in is not available (an Entra outage, a misconfigured Conditional
Access policy, or a full tenant recovery). Rules:
* Password (14+ characters) **and** a TOTP code or one-time recovery code,
always. TOTP codes cannot be replayed.
* 5 failed attempts lock the account for 15 minutes.
* Optional allow-list of networks the sign-in is accepted from.
* Every sign-in is audited and raises a notification event.
The first local admin is created during setup with a one-time **setup token**
printed in the API container log (or by ``s365b create-local-admin`` inside
the container), so nobody who merely reaches the page first can claim a new
installation.
"""
from __future__ import annotations
import hashlib
import ipaddress
import secrets
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from pydantic import Field, field_validator
from sqlalchemy import func, select, text
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from s365b.auth import passwords, totp
from s365b.core.secrets import SecretBox
from s365b.core.settings_store import SettingsGroup
from s365b.db.models import AuthSource, Setting, UserAccount, UserRole
[docs]
LOCKOUT = timedelta(minutes=15)
_BOOTSTRAP_KEY = "auth.bootstrap"
[docs]
USERNAME_RE = r"^[a-z0-9][a-z0-9._-]{2,63}$"
[docs]
class LoginError(Exception):
"""Sign-in refused. The message is safe to show (it never says which part was wrong).
Attributes:
locked_now: True if this failure just locked the account.
"""
def __init__(self, message: str, *, locked_now: bool = False) -> None:
super().__init__(message)
[docs]
self.locked_now = locked_now
[docs]
class LocalAuthSettings(SettingsGroup):
"""Break-glass sign-in settings.
Attributes:
allowed_networks: CIDR ranges local sign-in is accepted from; empty
means any network. Useful to restrict break-glass access to the
LAN or a management VLAN.
"""
[docs]
allowed_networks: list[str] = Field(default_factory=list)
@field_validator("allowed_networks")
@classmethod
def _cidrs(cls, value: list[str]) -> list[str]:
"""Normalise and validate CIDR ranges."""
return [str(ipaddress.ip_network(v.strip(), strict=False)) for v in value if v.strip()]
[docs]
def allows(self, ip: str | None) -> bool:
"""Return whether a client address may use local sign-in.
Args:
ip: Client IP address.
Returns:
True if allowed.
"""
if not self.allowed_networks:
return True
if not ip:
return False
try:
addr = ipaddress.ip_address(ip)
except ValueError:
return False
return any(addr in ipaddress.ip_network(n) for n in self.allowed_networks)
@dataclass(frozen=True, slots=True)
[docs]
class Enrolment:
"""What a new break-glass admin must save, shown once.
Attributes:
user_id: New user's ID.
totp_secret: Base32 secret (for manual entry).
totp_uri: ``otpauth://`` URI (for the QR code).
recovery_codes: One-time codes for when the authenticator is lost.
"""
[docs]
recovery_codes: list[str]
# --- setup token ---------------------------------------------------------------
[docs]
async def issue_setup_token(s: AsyncSession) -> str:
"""Create a new one-time setup token (replacing any earlier one).
Args:
s: Open session; the caller commits.
Returns:
The token, to print in the log. Only its hash is stored.
"""
token = secrets.token_urlsafe(18)
value = {
"token_hash": hashlib.sha256(token.encode()).hexdigest(),
"issued_at": datetime.now(UTC).isoformat(),
}
await s.execute(
insert(Setting)
.values(key=_BOOTSTRAP_KEY, value=value)
.on_conflict_do_update(index_elements=["key"], set_={"value": value})
)
return token
[docs]
async def check_setup_token(s: AsyncSession, token: str) -> bool:
"""Return whether a setup token is the current one.
Args:
s: Open session.
token: Token entered by the user.
Returns:
True if valid.
"""
row = await s.get(Setting, _BOOTSTRAP_KEY)
if row is None or not row.value.get("token_hash"):
return False
return secrets.compare_digest(
row.value["token_hash"], hashlib.sha256(token.encode()).hexdigest()
)
[docs]
async def clear_setup_token(s: AsyncSession) -> None:
"""Invalidate the setup token once the first admin exists.
Args:
s: Open session; the caller commits.
"""
row = await s.get(Setting, _BOOTSTRAP_KEY)
if row is not None:
await s.delete(row)
[docs]
async def has_local_admin(s: AsyncSession) -> bool:
"""Return whether a usable local admin exists (TOTP enrolled, not disabled).
Args:
s: Open session.
Returns:
True if one exists.
"""
count = await s.execute(
select(func.count())
.select_from(UserAccount)
.where(
UserAccount.source == AuthSource.LOCAL,
UserAccount.role == UserRole.ADMIN,
UserAccount.totp_confirmed,
~UserAccount.disabled,
)
)
return count.scalar_one() > 0
# --- accounts ------------------------------------------------------------------
[docs]
async def create_local_admin(
s: AsyncSession,
box: SecretBox,
username: str,
password: str,
*,
issuer: str,
display_name: str = "",
) -> Enrolment:
"""Create a break-glass admin. TOTP must be confirmed before it can sign in.
Args:
s: Open session; the caller commits.
box: Secret box for the TOTP secret.
username: Lowercase username.
password: Password (checked against the policy).
issuer: Name shown in the authenticator app.
display_name: Optional display name.
Returns:
Enrolment details to show once.
Raises:
passwords.PasswordPolicyError: If the password is too weak.
ValueError: If the username is invalid or taken.
"""
import re
username = username.strip().lower()
if not re.match(USERNAME_RE, username):
raise ValueError("username: 3-64 characters, lowercase letters, digits, '.', '_' or '-'")
passwords.check_policy(password, username)
existing = await s.execute(select(UserAccount).where(UserAccount.username == username))
if existing.scalar_one_or_none() is not None:
raise ValueError(f"username {username!r} is already in use")
secret = totp.new_secret()
codes, hashes = await passwords.generate_recovery_codes_async()
user = UserAccount(
source=AuthSource.LOCAL,
username=username,
display_name=display_name or username,
role=UserRole.ADMIN,
password_hash=await passwords.hash_password_async(password),
recovery_codes=hashes,
totp_confirmed=False,
)
s.add(user)
await s.flush()
user.totp_secret_enc = box.encrypt(secret.encode(), _totp_context(user))
return Enrolment(user.id, secret, totp.provisioning_uri(secret, username, issuer), codes)
[docs]
async def confirm_totp(s: AsyncSession, box: SecretBox, user: UserAccount, code: str) -> bool:
"""Activate TOTP for a new account by checking a first code.
Args:
s: Open session; the caller commits.
box: Secret box.
user: The local user.
code: Code from the authenticator app.
Returns:
True if the code was right and TOTP is now active.
"""
if not user.totp_secret_enc:
return False
secret = box.decrypt(user.totp_secret_enc, _totp_context(user)).decode()
step = totp.verify(secret, code, user.totp_last_step)
if step is None:
return False
user.totp_confirmed = True
user.totp_last_step = step
return True
[docs]
async def confirm_enrolment(
s: AsyncSession,
box: SecretBox,
settings: LocalAuthSettings,
*,
username: str,
password: str,
code: str,
ip: str | None,
) -> bool:
"""Activate a new or reset account: password and a first authenticator code.
Held to the same rules as sign-in: the network allow-list, and the
failed-attempt counter and lockout.
Args:
s: Open session; the caller commits (also on failure).
box: Secret box.
settings: Local sign-in settings.
username: Username.
password: Password.
code: Code from the authenticator app.
ip: Client IP address.
Returns:
True if the account is now active.
Raises:
LoginError: If not allowed from this network or the account is locked.
"""
if not settings.allows(ip):
raise LoginError("local sign-in is not allowed from this network")
user = (
await s.execute(
select(UserAccount)
.where(
UserAccount.username == username.strip().lower(),
UserAccount.source == AuthSource.LOCAL,
~UserAccount.totp_confirmed,
)
.with_for_update()
)
).scalar_one_or_none()
now = datetime.now(UTC)
if user is not None and user.locked_until and user.locked_until > now:
raise LoginError("account temporarily locked after repeated failures; try again later")
ok = await passwords.verify_password_async(user.password_hash if user else None, password)
if user is None:
return False
if ok and await confirm_totp(s, box, user, code):
user.failed_logins = 0
user.locked_until = None
return True
user.failed_logins += 1
if user.failed_logins >= MAX_FAILED_LOGINS:
user.locked_until = now + LOCKOUT
user.failed_logins = 0
return False
[docs]
async def authenticate(
s: AsyncSession,
box: SecretBox,
settings: LocalAuthSettings,
*,
username: str,
password: str,
code: str,
ip: str | None,
) -> tuple[UserAccount, bool]:
"""Check break-glass credentials.
Args:
s: Open session; the caller commits (also on failure, to keep the
failed-attempt counter).
box: Secret box.
settings: Local sign-in settings.
username: Username.
password: Password.
code: TOTP code, or a recovery code (``xxxxxx-xxxxxx``).
ip: Client IP address.
Returns:
``(user, used_recovery_code)``.
Raises:
LoginError: For any failure, with a generic message.
"""
generic = LoginError("sign-in failed: check the username, password and code")
if not settings.allows(ip):
raise LoginError("local sign-in is not allowed from this network")
user = (
await s.execute(
select(UserAccount)
.where(
UserAccount.username == username.strip().lower(),
UserAccount.source == AuthSource.LOCAL,
)
.with_for_update()
)
).scalar_one_or_none()
now = datetime.now(UTC)
if user is not None and user.locked_until and user.locked_until > now:
# Checked before the (deliberately slow) password check: a locked
# account costs nothing to try.
raise LoginError("account temporarily locked after repeated failures; try again later")
password_ok = await passwords.verify_password_async(
user.password_hash if user else None, password
)
if user is None:
raise generic
if user.disabled or not user.totp_confirmed:
raise generic
used_recovery = False
second_ok = False
if password_ok:
if "-" in code:
remaining = await passwords.use_recovery_code_async(list(user.recovery_codes), code)
if remaining is not None:
user.recovery_codes = remaining
second_ok = used_recovery = True
elif user.totp_secret_enc:
secret = box.decrypt(user.totp_secret_enc, _totp_context(user)).decode()
step = totp.verify(secret, code, user.totp_last_step)
if step is not None:
user.totp_last_step = step
second_ok = True
if not (password_ok and second_ok):
user.failed_logins += 1
if user.failed_logins >= MAX_FAILED_LOGINS:
user.locked_until = now + LOCKOUT
user.failed_logins = 0
raise LoginError(str(generic), locked_now=True)
raise generic
user.failed_logins = 0
user.locked_until = None
user.last_login_at = now
return user, used_recovery
# Advisory lock held while a change may remove a usable break-glass account,
# so two admins disabling each other cannot both pass the check.
_BREAK_GLASS_LOCK = 0x53365B01
[docs]
class LastBreakGlassError(Exception):
"""The change would leave no usable break-glass admin."""
[docs]
async def keep_a_break_glass_admin(s: AsyncSession, user_id: int) -> UserAccount | None:
"""Lock break-glass changes, then check one usable admin stays besides a user.
Call before disabling or resetting a local account; the lock is held
until the session's transaction ends.
Args:
s: Open session; the caller commits.
user_id: The account about to stop being usable.
Returns:
The account, read after the lock; ``None`` if it does not exist.
Raises:
LastBreakGlassError: If it is the last usable break-glass admin.
"""
await s.execute(text("SELECT pg_advisory_xact_lock(:k)"), {"k": _BREAK_GLASS_LOCK})
user = await s.get(UserAccount, user_id, populate_existing=True)
if (
user is None
or user.source is not AuthSource.LOCAL
or not user.totp_confirmed
or user.disabled
):
return user
others = await s.scalar(
select(func.count())
.select_from(UserAccount)
.where(
UserAccount.source == AuthSource.LOCAL,
UserAccount.totp_confirmed,
~UserAccount.disabled,
UserAccount.id != user.id,
)
)
if not others:
raise LastBreakGlassError
return user
[docs]
async def reset_credentials(
s: AsyncSession, box: SecretBox, user: UserAccount, *, password: str | None, issuer: str
) -> Enrolment:
"""Reset a break-glass account: new TOTP secret and recovery codes, optionally a new password.
Args:
s: Open session; the caller commits.
box: Secret box.
user: The local user.
password: New password, or ``None`` to keep the current one.
issuer: Name shown in the authenticator app.
Returns:
New enrolment details; TOTP must be confirmed again.
"""
if password is not None:
passwords.check_policy(password, user.username)
user.password_hash = await passwords.hash_password_async(password)
secret = totp.new_secret()
codes, hashes = await passwords.generate_recovery_codes_async()
user.totp_secret_enc = box.encrypt(secret.encode(), _totp_context(user))
user.totp_confirmed = False
user.totp_last_step = None
user.recovery_codes = hashes
user.failed_logins = 0
user.locked_until = None
return Enrolment(user.id, secret, totp.provisioning_uri(secret, user.username, issuer), codes)
def _totp_context(user: UserAccount) -> str:
return f"user_account:{user.id}:totp"