diff --git a/server/src/db/engine/postgres/pg-tools.ts b/server/src/db/engine/postgres/pg-tools.ts index db740a52d..1091768aa 100644 --- a/server/src/db/engine/postgres/pg-tools.ts +++ b/server/src/db/engine/postgres/pg-tools.ts @@ -3,7 +3,7 @@ import { CLEAR_SCHEMA_SQL, pluginSchemasSql } from './clear-schema'; import { pgConnectionEnv, PgOutputLimitError, refuseClientOlderThanServer, run, runToFile } from './pg-process'; import { isPluginSchemaName, PLUGIN_SCHEMA_PREFIX } from './plugin-schema'; import { refuseToolsWithoutRestrict } from './restore-safety'; -import { PRIVILEGED_ROLE_SQL, serverMajor } from './server-checks'; +import { PRIVILEGED_ROLE_DESCRIPTION, PRIVILEGED_ROLE_SQL, serverMajor } from './server-checks'; import fs from 'node:fs'; import os from 'node:os'; @@ -19,7 +19,7 @@ const RESTORE_SESSION_OPTIONS = '-c lock_timeout=60s -c client_min_messages=warn /** Why a restore refuses a role that could reach the database host (`PRIVILEGED_ROLE_SQL`). */ const PRIVILEGED_RESTORE_REFUSAL = - 'TREK_DB_URL connects as a superuser, or as a role that may run programs or write files on the database server. ' + + `TREK_DB_URL connects as ${PRIVILEGED_ROLE_DESCRIPTION}. ` + 'A backup archive is a SQL script that runs as this role, so a crafted one could take over the database host; ' + 'nothing was replaced. Connect TREK as a role that owns its database and is not a superuser ' + '(the wiki page "Database: Postgres" shows how).'; @@ -42,7 +42,7 @@ interface PgServer { pluginSchemas: string[]; /** The server's major version, which the client tools must reach. */ major: number; - /** Whether TREK's role could run programs or write files on the database host (`PRIVILEGED_ROLE_SQL`). */ + /** Whether TREK's role could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`). */ privileged: boolean; } @@ -176,7 +176,7 @@ async function writeRestoreScript( * other schema of the database is touched. Refused before anything is cleared: * * - client tools without the CVE-2025-8714 fix, or older than the server; - * - a role that could run programs or write files on the database host, + * - a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`), * since the script comes from an archive and runs as that role; * - a script past `maxScriptBytes` (BACKUP_MAX_DECOMPRESSED_MB): the dump is * compressed once more inside the archive, so its script is held to the diff --git a/server/src/db/engine/postgres/server-checks.ts b/server/src/db/engine/postgres/server-checks.ts index 00dd4e964..c297849c1 100644 --- a/server/src/db/engine/postgres/server-checks.ts +++ b/server/src/db/engine/postgres/server-checks.ts @@ -11,16 +11,34 @@ import { REFUSAL } from '../../legacy-baseline'; const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const; /** - * True when the current role is a superuser or may run programs or write - * files on the database server (the predefined roles - * `pg_execute_server_program` and `pg_write_server_files`, which a superuser - * holds implicitly). Such a role turns a restored archive, which is a SQL - * script, into a way onto the database host. + * True when the current role could reach the database host, or make itself + * able to, from SQL. A restored archive is a SQL script run as that role, so + * such a role turns a crafted archive into a way onto the host. It counts: + * + * - membership in any superuser role, its own included: `SET ROLE` to one is a + * superuser session, whatever the role's own `rolsuper` says; + * - membership in `pg_execute_server_program` (`COPY ... PROGRAM`), + * `pg_write_server_files` or `pg_read_server_files` (`COPY` to or from a + * server file), which a superuser holds implicitly; + * - CREATEROLE before PostgreSQL 16, where it may grant itself any role that + * is not a superuser, those predefined roles included. From 16 on it needs + * ADMIN OPTION on a role to grant it, which the checks above already see. + * + * `MEMBER` is membership whatever its INHERIT and SET options, since a member + * that can neither may still be one that can grant itself the rest. */ export const PRIVILEGED_ROLE_SQL = - 'coalesce((select r.rolsuper from pg_roles r where r.rolname = current_user), false)' + + "exists (select 1 from pg_roles r where r.rolsuper and pg_has_role(current_user, r.oid, 'MEMBER'))" + " or pg_has_role(current_user, 'pg_execute_server_program', 'MEMBER')" + - " or pg_has_role(current_user, 'pg_write_server_files', 'MEMBER')"; + " or pg_has_role(current_user, 'pg_write_server_files', 'MEMBER')" + + " or pg_has_role(current_user, 'pg_read_server_files', 'MEMBER')" + + " or (current_setting('server_version_num')::int < 160000" + + ' and coalesce((select r.rolcreaterole from pg_roles r where r.rolname = current_user), false))'; + +/** What {@link PRIVILEGED_ROLE_SQL} refuses, as the boot warning and the restore refusal say it. */ +export const PRIVILEGED_ROLE_DESCRIPTION = + 'a superuser or a member of a superuser role, a role that may run programs or read or write files on the ' + + 'database server, or (before PostgreSQL 16) a role with CREATEROLE, which may grant itself those'; /** The major version in `server_version_num` (`170011` is 17, `180001` is 18). Throws on anything else. */ export function serverMajor(versionNum: string | number | undefined): number { @@ -47,6 +65,6 @@ export function refuseUnsupportedServer(major: number): void { /** The boot warning for a privileged role (see {@link PRIVILEGED_ROLE_SQL}); a restore refuses such a role outright. */ export const PRIVILEGED_ROLE_WARNING = - 'TREK_DB_URL connects as a superuser, or as a role that may run programs or write files on the database server. ' + + `TREK_DB_URL connects as ${PRIVILEGED_ROLE_DESCRIPTION}. ` + 'Restores are refused for such a role. Connect TREK as a role that owns its database and is not a superuser ' + '(see the wiki page "Database: Postgres").'; diff --git a/server/tests/postgres/server-checks.test.ts b/server/tests/postgres/server-checks.test.ts new file mode 100644 index 000000000..5dba79ed2 --- /dev/null +++ b/server/tests/postgres/server-checks.test.ts @@ -0,0 +1,109 @@ +/** + * PGROLE-001..003 — the check that refuses a restore (and warns at boot) for a + * role that could reach the database host from SQL + * (src/db/engine/postgres/server-checks.ts), evaluated by the real server as + * each kind of role. Roles belong to the whole server, so this suite creates + * its own under one prefix and drops them again. TREK_TEST_DB_URL connects as + * a superuser, which `SET ROLE` lets act as each of them. + */ +import { PRIVILEGED_ROLE_SQL } from '../../src/db/engine/postgres/server-checks'; +import { oneByOne } from '../helpers/one-by-one'; +import { withAdmin } from './databases'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +const adminUrl = process.env.TREK_TEST_DB_URL as string; +const PREFIX = `trek_test_role_${process.pid}_`; +const role = (name: string) => `${PREFIX}${name}`; +const ROLES = ['plain', 'super', 'member', 'program', 'reader', 'writer', 'creator', 'granter']; + +/** The statements run as the admin, one after the other on its one connection. */ +function asAdmin(statements: string[]): Promise { + return withAdmin(adminUrl, (run) => oneByOne(statements, (sql) => run(sql))); +} + +/** Whether PRIVILEGED_ROLE_SQL holds for `name`, as the server evaluates it in a session acting as that role. */ +async function privileged(name: string): Promise { + return withAdmin(adminUrl, async (run) => { + await run(`set role ${role(name)}`); + try { + const [row] = await run<{ privileged: boolean }>(`select (${PRIVILEGED_ROLE_SQL}) as privileged`); + return row.privileged; + } finally { + await run('reset role'); + } + }); +} + +let major = 0; + +beforeAll(async () => { + await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`)); + await asAdmin([ + `create role ${role('plain')} nologin`, + `create role ${role('super')} nologin superuser`, + `create role ${role('member')} nologin nosuperuser`, + `grant ${role('super')} to ${role('member')}`, + `create role ${role('program')} nologin`, + `grant pg_execute_server_program to ${role('program')}`, + `create role ${role('reader')} nologin`, + `grant pg_read_server_files to ${role('reader')}`, + `create role ${role('writer')} nologin`, + `grant pg_write_server_files to ${role('writer')}`, + `create role ${role('creator')} nologin createrole`, + `create role ${role('granter')} nologin createrole`, + ]); + const [rows] = (await asAdmin(["select current_setting('server_version_num')::int / 10000 as major"])) as Array< + Array<{ major: number }> + >; + major = rows[0].major; +}); + +afterAll(async () => { + await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`)); +}); + +describe('the privileged-role check', () => { + it('PGROLE-001: passes a plain role, refuses a superuser and every role that reaches server programs or files', async () => { + expect(await privileged('plain')).toBe(false); + expect(await privileged('super')).toBe(true); + expect(await privileged('program')).toBe(true); + expect(await privileged('writer')).toBe(true); + expect(await privileged('reader')).toBe(true); + }); + + it('PGROLE-002: refuses a role that is no superuser itself but may SET ROLE to one', async () => { + const [states] = (await asAdmin([`select rolsuper from pg_roles where rolname = '${role('member')}'`])) as Array< + Array<{ rolsuper: boolean }> + >; + expect(states[0].rolsuper).toBe(false); + expect(await privileged('member')).toBe(true); + // What the check is for: from that role, SET ROLE gives a superuser session. + const superuser = await withAdmin(adminUrl, async (run) => { + await run(`set role ${role('member')}`); + try { + await run(`set role ${role('super')}`); + const [row] = await run<{ setting: string }>("select current_setting('is_superuser') as setting"); + return row.setting; + } finally { + await run('reset role'); + } + }); + expect(superuser).toBe('on'); + }); + + it('PGROLE-003: refuses CREATEROLE before PostgreSQL 16, where it may grant itself a predefined role, and not from 16 on', async () => { + expect(await privileged('creator')).toBe(major < 16); + // The reason, as this server answers it: such a role granting itself pg_execute_server_program. + const grant = withAdmin(adminUrl, async (run) => { + await run(`set role ${role('granter')}`); + try { + await run(`grant pg_execute_server_program to ${role('granter')}`); + } finally { + await run('reset role'); + } + }); + if (major < 16) await expect(grant).resolves.toBeUndefined(); + else await expect(grant).rejects.toThrow(/permission denied|must have admin option/); + }); +}); diff --git a/server/tests/unit/db/engine/postgres/pg-tools.test.ts b/server/tests/unit/db/engine/postgres/pg-tools.test.ts index 9fa9f758c..ce0165aef 100644 --- a/server/tests/unit/db/engine/postgres/pg-tools.test.ts +++ b/server/tests/unit/db/engine/postgres/pg-tools.test.ts @@ -270,10 +270,11 @@ describe('pg-tools', () => { snippets: [answersSchema('public', 'public', { privileged: true })], }); await expect(pgRestore(URL_WITH_SECRET, path.join(out, 'in.pgdump'), bin, LIMIT)).rejects.toThrow( - /connects as a superuser, or as a role that may run programs or write files on the database server/, + /connects as a superuser or a member of a superuser role, a role that may run programs or read or write files/, ); expect(existsSync(ran)).toBe(false); expect(readToolCall(psqlLog).args.join(' ')).toContain('pg_execute_server_program'); + expect(readToolCall(psqlLog).args.join(' ')).toContain('pg_read_server_files'); expect(readdirSync(out)).toEqual([]); });