Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,347 @@
|
||||
"use strict";
|
||||
|
||||
// Tests for the MySQL admin-channel hardening (phpMyAdmin setup ERROR 1044 +
|
||||
// root-access reduction) and the settings.js step-up challenge retry.
|
||||
//
|
||||
// Reproduced failure (the bug class this pins shut): the panel's admin
|
||||
// channel authenticated as 'root'@'localhost' via an auth-only probe
|
||||
// (`SELECT 1`), a legacy setup that adopted 'root' as its tracked database
|
||||
// administrator had demoted that very account (REVOKE ALL PRIVILEGES, GRANT
|
||||
// OPTION), and every account-management batch then aborted at its first
|
||||
// GRANT with:
|
||||
// ERROR 1044 (42000) at line 3: Access denied for user 'root'@'localhost'
|
||||
// to database 'phpmyadmin'
|
||||
// (the alphabetically first schema the per-database grant strategy may
|
||||
// touch). phpMyAdmin setup could never complete.
|
||||
//
|
||||
// Contracts locked here:
|
||||
// - the admin-channel probe checks CAPABILITY (Grant_priv/Create_user_priv
|
||||
// of the candidate's own mysql.user row), never authentication alone;
|
||||
// - the panel process prefers a dedicated least-privilege 'adpanel_admin'
|
||||
// account and NEVER probes MySQL root's password (MYSQL_PASSWORD);
|
||||
// - a demoted/absent admin state triggers the privileged
|
||||
// mysql-admin-bootstrap job (heal + provision + canary-certify), exactly
|
||||
// once per cooldown;
|
||||
// - the privileged runner's mysql-admin op capability-probes its methods;
|
||||
// - reserved server accounts (root, debian-sys-maint, adpanel_admin, ...)
|
||||
// can never be staged, re-passworded, dropped or torn down by panel
|
||||
// flows — including the legacy tracked-'root' re-setup exemption, which
|
||||
// must stay gone;
|
||||
// - account-statement batches carry no FLUSH PRIVILEGES (no RELOAD on the
|
||||
// admin channel);
|
||||
// - the phpMyAdmin control schema is protected from panel-issued users;
|
||||
// - the settings.js database request funnel opens the step-up modal and
|
||||
// retries once when the server challenges a stale client-side grace.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const net = require("node:net");
|
||||
const { once } = require("node:events");
|
||||
const mysql = require("mysql2/promise");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const indexSource = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
|
||||
const settingsSource = fs.readFileSync(path.join(ROOT, "public", "js", "settings.js"), "utf8");
|
||||
const privSource = fs.readFileSync(path.join(ROOT, "privileged", "adpanel-priv"), "utf8");
|
||||
const sudoersSource = fs.readFileSync(path.join(ROOT, "adpanel-sudoers"), "utf8");
|
||||
const priv = require("../utils/db-user-privileges");
|
||||
|
||||
// adpanel:mysql-auth-downgrade - a server-selected plugin must not disclose
|
||||
// the panel's database password over an unauthenticated plaintext transport.
|
||||
async function exerciseMysqlHandshake(switchToClearPassword) {
|
||||
const driverRoot = path.dirname(require.resolve("mysql2"));
|
||||
const packets = require(path.join(driverRoot, "lib", "packets", "index.js"));
|
||||
const flags = require(path.join(driverRoot, "lib", "constants", "client.js"));
|
||||
const password = "synthetic-review-password-not-a-real-credential";
|
||||
const sockets = new Set();
|
||||
let exposed = false;
|
||||
let connected = false;
|
||||
let connectionError;
|
||||
const server = net.createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => sockets.delete(socket));
|
||||
socket.on("error", () => {});
|
||||
const hello = new packets.Handshake({
|
||||
protocolVersion: 10, serverVersion: "8.0.0-review", connectionId: 1,
|
||||
capabilityFlags: flags.PROTOCOL_41 | flags.SECURE_CONNECTION | flags.PLUGIN_AUTH,
|
||||
characterSet: 45, statusFlags: 2,
|
||||
authPluginData1: Buffer.alloc(8, 0x41), authPluginData2: Buffer.alloc(12, 0x42),
|
||||
}).toPacket(0);
|
||||
hello.writeHeader(0);
|
||||
socket.write(hello.buffer);
|
||||
let buffered = Buffer.alloc(0);
|
||||
socket.on("data", (chunk) => {
|
||||
buffered = Buffer.concat([buffered, chunk]);
|
||||
while (buffered.length >= 4) {
|
||||
const size = buffered.readUIntLE(0, 3);
|
||||
if (buffered.length < size + 4) break;
|
||||
const sequence = buffered[3];
|
||||
const body = buffered.subarray(4, size + 4);
|
||||
buffered = buffered.subarray(size + 4);
|
||||
if (sequence === 1) {
|
||||
if (switchToClearPassword) {
|
||||
const request = new packets.AuthSwitchRequest({ pluginName: "mysql_clear_password", pluginData: Buffer.alloc(0) }).toPacket();
|
||||
request.writeHeader(2);
|
||||
socket.write(request.buffer);
|
||||
} else {
|
||||
socket.write(Buffer.from([7, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0]));
|
||||
}
|
||||
} else if (sequence === 3) {
|
||||
exposed = body.equals(Buffer.from(password + "\0"));
|
||||
socket.destroy();
|
||||
} else if (sequence === 0) {
|
||||
socket.end();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
const deadline = setTimeout(() => {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
}, 2000);
|
||||
try {
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const connection = await mysql.createConnection({ host: "127.0.0.1", port: server.address().port, user: "review-user", password, connectTimeout: 1500 });
|
||||
connected = true;
|
||||
await connection.end();
|
||||
} catch (error) {
|
||||
connectionError = error;
|
||||
} finally {
|
||||
clearTimeout(deadline);
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
return { exposed, connected, connectionError };
|
||||
}
|
||||
|
||||
test("MySQL handshake refuses plaintext credential disclosure on an insecure auth switch", async () => {
|
||||
const result = await exerciseMysqlHandshake(true);
|
||||
assert.strictEqual(result.exposed, false, "server-requested clear-password auth must never expose the credential on plaintext TCP");
|
||||
assert.strictEqual(result.connected, false, "the insecure handshake must be refused");
|
||||
assert.ok(result.connectionError, "refusal must surface as a connection error");
|
||||
});
|
||||
|
||||
test("MySQL handshake still accepts normal native-password authentication", async () => {
|
||||
const result = await exerciseMysqlHandshake(false);
|
||||
assert.strictEqual(result.connected, true, "normal MySQL authentication must remain compatible");
|
||||
assert.strictEqual(result.connectionError, undefined);
|
||||
assert.strictEqual(result.exposed, false);
|
||||
});
|
||||
|
||||
function stripComments(source) {
|
||||
return source
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
.split("\n")
|
||||
.map((line) => line.replace(/^\s*\/\/.*$/, ""))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function endIndexOfFunction(source, startMarker) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `marker ${startMarker} not found`);
|
||||
// The body's opening brace is the first `{` following the parameter list's
|
||||
// closing paren — a signature like `(service, options = {}) {` embeds a
|
||||
// brace pair that must not be taken for the body opener.
|
||||
const sigTail = source.slice(start);
|
||||
const bodyOpen = /\)\s*\{/.exec(sigTail);
|
||||
assert.ok(bodyOpen, `parameter list not found for ${startMarker}`);
|
||||
const bodyStart = start + bodyOpen.index + bodyOpen[0].indexOf("{");
|
||||
let depth = 0;
|
||||
for (let i = bodyStart; i < source.length; i += 1) {
|
||||
if (source[i] === "{") depth += 1;
|
||||
else if (source[i] === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) return i + 1;
|
||||
}
|
||||
}
|
||||
assert.fail(`unbalanced braces after marker ${startMarker}`);
|
||||
}
|
||||
|
||||
function extractFunction(source, name) {
|
||||
const start = source.indexOf(`function ${name}`);
|
||||
assert.ok(start !== -1, `function ${name} not found`);
|
||||
return source.slice(start, endIndexOfFunction(source, `function ${name}`));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. Capability-aware admin-channel probing (panel side)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("admin channel: probing checks capability (grant columns), not authentication alone", () => {
|
||||
const probeBody = stripComments(extractFunction(indexSource, "_probeMySqlAdminCapability"));
|
||||
assert.ok(
|
||||
indexSource.includes("MYSQL_ADMIN_CAPABILITY_PROBE_SQL") &&
|
||||
/Grant_priv='Y'/.test(indexSource) && /Create_user_priv='Y'/.test(indexSource),
|
||||
"the capability probe must query the candidate's Grant_priv/Create_user_priv columns"
|
||||
);
|
||||
assert.ok(
|
||||
probeBody.includes("MYSQL_ADMIN_CAPABILITY_PROBE_SQL") && probeBody.includes("'-N'"),
|
||||
"the probe must run the shared capability SQL in headerless batch mode"
|
||||
);
|
||||
// A FULLY demoted root cannot even read mysql.user: the probe then fails
|
||||
// with ERROR 1142/1044 ("command denied"), which must be classified as an
|
||||
// authenticated-but-incapable channel (triggering the heal), never as "no
|
||||
// auth" — otherwise the heal can never fire in the state it exists for.
|
||||
assert.ok(
|
||||
/ERROR 1142/.test(probeBody) && /command denied/.test(probeBody),
|
||||
"command-denied probe failures must classify as authenticated-but-incapable"
|
||||
);
|
||||
// The old auth-only probe must no longer be the admin gate: `SELECT 1` kept
|
||||
// passing for a demoted root whose GRANT batches failed with 1044.
|
||||
const getCmd = stripComments(extractFunction(indexSource, "getMySqlAdminCommand"));
|
||||
assert.ok(!/-e',\s*'SELECT 1'/.test(getCmd), "getMySqlAdminCommand must not probe with bare SELECT 1");
|
||||
});
|
||||
|
||||
test("admin channel: the dedicated least-privilege account is the primary channel", () => {
|
||||
const getCmd = stripComments(extractFunction(indexSource, "getMySqlAdminCommand"));
|
||||
assert.ok(getCmd.includes("getMySqlDedicatedAdminCredentials"), "the dedicated credential store must be consulted");
|
||||
assert.ok(getCmd.includes("MYSQL_DEDICATED_ADMIN_USER"), "the dedicated user must be referenced");
|
||||
// The panel PROCESS must never authenticate as MySQL root with a password:
|
||||
// root's env password (MYSQL_PASSWORD) is no longer probed, so the panel's
|
||||
// environment can no longer hold a usable MySQL root credential. (A panel
|
||||
// already running as the OS root user may use socket auth — that boundary
|
||||
// is out of scope here; root access stays behind the privileged runner for
|
||||
// every unprivileged installation.)
|
||||
assert.ok(!getCmd.includes("process.env.MYSQL_PASSWORD"), "the panel must not probe MySQL root with MYSQL_PASSWORD");
|
||||
assert.ok(getCmd.includes("privileged runner"), "the runner remains the privileged fallback for non-root panels");
|
||||
});
|
||||
|
||||
test("admin channel: a demoted (authenticated-but-incapable) state triggers the privileged bootstrap", () => {
|
||||
const getCmd = stripComments(extractFunction(indexSource, "getMySqlAdminCommand"));
|
||||
assert.ok(getCmd.includes("_ensureMySqlDedicatedAdmin"), "bootstrap orchestration must be wired into channel selection");
|
||||
assert.ok(getCmd.includes("sawAuthenticatedChannel"), "auth-but-not-capable channels must be tracked");
|
||||
const boot = stripComments(extractFunction(indexSource, "_ensureMySqlDedicatedAdmin"));
|
||||
assert.ok(boot.includes("mysql-admin-bootstrap"), "the bootstrap must run the privileged job");
|
||||
assert.ok(boot.includes("ADPANEL_DB_ADMIN_PASSWORD"), "the generated password must travel via sudoers env_keep");
|
||||
assert.ok(boot.includes("encryptWebhookSecret"), "the credential must be sealed at rest, never stored plaintext");
|
||||
assert.ok(boot.includes("MYSQL_ADMIN_BOOTSTRAP_COOLDOWN_MS"), "bootstrap attempts must be cooldown-limited");
|
||||
});
|
||||
|
||||
test("admin channel: 1044/1227 responses invalidate the cached channel", () => {
|
||||
const runnerBranch = indexSource.includes("stderr.includes('1044')");
|
||||
assert.ok(runnerBranch, "runMySqlAdmin must treat ERROR 1044 as a channel-invalidating failure");
|
||||
const directBody = stripComments(extractFunction(indexSource, "runMySqlAdmin"));
|
||||
assert.ok(
|
||||
directBody.includes("1045") && directBody.includes("1044") && directBody.includes("1227"),
|
||||
"auth (1045) and demotion (1044/1227) failures must both clear the cache"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2. Privileged runner + bootstrap job
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("privileged runner: mysql-admin op capability-probes its methods", () => {
|
||||
const opBody = stripComments(privSource.slice(privSource.indexOf("op_mysql_admin() {"), privSource.indexOf("op_mysql_admin() {") + 4000));
|
||||
assert.ok(opBody.includes("Grant_priv='Y'") && opBody.includes("Create_user_priv='Y'"), "runner probe must check grant columns");
|
||||
assert.ok(opBody.includes("no capable MySQL/MariaDB root auth method"), "the runner must fail closed without a capable channel");
|
||||
// argv hygiene contracts from argv-secret-exposure.test.js must survive.
|
||||
assert.ok(privSource.includes('MYSQL_PWD="$MYSQL_PASSWORD" mysql'), "probe must hand the password via MYSQL_PWD");
|
||||
assert.ok(privSource.includes('export MYSQL_PWD="$MYSQL_PASSWORD"'), "exec'd client must receive MYSQL_PWD");
|
||||
});
|
||||
|
||||
test("privileged bootstrap job: heals demoted root, provisions and certifies the dedicated account", () => {
|
||||
const jobPath = path.join(ROOT, "privileged", "jobs", "mysql-admin-bootstrap.sh");
|
||||
assert.ok(fs.existsSync(jobPath), "the bootstrap job must exist in the job catalog");
|
||||
const job = fs.readFileSync(jobPath, "utf8");
|
||||
assert.ok(job.includes("adpanel_admin"), "the job provisions the dedicated account");
|
||||
assert.ok(job.includes("--skip-grant-tables"), "the heal runs through skip-grant-tables");
|
||||
assert.ok(job.includes("GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION"),
|
||||
"MariaDB heal strategy: classic FLUSH+GRANT restore");
|
||||
assert.ok(job.includes("UPDATE mysql.user SET"), "MySQL heal strategy: direct grant-column restore");
|
||||
assert.ok(job.includes("GRANT CREATE USER ON *.*"), "the dedicated account holds CREATE USER (also authorizes DROP/ALTER USER)");
|
||||
assert.ok(job.includes("WITH GRANT OPTION"), "the dedicated account must be able to grant the panel privilege set");
|
||||
assert.ok(!/RELOAD|SUPER|FILE|SHUTDOWN/.test(job.replace(/^[#\s].*$/gm, "")) ||
|
||||
job.includes("canary"), "dangerous privileges must never appear in the grant batch");
|
||||
assert.ok(job.includes("DROP USER 'adpanel_admin_probe'@'localhost'"), "the canary must exercise DROP USER");
|
||||
assert.ok(job.includes("REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'adpanel_admin_probe'@'localhost'"),
|
||||
"the canary must exercise REVOKE ALL + GRANT OPTION");
|
||||
assert.ok(job.includes("die") && job.includes("canary_rc"), "a failed canary must fail the job (exit non-zero)");
|
||||
});
|
||||
|
||||
test("privileged bootstrap job: password validation and sudoers env_keep", () => {
|
||||
const job = fs.readFileSync(path.join(ROOT, "privileged", "jobs", "mysql-admin-bootstrap.sh"), "utf8");
|
||||
assert.ok(job.includes("ADPANEL_DB_ADMIN_PASSWORD must be lowercase hex"), "the job validates the password charset");
|
||||
assert.ok(sudoersSource.includes("ADPANEL_DB_ADMIN_PASSWORD"), "sudoers env_keep must pass the bootstrap password");
|
||||
// The env_keep line must not have been widened beyond the allowlist form.
|
||||
assert.ok(/env_keep \+= "DEBIAN_FRONTEND MYSQL_PASSWORD PGADMIN_SETUP_EMAIL PGADMIN_SETUP_PASSWORD ADPANEL_DB_ADMIN_PASSWORD"/.test(sudoersSource),
|
||||
"env_keep stays a closed allowlist");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. Reserved-account immutability
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("reserved accounts: staging, password and drop helpers refuse them at the SQL layer", () => {
|
||||
for (const [fn, marker] of [
|
||||
["ensureMySqlSetupAccount", "Refusing to stage reserved MySQL account"],
|
||||
["setMySqlSetupAccountPasswords", "Refusing to set passwords on reserved MySQL account"],
|
||||
["rollbackMySqlSetupAccounts", "Refusing to roll back reserved MySQL account"],
|
||||
["updateMySqlUserPassword", "Refusing to update reserved MySQL account"],
|
||||
["deleteMySqlUser", "Refusing to drop reserved MySQL account"],
|
||||
["createMySqlUser", "reserved MySQL system account name"],
|
||||
]) {
|
||||
const body = stripComments(extractFunction(indexSource, fn));
|
||||
assert.ok(body.includes("mySqlAccountIsReserved"), `${fn} must gate reserved names`);
|
||||
assert.ok(body.includes(marker), `${fn} must log the refusal distinctly`);
|
||||
}
|
||||
});
|
||||
|
||||
test("reserved accounts: the tracked-'root' re-setup exemption stays gone", () => {
|
||||
const setupStart = indexSource.indexOf('app.post("/api/settings/database/setup"');
|
||||
assert.ok(setupStart !== -1, "setup route found");
|
||||
const setupBody = stripComments(indexSource.slice(setupStart, indexSource.indexOf('app.post("/api/settings/database/disable"')));
|
||||
assert.ok(setupBody.includes("mySqlAccountIsReserved(cleanUsername)"), "the route gates reserved names");
|
||||
// The old exemption let a legacy tracked-'root' entry back into the staging
|
||||
// flow whose REVOKE demoted root@localhost. Any remnant of that condition
|
||||
// is a regression.
|
||||
assert.ok(!setupBody.includes("previousConfig.users.some(u => String(u?.username || '').toLowerCase() === cleanUsername.toLowerCase())"),
|
||||
"the tracked-reserved-name exemption must not return");
|
||||
});
|
||||
|
||||
test("reserved accounts: teardown drops skip them with a warning instead of failing or deleting", () => {
|
||||
const dropBody = stripComments(extractFunction(indexSource, "dropRemovedDbAccounts"));
|
||||
assert.ok(dropBody.includes("mySqlAccountIsReserved(u.username)"), "MySQL reserved names are skipped");
|
||||
assert.ok(dropBody.includes("postgresRoleIsReserved(u.username)"), "PostgreSQL reserved names are skipped");
|
||||
assert.ok(dropBody.includes("was NOT dropped"), "the skip must surface a warning to the response");
|
||||
});
|
||||
|
||||
test("phpmyadmin control schema is protected from panel-issued users", () => {
|
||||
assert.ok(priv.MYSQL_SYSTEM_DATABASES.includes("phpmyadmin"), "phpmyadmin joins the protected schema list");
|
||||
const perDb = priv.buildMySqlPerDatabaseGrantsSql("alice", "%", ["web1", "phpmyadmin", "blog2"], "adpanel");
|
||||
assert.ok(perDb.includes("`web1`"), "ordinary schemas are granted");
|
||||
assert.ok(!perDb.includes("`phpmyadmin`"), "the phpmyadmin control schema is never granted");
|
||||
const global = priv.buildMySqlGlobalGrantSql("alice", "%", "adpanel");
|
||||
assert.ok(global.includes("REVOKE SELECT ON `phpmyadmin`.* FROM 'alice'@'%'"),
|
||||
"the global strategy fences phpmyadmin off per privilege (a blanket REVOKE ALL fails 1141 under partial_revokes)");
|
||||
assert.ok(priv.mySqlAccountIsReserved("adpanel_admin"), "the dedicated admin name is reserved for panel users");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. settings.js step-up challenge retry (2FA popup fix)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("settings.js: the database request funnel opens the step-up modal on a server challenge and retries once", () => {
|
||||
const funnel = stripComments(extractFunction(settingsSource, "fetchDbRequestWithTokenRetry"));
|
||||
assert.ok(funnel.includes("isDbStepUpChallengePayload"), "step-up challenges must be classified");
|
||||
const classifier = stripComments(extractFunction(settingsSource, "isDbStepUpChallengePayload"));
|
||||
assert.ok(classifier.includes("'2fa-required'") && classifier.includes("'password-required'"),
|
||||
"both challenge codes must be recognized");
|
||||
assert.ok(funnel.includes("applyRevokeSecurityFromPayload"),
|
||||
"the challenge payload (authoritative grace state) must be applied to un-poison the stale snapshot");
|
||||
assert.ok(/openDatabaseInstallVerificationModal\(/.test(funnel) && funnel.includes("force: true"),
|
||||
"the modal must open FORCED — the server's requirement outranks the stale local grace");
|
||||
assert.ok(funnel.includes("refreshDbActionTokens"), "one-time action tokens must be re-minted before the retry");
|
||||
// Exactly one retry: a second challenge response is returned untouched, so
|
||||
// the modal can never loop.
|
||||
const retryCount = (funnel.match(/await fetchCall\(\)/g) || []).length;
|
||||
assert.ok(retryCount <= 3, `the funnel must not retry unboundedly (found ${retryCount} fetch calls)`);
|
||||
});
|
||||
|
||||
test("settings.js: the install-verification modal honors forced presentation", () => {
|
||||
const modal = stripComments(extractFunction(settingsSource, "openDatabaseInstallVerificationModal"));
|
||||
assert.ok(modal.includes("options.force"), "the grace-skip must be bypassable with options.force");
|
||||
assert.ok(modal.includes("titleText"), "the challenge path can retitle the modal");
|
||||
});
|
||||
Reference in new issue
Block a user