Sub topic 8
Privileges and security for server-side file access
This chapter covers who may use server-side COPY against files, what that access exposes, and how to limit the risk. It assumes you can run COPY FROM and COPY TO with the CSV options, and that you know the difference between server-side COPY and psql's \copy. It also assumes you know what roles and GRANT are. The examples use the products table from earlier chapters.
Two kinds of permission
A COPY statement can need two separate sets of permissions.
- Table privileges control which data you may read or write inside the database.
- File and program privileges control whether the server process may touch the server's filesystem or run commands on the server host.
Table privileges apply to every form of COPY. File and program privileges apply only when the statement names a file or a program on the server. COPY ... FROM STDIN and COPY ... TO STDOUT need only the table privileges. So does psql's \copy, which uses those two forms internally.
| Statement | Table privilege needed | Extra privilege needed |
|---|---|---|
| `COPY t TO STDOUT` or `\copy t TO 'f'` | `SELECT` on the columns copied | None |
| `COPY t FROM STDIN` or `\copy t FROM 'f'` | `INSERT` on the columns loaded | None |
| `COPY t TO '/server/path'` | `SELECT` | `pg_write_server_files` (or superuser) |
| `COPY t FROM '/server/path'` | `INSERT` | `pg_read_server_files` (or superuser) |
| `COPY t FROM PROGRAM '...'` or `TO PROGRAM '...'` | `INSERT` or `SELECT` | `pg_execute_server_program` (or superuser) |
A role that can only use \copy can still move any data it is allowed to see. It can't read or write files on the database host. This is the main reason \copy is the safer default.
Table privileges
COPY ... TO needs SELECT on the table. If you export a query, as in COPY (SELECT ...) TO, the query runs with your normal privileges. COPY ... FROM needs INSERT.
Privileges can be granted per column. In that case you must list only permitted columns in the COPY statement. COPY products FROM ... without a column list touches every column and fails if you lack privilege on one of them.
CREATE ROLE loader LOGIN PASSWORD 'change-me';
GRANT INSERT (id, name, price) ON products TO loader;
-- Connected as loader: this works, because the columns match the grant.
COPY products (id, name, price) FROM STDIN WITH (FORMAT csv);Row-level security (RLS) adds two limits. For COPY table TO, PostgreSQL rewrites the statement internally as COPY (SELECT * FROM table) TO, so the SELECT policies filter the output. COPY FROM is not supported on a table that has RLS enabled. For such tables you must load through a staging table, which has no RLS, and then run INSERT ... SELECT, so the policies apply. Check the documentation for your server version, because this restriction is part of the COPY reference notes.
The predefined file and program roles
Before PostgreSQL 11, only superusers could read or write server files. Superuser is far more power than a data loader needs, so PostgreSQL now provides three predefined roles:
pg_read_server_filesallowsCOPY FROM 'file'. It also allows other server-side file reads, such as those in some extensions.pg_write_server_filesallowsCOPY TO 'file'.pg_execute_server_programallowsCOPY ... PROGRAM.
You grant them like any other role membership:
GRANT pg_read_server_files TO loader;
GRANT pg_write_server_files TO exporter;Without the privilege, the server rejects the statement. The message looks like this (the exact wording varies by version):
ERROR: permission denied to COPY from a file
DETAIL: Only roles with privileges of the "pg_read_server_files" role may COPY from a file.
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.The hint points to the safer alternative, which is \copy.
You can check a role's membership without trying the statement:
SELECT pg_has_role('loader', 'pg_read_server_files', 'USAGE') AS can_read_files,
pg_has_role('loader', 'pg_write_server_files', 'USAGE') AS can_write_files,
pg_has_role('loader', 'pg_execute_server_program', 'USAGE') AS can_run_programs;USAGE checks that the role can actually use the privileges of the target role. If the grant was made without inheritance, the check returns false even though the membership exists. In that case the role would have to run SET ROLE pg_read_server_files first. PostgreSQL 16 lets you control this per grant with the INHERIT and SET options of GRANT.
Whose permissions apply to the file
Database privileges are only the first gate. The server process reads and writes files as the operating system user that runs PostgreSQL, usually postgres. So a granted role can access exactly the files that user can access. It does not matter which database role you connected as.
This has several practical effects:
- A file in your home directory is usually unreadable by the server, even if you can read it. A failure here shows up as
could not open file ... for reading: Permission denied, not as a PostgreSQL privilege error. - Files written by
COPY TOare owned by thepostgresOS user. You may need to change ownership or permissions on the host before anyone else can use them. - A relative path is relative to the server process's working directory, which is normally the data directory, not your current directory. Always use absolute paths.
- If PostgreSQL runs in a container or on another host, the path refers to that container's or host's filesystem. Your laptop's files are not visible to it.
- Mandatory access control systems such as SELinux and AppArmor can block access even when ordinary file permissions allow it.
What server-side access exposes
Think of pg_read_server_files as "may read any file the postgres user can read". That includes more than your import directory. A role with this privilege can run:
CREATE TEMP TABLE leak (line text);
COPY leak FROM '/var/lib/postgresql/data/postgresql.conf';
SELECT * FROM leak;The same trick reads pg_hba.conf, server logs, SSL private keys the postgres user can read, and other applications' files that happen to be readable. Reading configuration is often the first step toward a larger compromise.
pg_write_server_files is worse. COPY TO creates the file if it doesn't exist and overwrites it if it does. The postgres user can write to many sensitive places, including the data directory itself. A role that can write files can often corrupt the cluster or plant files that other tools later trust.
pg_execute_server_program is effectively arbitrary command execution as the postgres user:
COPY products FROM PROGRAM 'gunzip -c /var/lib/postgresql/import/products.csv.gz'
WITH (FORMAT csv, HEADER true);That is a legitimate use. The same privilege also allows any other shell command, so treat the role as equal to shell access on the database host. PostgreSQL documentation states that all three roles allow access to things a plain database role could not touch, and that you should grant them with that in mind.
Building a safer setup
You can't narrow pg_read_server_files to a single directory from inside PostgreSQL, so the restriction has to come from the operating system and from how you run the load. A reasonable setup:
- Prefer
\copyfor everything a person or script can run from a client machine. No file privilege is needed, and the client's own OS permissions decide which files are accessible. - Use a dedicated import directory owned by the postgres user and containing only files intended for loading, for example
/var/lib/postgresql/import. - Grant file roles to a separate role that is used only for batch jobs, and don't let it log in from untrusted networks. Restrict it in
pg_hba.conf. - Revoke when finished. If a one-time load needs the privilege, grant it, run the load, and revoke it.
- Keep the postgres OS user minimal. The fewer sensitive files it can read, the less a file-reading role can expose.
-- One-time load by an administrator
GRANT pg_read_server_files TO loader;
-- ... loader runs its COPY ...
REVOKE pg_read_server_files FROM loader;The COPY command's file name and PROGRAM string must be string literals. They can't be query parameters. That means code that builds a COPY statement from user input is building SQL text, which invites injection. If you must construct such a statement, validate the name against a fixed allow-list and quote it with format('%L', ...), or better, avoid server-side file names that originate from users at all.
The same care applies to \copy ... FROM PROGRAM and \copy ... TO PROGRAM. Those run the command on the client machine, through the client's shell, with the client user's permissions. Never place untrusted text in the command.
Managed services and other restrictions
Hosted PostgreSQL services such as Amazon RDS and Google Cloud SQL do not give you superuser, and you have no access to the server's filesystem. Server-side COPY FROM 'file' is not available there. You can use \copy or COPY FROM STDIN from a client, or a provider-specific import feature that reads from object storage. The privilege model in this chapter still describes how self-managed servers behave.
A script that runs psql from a controlled host works the same way against either kind of server:
psql "$DATABASE_URL" -c "\copy products FROM 'products.csv' WITH (FORMAT csv, HEADER true)"The file is read on the machine running psql. The server sees only the data arriving on the connection.
Decision summary
Use \copy unless you have a specific reason to use server-side COPY. Good reasons are a very large file that already sits on the database host, or a load run by a scheduler on the server itself. In those cases, use the narrowest role that works. Give it pg_read_server_files for import, pg_write_server_files for export, and pg_execute_server_program only when you truly need PROGRAM.
Exercise
A role named analyst has SELECT on products. It runs COPY products TO '/tmp/products.csv' WITH (FORMAT csv, HEADER true) and gets a permission error. Give two different ways to let the analyst export the data, and say which you prefer and why.
Show answer
One way is to grant pg_write_server_files to analyst. The server then writes the file as the postgres OS user, and the postgres user must be able to write to the target directory. The other way is to have the analyst use \copy products TO 'products.csv' WITH (FORMAT csv, HEADER true) or COPY ... TO STDOUT from a client, which needs only the existing SELECT privilege and writes the file on the analyst's own machine. The \copy approach is preferable because it grants no access to the server's filesystem. A role with pg_write_server_files can overwrite any file the postgres user can write.
Exercise
A role has pg_read_server_files but no other special privileges. Name one sensitive file it could read, and the statements it would use.
Show answer
It could read postgresql.conf or pg_hba.conf in the data directory. It would create a temporary single-column table, for example CREATE TEMP TABLE leak (line text);, run COPY leak FROM '/var/lib/postgresql/data/pg_hba.conf';, and then SELECT * FROM leak;. The server process reads the file as the postgres OS user, so any file that user can read is exposed, not only files in the import directory.
Exercise
You run COPY products FROM '/home/alice/products.csv' as a role with pg_read_server_files and get Permission denied on the file. The role's privileges are fine. What is the likely cause and what can you do?
Show answer
The error comes from the operating system, not PostgreSQL. The server runs as the postgres OS user, which cannot read a file in /home/alice. Either move the file to a directory the postgres user can read, such as a dedicated import directory, and fix its permissions, or avoid the problem by running \copy from a client where Alice can read the file.