Compare commits

...
Author SHA1 Message Date
parkel d691e20b16 Merge pull request 'Prepare Coulobre 0.11.1 with shared receiver and database hardening' (#150) from release/0.11.1 into main
Coulobre Panel CI / Checks (Python 3.12) (push) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (push) Canceled after 0s
Reviewed-on: #150
2026-11-23 07:27:10 +01:00
parkel 1bd09f8cd7 Hold receiver scopes stable during in-flight requests
Coulobre Panel CI / Checks (Python 3.12) (pull_request) Canceled after 0s
Coulobre Panel CI / Checks (Python 3.14) (pull_request) Canceled after 0s
2026-11-23 06:47:16 +01:00
parkel 0de4d0c854 Support SHA-2 authentication for new managed MariaDB logins 2026-11-23 06:42:47 +01:00
parkel 23e6e01303 Restrict linked receiver keys to assigned domains 2026-11-23 06:42:47 +01:00
14 changed files with 729 additions and 95 deletions

No files matched your search

@@ -1,4 +1,4 @@
Match User coulobre-dns-request,coulobre-mail-request
Match User coulobre-dns-request,coulobre-mail-request,coulobre-dns-p-*,coulobre-mail-p-*
AuthenticationMethods publickey
PubkeyAuthentication yes
PasswordAuthentication no
@@ -11,10 +11,10 @@ Match User coulobre-dns-request,coulobre-mail-request
PermitTTY no
PermitUserRC no
Match User coulobre-dns-request
Match User coulobre-dns-request,coulobre-dns-p-*
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-dns-apply.sock
Match User coulobre-mail-request
Match User coulobre-mail-request,coulobre-mail-p-*
ForceCommand /usr/bin/socat -t 185 STDIO UNIX-CONNECT:/run/coulobre-mail-apply.sock
Match all
+60
View File
@@ -697,6 +697,66 @@ the provisioning socket is stopped or paused.
sudo /opt/coulobre/bin/coulobre-node-setup finish-maintenance dns /root/dns-upgrade.json
```
### Limit linked provisioning to assigned domains
Use scoped keys when independent panels share a DNS or mail receiver. The
receiver authenticates a dedicated Unix account for each panel and checks
the requested domain before applying changes or inspecting its mail queue.
Each scope lists exact domains. DNS parent and child zones must belong to
the same panel if their scopes overlap.
Upgrade the receiver and the panels, then apply the current receiver SSH
configuration with `coulobre-node-setup --source /path/to/release
install-receiver dns` (or `mail`). Prepare the panel's role-specific key.
Copy its public half to the receiver and authorize the domains.
```sh
# On the panel
sudo /opt/coulobre/bin/coulobre-node-setup prepare-panel dns
# On the receiver
sudo /opt/coulobre/bin/coulobre-node-setup authorize-scoped-panel \
dns panel-one /root/panel-one-dns.pub example.net
# On the panel, using the receiver's verified host key
sudo /opt/coulobre/bin/coulobre-node-setup --source /path/to/release \
enrol-panel dns dns.example.org /root/dns-host.pub --scope panel-one
```
Repeat authorization with the same public key and the complete desired
domain list when assignments change. For an existing unrestricted receiver,
coordinate a maintenance window, back up and remove unrestricted panel
keys, enroll the scoped identities, and check both panels before resuming
provisioning. For an existing panel relay, update the `User` directive in
its role-specific `/etc/coulobre-remote/<role>/ssh_config` to the scoped
username printed by authorization. Keep its pinned host key and run
`coulobre-node-setup check-panel <role>` before enabling jobs.
On scoped mail receivers, use local administrative workflows for mailbox
credential and archive operations. The separate legacy SSH transports for
those operations are unavailable on a scoped receiver. Local mail
delivery and IMAP keep using their existing configuration.
### Use SHA-2 for new managed database logins
On a MariaDB build with `auth_mysql_sha2`, you can provision new managed
database logins with `caching_sha2_password`. Verify the active site's PHP
driver, phpMyAdmin, and administrative clients against a test login before
changing the policy. Coulobre retains the authentication plugin and password
for each existing login.
```sh
sudo mariadb -e "INSTALL SONAME 'auth_mysql_sha2';"
printf '%s\n' caching_sha2_password | sudo tee /etc/coulobre/database-authentication
sudo chown root:root /etc/coulobre/database-authentication
sudo chmod 0644 /etc/coulobre/database-authentication
```
Managed logins remain restricted to localhost. If the target host needs an
older driver or does not supply the SHA-2 plugin, use
`mysql_native_password` as the policy for new logins. Keep the SHA-2 plugin
loaded as long as any existing managed login uses it.
### Upgrade from v0.9 to v0.10
Use the in-place procedure above with the v0.10 source release. Keep a copy
+4 -5
View File
@@ -38,11 +38,10 @@ after users have a way to update.
the client-facing ports for the functions you run. Keep Unix sockets and
environment files restricted to the identities listed in the deployment
guide. Keep each site's PHP-FPM pool and SFTP keys scoped to that site.
- Pin SSH host keys for linked nodes and off-site backups. Use dedicated
receiver keys and accounts. The panel receiver protocol is authenticated
by the enrolled panel key. Share a receiver only among cooperating
administrators who agree on service ownership and coordinate releases.
The linked-node upgrade runbook accounts for every authorized panel key.
- Pin SSH host keys for linked nodes and off-site backups. Use separate
domain-scoped keys for independent panels that share a receiver. Keep
unrestricted keys within one trusted operator group. The linked-node
upgrade runbook accounts for every authorized panel key.
- Review DNS delegation, mail routing permissions, and allowed forwarding.
Keep private DKIM material on the mail receiver and publish the matching
public records. Verify the mail configuration after changing packages.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "coulobre-panel"
version = "0.11.0rc1"
version = "0.11.1rc1"
description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md"
requires-python = ">=3.12"
+173 -53
View File
@@ -1,6 +1,7 @@
import hashlib
import json
import os
import re
import secrets
from contextlib import closing, contextmanager, suppress
from pathlib import Path
@@ -8,6 +9,7 @@ from pathlib import Path
from .credential_rotation import (
ROTATION_IN_PROGRESS,
rotation_path,
save_credential_record,
valid_generation,
)
from .node_files import read_root_file, require_root_directory, write_new_file
@@ -15,6 +17,10 @@ from .node_retirement import RetirementRecord
STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
MANAGED_COMMENT_PREFIX = "Coulobre managed database "
AUTHENTICATION_POLICY = Path("/etc/coulobre/database-authentication")
NATIVE_PASSWORD = "mysql_native_password"
SHA2_PASSWORD = "caching_sha2_password"
SHA2_VERIFIER = re.compile(r"[0-9A-F]+")
def apply_database(database, socket):
@@ -25,8 +31,8 @@ def apply_database(database, socket):
require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750)
require_root_directory(STATE_DIRECTORY, create_mode=0o700)
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (_, cursor):
install_database(cursor, database, socket, record_path)
with locked_cursor(database, socket) as (driver, cursor):
install_database(cursor, database, socket, record_path, driver=driver)
return record_path
@@ -71,18 +77,25 @@ def locked_cursor(database, socket):
) from None
def read_resources(cursor, name):
def read_resources(cursor, name, *, sha2=False):
cursor.execute(
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
"WHERE SCHEMA_NAME = %s",
(name,),
)
schema = cursor.fetchone()
cursor.execute(
"SELECT Host, plugin, authentication_string FROM mysql.user "
"WHERE User = %s",
(name,),
)
if sha2:
cursor.execute(
"SELECT Host, plugin, HEX(authentication_string), "
"authentication_string FROM mysql.user WHERE User = %s",
(name,),
)
else:
cursor.execute(
"SELECT Host, plugin, authentication_string FROM mysql.user "
"WHERE User = %s",
(name,),
)
return schema, cursor.fetchall()
@@ -126,11 +139,11 @@ def checked_credentials(
pending_password=None,
):
name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready")
with suppress(FileNotFoundError):
require_root_directory(record_path.parent)
if not os.path.lexists(record_path):
schema, users = read_resources(cursor, name)
if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError(
"The database, login, or completion marker has no local "
@@ -147,30 +160,46 @@ def checked_credentials(
rotation_path(record_path)
):
raise ValueError(ROTATION_IN_PROGRESS)
sha2 = uses_sha2(record)
schema, users = read_resources(cursor, name, sha2=sha2)
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)
if sha2:
verifier, server_value = sha2_login(users)
if verifier != record.get("authentication_verifier"):
if not pending_password or not can_sign_in(
driver, record, pending_password
):
raise ValueError(
"The MariaDB verifier differs from the registry."
)
password = pending_password
user_details = ("localhost", SHA2_PASSWORD, verifier, server_value)
authentication = (
f"IDENTIFIED VIA {SHA2_PASSWORD} USING '{server_value}'"
)
else:
if pending_password is not None and users == (
(
"localhost",
NATIVE_PASSWORD,
native_password_hash(pending_password),
),
):
password = pending_password
password_hash = native_password_hash(password)
user_details = ("localhost", NATIVE_PASSWORD, password_hash)
authentication = f"IDENTIFIED BY PASSWORD '{password_hash}'"
check_resources(
schema,
users,
MANAGED_COMMENT_PREFIX + record["ownership"],
password_hash,
user_details,
require_complete=True,
)
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
grantee = f"`{name}`@`localhost`"
expected_grants = {
(
f"GRANT USAGE ON *.* TO {grantee} "
f"IDENTIFIED BY PASSWORD '{password_hash}'",
),
(f"GRANT USAGE ON *.* TO {grantee} {authentication}",),
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
}
grants = {
@@ -184,25 +213,71 @@ def checked_credentials(
and login_is_locked(cursor, name)
):
return record
if not can_sign_in(driver, record, password):
raise ValueError(
"The stored application credentials cannot open the managed "
"database."
)
return record
def can_sign_in(driver, record, password):
try:
with closing(
driver.connect(
host="localhost",
user=name,
user=record["user"],
passwd=password,
db=name,
unix_socket=str(socket),
db=record["database"],
unix_socket=record["socket"],
connect_timeout=5,
charset="utf8mb4",
)
):
pass
return True
except driver.Error:
return False
def uses_sha2(record):
return record.get("authentication_plugin") == SHA2_PASSWORD
def sha2_login(users):
if len(users) != 1 or len(users[0]) != 4:
raise ValueError("Expected one managed MariaDB SHA-2 login.")
host, plugin, verifier, server_value = users[0]
if (
host != "localhost"
or plugin != SHA2_PASSWORD
or not isinstance(verifier, str)
or not SHA2_VERIFIER.fullmatch(verifier)
or not isinstance(server_value, str)
or not server_value
):
raise ValueError("The existing MariaDB SHA-2 login is invalid.")
return verifier, server_value
def configured_authentication(cursor):
try:
policy = read_root_file(AUTHENTICATION_POLICY, mode=0o644).strip()
except FileNotFoundError:
return NATIVE_PASSWORD
if policy == NATIVE_PASSWORD:
return policy
if policy != SHA2_PASSWORD:
raise ValueError("Choose a supported MariaDB authentication plugin.")
cursor.execute(
"SELECT PLUGIN_STATUS FROM information_schema.PLUGINS "
"WHERE PLUGIN_NAME = %s",
(policy,),
)
if cursor.fetchone() != ("ACTIVE",):
raise ValueError(
"The stored application credentials cannot open the managed "
"database."
) from None
return record
"Enable the MariaDB caching_sha2_password plugin first."
)
return policy
def check_restore_complete(record_path):
@@ -212,7 +287,7 @@ def check_restore_complete(record_path):
)
def install_database(cursor, database, socket, record_path):
def install_database(cursor, database, socket, record_path, *, driver=None):
if os.path.lexists(record_path.with_suffix(".retired")):
raise ValueError(
"This database is retained for a retired hosting account."
@@ -221,17 +296,44 @@ def install_database(cursor, database, socket, record_path):
raise ValueError(ROTATION_IN_PROGRESS)
check_restore_complete(record_path)
name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready")
record = reserve_credentials(
database, socket, record_path, ready_path, schema, users
existing = os.path.lexists(record_path)
record = (
load_credentials(database, socket, record_path) if existing else {}
)
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
password_hash = native_password_hash(record["password"])
plugin = (
record.get("authentication_plugin", NATIVE_PASSWORD)
if existing
else configured_authentication(cursor)
)
sha2 = plugin == SHA2_PASSWORD
schema, users = read_resources(cursor, name, sha2=sha2)
ready_path = record_path.with_suffix(".ready")
if not existing:
record = reserve_credentials(
database, socket, record_path, ready_path, schema, users, plugin
)
ready = check_completion_marker(ready_path, record)
if ready and sha2:
checked_credentials(driver, cursor, database, socket, record_path)
return
comment = MANAGED_COMMENT_PREFIX + record["ownership"]
password = record["password"]
if sha2:
if users:
verifier, server_value = sha2_login(users)
expected_user = (
"localhost",
SHA2_PASSWORD,
verifier,
server_value,
)
else:
expected_user = None
else:
password_hash = native_password_hash(password)
expected_user = ("localhost", NATIVE_PASSWORD, password_hash)
check_resources(
schema, users, comment, password_hash, require_complete=ready
schema, users, comment, expected_user, require_complete=ready
)
if schema is None:
@@ -241,24 +343,40 @@ def install_database(cursor, database, socket, record_path):
(comment,),
)
if not users:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password "
"USING %s",
(name, password_hash),
)
if sha2:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA "
"caching_sha2_password USING PASSWORD(%s)",
(name, password),
)
else:
cursor.execute(
"CREATE USER %s@'localhost' IDENTIFIED VIA "
"mysql_native_password USING %s",
(name, password_hash),
)
cursor.execute(
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
(name,),
)
if sha2:
_, users = read_resources(cursor, name, sha2=True)
verifier, _ = sha2_login(users)
if not can_sign_in(driver, record, password):
raise ValueError(
"The managed MariaDB SHA-2 login could not sign in."
)
save_credential_record(
record_path, record | {"authentication_verifier": verifier}
)
if not ready:
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
def reserve_credentials(database, socket, path, ready_path, schema, users):
if os.path.lexists(path):
return load_credentials(database, socket, path)
def reserve_credentials(
database, socket, path, ready_path, schema, users, plugin
):
if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError(
"The database name or login already exists outside Coulobre's "
@@ -269,6 +387,8 @@ def reserve_credentials(database, socket, path, ready_path, schema, users):
"password": secrets.token_urlsafe(32),
"ownership": secrets.token_hex(16),
}
if plugin == SHA2_PASSWORD:
record["authentication_plugin"] = plugin
write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600)
return record
@@ -296,6 +416,8 @@ def load_credentials(database, socket, path):
or not isinstance(record.get("password"), str)
or not record["password"]
or not record["password"].isascii()
or record.get("authentication_plugin", NATIVE_PASSWORD)
not in (NATIVE_PASSWORD, SHA2_PASSWORD)
or not valid_generation(record.get("rotation_id"))
or not isinstance(record.get("ownership"), str)
or not record["ownership"]
@@ -325,7 +447,7 @@ def check_completion_marker(path, record):
def check_resources(
schema, users, comment, password_hash, *, require_complete
schema, users, comment, expected_user, *, require_complete
):
if require_complete and (schema is None or not users):
raise ValueError(
@@ -336,9 +458,7 @@ def check_resources(
raise ValueError(
"The existing database has a different ownership marker."
)
if users and users != (
("localhost", "mysql_native_password", password_hash),
):
if users and users != (expected_user,):
raise ValueError(
"The existing MariaDB login differs from its managed credentials."
)
+16 -5
View File
@@ -37,11 +37,18 @@ def rotate_database_credentials(request, socket):
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)),
)
if db.uses_sha2(record):
cursor.execute(
"ALTER USER %s@'localhost' IDENTIFIED VIA "
"caching_sha2_password USING PASSWORD(%s)",
(database.name, password),
)
else:
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,
@@ -55,6 +62,10 @@ def rotate_database_credentials(request, socket):
"password": password,
"rotation_id": request.rotation_id,
}
if db.uses_sha2(record):
_, users = db.read_resources(cursor, database.name, sha2=True)
verifier, _ = db.sha2_login(users)
record["authentication_verifier"] = verifier
save_credential_record(path, record)
finish_rotation(path)
return record
+2
View File
@@ -201,12 +201,14 @@ def serve_mail_archive(operation):
from .account_restore_request import apply_restore_once
from .mail_node_backup import backup_mailbox, restore_mailbox
from .node_files import require_root_directory
from .receiver_scope import check_mail_service_peer
source, output = sys.stdin.buffer, sys.stdout.buffer
identity = {"version": 1, "operation": operation}
try:
if os.geteuid() != 0:
raise ValueError("Run the mail archive service as root.")
check_mail_service_peer()
request = MailArchiveRequest.parse(read_header(source), operation)
identity = request.manifest()
require_root_directory(WORK_DIRECTORY)
+2 -2
View File
@@ -74,13 +74,13 @@ def replace_configuration(path, content, *, mode=0o644):
@contextmanager
def locked_root_directory(path):
def locked_root_directory(path, *, shared=False):
import fcntl
require_root_directory(path)
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
fcntl.flock(fd, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
yield fd
finally:
os.close(fd)
+16 -10
View File
@@ -43,17 +43,23 @@ def rollout_target(role):
def receiver_panel_keys(role):
require_root_directory(NODE_KEYS)
keys = read_root_file(NODE_KEYS / f"coulobre-{role}-request", mode=0o644)
accounts = sorted(NODE_KEYS.glob(f"coulobre-{role}-p-*"))
unrestricted = NODE_KEYS / f"coulobre-{role}-request"
if unrestricted.exists():
accounts.append(unrestricted)
fingerprints = set()
for line in keys.splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
_, key_type, key = shlex.split(line)
if key_type != "ssh-ed25519":
raise ValueError("Expected an Ed25519 key for every linked panel.")
digest = hashlib.sha256(base64.b64decode(key, validate=True)).digest()
fingerprint = base64.b64encode(digest).decode().rstrip("=")
fingerprints.add(f"SHA256:{fingerprint}")
for account in accounts:
for line in read_root_file(account, mode=0o644).splitlines():
if not line.strip() or line.lstrip().startswith("#"):
continue
_, key_type, key = shlex.split(line)
if key_type != "ssh-ed25519":
raise ValueError("Expected an Ed25519 key for every panel.")
digest = hashlib.sha256(
base64.b64decode(key, validate=True)
).digest()
fingerprint = base64.b64encode(digest).decode().rstrip("=")
fingerprints.add(f"SHA256:{fingerprint}")
if not fingerprints:
raise ValueError("No authorized panel keys were found.")
return fingerprints
+19 -9
View File
@@ -1,5 +1,8 @@
import json
import sys
from contextlib import nullcontext
from .receiver_scope import authorized_request
MAX_REQUEST_BYTES = 4096
@@ -14,6 +17,8 @@ def serve_apply_request(
include_result=False,
probe_role=None,
):
from .node_maintenance import rollout_target
report = {"version": manifest_version}
try:
body = sys.stdin.buffer.read(limit + 1)
@@ -28,7 +33,6 @@ def serve_apply_request(
and isinstance(payload, dict)
and payload.get("operation") == "probe"
):
from .node_maintenance import rollout_target
from .node_probe import (
PROBE,
STATUS_PROBE,
@@ -44,8 +48,9 @@ def serve_apply_request(
report = probe_identity(probe_role) | {
"version": payload["version"]
}
check_receiver(probe_role)
target = rollout_target(probe_role)
with authorized_request(probe_role):
check_receiver(probe_role)
target = rollout_target(probe_role)
if target and payload == PROBE:
raise ValueError("The receiver is in upgrade maintenance.")
if target:
@@ -61,14 +66,19 @@ def serve_apply_request(
)
return 0
else:
if probe_role is not None:
from .node_maintenance import rollout_target
if rollout_target(probe_role):
raise ValueError("The receiver is in upgrade maintenance.")
if probe_role is not None and rollout_target(probe_role):
raise ValueError("The receiver is in upgrade maintenance.")
spec = parse_manifest(payload)
report = spec.manifest() if identity is None else identity(spec)
result = apply(spec)
guard = (
nullcontext()
if probe_role is None
else authorized_request(probe_role, spec)
)
with guard:
if probe_role is not None and rollout_target(probe_role):
raise ValueError("The receiver is in upgrade maintenance.")
result = apply(spec)
if include_result and result is not None:
report.update(result)
except (OSError, ValueError) as error:
+117 -7
View File
@@ -1,6 +1,7 @@
import argparse
import grp
import ipaddress
import json
import os
import pwd
import re
@@ -30,6 +31,12 @@ from .node_maintenance import (
rollout_target,
)
from .node_probe import PROBE_BYTES, PROBE_LIMIT, check_receiver, verify_probe
from .receiver_scope import (
scope_files,
scope_path,
scoped_account,
scoped_domains,
)
from .sftp_keys import read_public_keys
PANEL_SSH = Path("/etc/coulobre-remote")
@@ -178,7 +185,21 @@ def install_receivers(assets, roles):
for role in roles:
install_receiver(assets, role)
config = assets / "openssh/coulobre-node-requests.conf.example"
added = put_file(SSH_DROP_IN, config.read_text())
desired = config.read_text()
original = (
read_root_file(SSH_DROP_IN) if SSH_DROP_IN.exists() else None
)
legacy = (
desired.replace(",coulobre-dns-p-*,coulobre-mail-p-*", "")
.replace(",coulobre-dns-p-*", "")
.replace(",coulobre-mail-p-*", "")
)
migrated = original == legacy
if migrated:
replace_configuration(SSH_DROP_IN, desired)
added = False
else:
added = put_file(SSH_DROP_IN, desired)
try:
require_root_directory(Path("/run/sshd"), create_mode=0o755)
run("/usr/sbin/sshd", "-t")
@@ -188,6 +209,8 @@ def install_receivers(assets, roles):
except (OSError, ValueError, subprocess.TimeoutExpired):
if added:
SSH_DROP_IN.unlink()
elif migrated:
replace_configuration(SSH_DROP_IN, original)
raise
run("systemctl", "daemon-reload")
run(
@@ -198,12 +221,13 @@ def install_receivers(assets, roles):
)
def check_ssh_receiver(role):
def check_ssh_receiver(role, account=None):
account = account or role.receiver
live = run(
"/usr/sbin/sshd",
"-T",
"-C",
f"user={role.receiver},host=localhost,addr=127.0.0.1",
f"user={account},host=localhost,addr=127.0.0.1",
).decode()
expected = {
f"forcecommand {role.relay}",
@@ -211,6 +235,8 @@ def check_ssh_receiver(role):
"authenticationmethods publickey",
"disableforwarding yes",
"permituserrc no",
"permituserenvironment no",
"permittunnel no",
"permittty no",
"pubkeyauthentication yes",
"passwordauthentication no",
@@ -219,8 +245,15 @@ def check_ssh_receiver(role):
"authorizedkeyscommand none",
}
if not expected <= set(live.splitlines()):
raise ValueError(f"Check the effective SSH policy for {account}.")
if account != role.receiver and any(
line.startswith("acceptenv ")
and set(line.split()[1:]) - {"LANG", "LC_*", "COLORTERM", "NO_COLOR"}
for line in live.splitlines()
):
raise ValueError(
f"Check the effective SSH policy for {role.receiver}."
"Restrict accepted SSH environment variables to locale and "
"terminal color settings."
)
@@ -237,6 +270,8 @@ def authorize_panel(role, key_path):
with locked_root_directory(NODE_KEYS):
if rollout_target(role.name):
raise ValueError("The receiver is in upgrade maintenance.")
if scope_files(role.name):
raise ValueError("Use domain-scoped keys on this receiver.")
check_ssh_receiver(role)
destination = NODE_KEYS / role.receiver
old = (
@@ -253,6 +288,60 @@ def authorize_panel(role, key_path):
write_new_file(destination, entry, mode=0o644)
def authorize_scoped_panel(role, panel, key_path, domains):
account = scoped_account(role.name, panel)
key = one_public_key(key_path)
if not key.startswith("ssh-ed25519 "):
raise ValueError("Use an Ed25519 panel public key.")
domains = {canonical_domain(domain) for domain in domains}
path = scope_path(account)
destination = NODE_KEYS / account
with locked_root_directory(NODE_KEYS):
if rollout_target(role.name):
raise ValueError("The receiver is in upgrade maintenance.")
legacy = NODE_KEYS / role.receiver
if legacy.exists() and any(
line.strip() and not line.lstrip().startswith("#")
for line in read_root_file(legacy, mode=0o644).splitlines()
):
raise ValueError(
"Remove unrestricted panel keys before enabling scopes."
)
for other in scope_files(role.name):
if other == path:
continue
assigned = scoped_domains(other)
if (
domains & assigned
or role.name == "dns"
and any(
domain.endswith(f".{existing}")
or existing.endswith(f".{domain}")
for domain in domains
for existing in assigned
)
):
raise ValueError("A domain overlaps another panel's scope.")
scoped_peers = NODE_KEYS.glob(f"coulobre-{role.name}-p-*")
for peer in scoped_peers:
if peer != destination and any(
has_authorized_key(line, key)
for line in read_root_file(peer, mode=0o644).splitlines()
):
raise ValueError(
"A panel key may have only one scope per role."
)
ensure_identity(account, home="/", shell="/bin/sh", group=role.group)
check_ssh_receiver(role, account)
entry = f'command="{role.relay}",restrict {key}\n'
contents = json.dumps(sorted(domains)) + "\n"
if path.exists():
scoped_domains(path)
put_file(destination, entry)
replace_configuration(path, contents, mode=0o600)
return account
def has_authorized_key(line, key):
if line.lstrip().startswith("#"):
return False
@@ -323,10 +412,14 @@ def normalize_host(host):
return canonical_domain(host)
def ssh_setup(assets, role, host, port):
def ssh_setup(assets, role, host, port, *, scope=None):
config = (
assets / f"openssh/{role.name}-node-client.conf.example"
).read_text()
if scope is not None:
config = config.replace(
f"User {role.receiver}", f"User {scoped_account(role.name, scope)}"
)
return config.replace(
f"HostName {role.name}.example.org", f"HostName {host}"
).replace("Port 22", f"Port {port}")
@@ -375,12 +468,12 @@ def stage_ssh_settings(role, config, known_hosts, group):
)
def enrol_panel(assets, role, host, port, host_key):
def enrol_panel(assets, role, host, port, host_key, *, scope=None):
host = normalize_host(host)
key = one_public_key(host_key)
entry = host if port == 22 else f"[{host}]:{port}"
known_hosts = f"{entry} {key}\n"
config = ssh_setup(assets, role, host, port)
config = ssh_setup(assets, role, host, port, scope=scope)
_, group = prepare_panel(role)
require_root_directory(SYSTEMD)
with locked_root_directory(PANEL_SSH):
@@ -473,6 +566,10 @@ def main(argv=None):
for command, help_text in (
("prepare-panel", "Prepare and print the panel's public SSH key."),
("authorize-panel", "Authorize a panel public key on this receiver."),
(
"authorize-scoped-panel",
"Assign exact domains to one panel identity.",
),
("check-receiver", "Check the service configuration on this node."),
("list-panels", "List the authorized panel key fingerprints."),
("begin-maintenance", "Stage a verified receiver upgrade plan."),
@@ -493,12 +590,17 @@ def main(argv=None):
action.add_argument("role", choices=ROLES)
if command == "authorize-panel":
action.add_argument("public_key", type=Path)
if command == "authorize-scoped-panel":
action.add_argument("panel")
action.add_argument("public_key", type=Path)
action.add_argument("domains", nargs="+")
if command in {"begin-maintenance", "finish-maintenance"}:
action.add_argument("inventory", type=Path)
if command == "enrol-panel":
action.add_argument("host")
action.add_argument("host_key", type=Path)
action.add_argument("--port", type=ssh_port, default=22)
action.add_argument("--scope")
args = parser.parse_args(argv)
if os.geteuid() != 0:
parser.exit(1, "coulobre-node-setup: Run this command as root.\n")
@@ -521,6 +623,13 @@ def main(argv=None):
elif args.command == "authorize-panel":
authorize_panel(role, args.public_key)
print(f"Authorized the panel key for the {role.name} receiver.")
elif args.command == "authorize-scoped-panel":
account = authorize_scoped_panel(
role, args.panel, args.public_key, args.domains
)
print(
f"Authorized {account}. Use --scope {args.panel} on the panel."
)
elif args.command == "check-receiver":
check_receiver(role.name)
print(f"The local {role.name} services are ready.")
@@ -543,6 +652,7 @@ def main(argv=None):
args.host,
args.port,
args.host_key,
scope=args.scope,
)
print(
f"Verified the {role.name} receiver. "
+121
View File
@@ -0,0 +1,121 @@
import json
import os
import pwd
import re
import socket
import stat
import struct
import sys
from contextlib import contextmanager
from .domain_names import canonical_domain
from .node_files import (
locked_root_directory,
read_root_file,
require_root_directory,
)
from .node_maintenance import NODE_KEYS, rollout_target
LOCAL_WORKERS = {
"dns": "coulobre-dns-publisher",
"mail": "coulobre-mail-provisioner",
}
MAIL_SERVICE_PEERS = {
"coulobre-mail-archive-backup",
"coulobre-mail-archive-restore",
"coulobre-mail-credential-request",
}
def scoped_account(role, panel):
if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,11}", panel):
raise ValueError(
"Use 1 to 12 lowercase letters, digits or hyphens for the panel."
)
return f"coulobre-{role}-p-{panel}"
def scope_files(role):
return sorted(NODE_KEYS.glob(f".scope-coulobre-{role}-p-*.json"))
def scope_path(account):
return NODE_KEYS / f".scope-{account}.json"
def scoped_domains(path):
require_root_directory(path.parent)
domains = json.loads(read_root_file(path, mode=0o600))
if (
not isinstance(domains, list)
or not domains
or any(
not isinstance(domain, str) or canonical_domain(domain) != domain
for domain in domains
)
):
raise ValueError("The receiver has an invalid domain scope.")
return set(domains)
def socket_peer():
try:
descriptor = sys.stdin.fileno()
except (AttributeError, OSError, ValueError):
return None
if type(descriptor) is not int or not stat.S_ISSOCK(
os.fstat(descriptor).st_mode
):
return None
with socket.fromfd(descriptor, socket.AF_UNIX, socket.SOCK_STREAM) as peer:
credentials = peer.getsockopt(
socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i")
)
_, uid, _ = struct.unpack("3i", credentials)
try:
return pwd.getpwuid(uid).pw_name
except KeyError as error:
raise ValueError(
"The receiver could not identify the peer."
) from error
def manifest_domain(spec):
manifest = spec.manifest()
for field in ("mailbox", "resource"):
if field in manifest:
manifest = manifest[field]
break
return manifest.get("domain")
@contextmanager
def authorized_request(role, spec=None):
peer = socket_peer()
if peer in (None, "root", LOCAL_WORKERS[role]):
yield
return
with locked_root_directory(NODE_KEYS, shared=True):
if peer == f"coulobre-{role}-request":
if scope_files(role):
raise ValueError(
"Use a domain-scoped panel key for this receiver."
)
elif peer.startswith(f"coulobre-{role}-p-"):
domains = scoped_domains(scope_path(peer))
if spec is not None and manifest_domain(spec) not in domains:
raise ValueError(
"The panel key is not assigned to this domain."
)
else:
raise ValueError("The peer is not authorized for this receiver.")
yield
def check_mail_service_peer():
if socket_peer() in MAIL_SERVICE_PEERS and (
scope_files("mail") or rollout_target("mail")
):
raise ValueError(
"The remote mail service is unavailable on this receiver."
)
+3
View File
@@ -6,6 +6,7 @@ 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
from .receiver_scope import check_mail_service_peer
REQUEST_VERSION = 1
CREDENTIAL_SOCKET = "/run/coulobre-service-credentials.sock"
@@ -98,6 +99,8 @@ def main(argv=None):
def parse(payload):
request = ServiceCredentialRequest.from_manifest(payload)
if request.kind == "mailbox":
check_mail_service_peer()
if args.mailbox_only and request.kind != "mailbox":
raise ValueError("This node handles mailbox requests only.")
return request
+192
View File
@@ -0,0 +1,192 @@
import io
import json
import os
import pwd
import socket
from contextlib import nullcontext
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import Mock, patch
from uuid import uuid4
from . import node_maintenance, node_setup, receiver_scope
from .dns_node import DnsZone
from .mail_node import MailboxQuotaUpdate, MailboxSpec
from .mail_policy import MailRouting
from .mail_queue import MailQueueRequest
from .node_requests import serve_apply_request
from .node_retirement import RetirementRequest
from .service_access import ServiceAccessRequest
def check_request(role, spec=None):
with receiver_scope.authorized_request(role, spec):
pass
class ReceiverScopeTests(TestCase):
def setUp(self):
lock = patch.object(
receiver_scope, "locked_root_directory", return_value=nullcontext()
)
lock.start()
self.addCleanup(lock.stop)
def test_unix_peer_identity_comes_from_the_kernel(self):
left, right = socket.socketpair()
with (
left,
right,
patch(
"coulobre.receiver_scope.sys.stdin.fileno",
return_value=left.fileno(),
),
):
try:
peer = receiver_scope.socket_peer()
except PermissionError:
self.skipTest("SO_PEERCRED is unavailable in this sandbox")
self.assertEqual(peer, pwd.getpwuid(os.getuid()).pw_name)
def test_exact_domain_applies_to_all_managed_mail_operations(self):
mailbox = MailboxSpec("alpha.example.test", "sales")
requests = (
mailbox,
MailboxQuotaUpdate(mailbox),
MailQueueRequest(mailbox.domain),
MailRouting(mailbox.domain, {}),
ServiceAccessRequest(mailbox, True),
RetirementRequest(mailbox, str(uuid4())),
)
with (
patch.object(
receiver_scope,
"socket_peer",
return_value="coulobre-mail-p-alpha",
),
patch.object(
receiver_scope, "scoped_domains", return_value={mailbox.domain}
),
):
for request in requests:
check_request("mail", request)
for domain in ("beta.example.test", "sub.alpha.example.test"):
with self.assertRaisesRegex(ValueError, "not assigned"):
check_request("mail", MailQueueRequest(domain))
def test_scope_is_enforced_before_dispatching_dns_operations(self):
zone = DnsZone(
"beta.example.test",
1,
("ns.example.test",),
"hostmaster.example.test",
)
apply = Mock()
request = RetirementRequest(zone, str(uuid4()))
with (
patch.object(
receiver_scope,
"socket_peer",
return_value="coulobre-dns-p-alpha",
),
patch.object(
receiver_scope,
"scoped_domains",
return_value={"alpha.example.test"},
),
patch(
"coulobre.node_requests.sys.stdin",
buffer=io.BytesIO(json.dumps(request.manifest()).encode()),
),
patch("sys.stdout", new_callable=io.StringIO) as output,
):
result = serve_apply_request(
1, lambda data: request, apply, probe_role="dns"
)
self.assertEqual(result, 1)
self.assertIn(
"not assigned", json.loads(output.getvalue())["problem"]
)
apply.assert_not_called()
def test_legacy_and_service_ssh_accounts_cannot_bypass_scoped_mail(self):
with (
patch.object(
receiver_scope,
"socket_peer",
return_value="coulobre-mail-request",
) as peer,
patch.object(
receiver_scope, "scope_files", return_value=[Path("/scope")]
),
):
with self.assertRaisesRegex(ValueError, "domain-scoped"):
check_request("mail")
peer.return_value = "coulobre-dns-p-alpha"
with self.assertRaisesRegex(ValueError, "not authorized"):
check_request("mail")
for name in receiver_scope.MAIL_SERVICE_PEERS:
peer.return_value = name
with self.assertRaisesRegex(ValueError, "unavailable"):
receiver_scope.check_mail_service_peer()
peer.return_value = "root"
check_request("mail")
receiver_scope.check_mail_service_peer()
def test_scopes_reject_overlap_and_record_both_keys(
self,
):
role = node_setup.ROLES["dns"]
key = Path("public-key")
with (
TemporaryDirectory() as scratch,
patch.object(
node_setup, "locked_root_directory", return_value=nullcontext()
),
patch.object(
node_setup,
"one_public_key",
side_effect=(
"ssh-ed25519 YWJj",
"ssh-ed25519 ZGVm",
"ssh-ed25519 ZGVm",
),
),
patch.object(node_setup, "check_ssh_receiver"),
patch.object(node_setup, "ensure_identity"),
patch.object(node_setup, "rollout_target", return_value=None),
):
root = Path(scratch)
def read(path, *, mode=None):
return path.read_text()
with (
patch.object(node_setup, "NODE_KEYS", root),
patch("coulobre.node_files.os.fchown"),
patch.object(receiver_scope, "NODE_KEYS", root),
patch.object(node_maintenance, "NODE_KEYS", root),
patch.object(receiver_scope, "require_root_directory"),
patch.object(node_maintenance, "require_root_directory"),
patch.object(
receiver_scope, "read_root_file", side_effect=read
),
patch.object(node_setup, "read_root_file", side_effect=read),
patch.object(
node_maintenance, "read_root_file", side_effect=read
),
):
node_setup.authorize_scoped_panel(
role, "one", key, ["alpha.example.test"]
)
with self.assertRaisesRegex(ValueError, "overlaps"):
node_setup.authorize_scoped_panel(
role, "two", key, ["sub.alpha.example.test"]
)
node_setup.authorize_scoped_panel(
role, "two", key, ["beta.example.test"]
)
self.assertEqual(
len(node_maintenance.receiver_panel_keys(role.name)), 2
)