Files
coulobre/src/coulobre/database_node_apply.py
T

588 lines
19 KiB
Python
Raw Normal View History

import hashlib
import json
import os
import re
import secrets
from contextlib import closing, contextmanager, suppress
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
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):
if os.geteuid() != 0:
raise ValueError("Run apply as root on the MariaDB node.")
socket = socket.resolve()
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 (driver, cursor):
install_database(cursor, database, socket, record_path, driver=driver)
return record_path
@contextmanager
def locked_cursor(database, socket):
try:
import MySQLdb
except ImportError:
raise ValueError(
"Install Coulobre Panel with its mariadb extra on the node."
) from None
try:
with (
closing(
MySQLdb.connect(
host="localhost",
user="root",
unix_socket=str(socket),
connect_timeout=5,
charset="utf8mb4",
)
) as connection,
closing(connection.cursor()) as cursor,
):
cursor.execute(
"SELECT GET_LOCK(%s, 10)", (f"coulobre:{database.name}",)
)
if cursor.fetchone() != (1,):
raise ValueError(
"Could not acquire the lock for this MariaDB database."
)
yield MySQLdb, cursor
except MySQLdb.Error as error:
code = (
error.args[0]
if error.args and type(error.args[0]) is int
else "unknown"
)
raise ValueError(
f"MariaDB rejected the operation (error {code})."
) from None
def read_resources(cursor, name, *, sha2=False):
cursor.execute(
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
"WHERE SCHEMA_NAME = %s",
(name,),
)
schema = cursor.fetchone()
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()
def database_status(database, socket):
if os.geteuid() != 0:
raise ValueError("Run status as root on the MariaDB node.")
socket = socket.resolve()
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
try:
state = check_database(
driver, cursor, database, socket, record_path
)
problem = None
except (OSError, ValueError) as error:
state = "needs_attention"
problem = str(error)
return {
"database": database.name,
"user": database.name,
"state": state,
"problem": problem,
}
def check_database(driver, cursor, database, socket, record_path):
record = checked_credentials(driver, cursor, database, socket, record_path)
return "configured" if record is not None else "not_installed"
def checked_credentials(
driver,
cursor,
database,
socket,
record_path,
*,
restoring=False,
verify_login=True,
pending_password=None,
):
name = database.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 "
"credentials record."
)
return None
record = load_credentials(database, socket, record_path)
if not check_completion_marker(ready_path, record):
raise ValueError("The database installation is incomplete.")
if not restoring:
check_restore_complete(record_path)
if pending_password is None and os.path.lexists(
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 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"],
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} {authentication}",),
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
}
grants = {
(grant.removesuffix(" ACCOUNT LOCK"),)
for (grant,) in cursor.fetchall()
}
if grants != expected_grants:
raise ValueError("The MariaDB login has unexpected grants.")
if not verify_login or (
load_access_checkpoint(record_path, record) is not None
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=record["user"],
passwd=password,
db=record["database"],
unix_socket=record["socket"],
connect_timeout=5,
charset="utf8mb4",
)
):
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(
"Enable the MariaDB caching_sha2_password plugin first."
)
return policy
def check_restore_complete(record_path):
if os.path.lexists(record_path.with_suffix(".restore-pending")):
raise ValueError(
"A MariaDB restore has not completed for this database."
)
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."
)
if os.path.lexists(rotation_path(record_path)):
raise ValueError(ROTATION_IN_PROGRESS)
check_restore_complete(record_path)
name = database.name
existing = os.path.lexists(record_path)
record = (
load_credentials(database, socket, record_path) if existing else {}
)
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, expected_user, require_complete=ready
)
if schema is None:
cursor.execute(
f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4 "
"COLLATE utf8mb4_unicode_ci COMMENT %s",
(comment,),
)
if not users:
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, 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 "
"registry."
)
record = {
**credential_identity(database, socket),
"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
def credential_identity(database, socket):
return {
"database": database.name,
"user": database.name,
"host": "localhost",
"socket": str(socket),
}
def load_credentials(database, socket, path):
try:
record = json.loads(read_root_file(path, mode=0o600))
except (json.JSONDecodeError, UnicodeDecodeError):
raise ValueError(
"The local credentials record is unreadable."
) from None
identity = credential_identity(database, socket)
if (
not isinstance(record, dict)
or any(record.get(key) != value for key, value in identity.items())
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"]
):
raise ValueError(
"The local credentials record conflicts with the manifest "
"or socket."
)
return record
def check_completion_marker(path, record):
if not os.path.lexists(path):
return False
try:
marker = read_root_file(path, mode=0o600).strip()
except UnicodeDecodeError:
raise ValueError(
"The database completion marker is unreadable."
) from None
if marker != record["ownership"]:
raise ValueError(
"The database completion marker conflicts with its credentials "
"record."
)
return True
def check_resources(
schema, users, comment, expected_user, *, require_complete
):
if require_complete and (schema is None or not users):
raise ValueError(
"The managed database or login is missing. "
"Restore it before reapplying."
)
if schema is not None and schema != (comment,):
raise ValueError(
"The existing database has a different ownership marker."
)
if users and users != (expected_user,):
raise ValueError(
"The existing MariaDB login differs from its managed credentials."
)
def grant_scope(name):
# A database-level GRANT treats underscores as wildcards, even in
# backticks.
escaped_name = name.replace("_", r"\_")
return f"`{escaped_name}`.*"
def native_password_hash(password):
first = hashlib.sha1(password.encode("utf-8")).digest()
return "*" + hashlib.sha1(first).hexdigest().upper()
def login_is_locked(cursor, name):
cursor.execute(
"SELECT COALESCE("
"JSON_UNQUOTE(JSON_EXTRACT(Priv, '$.account_locked')), 'false') "
"FROM mysql.global_priv WHERE User = %s AND Host = 'localhost'",
(name,),
)
row = cursor.fetchone()
if row not in (("true",), ("false",)):
raise ValueError("MariaDB returned an invalid login lock state.")
return row == ("true",)
def load_access_checkpoint(record_path, record):
try:
checkpoint = json.loads(
read_root_file(record_path.with_suffix(".suspended"), mode=0o600)
)
except FileNotFoundError:
return None
if (
not isinstance(checkpoint, dict)
or checkpoint.get("ownership") != record["ownership"]
or type(checkpoint.get("was_locked")) is not bool
):
raise ValueError("The MariaDB suspension checkpoint is invalid.")
return checkpoint
def set_database_access(database, socket, suspended):
if os.geteuid() != 0:
raise ValueError(
"Run the service access request as root on the MariaDB node."
)
socket = socket.resolve()
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
record = checked_credentials(
driver, cursor, database, socket, record_path, verify_login=False
)
if record is None:
raise ValueError(
"Apply the database manifest before changing its access."
)
if not suspended and os.path.lexists(
record_path.with_suffix(".retired")
):
raise ValueError(
"This database is retained for a retired account."
)
checkpoint = load_access_checkpoint(record_path, record)
marker = record_path.with_suffix(".suspended")
if suspended and checkpoint is None:
checkpoint = {
"ownership": record["ownership"],
"was_locked": login_is_locked(cursor, database.name),
}
write_new_file(marker, json.dumps(checkpoint), mode=0o600)
directory = os.open(
record_path.parent, os.O_RDONLY | os.O_DIRECTORY
)
try:
os.fsync(directory)
finally:
os.close(directory)
if checkpoint is None:
return
lock_login = suspended or checkpoint["was_locked"]
action = "LOCK" if lock_login else "UNLOCK"
cursor.execute(
f"ALTER USER %s@'localhost' ACCOUNT {action}", (database.name,)
)
if login_is_locked(cursor, database.name) != lock_login:
raise ValueError(
"MariaDB did not apply the requested login state."
)
from .database_node_logins import set_secondary_access
set_secondary_access(cursor, database, record["ownership"], suspended)
if not suspended:
marker.unlink()
def retire_database(request, socket):
database = request.resource
socket = socket.resolve()
record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (driver, cursor):
retirement = RetirementRecord(STATE_DIRECTORY, request)
if retirement.is_complete:
return
record = checked_credentials(
driver, cursor, database, socket, record_path, verify_login=False
)
if record is None or not login_is_locked(cursor, database.name):
raise ValueError(
"Suspend the managed database login before retirement."
)
from .database_node_logins import retire_secondary_logins
retirement.begin()
retire_secondary_logins(cursor, database, record["ownership"])
cursor.execute("KILL USER %s", (database.name,))
marker = record_path.with_suffix(".retired")
if not os.path.lexists(marker):
write_new_file(marker, retirement.document, mode=0o600)
elif read_root_file(marker, mode=0o600) != retirement.document:
raise ValueError("The database has a different retirement record.")
retirement.finish()