Rotate database and mailbox passwords from the panel #70

Merged
parkel merged 3 commits from feature/service-credential-rotation into main 2026-11-21 19:24:30 +01:00
9 changed files with 480 additions and 42 deletions
Showing only changes of commit c2655b57f5 - Show all commits

No files matched your search

+95
View File
@@ -0,0 +1,95 @@
import json
import os
import re
import secrets
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID
from .node_files import read_root_file, write_new_file
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
ROTATION_IN_PROGRESS = (
"Retry the current credential change before starting another."
)
def valid_generation(value):
if value is None:
return True
if not isinstance(value, str):
return False
try:
return str(UUID(value)) == value
except ValueError:
return False
def rotation_path(path):
return path.with_suffix(".rotation")
def load_pending_rotation(path):
try:
pending = json.loads(read_root_file(rotation_path(path), mode=0o600))
except FileNotFoundError:
return None
if (
not isinstance(pending, dict)
or not isinstance(pending.get("id"), str)
or not valid_generation(pending["id"])
or "previous" not in pending
or not valid_generation(pending["previous"])
or not isinstance(pending.get("password"), str)
or not PASSWORD.fullmatch(pending["password"])
):
raise ValueError("The pending credential record is invalid.")
return pending
def stage_rotation(path, request, generation, *, hash_password=None):
pending = load_pending_rotation(path)
if pending is not None and (
pending["id"] != request.rotation_id
or pending["previous"] != request.previous_id
):
raise ValueError(ROTATION_IN_PROGRESS)
if generation not in (request.previous_id, request.rotation_id):
raise ValueError(
"The credential changed after this request was opened."
)
if pending is not None or generation == request.rotation_id:
return pending
password = secrets.token_urlsafe(32)
pending = {
"id": request.rotation_id,
"previous": generation,
"password": password,
}
if hash_password is not None:
pending["password_hash"] = hash_password(password)
write_new_file(rotation_path(path), json.dumps(pending), mode=0o600)
sync_directory(path.parent)
return pending
def save_credential_record(path, record):
with TemporaryDirectory(dir=path.parent) as scratch:
staged = Path(scratch) / "credentials"
write_new_file(staged, json.dumps(record, indent=2) + "\n", mode=0o600)
os.replace(staged, path)
sync_directory(path.parent)
def finish_rotation(path):
rotation_path(path).unlink(missing_ok=True)
sync_directory(path.parent)
def sync_directory(path):
directory = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(directory)
finally:
os.close(directory)
+24 -2
View File
@@ -5,6 +5,11 @@ import secrets
from contextlib import closing, contextmanager, suppress
from pathlib import Path
from .credential_rotation import (
ROTATION_IN_PROGRESS,
rotation_path,
valid_generation,
)
from .node_files import read_root_file, require_root_directory, write_new_file
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
@@ -117,6 +122,7 @@ def checked_credentials(
*,
restoring=False,
verify_login=True,
pending_password=None,
):
name = database.name
schema, users = read_resources(cursor, name)
@@ -136,7 +142,20 @@ def checked_credentials(
raise ValueError("The database installation is incomplete.")
if not restoring:
check_restore_complete(record_path)
password_hash = native_password_hash(record["password"])
if pending_password is None and os.path.lexists(
rotation_path(record_path)
):
raise ValueError(ROTATION_IN_PROGRESS)
password = record["password"]
if pending_password is not None and users == (
(
"localhost",
"mysql_native_password",
native_password_hash(pending_password),
),
):
password = pending_password
password_hash = native_password_hash(password)
check_resources(
schema,
users,
@@ -169,7 +188,7 @@ def checked_credentials(
driver.connect(
host="localhost",
user=name,
passwd=record["password"],
passwd=password,
db=name,
unix_socket=str(socket),
connect_timeout=5,
@@ -193,6 +212,8 @@ def check_restore_complete(record_path):
def install_database(cursor, database, socket, record_path):
if os.path.lexists(rotation_path(record_path)):
raise ValueError(ROTATION_IN_PROGRESS)
check_restore_complete(record_path)
name = database.name
schema, users = read_resources(cursor, name)
@@ -270,6 +291,7 @@ def load_credentials(database, socket, path):
or not isinstance(record.get("password"), str)
or not record["password"]
or not record["password"].isascii()
or not valid_generation(record.get("rotation_id"))
or not isinstance(record.get("ownership"), str)
or not record["ownership"]
):
+81
View File
@@ -0,0 +1,81 @@
from contextlib import closing
from . import database_node_apply as db
from .credential_rotation import (
finish_rotation,
load_pending_rotation,
save_credential_record,
stage_rotation,
)
ACCESS_DENIED = 1045
def rotate_database_credentials(request, socket):
database = request.resource
socket = socket.resolve()
path = db.STATE_DIRECTORY / f"{database.name}.json"
with db.locked_cursor(database, socket) as (driver, cursor):
pending = load_pending_rotation(path)
record = db.checked_credentials(
driver,
cursor,
database,
socket,
path,
pending_password=pending["password"] if pending else None,
)
if record is None:
raise ValueError(
"Apply the database manifest before rotating its login."
)
if db.login_is_locked(cursor, database.name):
raise ValueError(
"Resume the database login before rotating its password."
)
generation = record.get("rotation_id")
pending = stage_rotation(path, request, generation)
if generation != request.rotation_id:
password = pending["password"]
cursor.execute(
"ALTER USER %s@'localhost' "
"IDENTIFIED VIA mysql_native_password USING %s",
(database.name, db.native_password_hash(password)),
)
db.checked_credentials(
driver,
cursor,
database,
socket,
path,
pending_password=password,
)
verify_old_password_rejected(driver, record)
record = record | {
"password": password,
"rotation_id": request.rotation_id,
}
save_credential_record(path, record)
finish_rotation(path)
return record
def verify_old_password_rejected(driver, record):
try:
with closing(
driver.connect(
host="localhost",
user=record["user"],
passwd=record["password"],
db=record["database"],
unix_socket=record["socket"],
connect_timeout=5,
charset="utf8mb4",
)
):
pass
except driver.Error as error:
if error.args and error.args[0] == ACCESS_DENIED:
return
raise
raise ValueError("MariaDB still accepts the previous password.")
@@ -8,6 +8,7 @@ from subprocess import CompletedProcess
from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import patch
from uuid import uuid4
from django.test import SimpleTestCase
@@ -18,10 +19,13 @@ from coulobre.mail_node_apply import (
check_dovecot_quota,
credential_path,
ensure_mail_home,
load_credentials,
mailbox_status,
run,
)
from coulobre.mail_node_quota import set_mailbox_access, set_mailbox_quota
from coulobre.mail_node_rotation import rotate_mailbox_credentials
from coulobre.service_credentials import ServiceCredentialRequest
class MailboxApplyRequestTests(SimpleTestCase):
@@ -301,6 +305,48 @@ class MailboxApplyTests(SimpleTestCase):
self.assertEqual(self.users.read_bytes(), table)
self.assertEqual(path.read_bytes(), credentials)
def test_interrupted_rotation_does_not_block_another_mailbox(self):
path = apply_mailbox(self.spec)
original = load_credentials(path)
replacement_hash = "{SHA512-CRYPT}$6$mockSalt$" + ("B" * 86)
rotation = ServiceCredentialRequest(self.spec, "rotate", str(uuid4()))
self.postfix_lookup.return_value = "1"
with (
patch("coulobre.mail_node_quota.require_root_directory"),
patch("coulobre.mail_node_apply.wait_for_dovecot_user"),
patch(
"coulobre.mail_node_rotation.verify_mailbox_rotation"
) as verify,
patch(
"coulobre.credential_rotation.read_root_file",
side_effect=lambda path, **kwargs: path.read_text(),
),
):
verify.side_effect = OSError("Verification interrupted.")
with (
patch(
"coulobre.mail_node_apply.hash_mailbox_password",
return_value=replacement_hash,
),
self.assertRaisesMessage(OSError, "Verification interrupted"),
):
rotate_mailbox_credentials(rotation)
self.assertEqual(load_credentials(path), original)
self.assertIn(replacement_hash, self.users.read_text())
sibling = MailboxSpec("other.example", "support")
apply_mailbox(sibling)
self.assertIn(replacement_hash, self.users.read_text())
self.assertIn(sibling.address, self.mailboxes.read_text())
verify.side_effect = None
result = rotate_mailbox_credentials(rotation)
self.assertNotEqual(result["password"], original.password)
self.assertEqual(
load_credentials(path).rotation_id, rotation.rotation_id
)
self.assertEqual(rotate_mailbox_credentials(rotation), result)
def test_waits_for_dovecot_to_read_the_updated_authentication_file(self):
home = self.storage / self.spec.domain / self.spec.local_part
self.resolve_home.side_effect = [None, None, str(home)]
@@ -328,7 +328,7 @@ class NativeServiceCredentialTests(SimpleTestCase):
patch("sys.stdin", SimpleNamespace(buffer=source)),
redirect_stdout(StringIO()) as output,
):
result = service_credentials.main()
result = service_credentials.main([])
return result, json.loads(output.getvalue())
def test_the_database_socket_accepts_only_managed_resource_identity(self):
+68 -20
View File
@@ -10,10 +10,18 @@ import stat
import subprocess
import time
from contextlib import contextmanager
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path
from tempfile import TemporaryDirectory
from .credential_rotation import (
PASSWORD,
ROTATION_IN_PROGRESS,
load_pending_rotation,
rotation_path,
save_credential_record,
valid_generation,
)
from .mail_node import MailboxSpec
from .node_files import read_root_file, require_root_directory, write_new_file
@@ -25,7 +33,6 @@ POSTFIX_MAILBOXES = Path("/etc/postfix/coulobre-mailboxes")
DOVECOT_USERS = Path("/etc/dovecot/coulobre-users")
LMTP_SOCKET = Path("/var/spool/postfix/private/dovecot-lmtp")
MANAGED_HEADER = "# Managed by Coulobre Panel\n"
PASSWORD = re.compile(r"[A-Za-z0-9_-]{43}")
PASSWORD_HASH = re.compile(
r"\{SHA512-CRYPT\}\$6\$(?:rounds=[0-9]+\$)?"
r"[./0-9A-Za-z]{1,16}\$[./0-9A-Za-z]{86}"
@@ -38,6 +45,7 @@ class Credentials:
password: str
password_hash: str
suspended: bool = False
rotation_id: str | None = None
@property
def home(self):
@@ -59,14 +67,14 @@ class Credentials:
}
if self.suspended:
document["suspended"] = True
text = json.dumps(document, indent=2) + "\n"
if self.rotation_id is not None:
document["rotation_id"] = self.rotation_id
if replace:
with TemporaryDirectory(dir=self.path.parent) as scratch:
staged = Path(scratch) / "credentials"
write_new_file(staged, text, mode=0o600)
os.replace(staged, self.path)
save_credential_record(self.path, document)
else:
write_new_file(self.path, text, mode=0o600)
write_new_file(
self.path, json.dumps(document, indent=2) + "\n", mode=0o600
)
def credential_path(mailbox):
@@ -86,10 +94,12 @@ def load_credentials(path):
data["password"],
data["password_hash"],
data.get("suspended", False),
data.get("rotation_id"),
)
if (
record.path != path
or type(record.suspended) is not bool
or not valid_generation(record.rotation_id)
or not PASSWORD.fullmatch(record.password)
or not PASSWORD_HASH.fullmatch(record.password_hash)
):
@@ -168,6 +178,8 @@ def configured_mail_account(mailbox):
)
return None
if os.path.lexists(rotation_path(path)):
raise ValueError(ROTATION_IN_PROGRESS)
record = load_credentials(path)
check_registered_manifest(record, mailbox)
if not home_is_prepared(record):
@@ -250,8 +262,14 @@ def install_mailbox(mailbox, state_directory):
None,
)
if active is not None:
if os.path.lexists(rotation_path(active.path)):
raise ValueError(ROTATION_IN_PROGRESS)
check_registered_manifest(active, mailbox)
prepared = [record for record in records if home_is_prepared(record)]
prepared = [
published_mailbox_credentials(record, account, auth_group, modern)
for record in records
if home_is_prepared(record)
]
if mailbox.quota_mib is not None or any(
record.mailbox.quota_mib is not None for record in prepared
):
@@ -278,17 +296,7 @@ def install_mailbox(mailbox, state_directory):
"The mailbox already exists outside Coulobre's registry."
)
password = secrets.token_urlsafe(32)
password_hash = run(
"doveadm",
"pw",
"-s",
"SHA512-CRYPT",
standard_input=f"{password}\n{password}\n",
)
if not PASSWORD_HASH.fullmatch(password_hash):
raise ValueError(
"Dovecot did not return the expected password hash."
)
password_hash = hash_mailbox_password(password)
active = Credentials(mailbox, password, password_hash)
active.save()
os.fsync(state_directory)
@@ -309,6 +317,46 @@ def install_mailbox(mailbox, state_directory):
return active.path
def hash_mailbox_password(password):
password_hash = run(
"doveadm",
"pw",
"-s",
"SHA512-CRYPT",
standard_input=f"{password}\n{password}\n",
)
if not PASSWORD_HASH.fullmatch(password_hash):
raise ValueError("Dovecot did not return the expected password hash.")
return password_hash
def replacement_credentials(record, pending):
password_hash = pending.get("password_hash")
if (
not isinstance(password_hash, str)
or not PASSWORD_HASH.fullmatch(password_hash)
or record.rotation_id not in (pending["previous"], pending["id"])
):
raise ValueError("The pending mailbox credential record is invalid.")
return replace(
record,
password=pending["password"],
password_hash=password_hash,
rotation_id=pending["id"],
)
def published_mailbox_credentials(record, account, auth_group, modern):
pending = load_pending_rotation(record.path)
if pending is None:
return record
replacement = replacement_credentials(record, pending)
table = read_lookup_table(DOVECOT_USERS, 0o640, auth_group)
replacement_row = dovecot_lookup_row(replacement, account, modern=modern)
# Preserve the live row while another mailbox's rotation is retried.
return replacement if replacement_row in table.splitlines() else record
def check_registered_manifest(record, mailbox):
if record.mailbox != mailbox:
raise ValueError(
+3
View File
@@ -3,6 +3,7 @@ import time
from dataclasses import replace
from . import mail_node_apply as mail
from .credential_rotation import ROTATION_IN_PROGRESS, rotation_path
from .node_files import require_root_directory
@@ -21,6 +22,8 @@ def update_mailbox(mailbox, *, suspended=None):
path = mail.credential_path(mailbox)
if state_directory is None or not os.path.lexists(path):
raise ValueError("Apply the mailbox manifest before updating it.")
if os.path.lexists(rotation_path(path)):
raise ValueError(ROTATION_IN_PROGRESS)
original = mail.load_credentials(path)
if suspended is None:
updated = replace(original, mailbox=mailbox)
+60
View File
@@ -0,0 +1,60 @@
import time
from . import mail_node_apply as mail
from .credential_rotation import (
finish_rotation,
load_pending_rotation,
stage_rotation,
)
from .mail_node_quota import publish_mailbox_update
def rotate_mailbox_credentials(request):
mailbox = request.resource
path = mail.credential_path(mailbox)
with mail.locked_state(create=False, exclusive=True) as directory:
if directory is None:
raise ValueError(
"Apply the mailbox manifest before rotating its login."
)
original = mail.load_credentials(path)
mail.check_registered_manifest(original, mailbox)
if original.suspended:
raise ValueError(
"Resume the mailbox before rotating its password."
)
if load_pending_rotation(path) is None:
mail.configured_mail_account(mailbox)
pending = stage_rotation(
path,
request,
original.rotation_id,
hash_password=mail.hash_mailbox_password,
)
if original.rotation_id != request.rotation_id:
updated = mail.replacement_credentials(original, pending)
publish_mailbox_update(original, updated, access_change=False)
verify_mailbox_rotation(original, updated)
updated.save(replace=True)
else:
updated = original
publish_mailbox_update(updated, updated, access_change=False)
if not mail.mailbox_can_authenticate(updated):
raise ValueError(
"Dovecot could not authenticate the saved login."
)
finish_rotation(path)
return {"user": mailbox.address, "password": updated.password}
def verify_mailbox_rotation(original, updated):
for _ in range(10):
mail.run("doveadm", "auth", "cache", "flush", updated.mailbox.address)
if mail.mailbox_can_authenticate(
updated
) and not mail.mailbox_can_authenticate(original):
return
time.sleep(0.2)
raise ValueError(
"Dovecot did not confirm the replacement mailbox password."
)
+102 -19
View File
@@ -1,19 +1,40 @@
import argparse
import os
from dataclasses import dataclass
from .credential_rotation import valid_generation
from .database_node import DEFAULT_SOCKET, DatabaseSpec
from .mail_node import MailboxSpec
from .node_requests import serve_apply_request
REQUEST_VERSION = 1
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
MAIL_CREDENTIAL_SOCKET = "/run/coulobre-mail-credentials.sock"
CREDENTIAL_TIMEOUT_SECONDS = 15
ROTATION_TIMEOUT_SECONDS = 25
CREDENTIALS_UNAVAILABLE = "The service credentials are currently unavailable."
@dataclass(frozen=True)
class ServiceCredentialRequest:
resource: DatabaseSpec | MailboxSpec
operation: str = "read"
rotation_id: str | None = None
previous_id: str | None = None
def __post_init__(self):
if self.operation in ("read", "generation"):
if self.rotation_id is None and self.previous_id is None:
return
elif (
self.operation == "rotate"
and isinstance(self.rotation_id, str)
and valid_generation(self.rotation_id)
and valid_generation(self.previous_id)
and self.rotation_id != self.previous_id
):
return
raise ValueError("Expected a valid credential operation.")
@property
def kind(self):
@@ -27,31 +48,62 @@ class ServiceCredentialRequest:
def from_manifest(cls, data):
if (
not isinstance(data, dict)
or data.keys() != {"version", "kind", "resource"}
or type(data["version"]) is not int
or type(data.get("version")) is not int
or data["version"] != REQUEST_VERSION
):
raise ValueError("Expected a local service credential request.")
if data["kind"] == "database":
return cls(DatabaseSpec.from_manifest(data["resource"]))
if data["kind"] == "mailbox":
return cls(MailboxSpec.from_manifest(data["resource"]))
raise ValueError("Expected a database or mailbox credential request.")
raise ValueError("Expected a service credential request.")
fields = {"version", "kind", "resource"}
operation = data.get("operation", "read")
if operation == "generation":
fields.add("operation")
elif operation == "rotate":
fields.update(("operation", "rotation_id", "previous_id"))
if data.keys() != fields:
raise ValueError("Expected a service credential request.")
parsers = {
"database": DatabaseSpec.from_manifest,
"mailbox": MailboxSpec.from_manifest,
}
kind = data["kind"]
if not isinstance(kind, str) or kind not in parsers:
raise ValueError(
"Expected a database or mailbox credential request."
)
return cls(
parsers[kind](data["resource"]),
operation,
data.get("rotation_id"),
data.get("previous_id"),
)
def manifest(self):
return {
manifest = {
"version": REQUEST_VERSION,
"kind": self.kind,
"resource": self.resource.manifest(),
}
if self.operation != "read":
manifest["operation"] = self.operation
if self.operation == "rotate":
manifest.update(
rotation_id=self.rotation_id, previous_id=self.previous_id
)
return manifest
def main():
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument("--mailbox-only", action="store_true")
args = parser.parse_args(argv)
def parse(payload):
request = ServiceCredentialRequest.from_manifest(payload)
if args.mailbox_only and request.kind != "mailbox":
raise ValueError("This node handles mailbox requests only.")
return request
return serve_apply_request(
REQUEST_VERSION,
ServiceCredentialRequest.from_manifest,
read_service_credentials,
include_result=True,
REQUEST_VERSION, parse, read_service_credentials, include_result=True
)
@@ -61,26 +113,55 @@ def read_service_credentials(request):
setting = f"COULOBRE_LOCAL_{request.kind.upper()}_CREDENTIALS"
if os.environ.get(setting) != "1":
raise ValueError(CREDENTIALS_UNAVAILABLE)
if (
request.operation != "read"
and os.environ.get(f"{setting}_ROTATION") != "1"
):
raise ValueError(CREDENTIALS_UNAVAILABLE)
try:
if request.kind == "database":
return read_database_credentials(request.resource)
return read_mailbox_credentials(request.resource)
if request.operation == "rotate":
return rotate_service_credentials(request)
read = (
read_database_credentials
if request.kind == "database"
else read_mailbox_credentials
)
if request.operation == "generation":
return {"generation": read(request.resource, generation_only=True)}
return read(request.resource)
except (OSError, ValueError):
raise ValueError(CREDENTIALS_UNAVAILABLE) from None
def read_database_credentials(database):
def rotate_service_credentials(request):
if request.kind == "database":
from .database_node_rotation import rotate_database_credentials
record = rotate_database_credentials(request, DEFAULT_SOCKET)
return {
key: record[key]
for key in ("database", "user", "host", "socket", "password")
}
from .mail_node_rotation import rotate_mailbox_credentials
return rotate_mailbox_credentials(request)
def read_database_credentials(database, *, generation_only=False):
from .database_node_backup import managed_database
with managed_database(database, DEFAULT_SOCKET) as (_, record, _path):
if generation_only:
return record.get("rotation_id")
return {
key: record[key]
for key in ("database", "user", "host", "socket", "password")
}
def read_mailbox_credentials(mailbox):
def read_mailbox_credentials(mailbox, *, generation_only=False):
from .mail_node_apply import (
configured_mail_account,
credential_path,
@@ -92,4 +173,6 @@ def read_mailbox_credentials(mailbox):
if configured_mail_account(mailbox) is None:
raise ValueError(CREDENTIALS_UNAVAILABLE)
credentials = load_credentials(credential_path(mailbox))
if generation_only:
return credentials.rotation_id
return {"user": mailbox.address, "password": credentials.password}