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] [project]
name = "coulobre-panel" name = "coulobre-panel"
version = "0.11.0rc1" version = "0.11.1rc1"
description = "A web hosting control panel for hosting providers and resellers." description = "A web hosting control panel for hosting providers and resellers."
readme = "README.md" readme = "README.md"
requires-python = ">=3.12" requires-python = ">=3.12"
+173 -53
View File
@@ -1,6 +1,7 @@
import hashlib import hashlib
import json import json
import os import os
import re
import secrets import secrets
from contextlib import closing, contextmanager, suppress from contextlib import closing, contextmanager, suppress
from pathlib import Path from pathlib import Path
@@ -8,6 +9,7 @@ from pathlib import Path
from .credential_rotation import ( from .credential_rotation import (
ROTATION_IN_PROGRESS, ROTATION_IN_PROGRESS,
rotation_path, rotation_path,
save_credential_record,
valid_generation, valid_generation,
) )
from .node_files import read_root_file, require_root_directory, write_new_file 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") STATE_DIRECTORY = Path("/var/lib/coulobre/database-node")
MANAGED_COMMENT_PREFIX = "Coulobre managed database " 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): 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.parent, create_mode=0o750)
require_root_directory(STATE_DIRECTORY, create_mode=0o700) require_root_directory(STATE_DIRECTORY, create_mode=0o700)
record_path = STATE_DIRECTORY / f"{database.name}.json" record_path = STATE_DIRECTORY / f"{database.name}.json"
with locked_cursor(database, socket) as (_, cursor): with locked_cursor(database, socket) as (driver, cursor):
install_database(cursor, database, socket, record_path) install_database(cursor, database, socket, record_path, driver=driver)
return record_path return record_path
@@ -71,18 +77,25 @@ def locked_cursor(database, socket):
) from None ) from None
def read_resources(cursor, name): def read_resources(cursor, name, *, sha2=False):
cursor.execute( cursor.execute(
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA " "SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA "
"WHERE SCHEMA_NAME = %s", "WHERE SCHEMA_NAME = %s",
(name,), (name,),
) )
schema = cursor.fetchone() schema = cursor.fetchone()
cursor.execute( if sha2:
"SELECT Host, plugin, authentication_string FROM mysql.user " cursor.execute(
"WHERE User = %s", "SELECT Host, plugin, HEX(authentication_string), "
(name,), "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() return schema, cursor.fetchall()
@@ -126,11 +139,11 @@ def checked_credentials(
pending_password=None, pending_password=None,
): ):
name = database.name name = database.name
schema, users = read_resources(cursor, name)
ready_path = record_path.with_suffix(".ready") ready_path = record_path.with_suffix(".ready")
with suppress(FileNotFoundError): with suppress(FileNotFoundError):
require_root_directory(record_path.parent) require_root_directory(record_path.parent)
if not os.path.lexists(record_path): 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: if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError( raise ValueError(
"The database, login, or completion marker has no local " "The database, login, or completion marker has no local "
@@ -147,30 +160,46 @@ def checked_credentials(
rotation_path(record_path) rotation_path(record_path)
): ):
raise ValueError(ROTATION_IN_PROGRESS) raise ValueError(ROTATION_IN_PROGRESS)
sha2 = uses_sha2(record)
schema, users = read_resources(cursor, name, sha2=sha2)
password = record["password"] password = record["password"]
if pending_password is not None and users == ( if sha2:
( verifier, server_value = sha2_login(users)
"localhost", if verifier != record.get("authentication_verifier"):
"mysql_native_password", if not pending_password or not can_sign_in(
native_password_hash(pending_password), driver, record, pending_password
), ):
): raise ValueError(
password = pending_password "The MariaDB verifier differs from the registry."
password_hash = native_password_hash(password) )
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( check_resources(
schema, schema,
users, users,
MANAGED_COMMENT_PREFIX + record["ownership"], MANAGED_COMMENT_PREFIX + record["ownership"],
password_hash, user_details,
require_complete=True, require_complete=True,
) )
cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,)) cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,))
grantee = f"`{name}`@`localhost`" grantee = f"`{name}`@`localhost`"
expected_grants = { expected_grants = {
( (f"GRANT USAGE ON *.* TO {grantee} {authentication}",),
f"GRANT USAGE ON *.* TO {grantee} "
f"IDENTIFIED BY PASSWORD '{password_hash}'",
),
(f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",), (f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",),
} }
grants = { grants = {
@@ -184,25 +213,71 @@ def checked_credentials(
and login_is_locked(cursor, name) and login_is_locked(cursor, name)
): ):
return record 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: try:
with closing( with closing(
driver.connect( driver.connect(
host="localhost", host="localhost",
user=name, user=record["user"],
passwd=password, passwd=password,
db=name, db=record["database"],
unix_socket=str(socket), unix_socket=record["socket"],
connect_timeout=5, connect_timeout=5,
charset="utf8mb4", charset="utf8mb4",
) )
): ):
pass return True
except driver.Error: 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( raise ValueError(
"The stored application credentials cannot open the managed " "Enable the MariaDB caching_sha2_password plugin first."
"database." )
) from None return policy
return record
def check_restore_complete(record_path): 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")): if os.path.lexists(record_path.with_suffix(".retired")):
raise ValueError( raise ValueError(
"This database is retained for a retired hosting account." "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) raise ValueError(ROTATION_IN_PROGRESS)
check_restore_complete(record_path) check_restore_complete(record_path)
name = database.name name = database.name
schema, users = read_resources(cursor, name) existing = os.path.lexists(record_path)
ready_path = record_path.with_suffix(".ready") record = (
record = reserve_credentials( load_credentials(database, socket, record_path) if existing else {}
database, socket, record_path, ready_path, schema, users
) )
comment = MANAGED_COMMENT_PREFIX + record["ownership"] plugin = (
password_hash = native_password_hash(record["password"]) 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) 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( check_resources(
schema, users, comment, password_hash, require_complete=ready schema, users, comment, expected_user, require_complete=ready
) )
if schema is None: if schema is None:
@@ -241,24 +343,40 @@ def install_database(cursor, database, socket, record_path):
(comment,), (comment,),
) )
if not users: if not users:
cursor.execute( if sha2:
"CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password " cursor.execute(
"USING %s", "CREATE USER %s@'localhost' IDENTIFIED VIA "
(name, password_hash), "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( cursor.execute(
f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'", f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO %s@'localhost'",
(name,), (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: if not ready:
write_new_file(ready_path, record["ownership"] + "\n", mode=0o600) write_new_file(ready_path, record["ownership"] + "\n", mode=0o600)
def reserve_credentials(database, socket, path, ready_path, schema, users): def reserve_credentials(
if os.path.lexists(path): database, socket, path, ready_path, schema, users, plugin
return load_credentials(database, socket, path) ):
if os.path.lexists(ready_path) or schema is not None or users: if os.path.lexists(ready_path) or schema is not None or users:
raise ValueError( raise ValueError(
"The database name or login already exists outside Coulobre's " "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), "password": secrets.token_urlsafe(32),
"ownership": secrets.token_hex(16), "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) write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600)
return record return record
@@ -296,6 +416,8 @@ def load_credentials(database, socket, path):
or not isinstance(record.get("password"), str) or not isinstance(record.get("password"), str)
or not record["password"] or not record["password"]
or not record["password"].isascii() 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 valid_generation(record.get("rotation_id"))
or not isinstance(record.get("ownership"), str) or not isinstance(record.get("ownership"), str)
or not record["ownership"] or not record["ownership"]
@@ -325,7 +447,7 @@ def check_completion_marker(path, record):
def check_resources( 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): if require_complete and (schema is None or not users):
raise ValueError( raise ValueError(
@@ -336,9 +458,7 @@ def check_resources(
raise ValueError( raise ValueError(
"The existing database has a different ownership marker." "The existing database has a different ownership marker."
) )
if users and users != ( if users and users != (expected_user,):
("localhost", "mysql_native_password", password_hash),
):
raise ValueError( raise ValueError(
"The existing MariaDB login differs from its managed credentials." "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) pending = stage_rotation(path, request, generation)
if generation != request.rotation_id: if generation != request.rotation_id:
password = pending["password"] password = pending["password"]
cursor.execute( if db.uses_sha2(record):
"ALTER USER %s@'localhost' " cursor.execute(
"IDENTIFIED VIA mysql_native_password USING %s", "ALTER USER %s@'localhost' IDENTIFIED VIA "
(database.name, db.native_password_hash(password)), "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( db.checked_credentials(
driver, driver,
cursor, cursor,
@@ -55,6 +62,10 @@ def rotate_database_credentials(request, socket):
"password": password, "password": password,
"rotation_id": request.rotation_id, "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) save_credential_record(path, record)
finish_rotation(path) finish_rotation(path)
return record return record