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

+566
View File
@@ -0,0 +1,566 @@
// Privilege builders for panel-issued database users (audit finding 2.1).
//
// Security invariant, enforced centrally in this module:
// A credential the panel hands out through its UI must never carry
// server-wide administrative privilege. Panel users get read/write and
// schema-management rights on ONE database derived from their username
// (PostgreSQL, MongoDB), or — MySQL — on the existing databases excluding
// the panel's own schema and the system schemas, which no panel-issued
// credential may read, write or drop. The only account allowed to hold
// server-wide admin rights is the install-time administrator created by
// the database setup flows, whose credential is never re-shown by the UI.
//
// All builders are pure functions (no I/O, no side effects) so the
// regression harness (scripts/verify-db-user-privileges.js) can exercise
// them directly. Mirrors the layout of utils/db-bind-policy.js.
//
// Identifier rules are fail-closed: anything outside [A-Za-z0-9_-] (or the
// per-engine length cap) is rejected with null rather than sanitized, so a
// validation gap upstream can never smuggle quoting metacharacters into a
// privileged shell.
"use strict";
const USERNAME_PATTERN = /^[A-Za-z0-9_-]+$/;
const USERNAME_MAX = 64;
// PostgreSQL identifiers (roles AND databases) are limited to 63 bytes.
// MongoDB has no hard database-name limit but we keep names identical
// across engines for operational clarity.
const DB_NAME_MAX = 63;
const USER_DB_PREFIX = "user_";
// MongoDB roles that grant power beyond the holder's own data — on ANY
// database they are granted on. Sourced from the MongoDB built-in roles
// reference; anything not listed here is either a per-database data role
// (read, readWrite, dbAdmin on a non-admin db) or a signer/monitoring role
// the panel never grants.
const DANGEROUS_MONGO_ROLES_ANY_DB = [
"root",
"__system",
"clusterAdmin",
"clusterManager",
"clusterMonitor",
"hostManager",
"backup",
"restore",
"readAnyDatabase",
"writeAnyDatabase",
"readWriteAnyDatabase",
"dbAdminAnyDatabase",
"userAdminAnyDatabase",
];
// Roles that are dangerous only when granted ON the admin database (they
// would administer the server's users/admin data rather than the holder's
// own database).
const DANGEROUS_MONGO_ROLES_ON_ADMIN = ["userAdmin", "dbAdmin"];
function isValidPanelUsername(username) {
return (
typeof username === "string" &&
username.length >= 1 &&
username.length <= USERNAME_MAX &&
USERNAME_PATTERN.test(username)
);
}
// Deterministic per-user database name: "user_<username>", lowercased.
// If the name would exceed the 63-byte engine limit, the username is
// truncated and disambiguated with a short hash of the full name so two
// long usernames sharing a prefix can never be collapsed into the same
// database (which would break the isolation this module exists to enforce).
//
// Case-folding contract: the database name folds username case ("Bob" and
// "bob" both map to "user_bob"), so two panel usernames differing only by
// letter case share ONE per-user database — a per-user isolation break,
// because either account's credential (readWrite + dbAdmin on that db)
// could destroy the other's data. Provisioning endpoints MUST therefore
// enforce case-insensitive username uniqueness using the exported helper
// below (panelUsernameCaseCollides) before creating anything.
// Do NOT change this function's output: existing deployments' data lives
// in the folded names, and changing the mapping would orphan it.
function panelUserDatabaseName(username) {
if (!isValidPanelUsername(username)) return null;
const name = username.toLowerCase();
const candidate = USER_DB_PREFIX + name;
if (candidate.length <= DB_NAME_MAX) return candidate;
const crypto = require("crypto");
const hash = crypto.createHash("sha256").update(name).digest("hex").slice(0, 8);
// "user_" (5) + truncated name + "_" (1) + hash (8) must fit in 63 bytes.
const keep = DB_NAME_MAX - USER_DB_PREFIX.length - 1 - hash.length;
return USER_DB_PREFIX + name.slice(0, keep) + "_" + hash;
}
// True when `username` differs only by letter case from another entry in
// `existingUsernames`. panelUserDatabaseName folds case, so provisioning
// such a pair would point two panel users at ONE per-user database — a
// per-user isolation break (either credential could destroy the other's
// data). Exact duplicates are NOT reported here: callers handle the
// ordinary "already exists" case themselves.
function panelUsernameCaseCollides(username, existingUsernames) {
if (!isValidPanelUsername(username) || !Array.isArray(existingUsernames)) return false;
const lower = username.toLowerCase();
return existingUsernames.some((u) => typeof u === "string" && u !== username && u.toLowerCase() === lower);
}
// Least-privilege role set for a panel user: full data + schema rights on
// their own database only. dbAdmin (on their own db) lets the user create
// indexes, validate, compact and view server status for that db — the
// per-database equivalent of the DDL grants the MySQL path gives.
function mongoPanelUserRoles(username) {
const db = panelUserDatabaseName(username);
if (!db) return null;
return [
{ role: "readWrite", db },
{ role: "dbAdmin", db },
];
}
function mongoRoleIsDangerous(role) {
return Boolean(
role &&
typeof role === "object" &&
(DANGEROUS_MONGO_ROLES_ANY_DB.includes(role.role) ||
(role.db === "admin" && DANGEROUS_MONGO_ROLES_ON_ADMIN.includes(role.role)))
);
}
// mongosh --eval script that creates a panel user with scoped roles.
// Uses getSiblingDB('admin') rather than the `use` helper, which is not
// available in non-interactive eval in mongosh. Works in the legacy
// `mongo` shell as well, so one builder serves both code paths.
function buildMongoCreateUserEval(username, password) {
if (!isValidPanelUsername(username)) return null;
if (typeof password !== "string" || password.length < 1) return null;
const roles = mongoPanelUserRoles(username);
if (!roles) return null;
return (
"db.getSiblingDB('admin').createUser({user:" +
JSON.stringify(username) +
",pwd:" +
JSON.stringify(password) +
",roles:" +
JSON.stringify(roles) +
"})"
);
}
// mongosh --eval script that re-scopes an EXISTING panel user: grants the
// scoped roles first, then revokes exactly the dangerous {role, db} pairs
// the user currently holds (revoking with the pairs reported by getUser is
// exact — revoking a role on the wrong db is an error). Grant-before-revoke
// means a failure halfway through leaves the user with scoped access rather
// than none. Prints ADP_RESCOPE_OK on success.
function buildMongoRescopeEval(username) {
if (!isValidPanelUsername(username)) return null;
const scoped = mongoPanelUserRoles(username);
if (!scoped) return null;
const dangerousAny = JSON.stringify(DANGEROUS_MONGO_ROLES_ANY_DB);
const dangerousAdmin = JSON.stringify(DANGEROUS_MONGO_ROLES_ON_ADMIN);
return (
"(function(){var u=" + JSON.stringify(username) +
",scoped=" + JSON.stringify(scoped) +
",dangerousAny=" + dangerousAny +
",dangerousAdmin=" + dangerousAdmin +
";var adb=db.getSiblingDB('admin');" +
"var info=adb.getUser(u,{showPrivileges:false});" +
"if(!info){print('ADP_USER_MISSING');return;}" +
"var revoke=(info.roles||[]).filter(function(r){return (dangerousAny.indexOf(r.role)>=0)||(r.db==='admin'&&dangerousAdmin.indexOf(r.role)>=0);});" +
"adb.grantRolesToUser(u,scoped);" +
"if(revoke.length){adb.revokeRolesFromUser(u,revoke);}" +
"print('ADP_RESCOPE_OK');printjson(adb.getUser(u,{showPrivileges:false}).roles);})()"
);
}
// ---- PostgreSQL ------------------------------------------------------------
// Fail-closed identifier validation. Quoting alone would make almost any
// string a legal identifier; rejecting anything outside [A-Za-z0-9_-]
// keeps the builders safe even if an endpoint's own validation regresses.
// A leading dash is refused as well: "-name" is legal when quoted, but it
// is option-shaped and hazardous to any downstream tool that forgets to
// quote. Panel usernames may start with a dash at the API layer; for
// PostgreSQL provisioning such names now fail closed.
function pgQuoteIdent(name) {
if (
typeof name !== "string" ||
name.length < 1 ||
name.length > 63 ||
!/^[A-Za-z0-9_-]+$/.test(name) ||
name.startsWith("-")
) {
return null;
}
return '"' + name + '"';
}
// Single-quoted SQL literal body (caller adds the surrounding quotes):
// doubles embedded single quotes per SQL standard.
function pgLiteral(value) {
return String(value).replace(/'/g, "''");
}
// Dollar-quoted literal with a caller-supplied tag. Verifies the tag does
// not occur in the body (collision would terminate the literal early and
// splice arbitrary SQL).
function pgDollarQuoted(body, tag) {
if (!/^[A-Za-z0-9_]+$/.test(tag)) return null;
const text = String(body);
if (text.includes("$" + tag + "$")) return null;
return "$" + tag + "$" + text + "$" + tag + "$";
}
// Role flags for each panel-issued account type:
// - unified database-users panel accounts: no server-wide powers at all;
// their reach is the per-user database created alongside the role.
// - the pgAdmin bootstrap login: still no superuser/createrole, but
// CREATEDB because pgAdmin's "Create Database" feature is core to what
// the panel installs it for.
function buildPostgresCreateRoleSql(options) {
const { username, password, createdb = false } = options || {};
const ident = pgQuoteIdent(username);
if (!ident) return null;
if (typeof password !== "string" || password.length < 1) return null;
const tag = "adp_" + require("crypto").randomBytes(6).toString("hex");
const pwd = pgDollarQuoted(password, tag);
if (!pwd) return null;
const createdbFlag = createdb ? "CREATEDB" : "NOCREATEDB";
return (
"CREATE ROLE " + ident + " WITH LOGIN " + createdbFlag +
" NOSUPERUSER NOCREATEROLE PASSWORD " + pwd + ";"
);
}
// Self-healing ALTER for existing roles: drops server-wide flags even if
// the role was created by an older, over-granting panel version. NEVER
// raises flags — it only removes privilege.
function buildPostgresDeflagSql(username) {
const ident = pgQuoteIdent(username);
if (!ident) return null;
return "ALTER ROLE " + ident + " WITH NOSUPERUSER NOCREATEDB NOCREATEROLE;";
}
// CREATE DATABASE cannot run inside a transaction/DO block, so the
// existence check uses psql's \gexec: the SELECT emits the CREATE DATABASE
// statement as a result row only when the database is missing, and \gexec
// executes that row. Idempotent, race-free enough for panel provisioning,
// and safe to re-run by the migration.
function buildPostgresEnsureUserDatabaseSql(username) {
const ident = pgQuoteIdent(username);
const dbName = panelUserDatabaseName(username);
const dbIdent = dbName && pgQuoteIdent(dbName);
if (!ident || !dbIdent) return null;
return (
"SELECT 'CREATE DATABASE " + dbIdent + " OWNER " + ident + "'" +
" WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '" + pgLiteral(dbName) + "')\\gexec\n"
);
}
// Random dollar-quote tag absent from `conflict` (the password) and from
// `taken` (tags already chosen). Retries a few times, then fails closed —
// with 12 random hex chars per tag a collision is not a practical concern,
// but a hostile password must never be able to force a known tag.
function makeDollarQuoteTag(conflict, taken) {
for (let attempt = 0; attempt < 3; attempt++) {
const tag = "adp_" + require("crypto").randomBytes(6).toString("hex");
if (!conflict.includes(tag) && !(taken && taken.has(tag))) return tag;
}
return null;
}
// Full statement sequence the panel runs when provisioning a unified
// PostgreSQL user: create the role if missing, clamp flags, then ensure the
// per-user database exists and is owned by the role.
//
// Creation is CREATE-ONLY: when the role already exists the DO block raises
// ADP_PG_ROLE_ALREADY_EXISTS instead of resetting its password. An earlier
// version ran ALTER ROLE ... PASSWORD in the ELSE branch, which silently
// re-passworded ANY pre-existing role — including "postgres", the panel's
// own peer-auth superuser — and then demoted it, because existence was only
// ever checked against panel bookkeeping. With the marker raised, the
// provisioning batch must abort before the trailing statements run, so the
// psql channel it executes through sets ON_ERROR_STOP (op_psql_postgres);
// callers classify the marker as a 409-style refusal.
//
// Dollar-quote tags: the DO block and the embedded password literal each
// get their OWN random tag — sharing one tag would make the DO-body scan
// terminate at the password literal's opening tag and turn the remainder
// of the password into bare SQL. Tags are drawn so that neither occurs in
// the password (fail closed if that is somehow impossible).
function buildPostgresCreatePanelUserSql(options) {
const { username, password } = options || {};
const ident = pgQuoteIdent(username);
if (!ident) return null;
if (typeof password !== "string" || password.length < 1) return null;
const taken = new Set();
const tagPwd = makeDollarQuoteTag(password, taken);
if (!tagPwd) return null;
taken.add(tagPwd);
const tagDo = makeDollarQuoteTag(password, taken);
if (!tagDo) return null;
const pwdLit = "$" + tagPwd + "$" + password + "$" + tagPwd + "$";
const nameLit = pgLiteral(username);
const doBlock =
"DO $" + tagDo + "$\n" +
"BEGIN\n" +
" IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '" + nameLit + "') THEN\n" +
" CREATE ROLE " + ident + " WITH LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD " + pwdLit + ";\n" +
" ELSE\n" +
" RAISE EXCEPTION 'ADP_PG_ROLE_ALREADY_EXISTS: role " + ident + " already exists on the PostgreSQL server';\n" +
" END IF;\n" +
"END\n" +
"$" + tagDo + "$;\n";
const ensureDb = buildPostgresEnsureUserDatabaseSql(username);
if (!ensureDb) return null;
// No trailing flag clamp: the CREATE ROLE inside the DO block already
// emits the exact scoped flags, and a clamp after the RAISE would demote
// an existing role on any channel that ignored ON_ERROR_STOP.
return doBlock + ensureDb;
}
// Migration statement sequence for an existing role: clamp flags, and
// (unless withDatabase:false, used for the pgAdmin bootstrap whose
// fresh-install path creates no per-user database) ensure the per-user
// database exists. Does NOT steal ownership of databases the role did not
// create — only new per-user databases are created with the role as owner.
function buildPostgresRescopeSql(options) {
const { username, createdb = false, withDatabase = true } = options || {};
const ident = pgQuoteIdent(username);
if (!ident) return null;
const createdbFlag = createdb ? "CREATEDB" : "NOCREATEDB";
const ensureDb = withDatabase ? buildPostgresEnsureUserDatabaseSql(username) : "";
if (withDatabase && !ensureDb) return null;
return (
"ALTER ROLE " + ident + " WITH NOSUPERUSER " + createdbFlag + " NOCREATEROLE;\n" +
ensureDb
);
}
// ---- MySQL -------------------------------------------------------------------
// DML + schema-management privileges for panel-issued MySQL accounts. The
// admin-only privileges (SUPER, FILE, PROCESS, RELOAD, SHUTDOWN, GRANT
// OPTION, CREATE USER, replication and role management) are deliberately
// absent. index.js and the builders below share this constant so the granted
// set cannot drift between call sites.
const MYSQL_PANEL_USER_PRIVILEGES = [
"SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "DROP", "ALTER", "INDEX",
"CREATE TEMPORARY TABLES", "LOCK TABLES", "EXECUTE", "CREATE VIEW",
"SHOW VIEW", "CREATE ROUTINE", "ALTER ROUTINE", "EVENT", "TRIGGER",
];
// System schemas no panel-issued credential may touch. The panel's own
// database (password hashes, 2FA secrets, recovery codes, node tokens) is
// enforced separately through the panelDb parameter of the helpers below.
// `phpmyadmin` is phpMyAdmin's control/storage schema (created by
// dbconfig-common on packaged installs): panel users must never hold DML on
// it, both for isolation and because a GRANT on it was the first statement of
// every demoted-root failure batch.
const MYSQL_SYSTEM_DATABASES = [
"mysql",
"sys",
"information_schema",
"performance_schema",
"phpmyadmin",
];
// Accounts that exist (or are created) by the server, the OS packaging, or
// the panel's own admin channel — a panel-issued credential must never be
// able to take them over. Provisioning that runs CREATE USER / ALTER USER /
// REVOKE against one of these names would re-password and demote the very
// account the panel (or the OS) depends on: root and debian-sys-maint are
// BOTH panel admin-channel identities (unix socket / MYSQL_PWD /
// /etc/mysql/debian.cnf), so hijacking them bricks database management
// itself. Comparison is case-insensitive because MySQL matches user names
// case-insensitively ('ROOT'@'%' IS 'root'@'%'). Every other pre-existing
// account (app accounts, a phpMyAdmin controluser) is covered separately by
// the live-server pre-existence probe in the provisioning routes; this list
// exists because those names must be refused even on a server where the
// account does not exist yet.
const MYSQL_RESERVED_USERNAMES = [
"root",
"debian-sys-maint",
"mysql",
"mariadb",
"mysql.sys",
"mysql.session",
"mysql.infoschema",
"mysqlxsys",
"mariadb.sys",
"mariadb.session",
"mariadb.infoschema",
// The panel's own dedicated admin account (provisioned by the privileged
// mysql-admin-bootstrap job). No panel-issued credential may take its name:
// a panel user holding it would ride the admin channel's GRANT OPTION.
"adpanel_admin",
];
function mySqlAccountIsReserved(username) {
if (typeof username !== "string") return false;
return MYSQL_RESERVED_USERNAMES.includes(username.toLowerCase());
}
// PostgreSQL role names the panel must never issue or touch. "postgres" is
// the bootstrap superuser AND the identity of the panel's own psql channel
// (the privileged runner executes psql as the postgres OS user / peer auth),
// so re-passwording or flag-clamping it locks the panel out of PostgreSQL
// entirely. "public" is a pseudo-role and pg_* is reserved by the server
// itself (CREATE ROLE pg_x fails with "unacceptable role name") — refused
// here so provisioning produces a clear message instead of a SQL error.
const POSTGRES_RESERVED_ROLE_NAMES = ["postgres", "public"];
function postgresRoleIsReserved(username) {
if (typeof username !== "string") return false;
const lower = username.toLowerCase();
if (POSTGRES_RESERVED_ROLE_NAMES.includes(lower)) return true;
return lower.startsWith("pg_");
}
// MySQL account parts. Usernames follow the module-wide fail-closed rule;
// host parts legitimately include % wildcards, IPv6 colons and dots, so they
// get their own charset. Anything outside these charsets is rejected with
// null rather than quoted, because a quoting layer alone would make almost
// any string legal and only shifts the injection burden to the regex.
const MYSQL_HOST_PATTERN = /^[A-Za-z0-9._%:-]+$/;
const MYSQL_HOST_MAX = 255;
function mySqlHostIsValid(host) {
return (
typeof host === "string" &&
host.length >= 1 &&
host.length <= MYSQL_HOST_MAX &&
MYSQL_HOST_PATTERN.test(host)
);
}
// Database names: unquoted-identifier charset plus '-' (legal in backticks).
// The panel schema name comes from the environment, so it must survive the
// same fail-closed gate before it may be quoted into a REVOKE.
function mySqlDbNameIsValid(name) {
return (
typeof name === "string" &&
name.length >= 1 &&
name.length <= DB_NAME_MAX &&
/^[A-Za-z0-9_$-]+$/.test(name)
);
}
function mySqlAccountIsValid(username, host) {
return isValidPanelUsername(username) && mySqlHostIsValid(host);
}
// Case-insensitive by design: database-name case folding depends on the
// server's lower_case_table_names setting, so protection must never depend
// on the case in which a name was created.
function isProtectedMySQLDatabase(name, panelDb) {
if (typeof name !== "string" || !name) return false;
const lower = name.toLowerCase();
if (MYSQL_SYSTEM_DATABASES.includes(lower)) return true;
return typeof panelDb === "string" && panelDb !== "" && lower === panelDb.toLowerCase();
}
// Strategy for engines with @@partial_revokes=ON (MySQL >= 8.0): the DML/DDL
// grant stays global, and schema-level REVOKEs then fence off the panel
// database, phpMyAdmin's control schema and the mysql and sys privilege
// stores. With partial revokes a REVOKE on db.* against a holder of a global
// grant restricts that schema instead of erroring — BUT only per privilege:
// `REVOKE ALL PRIVILEGES ON db.*` expands ALL to the full static privilege
// set and fails with ER_NONEXISTING_GRANT (1141) for privileges the account
// does not hold. Because the mysql client aborts the batch at the first
// failed statement, that error left the account live with its fresh global
// grant and no fences at all. Revoking exactly the granted privilege set,
// per schema, restricts what the account actually holds.
// information_schema and performance_schema cannot be granted on and need no
// revoke; they hold no panel data.
function buildMySqlGlobalGrantSql(username, host, panelDb) {
if (!mySqlAccountIsValid(username, host)) return null;
if (!mySqlDbNameIsValid(panelDb)) return null;
const account = `'${username}'@'${host}'`;
const privs = MYSQL_PANEL_USER_PRIVILEGES.join(", ");
// De-duplicated case-insensitively (mirrors buildMySqlPerDatabaseGrantsSql):
// a panelDb misconfigured to a system schema would otherwise emit the same
// REVOKE twice, and the duplicate can raise ER_NONEXISTING_GRANT (1141)
// mid-batch after the global grant already ran.
const seen = new Set();
const fencedSchemas = [
panelDb,
...MYSQL_SYSTEM_DATABASES.filter((db) => db !== "information_schema" && db !== "performance_schema"),
].filter((schema) => {
const key = String(schema || "").toLowerCase();
if (!key || seen.has(key)) return false;
seen.add(key);
return true;
});
const statements = [`GRANT ${privs} ON *.* TO ${account};`];
for (const schema of fencedSchemas) {
if (!mySqlDbNameIsValid(schema)) continue;
for (const privilege of MYSQL_PANEL_USER_PRIVILEGES) {
statements.push(`REVOKE ${privilege} ON \`${schema}\`.* FROM ${account};`);
}
}
return statements.join("\n");
}
// Strategy for MariaDB / MySQL 5.7 / partial_revokes OFF: a global grant
// cannot be restricted, so the same privilege set is granted per database
// over the existing non-protected databases only. Databases that fail the
// identifier rules are skipped (not granted) rather than fatal — the user
// ends up with less access, never more. An empty result is a valid
// fail-closed outcome (the account exists but touches nothing).
function buildMySqlPerDatabaseGrantsSql(username, host, databases, panelDb) {
if (!mySqlAccountIsValid(username, host)) return null;
if (!mySqlDbNameIsValid(panelDb)) return null;
if (!Array.isArray(databases)) return null;
const account = `'${username}'@'${host}'`;
const privs = MYSQL_PANEL_USER_PRIVILEGES.join(", ");
const seen = new Set();
const statements = [];
for (const db of databases) {
if (!mySqlDbNameIsValid(db)) continue;
const key = db.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
if (isProtectedMySQLDatabase(db, panelDb)) continue;
statements.push(`GRANT ${privs} ON \`${db}\`.* TO ${account};`);
}
return statements.join("\n");
}
module.exports = {
USERNAME_MAX,
USER_DB_PREFIX,
DANGEROUS_MONGO_ROLES_ANY_DB,
DANGEROUS_MONGO_ROLES_ON_ADMIN,
isValidPanelUsername,
panelUserDatabaseName,
panelUsernameCaseCollides,
mongoPanelUserRoles,
mongoRoleIsDangerous,
buildMongoCreateUserEval,
buildMongoRescopeEval,
pgQuoteIdent,
pgLiteral,
pgDollarQuoted,
buildPostgresCreateRoleSql,
buildPostgresDeflagSql,
buildPostgresEnsureUserDatabaseSql,
buildPostgresCreatePanelUserSql,
buildPostgresRescopeSql,
MYSQL_PANEL_USER_PRIVILEGES,
MYSQL_SYSTEM_DATABASES,
MYSQL_RESERVED_USERNAMES,
POSTGRES_RESERVED_ROLE_NAMES,
mySqlHostIsValid,
mySqlDbNameIsValid,
mySqlAccountIsValid,
mySqlAccountIsReserved,
postgresRoleIsReserved,
isProtectedMySQLDatabase,
buildMySqlGlobalGrantSql,
buildMySqlPerDatabaseGrantsSql,
};