Support SHA-2 authentication for new managed MariaDB logins

This commit is contained in:
parkel committed 2026-11-23 06:42:47 +01:00
1 parent 23e6e01303
commit 0de4d0c854
3 files changed
+190 -59

No files matched your search

+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