Database credentials are only one part of controlling access to stored data. A secure self-managed PostgreSQL server installed from Ubuntu packages also limits where clients can connect, requires encrypted connections, and keeps application accounts separate from administrators.
PostgreSQL checks authentication rules in order and uses the first matching rule. An explicit application allowlist can require both TLS and SCRAM authentication while rejecting other connections, even when those clients know a valid database password.
Changing connection policy can interrupt applications or lock out remote administrators. On a self-managed Ubuntu server, local sudo access provides a recovery route while the network policy changes. A working server certificate and a client that trusts its issuing certificate authority are prerequisites for verifying the server's identity.
This single-application configuration assumes an existing database, a runtime role that owns no database objects, and only the object grants the application needs. Other applications, replication, monitoring, and remote backup connections need their own explicit allow rules. A supported, patched server and recoverable backups remain necessary alongside connection hardening.
Steps to secure a PostgreSQL server:
- Retain a sudo-capable console or SSH session for recovery.
Database logins can fail during access changes while the operating-system session remains available for repairs.
- Locate the running cluster's configuration files and connection settings.
$ sudo -u postgres psql -c "SELECT name, setting FROM pg_settings WHERE name IN ('config_file', 'hba_file', 'data_directory', 'listen_addresses', 'ssl', 'password_encryption') ORDER BY name;" name | setting ---------------------+----------------------------------------- config_file | /etc/postgresql/18/main/postgresql.conf data_directory | /var/lib/postgresql/18/main hba_file | /etc/postgresql/18/main/pg_hba.conf listen_addresses | localhost password_encryption | scram-sha-256 ssl | on (6 rows)The paths below belong to an Ubuntu 18/main cluster. Your running cluster's paths and version may differ. The server certificate must cover the database hostname, and the application client needs its issuing CA certificate in ~/.postgresql/root.crt.
- Back up the active authentication file.
$ sudo cp -p /etc/postgresql/18/main/pg_hba.conf /etc/postgresql/18/main/pg_hba.conf.before-hardening
- Back up the cluster's automatic settings file.
$ sudo cp -p /var/lib/postgresql/18/main/postgresql.auto.conf /var/lib/postgresql/18/main/postgresql.auto.conf.before-hardening
If the server fails to start or connections fail after applying changes, recovery consists of copying each .before-hardening file back over its original from the retained operating-system session, then restarting the same cluster. These copies preserve file settings, not a role's previous attributes or password.
- Inspect the runtime role's attributes and role memberships.
$ sudo -u postgres psql -c '\du app_runtime' -c '\drg app_runtime' List of roles Role name | Attributes -------------+------------------------------------------------------------ app_runtime | Superuser, Create role, Create DB, Replication, Bypass RLS List of role grants Role name | Member of | Options | Grantor -----------+-----------+---------+--------- (0 rows)app_runtime represents the existing application login. Elevated attributes in this output are removed next. A membership in an owner or administrator role also grants access beyond ordinary application privileges; such memberships need removal before this login is suitable for application use.
- Remove administrative attributes from the application login.
Applications that rely on superuser rights, object ownership, or schema changes need a separate reviewed migration account before runtime privileges are reduced. Ordinary reads and writes should rely on explicit object grants.
$ sudo -u postgres psql -c "ALTER ROLE app_runtime NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;" ALTER ROLE
- Set the cluster's private listener and authentication defaults.
$ sudo -u postgres psql \ -c "ALTER SYSTEM SET listen_addresses = 'localhost,192.0.2.10';" \ -c "ALTER SYSTEM SET password_encryption = 'scram-sha-256';" \ -c "ALTER SYSTEM SET ssl = 'on';" ALTER SYSTEM ALTER SYSTEM ALTER SYSTEM
192.0.2.10 represents the server's private interface address. ALTER SYSTEM writes to postgresql.auto.conf, which overrides postgresql.conf. The listener change takes effect at restart. A firewall should also limit port 5432 to approved clients; a public listener is unnecessary for this private connection.
- Store the application's password as a SCRAM verifier.
$ sudo -u postgres psql -c "SET password_encryption = 'scram-sha-256';" -c '\password app_runtime' SET Enter new password for user "app_runtime": Enter it again:
Re-entering an existing strong password converts its stored verifier without changing the application's secret. Choosing a new password also requires a coordinated update to the application's secret store. The prompts hide input; a password does not belong in a SQL literal or shell argument. All application drivers must support SCRAM before the new authentication rule is enabled.
- Open the active authentication file in your text editor.
$ sudoedit /etc/postgresql/18/main/pg_hba.conf
- Replace the authentication rule lines with the single-application allowlist.
This policy blocks other local database users and every unlisted TCP connection, including existing remote administration paths. It preserves Unix-socket peer access for the operating-system postgres account. Required additional clients need narrowly scoped rules before the reject rules.
local all postgres peer local all all reject hostssl appdb app_runtime 192.0.2.20/32 scram-sha-256 host all all 0.0.0.0/0 reject host all all ::/0 reject
The database appdb, login app_runtime, and single client address 192.0.2.20/32 must match the application. Existing comments can stay, but earlier permissive rules or authentication includes would bypass this allowlist. hostssl matches TLS connections only; the catch-all reject rules cover encrypted and unencrypted TCP connections.
- Save the authentication file in your editor.
The server keeps its loaded authentication policy until reload or restart.
- Check the saved authentication rules for parse errors.
$ sudo -u postgres psql -c "SELECT line_number, error FROM pg_hba_file_rules WHERE error IS NOT NULL;" line_number | error -------------+------- (0 rows)
Any returned row needs correction before applying the file. This view reads the saved file; it does not prove the server has loaded it.
- Restart the selected cluster to apply the connection policy.
The restart disconnects current database sessions. A maintenance window is necessary for a server already serving applications, and the authentication error query must return no rows first.
$ sudo pg_ctlcluster 18 main restart
- Confirm local administration and the loaded connection settings in a fresh session.
$ sudo -u postgres psql -c "SELECT current_user, name, setting, pending_restart FROM pg_settings WHERE name IN ('listen_addresses', 'ssl', 'password_encryption') ORDER BY name;" current_user | name | setting | pending_restart --------------+---------------------+-----------------------+----------------- postgres | listen_addresses | localhost,192.0.2.10 | f postgres | password_encryption | scram-sha-256 | f postgres | ssl | on | f (3 rows)The retained operating-system session remains the recovery route until new client connections also work.
- Test an unencrypted connection from the application host.
$ psql "host=db.example.net dbname=appdb user=app_runtime sslmode=disable" -c "SELECT 1;" psql: error: connection to server at "db.example.net" (192.0.2.10), port 5432 failed: FATAL: pg_hba.conf rejects connection for host "192.0.2.20", user "app_runtime", database "appdb", no encryption
db.example.net represents the certificate's database hostname. A returned 1 means cleartext access is still allowed. A timeout or connection refusal does not prove the authentication rule rejected the connection.
- Check that the application login cannot connect to an unlisted database.
$ psql "host=db.example.net dbname=postgres user=app_runtime sslmode=verify-full" -c "SELECT 1;" psql: error: connection to server at "db.example.net" (192.0.2.10), port 5432 failed: FATAL: pg_hba.conf rejects connection for host "192.0.2.20", user "app_runtime", database "postgres", SSL encryption
This rejection confirms the allowlist is scoped to appdb rather than every database.
- Read an application table through a certificate-verified TLS connection.
$ psql "host=db.example.net dbname=appdb user=app_runtime sslmode=verify-full" -c "SELECT current_user, current_database(), ssl, (SELECT count(*) FROM app.accounts) AS accounts FROM pg_stat_ssl WHERE pid = pg_backend_pid();" current_user | current_database | ssl | accounts --------------+------------------+-----+---------- app_runtime | appdb | t | 1 (1 row)app.accounts represents an existing table the runtime role is permitted to read. The row confirms the intended login and database, TLS in use, and application data access. verify-full also checks the certificate chain and hostname; sslmode=require alone does not provide the same identity check. Missing trust, a hostname mismatch, a bad password, or a missing table grant must cause this connection or query to fail.