Sub topic 15
Hardening checklist
This chapter gathers the earlier material into one review list. It assumes you can read pg_hba.conf records and know that the first matching rule wins. It also assumes you have met password_encryption, SCRAM-SHA-256, and pg_hba_file_rules. Each item below names a risk, a way to check for it, and a fix.
Where the checks sit
Authentication is a chain, and a weak link in any layer can undo the others. The checklist follows the chain from the network inward.
1. Keep the rule file narrow and ordered
Review pg_hba.conf from top to bottom with these questions.
- Does any
hostrule usetrust?trustaccepts any connection that matches the rule, with no password. Remove it from network rules. If you keep it anywhere, restrict it to alocalrule on a single-user development machine. - Does any rule use
passwordormd5? Thepasswordmethod sends the cleartext password, which is only safe inside TLS. Themd5method relies on a weak hash. Usescram-sha-256. - Are the database, user, and address fields as specific as they can be? Names such as
appdbandapp_userand a CIDR range such as10.0.0.0/24are better thanalland0.0.0.0/0. - Do specific rules come before general ones? A broad rule above a narrow one makes the narrow one unreachable.
- Does the file end with an explicit
reject? PostgreSQL already refuses a connection that matches no rule. The explicit last line makes that intent visible to the next reader. - Do remote connections have to use TLS? Allow
hostsslfor the real clients and let a final catch-allrejectstop everything else, includinghostnossltraffic.
This file applies those points:
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
local all all scram-sha-256
host all all 127.0.0.1/32 scram-sha-256
host all all ::1/128 scram-sha-256
hostssl appdb app_user 10.0.0.0/24 scram-sha-256
host all all 0.0.0.0/0 rejectThe last rule rejects any IPv4 address that did not match earlier. IPv6 clients are already refused because no rule matches them. If your server listens on IPv6, add host all all ::/0 reject as well.
You can audit the loaded rules with SQL instead of reading the file by eye. This query lists rules that use weak methods or accept any address:
SELECT line_number, type, database, user_name, address, auth_method
FROM pg_hba_file_rules
WHERE error IS NULL
AND auth_method <> 'reject'
AND (auth_method IN ('trust', 'password', 'md5')
OR address = 'all'
OR netmask IN ('0.0.0.0', '::'))
ORDER BY line_number;An empty result is the goal. Any row is a rule to justify or change.
2. Make every stored password a SCRAM verifier
Rules only help if the stored credentials match them. Check the setting first.
SHOW password_encryption;The default is scram-sha-256 from PostgreSQL 14 onward. On older servers, or where someone changed it, set it in postgresql.conf and reload. Then list every login role with the scheme it uses:
SELECT rolname,
CASE
WHEN rolpassword LIKE 'SCRAM-SHA-256$%' THEN 'scram'
WHEN rolpassword LIKE 'md5%' THEN 'md5'
WHEN rolpassword IS NULL THEN 'none'
ELSE 'other'
END AS scheme
FROM pg_authid
WHERE rolcanlogin
ORDER BY rolname;Reading pg_authid requires superuser. Act on each result:
md5: The hash cannot be converted. The role needs a new password, set with\passwordwhilepassword_encryptionisscram-sha-256. Do this before you remove anymd5rule.none: A login role with no password cannot pass ascram-sha-256rule. That is fine when the role connects throughpeerorcert. For any other role it is a mistake to fix.other: Investigate, since this is neither a SCRAM verifier nor an MD5 hash.
Use \password app_user in psql to set passwords. The client hashes the password before sending it, so the plain text stays out of the server logs and your shell history. A plain ALTER ROLE app_user PASSWORD '...' sends the text in the statement, and statement logging can record it.
3. Require TLS and verify the server
Passwords protected by SCRAM are not sent in the clear, but the rest of the session still is. Encrypt it. On the server, turn on ssl, point it at your certificate and key, and keep ssl_min_protocol_version at TLSv1.2 or higher. The private key file must not be readable by other users, and PostgreSQL refuses to start if its permissions are too loose.
The client side matters just as much. The default sslmode is prefer, which falls back to an unencrypted connection and does not check the certificate. An attacker who sits between client and server can force that fallback. Set sslmode=verify-full so the client checks the certificate chain and the host name. Add channel_binding=require so the client refuses to continue unless SCRAM is bound to the TLS session:
psql "host=db.example.com dbname=appdb user=app_user sslmode=verify-full channel_binding=require"Channel binding fails against a server that stores MD5 hashes or uses a method other than SCRAM. This is intended, because it exposes servers that were not fully migrated. Apply it to application connection strings after the migration is complete.
4. Reduce what is reachable
Authentication rules are the second line of defense. The first is not being reachable at all.
listen_addresses: Set it to the interfaces you need. The defaultlocalhostis right for a database used only by local processes. Avoid'*'unless a firewall limits who can reach the port.- Firewall or security group: Allow TCP 5432 only from the application subnets. This duplicates the CIDR in
pg_hba.confon purpose, so one mistake does not open the server. - Superuser access: Limit remote superuser logins. In the example file,
postgresis allowed only through localpeer. The application's rules nameapp_user, never a superuser. - Service accounts: For automated clients, consider the
certmethod withclientcert=verify-full, which removes the password from the connection string.
5. Add authorization and accountability
Authentication only answers who is connecting. Limit what they can do, and keep a record.
- Revoke default access: By default every role can connect to a new database through
PUBLIC. RunREVOKE CONNECT ON DATABASE appdb FROM PUBLIC;and grantCONNECTonly to the roles that need it. - Log connections: Set
log_connections = onandlog_disconnections = on. Failed attempts then leave a trace, and the server log names thepg_hba.confline that matched. - Expire passwords where policy requires it:
ALTER ROLE app_user VALID UNTIL '2027-06-01';makes a password stop working on that date. Make sure someone owns the renewal. - Protect the files:
pg_hba.conf,pg_ident.conf, and the TLS key should be owned by thepostgresoperating system user and not writable by anyone else.
6. Change safely
A mistake in pg_hba.conf can lock out every administrator. Follow the same routine each time:
- Copy the current file somewhere safe.
- Edit, then run
SELECT pg_reload_conf();. - Query
pg_hba_file_rulesand confirm theerrorcolumn is empty. A file with a syntax error leaves the old rules in place, so check that the new rules actually loaded. - Keep an existing superuser session open, and test the new rule from a second session before closing the first.
Checklist summary
| Area | Check | Healthy result |
|---|---|---|
| Rules | No `trust`, `password`, or `md5` on network rules | Audit query returns no rows |
| Rules | Specific addresses, databases, and users | No `all` and `0.0.0.0/0` except a final `reject` |
| Rules | Order reviewed, last line rejects | Narrow rules first |
| Passwords | `password_encryption` and `pg_authid` | All login roles show `scram` or intentionally `none` |
| TLS | Client `sslmode` and `channel_binding` | `verify-full` and `require` |
| Network | `listen_addresses` and firewall | Only the needed interfaces and subnets |
| Privileges | `CONNECT` on `PUBLIC` | Revoked, then granted per role |
| Logging | `log_connections` | On |
Exercise
A review of pg_hba_file_rules shows two rules, in this order: line 8 host all all 10.0.0.0/8 md5 and line 9 hostssl appdb app_user 10.0.0.0/24 scram-sha-256. A client from 10.0.0.5 connects as app_user to appdb over TLS. Which rule applies, and what two changes harden this setup?
Show answer
Line 8 applies, because the first matching rule wins and host matches both TLS and non-TLS connections. The hostssl rule on line 9 is never reached. First, remove or replace line 8 so that the narrow hostssl rule on line 9 is the one that matches, and replace md5 with scram-sha-256 after resetting any MD5 passwords. Second, keep a final reject rule so that other 10.x addresses and non-TLS connections are refused.
Exercise
Why can enabling channel_binding=require in an application's connection string make connections fail after you have changed pg_hba.conf to scram-sha-256, and how do you find the cause?
Show answer
The role may still have an MD5 hash in pg_authid, so the server cannot use SCRAM and the client refuses to continue without channel binding. Run the query that classifies rolpassword by scheme, find the roles marked md5, and set a new password for each with \password while password_encryption is scram-sha-256. The connection must also use TLS, because channel binding needs it.