#!/usr/bin/env bash # ADPanel privileged job: MySQL/MariaDB admin bootstrap. # Invoked via adpanel-priv: adpanel-priv job mysql-admin-bootstrap # env: ADPANEL_DB_ADMIN_PASSWORD (required) — the password for the dedicated # panel admin account, generated by the panel process and passed through # the sudoers env_keep allowlist (never argv, never a file the panel # writes as root). # # Why this job exists: the panel's database-management SQL (CREATE/ALTER/DROP # USER, GRANT, REVOKE, probe queries) used to run through whatever account the # admin-channel probe could authenticate as — most commonly MySQL/MariaDB # 'root'@'localhost' via the unix socket or the operator-reused MYSQL_PASSWORD. # That identity is (a) far too powerful for a network-facing panel process and # (b) demotable by the panel's own account-management flows: a legacy setup # that adopted 'root' as its tracked database administrator ran # `REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'root'@'localhost'` while staging, # after which every GRANT batch failed with ERROR 1044 and phpMyAdmin setup # became impossible. # # This job fixes both directions, once, as OS root: # 1. HEAL — if a root account exists but cannot administer (the panel-demoted # state), restore its packaging-default static privileges via the # skip-grant-tables mechanism. MySQL and MariaDB need different SQL here # (MySQL 8 rejects FLUSH/GRANT in skip-grant mode; MariaDB's mysql.user is # a read-only view), so both strategies are attempted. # 2. PROVISION — create the dedicated least-privilege panel admin account # ('adpanel_admin'@'localhost'). It holds exactly the privileges the # panel's account-management batches need: the panel DML/DDL set on *.* # WITH GRANT OPTION (so it can grant that same set to panel users on any # schema) plus CREATE USER (which also authorizes DROP USER and ALTER USER # password changes on MySQL 8 and MariaDB). It deliberately holds NO # SUPER, FILE, SHUTDOWN, RELOAD, mysql.* write access or dynamic # privileges — a compromised panel can no longer read the server's # password hashes with administrative authority, restart the server, # read files, or touch the privilege tables directly. # 3. CERTIFY — run a full canary AS the dedicated account covering every # statement class the panel issues (CREATE/ALTER/DROP USER, db-scoped # GRANT, REVOKE ALL+GRANT OPTION, mysql.user probe, SHOW DATABASES). The # job exits non-zero unless the canary passed, so the panel never switches # to a channel that cannot actually administer the server. # # The job is idempotent: re-running heals nothing (already capable), resets the # dedicated account's password to the freshly supplied one, and re-certifies. set -u ADMIN_USER="adpanel_admin" ADMIN_HOST="localhost" ADMIN_PASSWORD="${ADPANEL_DB_ADMIN_PASSWORD:-}" CANARY_DB="adpanel_admin_canary" CANARY_USER="adpanel_admin_probe" die() { echo "mysql-admin-bootstrap: $*" >&2 exit 1 } # The panel generates this password as crypto.randomBytes(...).toString('hex'); # accepting only lowercase hex keeps it safely embeddable in single-quoted SQL. [ -n "$ADMIN_PASSWORD" ] || die "ADPANEL_DB_ADMIN_PASSWORD is not set" case "$ADMIN_PASSWORD" in *[!0-9a-f]*) die "ADPANEL_DB_ADMIN_PASSWORD must be lowercase hex" ;; esac [ "${#ADMIN_PASSWORD}" -ge 48 ] || die "ADPANEL_DB_ADMIN_PASSWORD is too short" [ "${#ADMIN_PASSWORD}" -le 128 ] || die "ADPANEL_DB_ADMIN_PASSWORD is too long" # Serialize invocations: a manual run must never interleave its stop / # skip-grant / restart sequence with the panel's own cooldown-gated attempt. # Fail loudly rather than silently running unserialized. if command -v flock >/dev/null 2>&1; then mkdir -p /run/lock 2>/dev/null || true exec 9>/run/lock/adpanel-mysql-bootstrap.lock || die "cannot open /run/lock/adpanel-mysql-bootstrap.lock" flock -n 9 || die "another mysql-admin-bootstrap is already running" fi # --- service / binary detection (same contract as mysql-skip-grant.sh) ------- SVC="" for s in mariadb mysql mysqld; do if systemctl list-unit-files "$s.service" >/dev/null 2>&1; then SVC="$s" break fi done [ -n "$SVC" ] || die "Could not detect MySQL/MariaDB service name" SERVER_BIN="" for bin in mariadbd mysqld; do if command -v "$bin" >/dev/null 2>&1; then SERVER_BIN="$bin" break fi for p in /usr/sbin /usr/bin /usr/libexec; do if [ -x "$p/$bin" ]; then SERVER_BIN="$p/$bin" break 2 fi done done [ -n "$SERVER_BIN" ] || die "Could not find mariadbd or mysqld binary" CLIENT_BIN="" for bin in mariadb mysql; do if command -v "$bin" >/dev/null 2>&1; then CLIENT_BIN="$bin" break fi done [ -n "$CLIENT_BIN" ] || die "Could not find mariadb or mysql client" # --- capability probe --------------------------------------------------------- # Authenticated AND authorized: the account's own row in mysql.user must hold # Create_user_priv and Grant_priv. SELECT 1 alone passes for a demoted root — # the exact failure mode this job exists to repair — so the probe must query # the grant columns. Both engines expose them (MariaDB 10.4+ through the # mysql.user compatibility view). CURRENT_USER() never contains '@' inside its # user part for any account the panel authenticates as. CAP_PROBE_SQL="SELECT COUNT(*) FROM mysql.user WHERE user=SUBSTRING_INDEX(CURRENT_USER(),'@',1) AND host=SUBSTRING_INDEX(CURRENT_USER(),'@',-1) AND Grant_priv='Y' AND Create_user_priv='Y'" # Make sure the server is actually up before probing: the panel calls this job # after ensureMySqlRunning, but the job stays self-sufficient when the service # is down (a stop-point heal also leaves it stopped until the trailing start). if ! systemctl is-active "$SVC" >/dev/null 2>&1; then systemctl start "$SVC" >/dev/null 2>&1 || true for i in $(seq 1 30); do systemctl is-active "$SVC" >/dev/null 2>&1 && break sleep 0.5 done fi # Candidates are probed with the capability SQL and remembered as # (KIND, ARGS) so the winning method can be re-run for provisioning: # KIND=plain -> "$CLIENT_BIN" "${CAPABLE_ARGS[@]+"${CAPABLE_ARGS[@]}"}" ... # KIND=envpw -> MYSQL_PWD="$MYSQL_PASSWORD" "$CLIENT_BIN" "${CAPABLE_ARGS[@]+"${CAPABLE_ARGS[@]}"}" ... # (bash variable-prefix assignment, not env(1): the password must never # appear in a process argv, which /proc//cmdline publishes.) AUTH_SEEN=0 CAPABLE_KIND="" CAPABLE_ARGS=() run_probe() { local kind="$1" shift local merged out if [ "$kind" = "envpw" ]; then merged="$(MYSQL_PWD="$MYSQL_PASSWORD" "$CLIENT_BIN" "$@" -N -e "$CAP_PROBE_SQL" 2>&1)" else merged="$("$CLIENT_BIN" "$@" -N -e "$CAP_PROBE_SQL" 2>&1)" fi # No (usable) count output with an error code: an ERROR 1045/1698 means the # channel could not even authenticate; ERROR 1044/1142 ("command denied") # means the identity IS authenticated but too demoted to read mysql.user — # exactly the state the heal exists to repair, so it counts as auth. case "$merged" in *"ERROR 1045"*|*"ERROR 1698"*) echo no ;; *"ERROR 1044"*|*"ERROR 1142"*|*"command denied"*) echo auth ;; *) out="$(printf '%s\n' "$merged" | tail -n 1 | tr -d '[:space:]')" case "$out" in 1) echo capable ;; 0) echo auth ;; *) echo no ;; esac ;; esac } check_method() { local kind="$1" shift local state state="$(run_probe "$kind" "$@")" if [ "$state" = "capable" ]; then CAPABLE_KIND="$kind" CAPABLE_ARGS=("$@") return 0 fi if [ "$state" = "auth" ]; then AUTH_SEEN=1 fi return 1 } # Re-run the winning method's client with the caller's SQL on stdin/args. run_capable_client() { if [ "$CAPABLE_KIND" = "envpw" ]; then MYSQL_PWD="$MYSQL_PASSWORD" "$CLIENT_BIN" ${CAPABLE_ARGS[@]+"${CAPABLE_ARGS[@]}"} "$@" else "$CLIENT_BIN" ${CAPABLE_ARGS[@]+"${CAPABLE_ARGS[@]}"} "$@" fi } find_capable_method() { CAPABLE_KIND="" CAPABLE_ARGS=() AUTH_SEEN=0 # Method order mirrors op_mysql_admin's catalog. if [ -n "${MYSQL_PASSWORD:-}" ]; then check_method envpw -u root && return 0 check_method envpw -u root -h 127.0.0.1 && return 0 fi check_method plain && return 0 check_method plain -u root && return 0 check_method plain -u root --skip-password && return 0 if [ -f /etc/mysql/debian.cnf ]; then check_method plain --defaults-file=/etc/mysql/debian.cnf && return 0 fi return 1 } # --- heal: restore a demoted root via skip-grant-tables ----------------------- heal_needed=0 if find_capable_method; then echo "mysql-admin-bootstrap: capable admin channel found (kind=$CAPABLE_KIND args=${CAPABLE_ARGS[*]})" else heal_needed=1 [ "$AUTH_SEEN" = "1" ] || die "No MySQL/MariaDB auth method works at all; not auto-healing a server the panel cannot even reach" echo "mysql-admin-bootstrap: admin identities authenticate but cannot administer; healing via skip-grant-tables" fi if [ "$heal_needed" = "1" ]; then SOCK_DIR="/var/run/mysqld" SOCK_PATH="$SOCK_DIR/mysqld.sock" mkdir -p "$SOCK_DIR" chown mysql:mysql "$SOCK_DIR" 2>/dev/null || true chmod 755 "$SOCK_DIR" systemctl stop "$SVC" 2>/dev/null || true pkill -9 -x mariadbd 2>/dev/null || true pkill -9 -x mysqld 2>/dev/null || true sleep 2 rm -f "$SOCK_PATH" "$SOCK_PATH.lock" 2>/dev/null || true "$SERVER_BIN" --skip-grant-tables --skip-networking --user=mysql --socket="$SOCK_PATH" & SAFE_PID=$! READY=0 for i in $(seq 1 40); do if [ -S "$SOCK_PATH" ]; then if "$CLIENT_BIN" --socket="$SOCK_PATH" -u root -e "SELECT 1" >/dev/null 2>&1; then READY=1 break fi fi sleep 0.5 done if [ "$READY" -ne 1 ]; then kill "$SAFE_PID" 2>/dev/null || true pkill -9 -x mariadbd 2>/dev/null || true pkill -9 -x mysqld 2>/dev/null || true systemctl start "$SVC" 2>/dev/null || true die "skip-grant-tables server did not become ready" fi heal_applied=0 # Strategy 1 (MariaDB): FLUSH PRIVILEGES loads the grant tables, then the # session (whose identity is root@localhost on the skip-grant socket) is # authorized and GRANT ALL ... WITH GRANT OPTION restores the packaging # default. MySQL 8 rejects the FLUSH with ER_SPECIFIC_ACCESS_DENIED (RELOAD) # — there the grant tables are updated directly instead. if [ "$heal_applied" = "0" ]; then if "$CLIENT_BIN" --socket="$SOCK_PATH" -u root <<'HEALSQL' >/dev/null 2>&1; then FLUSH PRIVILEGES; GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION; HEALSQL heal_applied=1 fi fi # Strategy 2 (MySQL 8.x): mysql.user is a base table; in skip-grant mode # direct DML on it is authorized (the earlier probe proved FLUSH is refused, # table DML is not). Every static _priv column is set to 'Y' — the packaging # default for root@localhost — with the column list read from # information_schema so a schema change across server versions cannot break # the UPDATE shape. Dynamic privileges (mysql.global_grants) are not touched. if [ "$heal_applied" = "0" ]; then PRIV_COLS="$("$CLIENT_BIN" --socket="$SOCK_PATH" -u root -N -e \ "SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema='mysql' AND table_name='user' AND column_name LIKE '%_priv' ORDER BY ordinal_position" 2>/dev/null | tr '\n' ' ' | sed 's/ $//')" [ -n "$PRIV_COLS" ] || PRIV_COLS="Select_priv Insert_priv Update_priv Delete_priv Create_priv Drop_priv Reload_priv Shutdown_priv Process_priv File_priv Grant_priv References_priv Index_priv Alter_priv Show_db_priv Super_priv Create_tmp_table_priv Lock_tables_priv Execute_priv Repl_slave_priv Repl_client_priv Create_view_priv Show_view_priv Create_routine_priv Alter_routine_priv Create_user_priv Event_priv Trigger_priv Create_tablespace_priv" SET_LIST="" for col in $PRIV_COLS; do case "$col" in *[!A-Za-z0-9_]*) die "unexpected privilege column name: $col" ;; esac SET_LIST="${SET_LIST:+$SET_LIST, }${col}='Y'" done if "$CLIENT_BIN" --socket="$SOCK_PATH" -u root -e "UPDATE mysql.user SET $SET_LIST WHERE User='root' AND Host='localhost'" >/dev/null 2>&1; then heal_applied=1 fi fi kill "$SAFE_PID" 2>/dev/null || true pkill -9 -x mariadbd 2>/dev/null || true pkill -9 -x mysqld 2>/dev/null || true sleep 2 systemctl start "$SVC" 2>/dev/null || true for i in $(seq 1 30); do if systemctl is-active "$SVC" >/dev/null 2>&1; then break fi sleep 0.5 done if [ "$heal_applied" != "1" ]; then die "both heal strategies failed; root@localhost could not be restored" fi echo "mysql-admin-bootstrap: root@localhost privileges restored" find_capable_method || die "root@localhost was healed but still cannot administer the server" fi # --- provision the dedicated panel admin account ------------------------------ # Batch aborts on the first error (plain client semantics), so a partial state # is always visible in the exit code. CREATE USER IF NOT EXISTS + ALTER USER # gives a deterministic final password whether or not a previous bootstrap (or # a degraded older panel) left the account behind; the account name is # panel-reserved (MYSQL_RESERVED_USERNAMES) so no other panel flow may ever # create, re-password or drop it. run_capable_client </dev/null || die "cannot create the canary database" canary_cleanup() { # Separate invocations: either statement may be a no-op error (the probe # user is absent when the canary failed before creating it) and must not # mask the other. MYSQL_PWD="$ADMIN_PASSWORD" "$CLIENT_BIN" -u "$ADMIN_USER" \ -e "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '$CANARY_USER'@'localhost'" >/dev/null 2>&1 || true MYSQL_PWD="$ADMIN_PASSWORD" "$CLIENT_BIN" -u "$ADMIN_USER" \ -e "DROP USER IF EXISTS '$CANARY_USER'@'localhost'" >/dev/null 2>&1 || true run_capable_client -e "DROP DATABASE IF EXISTS \`$CANARY_DB\`" >/dev/null 2>&1 || true } canary_rc=0 MYSQL_PWD="$ADMIN_PASSWORD" "$CLIENT_BIN" -u "$ADMIN_USER" <<'CANARY' >/dev/null 2>&1 || canary_rc=$? CREATE USER IF NOT EXISTS 'adpanel_admin_probe'@'localhost' IDENTIFIED BY 'canary-probe-password'; ALTER USER 'adpanel_admin_probe'@'localhost' IDENTIFIED BY 'canary-probe-password-2'; GRANT SELECT ON `adpanel_admin_canary`.* TO 'adpanel_admin_probe'@'localhost'; SELECT COUNT(*) FROM mysql.user WHERE user = 'adpanel_admin_probe'; SHOW DATABASES; REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'adpanel_admin_probe'@'localhost'; DROP USER 'adpanel_admin_probe'@'localhost'; CANARY if [ "$canary_rc" != "0" ]; then canary_cleanup die "canary failed: the dedicated account cannot administer the server" fi canary_cleanup echo "mysql-admin-bootstrap: dedicated admin account '$ADMIN_USER'@'$ADMIN_HOST' provisioned and certified" exit 0