mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-20 02:56:10 +00:00
fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants
The privileged-role check missed three ways a role can reach the database host from SQL. Before PostgreSQL 16 a member of a CREATEROLE role sets its role to it and grants itself pg_execute_server_program, since role attributes are not inherited but the grant checks the role in effect. A role granted EXECUTE on lo_export, lo_import, pg_read_file, pg_ls_dir and their siblings reads or writes server files, and lo_export keeps the file after the transaction rolls back. From PostgreSQL 15 on a role can be granted ALTER SYSTEM on a setting or SET on a superuser-only one. PRIVILEGED_ROLE_SQL now counts all three. The parameter grants are read through query_to_xml inside a CASE taken only on 15 or later, because a statement naming pg_parameter_acl does not parse on 14. A SET grant on a setting every role may change anyway, and pg_monitor, stay ordinary. The lane test creates each kind of role and shows the escalation the check is for on the server it runs against.
This commit is contained in:
+1
-1
File diff suppressed because one or more lines are too long
@@ -10,6 +10,48 @@ import { REFUSAL } from '../../legacy-baseline';
|
||||
/** The PostgreSQL majors TREK supports and CI runs: the oldest and the newest. */
|
||||
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
|
||||
|
||||
/**
|
||||
* The `pg_catalog` functions that read, list or write files on the database
|
||||
* server, or move a large object to or from one. PostgreSQL revokes EXECUTE on
|
||||
* them from PUBLIC (since 11) instead of checking for a superuser, so a grant
|
||||
* of one hands that reach to an ordinary role. The `pg_file_*` ones are
|
||||
* adminpack's, which installs into `pg_catalog` where it exists at all. The
|
||||
* `pg_ls_*dir` functions `pg_monitor` holds only list fixed directories and
|
||||
* are not counted.
|
||||
*/
|
||||
const SERVER_FILE_FUNCTIONS = [
|
||||
'lo_import',
|
||||
'lo_export',
|
||||
'pg_read_file',
|
||||
'pg_read_binary_file',
|
||||
'pg_ls_dir',
|
||||
'pg_stat_file',
|
||||
'pg_file_write',
|
||||
'pg_file_rename',
|
||||
'pg_file_unlink',
|
||||
'pg_file_sync',
|
||||
];
|
||||
|
||||
/**
|
||||
* A privilege on a server setting that an ordinary role does not have:
|
||||
* `ALTER SYSTEM` on any parameter (it rewrites `postgresql.auto.conf`, where
|
||||
* `archive_command` or a preload library runs on the host), or `SET` on one
|
||||
* that only a superuser may set (`lo_compat_privileges` turns off the large
|
||||
* object checks). A grant to PUBLIC counts, and so does one on a parameter
|
||||
* this server does not know yet. `pg_parameter_acl` exists from PostgreSQL 15
|
||||
* on, and a statement naming it does not even parse on 14, so the query runs
|
||||
* through `query_to_xml` and only on 15 or later; it answers an empty string
|
||||
* when no row matches.
|
||||
*/
|
||||
const PARAMETER_GRANT_SQL =
|
||||
'select 1 from pg_catalog.pg_parameter_acl a, aclexplode(a.paracl) e' +
|
||||
" where (e.privilege_type = 'ALTER SYSTEM'" +
|
||||
" or coalesce((select s.context from pg_catalog.pg_settings s where s.name = a.parname), 'superuser') <> 'user')" +
|
||||
" and case when e.grantee = 0 then true else pg_has_role(current_user, e.grantee, 'MEMBER') end limit 1";
|
||||
|
||||
/** `text` as a SQL string literal. */
|
||||
const literal = (text: string) => `'${text.replaceAll("'", "''")}'`;
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -20,25 +62,42 @@ const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
|
||||
* - 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.
|
||||
* - EXECUTE on one of {@link SERVER_FILE_FUNCTIONS} (`lo_export` writes a
|
||||
* server file and keeps it after its transaction rolled back);
|
||||
* - from PostgreSQL 15 on, a privilege on a server setting an ordinary role
|
||||
* lacks ({@link PARAMETER_GRANT_SQL});
|
||||
* - before PostgreSQL 16, membership in a role with CREATEROLE, its own
|
||||
* included: such a role may grant itself any role that is not a superuser,
|
||||
* those predefined roles included, and a member may `SET ROLE` to it first,
|
||||
* since role attributes are not inherited but the grant checks the role in
|
||||
* effect. 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.
|
||||
* that can neither may still be one that can grant itself the rest. The
|
||||
* version-gated parts sit in CASE, whose branches PostgreSQL evaluates only
|
||||
* when taken.
|
||||
*/
|
||||
export const PRIVILEGED_ROLE_SQL =
|
||||
"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_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))';
|
||||
" or exists (select 1 from pg_proc p where p.pronamespace = 'pg_catalog'::regnamespace" +
|
||||
` and p.proname in (${SERVER_FILE_FUNCTIONS.map(literal).join(', ')})` +
|
||||
" and has_function_privilege(current_user, p.oid, 'EXECUTE'))" +
|
||||
" or (case when current_setting('server_version_num')::int >= 150000" +
|
||||
` then query_to_xml(${literal(PARAMETER_GRANT_SQL)}, false, true, '')::text <> '' else false end)` +
|
||||
" or (case when current_setting('server_version_num')::int < 160000" +
|
||||
" then exists (select 1 from pg_roles r where r.rolcreaterole and pg_has_role(current_user, r.oid, 'MEMBER'))" +
|
||||
' else false end)';
|
||||
|
||||
/** 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';
|
||||
'database server (through a predefined role or a granted server file function such as lo_export), a role ' +
|
||||
'granted ALTER SYSTEM or a superuser-only setting (PostgreSQL 15 and later), or (before PostgreSQL 16) a ' +
|
||||
'member of 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 {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* PGROLE-001..003 — the check that refuses a restore (and warns at boot) for a
|
||||
* PGROLE-001..006 — 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
|
||||
@@ -15,7 +15,18 @@ 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'];
|
||||
|
||||
/**
|
||||
* Drops every role this suite created, whatever it was granted. DROP OWNED
|
||||
* revokes what a role holds in this database and on shared objects, its
|
||||
* function and parameter grants included, which DROP ROLE alone refuses to
|
||||
* leave behind.
|
||||
*/
|
||||
const DROP_ROLES =
|
||||
'do $drop$ declare name text; begin' +
|
||||
` for name in select rolname from pg_roles where left(rolname, ${PREFIX.length}) = '${PREFIX}' loop` +
|
||||
" execute format('drop owned by %I', name); execute format('drop role %I', name);" +
|
||||
' end loop; end $drop$';
|
||||
|
||||
/** The statements run as the admin, one after the other on its one connection. */
|
||||
function asAdmin(statements: string[]): Promise<unknown[]> {
|
||||
@@ -38,7 +49,7 @@ async function privileged(name: string): Promise<boolean> {
|
||||
let major = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`));
|
||||
await asAdmin([DROP_ROLES]);
|
||||
await asAdmin([
|
||||
`create role ${role('plain')} nologin`,
|
||||
`create role ${role('super')} nologin superuser`,
|
||||
@@ -52,15 +63,44 @@ beforeAll(async () => {
|
||||
`grant pg_write_server_files to ${role('writer')}`,
|
||||
`create role ${role('creator')} nologin createrole`,
|
||||
`create role ${role('granter')} nologin createrole`,
|
||||
// A login role that holds no CREATEROLE itself but belongs to a group that does.
|
||||
`create role ${role('admins')} nologin createrole`,
|
||||
`create role ${role('in_admins')} nologin in role ${role('admins')}`,
|
||||
// Server file functions, granted one by one as a DBA would for a maintenance tool.
|
||||
`create role ${role('lo_export')} nologin`,
|
||||
`grant execute on function lo_export(oid, text) to ${role('lo_export')}`,
|
||||
`create role ${role('lo_import')} nologin`,
|
||||
`grant execute on function lo_import(text) to ${role('lo_import')}`,
|
||||
`create role ${role('read_file')} nologin`,
|
||||
`grant execute on function pg_read_file(text) to ${role('read_file')}`,
|
||||
`create role ${role('ls_dir')} nologin`,
|
||||
`grant execute on function pg_ls_dir(text) to ${role('ls_dir')}`,
|
||||
// pg_monitor lists fixed directories only, and stays an ordinary role.
|
||||
`create role ${role('monitor')} nologin`,
|
||||
`grant pg_monitor to ${role('monitor')}`,
|
||||
`create role ${role('set_suset')} nologin`,
|
||||
`create role ${role('alter_system')} nologin`,
|
||||
`create role ${role('set_userset')} nologin`,
|
||||
`create role ${role('setters')} nologin`,
|
||||
`create role ${role('in_setters')} nologin in role ${role('setters')}`,
|
||||
]);
|
||||
const [rows] = (await asAdmin(["select current_setting('server_version_num')::int / 10000 as major"])) as Array<
|
||||
Array<{ major: number }>
|
||||
>;
|
||||
major = rows[0].major;
|
||||
// Privileges on parameters exist from PostgreSQL 15 on; the statements do not parse before.
|
||||
if (major >= 15) {
|
||||
await asAdmin([
|
||||
`grant set on parameter lo_compat_privileges to ${role('set_suset')}`,
|
||||
`grant alter system on parameter archive_command to ${role('alter_system')}`,
|
||||
`grant set on parameter work_mem to ${role('set_userset')}`,
|
||||
`grant set on parameter log_statement to ${role('setters')}`,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await asAdmin(ROLES.map((name) => `drop role if exists ${role(name)}`));
|
||||
await asAdmin([DROP_ROLES]);
|
||||
});
|
||||
|
||||
describe('the privileged-role check', () => {
|
||||
@@ -106,4 +146,50 @@ describe('the privileged-role check', () => {
|
||||
if (major < 16) await expect(grant).resolves.toBeUndefined();
|
||||
else await expect(grant).rejects.toThrow(/permission denied|must have admin option/);
|
||||
});
|
||||
|
||||
it('PGROLE-004: refuses before PostgreSQL 16 a role that is only a member of a CREATEROLE role, and not from 16 on', async () => {
|
||||
const [states] = (await asAdmin([
|
||||
`select rolcreaterole from pg_roles where rolname = '${role('in_admins')}'`,
|
||||
])) as Array<Array<{ rolcreaterole: boolean }>>;
|
||||
expect(states[0].rolcreaterole).toBe(false);
|
||||
expect(await privileged('in_admins')).toBe(major < 16);
|
||||
// The reason: the member sets its role to the group and grants itself what reaches the host.
|
||||
const grant = withAdmin(adminUrl, async (run) => {
|
||||
await run(`set role ${role('in_admins')}`);
|
||||
try {
|
||||
await run(`set role ${role('admins')}`);
|
||||
await run(`grant pg_execute_server_program to ${role('in_admins')}`);
|
||||
} 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/);
|
||||
});
|
||||
|
||||
it('PGROLE-005: refuses a role granted a server file function, and passes pg_monitor', async () => {
|
||||
expect(await privileged('lo_export')).toBe(true);
|
||||
expect(await privileged('lo_import')).toBe(true);
|
||||
expect(await privileged('read_file')).toBe(true);
|
||||
expect(await privileged('ls_dir')).toBe(true);
|
||||
expect(await privileged('monitor')).toBe(false);
|
||||
// The reason, as this server answers it: the grant alone lets the role read the host's file system.
|
||||
const listed = await withAdmin(adminUrl, async (run) => {
|
||||
await run(`set role ${role('ls_dir')}`);
|
||||
try {
|
||||
return await run<{ name: string }>("select pg_ls_dir('.') as name");
|
||||
} finally {
|
||||
await run('reset role');
|
||||
}
|
||||
});
|
||||
expect(listed.map((row) => row.name)).toContain('PG_VERSION');
|
||||
});
|
||||
|
||||
it('PGROLE-006: refuses from PostgreSQL 15 on a role granted ALTER SYSTEM or a superuser-only setting, directly or through a group', async () => {
|
||||
expect(await privileged('set_suset')).toBe(major >= 15);
|
||||
expect(await privileged('alter_system')).toBe(major >= 15);
|
||||
expect(await privileged('in_setters')).toBe(major >= 15);
|
||||
// SET on a setting every role may set anyway gives nothing.
|
||||
expect(await privileged('set_userset')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ Postgres does not make TREK scale out. TREK still runs as one process. See [Limi
|
||||
|
||||
- **PostgreSQL 14 to 18.** TREK refuses to start on any other server version, before it writes anything.
|
||||
- **An empty database dedicated to TREK.** TREK creates its schema in an empty database. It refuses a database that holds tables it did not create, and a restore replaces everything in the schema it loads into. Do not share the database with another application.
|
||||
- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a role that could reach the database server from SQL (a superuser, a member of a superuser role, a role that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, and on PostgreSQL 14 and 15 a role with CREATEROLE), and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
|
||||
- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a role that could reach the database server from SQL (a superuser, a member of a superuser role, a role that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files` or may run a server file function such as `lo_export` or `pg_read_file`, from PostgreSQL 15 on a role granted ALTER SYSTEM or a superuser-only setting, and on PostgreSQL 14 and 15 a role with CREATEROLE or a member of one), and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
|
||||
- **ICU support in the server.** The schema creates the collation `nocase` with `provider = icu`, so the server must be built with ICU. The official `postgres` images include it.
|
||||
- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 18 client, which works with every supported server. A client works with servers up to its own major version, so a client outside the image must be at least as new as the server; TREK refuses an older one with a message that names both versions. See [Configuration](#configuration).
|
||||
- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19.
|
||||
@@ -78,7 +78,7 @@ CREATE DATABASE trek OWNER trek;
|
||||
ALTER SCHEMA public OWNER TO trek;
|
||||
```
|
||||
|
||||
Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser or a member of one (`SET ROLE` would make it a superuser), that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, or, on PostgreSQL 14 and 15, that has CREATEROLE (there it may grant itself those roles). A crafted archive could use any of these to run commands on the database server or to read or write its files. TREK also logs a warning about such a role when it starts.
|
||||
Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser or a member of one (`SET ROLE` would make it a superuser), that holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, that may run a server file function (`lo_import`, `lo_export`, `pg_read_file`, `pg_read_binary_file`, `pg_ls_dir`, `pg_stat_file` or adminpack's `pg_file_*`), that was granted ALTER SYSTEM on any setting or SET on a superuser-only one (PostgreSQL 15 and later), or, on PostgreSQL 14 and 15, that has CREATEROLE or is a member of a role that has it (there it may grant itself those roles). A crafted archive could use any of these to run commands on the database server or to read or write its files. A member of `pg_monitor` is not refused. TREK also logs a warning about such a role when it starts.
|
||||
|
||||
TREK creates its tables in the role's current schema, normally `public`. A role whose `search_path` points at a schema of its own works too: TREK keeps its tables and its migration history there, and backups and restores cover that schema.
|
||||
|
||||
@@ -177,7 +177,7 @@ Restoring a backup on Postgres follows these rules:
|
||||
- **Plugin data is replaced with the archive's.** The same transaction drops every `trek_plugin_*` schema the role owns and loads the ones the dump holds, so a plugin installed after the backup loses its data, as it does on SQLite. Schemas the role does not own, and every other schema of the database, are never touched.
|
||||
- **TREK checks the archive before it replaces anything.** The archive must hold a Postgres dump, not a SQLite file. The dump must carry TREK's migration history, and it must not come from a newer TREK. TREK refuses the restore with a message saying which check failed.
|
||||
- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, and tools older than the server.
|
||||
- **The role must not be a superuser.** The restore refuses a role that is a superuser or a member of one, holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, or has CREATEROLE on PostgreSQL 14 or 15. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
|
||||
- **The role must not be a superuser.** The restore refuses a role that is a superuser or a member of one, holds `pg_execute_server_program`, `pg_read_server_files` or `pg_write_server_files`, may run a server file function, was granted ALTER SYSTEM or a superuser-only setting, or on PostgreSQL 14 or 15 has CREATEROLE or is a member of a role that has it. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
|
||||
- **The restore needs free space in the data directory.** `pg_restore` writes the dump out as a SQL script next to the unpacked archive before `psql` runs it, and the script is several times larger than the dump. It may grow to `BACKUP_MAX_DECOMPRESSED_MB` (5 GB by default); a larger one is stopped, nothing is replaced, and the work files are removed. Raise the limit for a genuine backup that needs more.
|
||||
|
||||
`RESTORE_FROM_BACKUP` works on Postgres too. On the first start, TREK loads the archive's dump into the database when that database holds no tables. An empty migration history with no other table beside it counts as no tables. When the database already has tables, the variable is ignored and TREK logs a warning. See [Backups: Restoring on a new install, before setup](Backups#restoring-on-a-new-install-before-setup).
|
||||
|
||||
Reference in New Issue
Block a user