Sub topic 3
Applying and validating changes with pg_hba_file_rules
This chapter assumes you know basic SQL and psql, can connect as a superuser, and can edit pg_hba.conf on a Linux server.
Reloading and checking the rules
PostgreSQL reads pg_hba.conf at startup and when it receives a reload signal. Run this as a superuser to reload the file, then list the parsed rules:
SELECT pg_reload_conf();
SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;A non-empty error column names a rule that failed to parse. Rules are listed in file order, so you can also confirm which rule will match first.
Migrating roles from MD5 to SCRAM
Find the roles that still store MD5 hashes:
SELECT rolname
FROM pg_authid
WHERE rolpassword LIKE 'md5%';For each role, set the session to SCRAM and set a new password. In psql, \password hashes the value before sending it:
SET password_encryption = 'scram-sha-256';
\password app_user> The old MD5 hash cannot be converted. Each role needs a new password.
Adding TLS and channel binding
Use a hostssl rule to accept only encrypted connections. On the client, channel_binding=require makes libpq refuse any server that does not bind the SCRAM exchange to the TLS session:
psql "host=db.example.com dbname=appdb user=app_user sslmode=verify-full channel_binding=require"Troubleshooting common errors
| Error message | Likely cause | Check |
|---|---|---|
| no pg_hba.conf entry for host | No rule matches the connection | Query `pg_hba_file_rules` and add a rule |
| password authentication failed | Wrong password or stale hash | Re-run `\password` and check `rolpassword` |
| Peer authentication failed | OS user differs from role name | Check the `peer` rule and any map |
Mapping OS users with pg_ident.conf
A peer or cert rule can use a map from pg_ident.conf:
# MAPNAME SYSTEM-USERNAME PG-USERNAME
mymap alice app_userlocal appdb all peer map=mymapHardening checklist
- Put specific rules above general ones, and end with an explicit
reject. - Use
scram-sha-256for every password rule. - Require
hostsslfor remote connections. - Limit
trustto no rules.
Exercise
A rule in pghbafile_rules shows an error. What should you do first?
Show answer
Fix the syntax in pghba.conf, reload with pgreloadconf(), and query pghbafilerules again until the error column is empty.