Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+806
View File
@@ -0,0 +1,806 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# ADPanel privileged operations runner.
#
# This is the ONLY binary the 'adpanel' user may run via sudo (see
# adpanel-sudoers). It exposes a fixed catalog of narrowly-scoped operations
# and rejects everything else, so a panel compromise can no longer translate
# into arbitrary root command execution (previously: NOPASSWD: ALL).
#
# Install location : /usr/local/lib/adpanel/adpanel-priv (root:root 0755)
# Job scripts : /usr/local/lib/adpanel/jobs/*.sh (root:root 0755)
#
# Usage: adpanel-priv <op> [args...]
# apt update
# apt install <pkg>... max 24 packages, names validated
# apt remove-purge <pkg>...
# apt autoremove
# svc <action> <unit> action: start|stop|restart|reload|enable|
# disable|is-active|daemon-reload
# kill-procs <name> name: mysqld|mariadbd|postgres|apache2|mongod
# mysql-recovery kill mysqld/mariadbd, restart mariadb|mysql|mysqld
# write-file <path> <mode> base64 content on stdin, allowlisted paths;
# /etc/apt/sources.list.d/* payloads are
# content-validated (validate_apt_source_content):
# only one-line deb/deb-src stanzas with a
# mandatory signed-by= option pinned to
# /usr/share/keyrings/*, so a panel compromise
# cannot plant an unsigned or trusted=yes repo
# append-file <path> base64 content on stdin, allowlisted paths;
# same sources.list.d content policy as
# write-file (bytes are validated before they
# are appended)
# rm-file <path> allowlisted paths
# phpmyadmin-secure-config <path>
# enforce root:www-data 0640 on the two
# config.inc.php copies (blowfish_secret)
# rm-dir <path> allowlisted roots (/var/lib/pgadmin etc.)
# nginx-test-reload nginx -t && systemctl reload (restart fallback)
# nginx-test-restart nginx -t && systemctl restart
# a2enmod <mod> mod: wsgi|headers
# apache-configtest apache2ctl configtest
# journal <unit> <lines> journalctl -u <unit> --no-pager -n <lines>
# psql-postgres SQL on stdin, executed as the postgres user
# mysql-admin SQL on stdin, executed with the first working
# root auth method (socket/debian.cnf/env, the
# env password passed via MYSQL_PWD, never argv)
# pg-set-listen <host> <port> patch postgresql.conf listen_addresses/port
# pg-add-hba append scram-sha-256 host rules if missing
# pg-restart enable + restart/reload + pg_ctlcluster fallback
# pgadmin-setup run pgAdmin setup-web.sh (env: email/password)
# prepare-dirs <profile> pgadmin | mongodb (fixed mkdir/chown sets)
# mongo-clear-locks remove stale mongod socket/lock files
# fetch-dearmor <name> fetch+dearmor a pinned apt signing key
# name: pgdg|pgadmin|mongodb
# firewall-allow <port> ufw/iptables allow <port>/tcp
# firewall-deny <port> ufw/iptables remove the allow rule
# restart-panel restart the adpanel service (systemd/openrc/pm2)
# job <name> execute a root-owned script from jobs/
# (job-level arguments default to rejected:
# the job_max_args policy is 0 unless a job
# has an explicit reviewed entry, so
# caller-controlled argv only reaches a
# root-run script where that script
# validates the value before use)
# -----------------------------------------------------------------------------
set -u
PRIV_LIB_DIR="/usr/local/lib/adpanel"
JOB_DIR="${PRIV_LIB_DIR}/jobs"
die() {
echo "adpanel-priv: $*" >&2
exit 2
}
# --- shared validators -------------------------------------------------------
valid_port() {
case "${1:-}" in
''|*[!0-9]*) return 1 ;;
esac
[ "$1" -ge 1 ] && [ "$1" -le 65535 ]
}
valid_octal_mode() {
case "${1:-}" in
''|*[!0-7]*) return 1 ;;
*) [ "${#1}" -ge 3 ] && [ "${#1}" -le 4 ] ;;
esac
}
valid_pkg() {
printf '%s' "$1" | grep -Eq '^[a-zA-Z0-9][a-zA-Z0-9.+:~-]{0,100}$'
}
valid_svc_unit() {
# adpanel-sshterm: the panel's sshterm recovery path restarts its own
# service unit through this runner (the sudoers policy forbids bare
# `sudo systemctl` for the unprivileged 'adpanel' user).
printf '%s' "$1" | grep -Eq '^(adpanel|adpanel-sshterm|nginx|apache2|postgresql|postgresql@[0-9A-Za-z._-]+|mariadb|mysql|mysqld|mongod|php[0-9.]+-fpm)(\.service)?$'
}
# Lexically normalize a path (resolve "." and ".." components) without
# requiring it to exist. Refuses paths that still climb above / after
# normalization. Prefix allowlists MUST be applied to the normalized form,
# otherwise "/etc/nginx/../../tmp/x" would pass a "/etc/nginx/*" glob.
normpath() {
local p="${1:-}" part out=""
[ -n "$p" ] || return 1
case "$p" in
/*) ;;
*) return 1 ;; # only absolute paths are accepted
esac
IFS='/'
for part in $p; do
case "$part" in
''|.) continue ;;
..)
out="${out%/*}"
case "$out" in
'') out="" ;;
esac
;;
*) out="$out/$part" ;;
esac
done
unset IFS
norm_result="${out:-/}"
return 0
}
path_allowed_write() {
local p="$1"
normpath "$p" || return 1
p="$norm_result"
case "$p" in
/etc/nginx/*|/etc/apache2/*|/etc/phpmyadmin/*|/usr/share/phpmyadmin/*|\
/etc/pgadmin/*|/etc/apt/sources.list.d/*|/etc/mongod.conf)
return 0 ;;
*) return 1 ;;
esac
}
path_allowed_rm() {
local p="$1"
normpath "$p" || return 1
p="$norm_result"
case "$p" in
/etc/nginx/*|/etc/apache2/*|/etc/phpmyadmin/*|/usr/share/phpmyadmin/*|\
/etc/pgadmin/*|/etc/apt/sources.list.d/*|/usr/share/keyrings/*|\
/tmp/mongodb-*.sock|/var/lib/mongodb/mongod.lock|/var/lib/pgadmin/sessions/*)
return 0 ;;
*) return 1 ;;
esac
}
path_allowed_rmdir() {
local p="$1"
normpath "$p" || return 1
p="$norm_result"
case "$p" in
/var/lib/pgadmin|/var/lib/pgadmin/*|/var/log/pgadmin|/etc/pgadmin|\
/usr/pgadmin4|/var/lib/mongodb|/var/log/mongodb)
return 0 ;;
*) return 1 ;;
esac
}
require_root_file() {
# $1 = file that must be a regular file owned by root and not group/world
# writable. Symlinks are rejected so an 'adpanel'-owned redirect cannot be
# planted in front of a job script.
local f="$1" owner perms
[ -f "$f" ] || return 1
[ -L "$f" ] && return 1
owner="$(stat -c '%u' "$f" 2>/dev/null)" || return 1
[ "$owner" = "0" ] || return 1
perms="$(stat -c '%a' "$f" 2>/dev/null)" || return 1
[ $(( 8#${perms:-777} & 022 )) -eq 0 ] || return 1
return 0
}
# --- apt sources.list.d content policy ---------------------------------------
# Validates one line of an apt one-line-style source stanza. Blank lines and
# '#' comments are always accepted. A stanza must parse as:
# deb|deb-src [arch=<v> signed-by=<v> ...] <uri> <suite> <component>...
# where:
# - the ONLY option keys are arch= and signed-by= (anything else - notably
# trusted=yes, which disables signature verification entirely - dies);
# - signed-by= is REQUIRED on every stanza and its value must be a pinned
# keyring under /usr/share/keyrings/ (this runner can only create keyring
# files there via fetch-dearmor, and the panel cannot write keyring
# content anywhere else, so apt signature verification can never be
# bypassed through a source written by the panel);
# - values may be wrapped in double quotes, which are stripped first;
# - URI is an http/https URL (http stays allowed: signature verification is
# what matters and it is mandatory);
# - suite and components are restricted charsets (suite may contain '/',
# e.g. jammy/mongodb-org/8.0); at most 16 components.
# Prints a reason on stderr and returns 1 on the first invalid line.
valid_apt_source_line() {
local line="${1:-}" tok key val uri suite
local -a toks opts rest
local re_signed_by='^/usr/share/keyrings/[A-Za-z0-9._-]+\.(gpg|asc)$'
local re_arch_val='^[A-Za-z0-9][A-Za-z0-9,._+-]{0,127}$'
local re_uri='^(http|https)://[][A-Za-z0-9._~:/?#@!$&'"'"'()*+,;=%-]+$'
local re_suite='^[A-Za-z0-9._~/-]+$'
local re_comp='^[A-Za-z0-9._~-]+$'
# Trim surrounding whitespace (also normalizes CRLF line tails).
line="${line#"${line%%[![:space:]]*}"}"
line="${line%"${line##*[![:space:]]}"}"
case "$line" in
''|'#'*) return 0 ;;
esac
read -r -a toks <<< "$line"
case "${toks[0]:-}" in
deb|deb-src) ;;
*)
echo "adpanel-priv: apt source: stanza must start with 'deb' or 'deb-src' (got '${toks[0]:-}')" >&2
return 1 ;;
esac
# Optional ONE options block: '[' ... ']' spanning one or more tokens, with
# the closing ']' possibly attached to the last option token.
local idx=1
opts=()
case "${toks[1]:-}" in
'['*)
tok="${toks[1]#\[}"
while :; do
case "$tok" in
*\])
tok="${tok%\]}"
[ -n "$tok" ] && opts+=("$tok")
idx=$((idx + 1))
break ;;
esac
[ -n "$tok" ] && opts+=("$tok")
idx=$((idx + 1))
if [ "$idx" -ge "${#toks[@]}" ]; then
echo "adpanel-priv: apt source: unterminated '[' options block" >&2
return 1
fi
tok="${toks[$idx]}"
done ;;
esac
rest=()
while [ "$idx" -lt "${#toks[@]}" ]; do
rest+=("${toks[$idx]}")
idx=$((idx + 1))
done
# Option tokens: arch=<v> / signed-by=<v> ONLY, values optionally quoted.
local have_signed_by=0
for tok in ${opts[@]+"${opts[@]}"}; do
case "$tok" in
arch=*|signed-by=*) ;;
*)
echo "adpanel-priv: apt source: option '${tok}' not allowed (only arch= and signed-by=)" >&2
return 1 ;;
esac
key="${tok%%=*}"
val="${tok#*=}"
case "$val" in
'"'*'"') val="${val#\"}"; val="${val%\"}" ;;
esac
case "$key" in
signed-by)
printf '%s' "$val" | LC_ALL=C grep -Eq "$re_signed_by" || {
echo "adpanel-priv: apt source: signed-by must be a pinned keyring under /usr/share/keyrings/ (got '${val}')" >&2
return 1
}
have_signed_by=1 ;;
*)
printf '%s' "$val" | LC_ALL=C grep -Eq "$re_arch_val" || {
echo "adpanel-priv: apt source: invalid arch value '${val}'" >&2
return 1
} ;;
esac
done
[ "$have_signed_by" -eq 1 ] || {
echo "adpanel-priv: apt source: signed-by=<pinned keyring> is required on every stanza" >&2
return 1
}
# <uri> <suite> <component>... (uri, suite and 1..16 components required).
[ "${#rest[@]}" -ge 3 ] || {
echo "adpanel-priv: apt source: stanza needs <uri> <suite> and at least one component" >&2
return 1
}
[ "${#rest[@]}" -le 18 ] || {
echo "adpanel-priv: apt source: too many components (max 16)" >&2
return 1
}
uri="${rest[0]}"
suite="${rest[1]}"
printf '%s' "$uri" | LC_ALL=C grep -Eq "$re_uri" || {
echo "adpanel-priv: apt source: URI not allowed '${uri}' (http(s) URLs only)" >&2
return 1
}
printf '%s' "$suite" | LC_ALL=C grep -Eq "$re_suite" || {
echo "adpanel-priv: apt source: invalid suite '${suite}'" >&2
return 1
}
local comp
for comp in "${rest[@]:2}"; do
printf '%s' "$comp" | LC_ALL=C grep -Eq "$re_comp" || {
echo "adpanel-priv: apt source: invalid component '${comp}'" >&2
return 1
}
done
return 0
}
# Validates a decoded sources.list.d payload read from stdin (the exact bytes
# that would be written): plain text (no NUL bytes) of at most 65536 bytes
# where every line passes valid_apt_source_line. A file consisting solely of
# blank/comment lines (e.g. a disabled repo) is valid. Returns non-zero with
# a reason on stderr; callers clean up any temp file and die.
validate_apt_source_content() {
local tmp size line rc=0
tmp="$(mktemp)" || return 1
cat > "$tmp"
size="$(wc -c < "$tmp")"
if [ "$size" -gt 65536 ]; then
rm -f "$tmp"
echo "adpanel-priv: apt source payload too large (${size} > 65536 bytes)" >&2
return 1
fi
if [ "$size" -ne "$(LC_ALL=C tr -d '\000' < "$tmp" | wc -c)" ]; then
rm -f "$tmp"
echo "adpanel-priv: apt source payload must be plain text (NUL byte found)" >&2
return 1
fi
while IFS= read -r line || [ -n "$line" ]; do
if ! valid_apt_source_line "$line"; then
rc=1
break
fi
done < "$tmp"
rm -f "$tmp"
return "$rc"
}
# --- operations --------------------------------------------------------------
op_apt() {
local action="${1:-}"; shift || true
case "$action" in
update) exec apt-get update -qq ;;
autoremove) exec env DEBIAN_FRONTEND=noninteractive apt-get autoremove -y ;;
install|remove-purge)
[ $# -ge 1 ] || die "apt $action: missing packages"
[ $# -le 24 ] || die "apt $action: too many packages"
local pkgs=()
for p in "$@"; do
valid_pkg "$p" || die "apt $action: invalid package name '$p'"
pkgs+=("$p")
done
if [ "$action" = "install" ]; then
exec env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${pkgs[@]}"
fi
exec env DEBIAN_FRONTEND=noninteractive apt-get remove --purge -y "${pkgs[@]}"
;;
*) die "unknown apt action '$action'" ;;
esac
}
op_svc() {
local action="${1:-}" unit="${2:-}"
case "$action" in
daemon-reload)
exec systemctl daemon-reload ;;
start|stop|restart|reload|enable|disable|is-active)
[ -n "$unit" ] || die "svc: missing unit"
valid_svc_unit "$unit" || die "svc: unit not allowed '$unit'"
exec systemctl "$action" "$unit" ;;
*) die "svc: action not allowed '$action'" ;;
esac
}
op_agent_service() {
[ "$#" -eq 1 ] || die "agent-service: one action required"
case "$1" in
start|stop|restart) exec systemctl "$1" adpanel-agent.service ;;
*) die "agent-service: action not allowed" ;;
esac
}
op_kill_procs() {
case "${1:-}" in
mysqld|mariadbd) pkill -9 -x mysqld 2>/dev/null; exec pkill -9 -x mariadbd ;;
postgres) exec pkill -9 -x postgres ;;
apache2) exec pkill -9 -x apache2 ;;
mongod) exec pkill -9 -x mongod ;;
*) die "kill-procs: name not allowed '${1:-}'" ;;
esac
}
op_mysql_recovery() {
pkill -9 -x mysqld 2>/dev/null || true
pkill -9 -x mariadbd 2>/dev/null || true
sleep 1
systemctl start mariadb 2>/dev/null || \
systemctl start mysql 2>/dev/null || \
systemctl start mysqld 2>/dev/null || true
}
op_write_file() {
local target="${1:-}" mode="${2:-}"
[ -n "$target" ] || die "write-file: missing path"
path_allowed_write "$target" || die "write-file: path not allowed '$target'"
valid_octal_mode "$mode" || die "write-file: invalid mode '${mode}'"
target="$norm_result"
case "$target" in
/etc/mongod.conf) : ;;
*) mkdir -p "$(dirname "$target")" ;;
esac
local tmp
tmp="$(mktemp "$(dirname "$target")/.adpanel-priv.XXXXXX")" || die "write-file: mktemp failed"
if ! base64 -d > "$tmp"; then
rm -f "$tmp"
die "write-file: invalid base64 payload"
fi
case "$target" in
/etc/apt/sources.list.d/*)
# Content policy (see validate_apt_source_content): a compromised panel
# must not be able to plant an unsigned or trusted=yes apt repository,
# whose package maintainer scripts would execute as root on the next
# `apt install`.
validate_apt_source_content < "$tmp" || {
rm -f "$tmp"
die "write-file: $target rejected as an apt source list"
}
;;
esac
chmod "$mode" "$tmp"
if ! mv -f "$tmp" "$target"; then
rm -f "$tmp"
die "write-file: failed to move into place"
fi
}
op_append_file() {
local target="${1:-}"
[ -n "$target" ] || die "append-file: missing path"
path_allowed_write "$target" || die "append-file: path not allowed '$target'"
target="$norm_result"
mkdir -p "$(dirname "$target")"
case "$target" in
/etc/apt/sources.list.d/*)
# Decode to a temp file and validate the exact bytes before they touch
# the target: unvalidated content is never appended to an apt source.
local tmp
tmp="$(mktemp "$(dirname "$target")/.adpanel-priv.XXXXXX")" \
|| die "append-file: mktemp failed"
if ! base64 -d > "$tmp"; then
rm -f "$tmp"
die "append-file: invalid base64 payload"
fi
validate_apt_source_content < "$tmp" || {
rm -f "$tmp"
die "append-file: $target rejected as an apt source list"
}
cat "$tmp" >> "$target" || {
rm -f "$tmp"
die "append-file: failed to append"
}
rm -f "$tmp"
;;
*)
base64 -d >> "$target" || die "append-file: invalid base64 payload"
;;
esac
}
op_rm_file() {
local target="${1:-}"
[ -n "$target" ] || die "rm-file: missing path"
path_allowed_rm "$target" || die "rm-file: path not allowed '$target'"
rm -f -- "$norm_result"
}
op_rm_dir() {
local target="${1:-}"
[ -n "$target" ] || die "rm-dir: missing path"
path_allowed_rmdir "$target" || die "rm-dir: path not allowed '$target'"
rm -rf -- "$norm_result"
}
op_nginx_test_reload() {
nginx -t || exit 1
systemctl reload nginx || systemctl restart nginx
}
op_nginx_test_restart() {
nginx -t || exit 1
systemctl restart nginx
}
op_a2enmod() {
case "${1:-}" in
wsgi|headers) exec a2enmod "$1" ;;
*) die "a2enmod: module not allowed '${1:-}'" ;;
esac
}
op_journal() {
local unit="${1:-}" lines="${2:-20}"
[ -n "$unit" ] || die "journal: missing unit"
valid_svc_unit "$unit" || die "journal: unit not allowed '$unit'"
valid_port "$lines" || lines=20
[ "$lines" -le 500 ] || lines=500
exec journalctl -u "$unit" --no-pager -n "$lines"
}
op_psql_postgres() {
command -v runuser >/dev/null 2>&1 || die "psql-postgres: runuser not available"
# ON_ERROR_STOP=1 is required by every caller: without it psql CONTINUES
# after a failed statement and still exits 0, so a multi-statement batch
# would report success while half-applied (e.g. the panel-user provisioning
# batch raises ADP_PG_ROLE_ALREADY_EXISTS and must abort BEFORE its
# remaining statements touch the role; a failed ALTER ROLE PASSWORD or
# DROP ROLE must surface as a non-zero exit, not a false success). This
# mirrors scripts/migrate-db-user-privileges.js, which runs its own psql
# channel with the same flag. No transaction flag: the batches include
# CREATE DATABASE via \gexec, which cannot run inside a transaction.
exec runuser -u postgres -- psql -v ON_ERROR_STOP=1
}
op_mysql_admin() {
# Runs as root: try the standard local auth methods, the first one whose
# identity can ADMINISTER (its own mysql.user row holds Grant_priv and
# Create_user_priv — authentication alone keeps passing for a demoted root
# whose every GRANT fails with ERROR 1044) wins, then hand it the SQL from
# stdin. MYSQL_PASSWORD reaches us through the sudoers env_keep allowlist
# and is handed to the client via MYSQL_PWD — /proc/<pid>/environ is 0400
# and owned by the process uid, while argv (--password=) would be
# world-readable through /proc/<pid>/cmdline.
local -a cmd=()
local use_env_pw=0
local cap_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'"
capable() {
[ "$("$@" -N -e "$cap_sql" 2>/dev/null | tail -n 1 | tr -d '[:space:]')" = "1" ]
}
if [ -n "${MYSQL_PASSWORD:-}" ] && \
[ "$(MYSQL_PWD="$MYSQL_PASSWORD" mysql -u root --connect-timeout=3 -N -e "$cap_sql" 2>/dev/null | tail -n 1 | tr -d '[:space:]')" = "1" ]; then
cmd=(mysql -u root)
use_env_pw=1
elif capable mysql --connect-timeout=3; then
cmd=(mysql --connect-timeout=3)
elif capable mariadb --connect-timeout=3; then
cmd=(mariadb --connect-timeout=3)
elif [ -f /etc/mysql/debian.cnf ] && \
capable mysql --defaults-file=/etc/mysql/debian.cnf --connect-timeout=3; then
cmd=(mysql --defaults-file=/etc/mysql/debian.cnf --connect-timeout=3)
elif capable mysql -u root --skip-password --connect-timeout=3; then
cmd=(mysql -u root --skip-password --connect-timeout=3)
else
echo "adpanel-priv: no capable MySQL/MariaDB root auth method" >&2
exit 1
fi
if [ "$use_env_pw" = 1 ]; then
# Exported solely for the exec'd client below; exec replaces this shell,
# so the variable cannot leak into any other process.
export MYSQL_PWD="$MYSQL_PASSWORD"
fi
exec "${cmd[@]}"
}
op_pg_set_listen() {
local host="${1:-}" port="${2:-}"
printf '%s' "$host" | grep -Eq '^[a-zA-Z0-9._:-]{1,64}$' || die "pg-set-listen: invalid host '$host'"
valid_port "$port" || die "pg-set-listen: invalid port '$port'"
local conf found=0
while IFS= read -r conf; do
[ -f "$conf" ] || continue
found=1
sed -i "s/^#\?listen_addresses = 'localhost'/listen_addresses = '${host}'/" "$conf"
sed -i "s/^listen_addresses = 'localhost'/listen_addresses = '${host}'/" "$conf"
sed -i "s/^#port = 5432/port = ${port}/" "$conf"
sed -i "s/^port = 5432/port = ${port}/" "$conf"
done < <(find /etc/postgresql -name postgresql.conf 2>/dev/null)
[ "$found" -eq 1 ] || echo "adpanel-priv: no postgresql.conf found under /etc/postgresql" >&2
}
op_pg_add_hba() {
local conf
while IFS= read -r conf; do
[ -f "$conf" ] || continue
# Idempotent: skip when the allow rules already exist, whether inside a
# previous ADPanel-managed block or as legacy untagged lines from older
# panel versions (legacy lines are left in place here; the pgadmin-disable
# job removes both forms).
if grep -q "host all all 0.0.0.0/0" "$conf" || grep -q "host all all ::0/0" "$conf"; then
continue
fi
{
echo '# BEGIN ADPanel-managed remote-bind rules (added by adpanel-priv pg-add-hba)'
# pg_hba.conf is first-match-wins and the stock file keeps its local
# (socket + 127.0.0.1/::1 loopback) rules ahead of anything appended
# here, so local superuser access keeps working. Rejecting the postgres
# superuser from remote sources stops the wildcard scram allow below
# from making it brute-forceable from any host; panel-created
# non-superuser roles keep remote scram-sha-256 access (the feature
# being configured).
echo 'host all postgres 0.0.0.0/0 reject'
echo 'host all postgres ::0/0 reject'
echo 'host all all 0.0.0.0/0 scram-sha-256'
echo 'host all all ::0/0 scram-sha-256'
echo '# END ADPanel-managed remote-bind rules'
} >> "$conf"
done < <(find /etc/postgresql -name pg_hba.conf 2>/dev/null)
}
op_pg_restart() {
systemctl enable postgresql 2>/dev/null || true
systemctl restart postgresql 2>/dev/null || \
systemctl reload postgresql 2>/dev/null || \
pg_ctlcluster --skip-systemctl-redirect \
$(pg_lsclusters -h 2>/dev/null | head -1 | awk '{print $1, $2}') restart 2>/dev/null || true
}
op_pgadmin_setup() {
local script=""
if [ -x /usr/pgadmin4/bin/setup-web.sh ]; then
script="/usr/pgadmin4/bin/setup-web.sh"
elif [ -x /usr/share/pgadmin4/bin/setup-web.sh ]; then
script="/usr/share/pgadmin4/bin/setup-web.sh"
else
echo "adpanel-priv: pgAdmin setup-web.sh not found" >&2
exit 1
fi
exec "$script" --yes
}
op_prepare_dirs() {
case "${1:-}" in
pgadmin)
mkdir -p /var/lib/pgadmin/sessions /var/lib/pgadmin/storage /var/log/pgadmin /etc/pgadmin
chown -R www-data:www-data /var/lib/pgadmin /var/log/pgadmin 2>/dev/null || true
chmod 750 /var/lib/pgadmin
;;
mongodb)
mkdir -p /var/lib/mongodb /var/log/mongodb
chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb 2>/dev/null || true
chmod 755 /var/lib/mongodb /var/log/mongodb
;;
*) die "prepare-dirs: unknown profile '${1:-}'" ;;
esac
}
op_mongo_clear_locks() {
rm -f /tmp/mongodb-*.sock /var/lib/mongodb/mongod.lock 2>/dev/null || true
}
op_fetch_dearmor() {
local url keyring
case "${1:-}" in
pgdg)
url="https://www.postgresql.org/media/keys/ACCC4CF8.asc"
keyring="/usr/share/keyrings/adpanel-pgdg.gpg" ;;
pgadmin)
url="https://www.pgadmin.org/static/packages_pgadmin_org.pub"
keyring="/usr/share/keyrings/packages-pgadmin-org.gpg" ;;
mongodb)
url="https://www.mongodb.org/static/pgp/server-8.0.asc"
keyring="/usr/share/keyrings/mongodb-server-8.0.gpg" ;;
*) die "fetch-dearmor: unknown key '${1:-}'" ;;
esac
curl -fsSL --retry 3 --retry-delay 5 "$url" | gpg --batch --yes --dearmor -o "$keyring"
}
op_firewall() {
local action="${1:-}" port="${2:-}"
valid_port "$port" || die "firewall-$action: invalid port '${port}'"
if [ "$action" = "allow" ]; then
ufw allow "${port}/tcp" 2>/dev/null || true
iptables -C INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || \
iptables -A INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || true
elif [ "$action" = "deny" ]; then
ufw delete allow "${port}/tcp" 2>/dev/null || true
iptables -D INPUT -p tcp --dport "$port" -j ACCEPT 2>/dev/null || true
else
die "firewall: unknown action '$action'"
fi
}
op_restart_panel() {
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
exec systemctl restart adpanel
elif command -v rc-service >/dev/null 2>&1; then
exec rc-service adpanel restart
elif command -v service >/dev/null 2>&1; then
exec service adpanel restart
elif command -v pm2 >/dev/null 2>&1; then
exec pm2 restart adpanel --update-env
fi
echo "adpanel-priv: no supported init system found" >&2
exit 1
}
# Per-job argument policy for the job op: the maximum number of job-level
# arguments each script may receive. Caller-controlled argv forwarded into a
# root-run script is an option-injection hazard (e.g. a mysql client flag
# like --plugin-dir), so the policy is 0 by default. pgadmin-disable.sh and
# mongodb-disable.sh consume exactly one argument — the former service's
# listen port for firewall cleanup — and both validate it as a pure 1..65535
# number inside the script before it reaches ufw/iptables, so an explicit
# 1-arg entry is safe for them. Adding arguments for any other job requires
# an explicit, reviewed entry here - never a loosened default.
job_max_args() {
case "$1" in
pgadmin-disable.sh|mongodb-disable.sh)
echo 1 ;;
apache-cleanup-sites.sh|install-phpmyadmin.sh|\
mysql-admin-bootstrap.sh|mysql-skip-grant.sh|pgadmin-prepare.sh|\
pgadmin-setup-recover.sh|phpmyadmin-prepare.sh)
echo 0 ;;
*) echo 0 ;;
esac
}
op_job() {
local name="${1:-}"; shift || true
printf '%s' "$name" | grep -Eq '^[a-zA-Z0-9._-]{1,64}$' || die "job: invalid name '${name}'"
local max_args
max_args="$(job_max_args "${name}.sh")"
[ "$#" -le "$max_args" ] || die "job: arguments not allowed for '${name}' (max ${max_args})"
local script="${JOB_DIR}/${name}.sh"
# Defense in depth: the jobs directory and the script itself must be
# root-owned and non-writable by group/world, and must not be a symlink.
local owner perms
[ -d "$JOB_DIR" ] || die "job: jobs directory missing at $JOB_DIR"
owner="$(stat -c '%u' "$JOB_DIR" 2>/dev/null)" || die "job: cannot stat jobs directory"
[ "$owner" = "0" ] || die "job: jobs directory not root-owned"
perms="$(stat -c '%a' "$JOB_DIR" 2>/dev/null)" || die "job: cannot stat jobs directory"
[ $(( 8#${perms:-777} & 022 )) -eq 0 ] || die "job: jobs directory writable by group/world"
require_root_file "$script" || die "job: refused to execute '${name}.sh' (missing, not root-owned, or writable)"
exec bash "$script" "$@"
}
op_phpmyadmin_secure_config() {
# Security fix: config.inc.php holds the phpMyAdmin blowfish_secret, so it
# must not stay world-readable. PHP-FPM runs as www-data, which still needs
# read access - hence root:www-data 0640 rather than 0600. chmod runs before
# chown so a chown failure cannot leave the old (world-readable) mode behind.
local target="${1:-}"
normpath "$target" || die "phpmyadmin-secure-config: invalid path"
target="$norm_result"
case "$target" in
/etc/phpmyadmin/config.inc.php|/usr/share/phpmyadmin/config.inc.php) : ;;
*) die "phpmyadmin-secure-config: path not allowed '$target'" ;;
esac
[ -f "$target" ] || die "phpmyadmin-secure-config: missing file '$target'"
if [ -L "$target" ]; then
die "phpmyadmin-secure-config: refusing symlink '$target'"
fi
chmod 0640 "$target" || die "phpmyadmin-secure-config: chmod failed for '$target'"
chown root:www-data "$target" || die "phpmyadmin-secure-config: chown failed for '$target' (is the www-data group present?)"
}
# --- dispatch ----------------------------------------------------------------
[ "$(id -u)" -eq 0 ] || die "must run as root (via sudo)"
op="${1:-}"; shift || true
case "$op" in
apt) op_apt "$@" ;;
svc) op_svc "$@" ;;
agent-service) op_agent_service "$@" ;;
kill-procs) op_kill_procs "$@" ;;
mysql-recovery) op_mysql_recovery "$@" ;;
write-file) op_write_file "$@" ;;
phpmyadmin-secure-config) op_phpmyadmin_secure_config "$@" ;;
append-file) op_append_file "$@" ;;
rm-file) op_rm_file "$@" ;;
rm-dir) op_rm_dir "$@" ;;
nginx-test-reload) op_nginx_test_reload "$@" ;;
nginx-test-restart) op_nginx_test_restart "$@" ;;
a2enmod) op_a2enmod "$@" ;;
apache-configtest) exec apache2ctl configtest ;;
journal) op_journal "$@" ;;
psql-postgres) op_psql_postgres "$@" ;;
mysql-admin) op_mysql_admin "$@" ;;
pg-set-listen) op_pg_set_listen "$@" ;;
pg-add-hba) op_pg_add_hba "$@" ;;
pg-restart) op_pg_restart "$@" ;;
pgadmin-setup) op_pgadmin_setup "$@" ;;
prepare-dirs) op_prepare_dirs "$@" ;;
mongo-clear-locks) op_mongo_clear_locks "$@" ;;
fetch-dearmor) op_fetch_dearmor "$@" ;;
firewall-allow) op_firewall allow "$@" ;;
firewall-deny) op_firewall deny "$@" ;;
restart-panel) op_restart_panel "$@" ;;
job) op_job "$@" ;;
*) die "unknown operation '${op}' (usage: adpanel-priv <op> [args...])" ;;
esac
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Installs the ADPanel privileged runner + job scripts.
#
# Deploys privileged/adpanel-priv to /usr/local/lib/adpanel/adpanel-priv and
# privileged/jobs/*.sh to /usr/local/lib/adpanel/jobs/, all owned root:root
# with no group/world write bits, so the sudoers policy can safely allow
# 'adpanel' to run exactly one command as root (see adpanel-sudoers).
#
# Must be run as root. Idempotent. Uses the panel dir as $1 or the directory
# containing this script when omitted.
# -----------------------------------------------------------------------------
set -euo pipefail
PANEL_DIR="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
PRIV_SRC="${PANEL_DIR}/privileged"
DEST="/usr/local/lib/adpanel"
JOBS_SRC="${PRIV_SRC}/jobs"
JOBS_DEST="${DEST}/jobs"
if [ "$(id -u)" -ne 0 ]; then
echo "install-privileged.sh: must be run as root" >&2
exit 1
fi
if [ ! -f "${PRIV_SRC}/adpanel-priv" ] || [ ! -d "$JOBS_SRC" ]; then
echo "install-privileged.sh: privileged sources missing under ${PRIV_SRC}" >&2
exit 1
fi
install -d -o root -g root -m 0755 "$DEST"
install -d -o root -g root -m 0755 "$JOBS_DEST"
# Remove any job no longer shipped in the source tree (stale root-owned
# leftovers must not survive a panel update).
for f in "${JOBS_DEST}"/*.sh; do
[ -e "$f" ] || continue
base="$(basename "$f")"
[ -f "${JOBS_SRC}/${base}" ] || rm -f "$f"
done
install -o root -g root -m 0755 "${PRIV_SRC}/adpanel-priv" "${DEST}/adpanel-priv"
for f in "${JOBS_SRC}"/*.sh; do
[ -e "$f" ] || continue
install -o root -g root -m 0755 "$f" "${JOBS_DEST}/$(basename "$f")"
done
# Keep an installed copy of the (restricted) sudoers snippet in sync so
# start.sh's visudo-validated sync cannot regress to a wider policy.
if [ -f "${PANEL_DIR}/adpanel-sudoers" ]; then
tmp="$(mktemp)"
cp "${PANEL_DIR}/adpanel-sudoers" "$tmp"
chmod 0440 "$tmp"
if command -v visudo >/dev/null 2>&1 && ! visudo -cf "$tmp" >/dev/null 2>&1; then
rm -f "$tmp"
echo "install-privileged.sh: WARNING sudoers snippet failed validation; leaving existing policy" >&2
else
mkdir -p /etc/sudoers.d
mv "$tmp" /etc/sudoers.d/adpanel-panel
chmod 0440 /etc/sudoers.d/adpanel-panel
fi
fi
echo "install-privileged.sh: privileged runner installed at ${DEST}/adpanel-priv"
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
# ADPanel privileged job: remove conflicting Apache default sites and any
# site config that would try to bind port 80 (nginx owns port 80).
# Invoked via adpanel-priv: adpanel-priv job apache-cleanup-sites
set -u
rm -f /etc/apache2/sites-enabled/000-default.conf 2>/dev/null || true
rm -f /etc/apache2/sites-enabled/default-ssl.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/phpmyadmin.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/serve-cgi-bin.conf 2>/dev/null || true
grep -l ':80>' /etc/apache2/sites-enabled/*.conf 2>/dev/null | xargs -r rm -f
grep -l 'Listen 80' /etc/apache2/sites-enabled/*.conf 2>/dev/null | xargs -r rm -f
true
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# ADPanel privileged job: install PHP-FPM + phpMyAdmin.
# Invoked via adpanel-priv: adpanel-priv job install-phpmyadmin
set -u
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
# Install PHP-FPM and required extensions first
apt-get install -y --no-install-recommends \
php-fpm php-mysql php-mbstring php-zip php-gd php-curl php-xml php-cli
# Install phpMyAdmin (skip Apache recommends)
apt-get install -y --no-install-recommends phpmyadmin
# If Apache was pulled in anyway, stop and disable it - nginx handles traffic
if systemctl is-active apache2 >/dev/null 2>&1; then
systemctl stop apache2 2>/dev/null || true
fi
systemctl disable apache2 2>/dev/null || true
# Ensure PHP-FPM is running (prefer the newest installed version)
PHP_FPM_SVC=$(systemctl list-units --type=service --state=running,exited --no-legend 2>/dev/null | grep -oP 'php[\d.]+-fpm\.service' | sort -rV | head -1)
if [ -z "$PHP_FPM_SVC" ]; then
PHP_FPM_SVC=$(systemctl list-unit-files --type=service --no-legend 2>/dev/null | grep -oP 'php[\d.]+-fpm\.service' | sort -rV | head -1)
fi
if [ -n "$PHP_FPM_SVC" ]; then
systemctl enable "$PHP_FPM_SVC" 2>/dev/null || true
systemctl restart "$PHP_FPM_SVC" 2>/dev/null || true
fi
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
# ADPanel privileged job: fully disable and remove MongoDB.
# Invoked via adpanel-priv: adpanel-priv job mongodb-disable [listen-port]
#
# Failure policy: every critical step (service stop, package purge, config and
# data removal) emits an ADP_MONGO_DISABLE_FAIL marker on stderr and sets
# FAILED=1. The script NEVER exits early — later cleanup still runs — and it
# stays idempotent: already-clean states (stopped service, purged packages,
# absent files) count as success, so a re-run after a partial failure attempts
# every step again. The runner exits non-zero when FAILED=1 so the caller can
# refuse to wipe the panel's MongoDB bookkeeping while cleanup is incomplete.
set -u
export DEBIAN_FRONTEND=noninteractive
FAILED=0
fail() { echo "ADP_MONGO_DISABLE_FAIL: $*" >&2; FAILED=1; }
# --- stop the service (critical: a live mongod must not survive "disabled") ---
if ! systemctl stop mongod 2>/dev/null; then
# Tolerate an already-stopped or already-removed unit (idempotent re-run);
# only a unit that is still active after the stop attempt is a failure.
if systemctl is-active mongod >/dev/null 2>&1; then
fail "could not stop the mongod service"
fi
fi
systemctl disable mongod 2>/dev/null
if systemctl is-enabled mongod >/dev/null 2>&1; then
fail "could not disable the mongod service (boot start still enabled)"
fi
pkill -9 -x mongod 2>/dev/null
sleep 1
if pgrep -x mongod >/dev/null 2>&1; then
fail "a mongod process is still running"
fi
# --- purge packages (critical; only purge what is actually installed so
# re-runs after a successful purge stay green) ---
PURGE_PKGS=""
for pkg in mongodb-org mongodb-org-server mongodb-org-mongos mongodb-org-shell mongodb-org-tools mongodb-mongosh; do
if dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "installed"; then
PURGE_PKGS="$PURGE_PKGS $pkg"
fi
done
if [ -n "$PURGE_PKGS" ]; then
apt-get purge -y $PURGE_PKGS 2>/dev/null || fail "apt-get purge failed for:$PURGE_PKGS"
fi
apt-get autoremove -y 2>/dev/null || true
# --- remove data, logs and config (critical) ---
rm -rf /var/lib/mongodb /var/log/mongodb 2>/dev/null
if [ -e /var/lib/mongodb ] || [ -e /var/log/mongodb ]; then
fail "MongoDB data/log directories could not be removed"
fi
rm -f /etc/mongod.conf 2>/dev/null
if [ -e /etc/mongod.conf ]; then
fail "/etc/mongod.conf could not be removed"
fi
# Best-effort leftovers only: stale sockets, apt sources, keyrings, indexes.
rm -f /tmp/mongodb-*.sock 2>/dev/null || true
rm -f /etc/apt/sources.list.d/mongodb*.list 2>/dev/null || true
rm -f /usr/share/keyrings/mongodb*.gpg 2>/dev/null || true
apt-get update 2>/dev/null || true
systemctl daemon-reload 2>/dev/null || true
# Optional: remove the firewall rule for the former MongoDB port.
PORT="${1:-}"
if [ -n "$PORT" ] && [ "$PORT" = "${PORT//[!0-9]/}" ] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ]; then
ufw delete allow "${PORT}/tcp" 2>/dev/null || true
iptables -D INPUT -p tcp --dport "$PORT" -j ACCEPT 2>/dev/null || true
fi
if [ "$FAILED" -ne 0 ]; then
echo "ADP_MONGO_DISABLE_FAIL: one or more critical cleanup steps failed" >&2
exit 1
fi
exit 0
+361
View File
@@ -0,0 +1,361 @@
#!/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/<pid>/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 <<PROVISION
CREATE USER IF NOT EXISTS '$ADMIN_USER'@'$ADMIN_HOST' IDENTIFIED BY '$ADMIN_PASSWORD';
ALTER USER '$ADMIN_USER'@'$ADMIN_HOST' IDENTIFIED BY '$ADMIN_PASSWORD';
REVOKE ALL PRIVILEGES, GRANT OPTION FROM '$ADMIN_USER'@'$ADMIN_HOST';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON *.* TO '$ADMIN_USER'@'$ADMIN_HOST' WITH GRANT OPTION;
GRANT CREATE USER ON *.* TO '$ADMIN_USER'@'$ADMIN_HOST' WITH GRANT OPTION;
PROVISION
[ $? -eq 0 ] || die "provisioning the dedicated admin account failed"
# --- certify the dedicated account with a full canary -------------------------
# Every statement class the panel's database-management SQL relies on. The
# canary database is created by the root channel; everything else runs AS the
# dedicated account through the socket, exactly like the panel's own channel.
run_capable_client -e "CREATE DATABASE IF NOT EXISTS \`$CANARY_DB\`" 2>/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
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env bash
# ADPanel privileged job: MySQL/MariaDB admin reset via skip-grant-tables.
# Invoked via adpanel-priv: adpanel-priv job mysql-skip-grant
# stdin: SQL statements to execute as root once the server is in
# skip-grant-tables mode.
set -u
SQL="$(cat)"
[ -n "$SQL" ] || { echo "mysql-skip-grant: no SQL on stdin" >&2; exit 2; }
SOCK_DIR="/var/run/mysqld"
SOCK_PATH="$SOCK_DIR/mysqld.sock"
# Detect service name (mariadb, mysql or mysqld)
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
if [ -z "$SVC" ]; then
echo "ERROR: Could not detect MySQL/MariaDB service name" >&2
exit 1
fi
# Detect the server binary (mariadbd or mysqld)
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
if [ -z "$SERVER_BIN" ]; then
echo "ERROR: Could not find mariadbd or mysqld binary" >&2
exit 1
fi
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
mkdir -p "$SOCK_DIR"
chown mysql:mysql "$SOCK_DIR" 2>/dev/null || true
chmod 755 "$SOCK_DIR"
rm -f "$SOCK_PATH" 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 mysql --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
echo "ERROR: skip-grant-tables server did not become ready" >&2
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
exit 1
fi
{ echo "FLUSH PRIVILEGES;"; printf '%s\n' "$SQL"; } | mysql --socket="$SOCK_PATH" -u root
SQL_EXIT=$?
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
exit "$SQL_EXIT"
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
# ADPanel privileged job: fully disable and remove pgAdmin4 + PostgreSQL.
# Invoked via adpanel-priv: adpanel-priv job pgadmin-disable [listen-port]
set -u
export DEBIAN_FRONTEND=noninteractive
systemctl stop postgresql 2>/dev/null || true
systemctl disable postgresql 2>/dev/null || true
pkill -9 -x postgres 2>/dev/null || true
# Remove the ADPanel-managed remote-bind pg_hba.conf rules installed by
# pg-add-hba (marker-delimited block) plus any legacy untagged allow lines
# from older panel versions. Only those lines are removed; PostgreSQL
# packages and data are deliberately NOT purged here — the panel's database
# management feature (type=postgresql) can reuse the same instance and a
# purge would destroy user databases.
# pg_hba.conf lives at /etc/postgresql/<version>/<cluster>/pg_hba.conf on
# Debian — the same recursive layout pg-add-hba writes to — so locate the
# files the same way instead of a single-level glob.
while IFS= read -r hba; do
[ -f "$hba" ] || continue
sed -i \
-e '/^# BEGIN ADPanel-managed remote-bind rules (added by adpanel-priv pg-add-hba)$/,/^# END ADPanel-managed remote-bind rules$/d' \
-e '/^host all all 0\.0\.0\.0\/0 scram-sha-256$/d' \
-e '/^host all all ::0\/0 scram-sha-256$/d' \
"$hba" 2>/dev/null || true
done < <(find /etc/postgresql -name pg_hba.conf 2>/dev/null)
# Only if PostgreSQL is somehow still active (it was just stopped above),
# reload so the removed rules take effect; otherwise leave the on-disk
# config clean for the next start.
if systemctl is-active --quiet postgresql 2>/dev/null; then
systemctl reload postgresql 2>/dev/null || true
fi
systemctl stop apache2 2>/dev/null || true
systemctl disable apache2 2>/dev/null || true
pkill -9 -x apache2 2>/dev/null || true
rm -f /etc/apache2/sites-enabled/pgadmin4.conf 2>/dev/null || true
rm -f /etc/apache2/sites-available/pgadmin4.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true
rm -f /etc/apache2/conf-available/pgadmin4.conf 2>/dev/null || true
# Remove Listen 5050 from ports.conf (clean slate for reinstall); if no
# listener remains, leave a placeholder comment (nginx owns port 80).
sed -i '/Listen 5050/d' /etc/apache2/ports.conf 2>/dev/null || true
if ! grep -q '^Listen' /etc/apache2/ports.conf 2>/dev/null; then
echo '# Apache ports - no active listeners (nginx handles web traffic)' > /etc/apache2/ports.conf
fi
# Placeholder keeps nginx include lines valid without serving pgAdmin.
echo '# pgAdmin4 disabled - placeholder to prevent nginx include errors' > /etc/nginx/snippets/pgadmin4.conf 2>/dev/null || true
for conf in /etc/nginx/sites-available/*.conf /etc/nginx/sites-enabled/*.conf /etc/nginx/conf.d/*.conf; do
if [ -f "$conf" ]; then
sed -i '/include.*pgadmin4.conf/d' "$conf" 2>/dev/null || true
fi
done
nginx -t 2>/dev/null && systemctl reload nginx 2>/dev/null || true
apt-get remove --purge -y pgadmin4-web pgadmin4-desktop pgadmin4 2>/dev/null || true
apt-get autoremove -y 2>/dev/null || true
rm -rf /var/lib/pgadmin /var/log/pgadmin /etc/pgadmin /usr/pgadmin4 2>/dev/null || true
rm -f /etc/apt/sources.list.d/pgadmin4.list 2>/dev/null || true
rm -f /usr/share/keyrings/packages-pgadmin-org.gpg 2>/dev/null || true
apt-get update -qq 2>/dev/null || true
# Optional: remove the firewall rule for the former PostgreSQL port.
PORT="${1:-}"
if [ -n "$PORT" ] && [ "$PORT" = "${PORT//[!0-9]/}" ] && [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ]; then
ufw delete allow "${PORT}/tcp" 2>/dev/null || true
iptables -D INPUT -p tcp --dport "$PORT" -j ACCEPT 2>/dev/null || true
fi
true
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
# ADPanel privileged job: prepare the pgAdmin Apache backend (localhost:5050).
# Invoked via adpanel-priv: adpanel-priv job pgadmin-prepare
# stdin: base64-encoded Apache VirtualHost configuration for pgAdmin4.
set -u
CONF_B64="$(cat)"
[ -n "$CONF_B64" ] || { echo "pgadmin-prepare: missing config payload" >&2; exit 2; }
systemctl daemon-reload 2>/dev/null || true
systemctl start postgresql 2>/dev/null || true
mkdir -p /etc/apache2/sites-available /etc/apache2/sites-enabled
printf %s "$CONF_B64" | base64 -d > /etc/apache2/sites-available/pgadmin4.conf
chmod 0644 /etc/apache2/sites-available/pgadmin4.conf
ln -sf /etc/apache2/sites-available/pgadmin4.conf /etc/apache2/sites-enabled/pgadmin4.conf
rm -f /etc/apache2/sites-enabled/000-default.conf 2>/dev/null || true
rm -f /etc/apache2/sites-enabled/default-ssl.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/phpmyadmin.conf 2>/dev/null || true
rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true
cat > /etc/apache2/ports.conf <<'EOF'
# Apache ports configuration - managed by ADPanel
Listen 127.0.0.1:5050
EOF
a2enmod wsgi >/dev/null 2>&1 || true
a2enmod headers >/dev/null 2>&1 || true
apache2ctl -t >/dev/null 2>&1 || true
systemctl restart apache2 2>/dev/null || systemctl start apache2 2>/dev/null || true
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
# ADPanel privileged job: re-run pgAdmin setup-web.sh to (re)create the
# initial admin account, then restart Apache.
# Invoked via adpanel-priv: adpanel-priv job pgadmin-setup-recover
# Environment: PGADMIN_SETUP_EMAIL, PGADMIN_SETUP_PASSWORD
set -u
SETUP_SCRIPT=""
if [ -x /usr/pgadmin4/bin/setup-web.sh ]; then
SETUP_SCRIPT="/usr/pgadmin4/bin/setup-web.sh"
elif [ -x /usr/share/pgadmin4/bin/setup-web.sh ]; then
SETUP_SCRIPT="/usr/share/pgadmin4/bin/setup-web.sh"
fi
if [ -n "$SETUP_SCRIPT" ]; then
: "${PGADMIN_SETUP_EMAIL:?PGADMIN_SETUP_EMAIL not set}"
: "${PGADMIN_SETUP_PASSWORD:?PGADMIN_SETUP_PASSWORD not set}"
"$SETUP_SCRIPT" --yes >/dev/null 2>&1 || true
rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true
systemctl restart apache2 2>/dev/null || systemctl start apache2 2>/dev/null || true
fi
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# ADPanel privileged job: prepare the phpMyAdmin backend (PHP-FPM + nginx).
# Invoked via adpanel-priv: adpanel-priv job phpmyadmin-prepare
set -u
PHP_FPM_SVC=$(systemctl list-unit-files --type=service --no-legend | awk '{print $1}' | grep -E '^php[0-9.]+-fpm\.service$' | sort -rV | head -1)
if [ -n "$PHP_FPM_SVC" ]; then
systemctl enable "$PHP_FPM_SVC" 2>/dev/null || true
systemctl restart "$PHP_FPM_SVC" 2>/dev/null || true
fi
systemctl start nginx 2>/dev/null || true
nginx -t >/dev/null 2>&1 && systemctl reload nginx 2>/dev/null || systemctl restart nginx 2>/dev/null || true