Sub topic 9
Setting up SCRAM for roles and rules
This chapter assumes basic SQL and psql usage, familiarity with PostgreSQL roles and databases, and comfort editing Linux configuration files. You should also understand IP addresses and CIDR notation.
SCRAM-SHA-256 is a password authentication method. PostgreSQL stores a verifier derived from the password, rather than storing the password itself. During login, the client and server prove that they know the password without sending the password across the network.
Prepare a role for SCRAM
Set password_encryption to scram-sha-256 before assigning or changing a role password. The setting controls how PostgreSQL stores the new verifier. It does not convert existing MD5 verifiers.
Run these commands in psql as a role that can manage users:
SHOW password_encryption;
SET password_encryption = 'scram-sha-256';
CREATE ROLE app_user LOGIN;
\password app_userThe \password command is a psql command. It prompts for the password instead of putting the plain text in SQL history or a shell command. If app_user already exists, use ALTER ROLE app_user LOGIN if necessary, then run \password app_user.
A superuser can inspect the verifier format without viewing the password:
SELECT rolname, left(rolpassword, 14) AS stored_prefix
FROM pg_authid
WHERE rolname = 'app_user';The prefix should begin with SCRAM-SHA-256$. Access to pg_authid is restricted because its contents are sensitive.
Add an HBA rule
pg_hba.conf controls which clients may authenticate. Add a specific rule for the application before broader rules:
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
local all all scram-sha-256
hostssl appdb app_user 10.0.0.0/24 scram-sha-256
host all all 0.0.0.0/0 rejectThe hostssl record permits only TLS connections from the 10.0.0.0/24 network. It applies to app_user connecting to appdb. The final reject rule makes unmatched remote connections fail explicitly.
Rules are evaluated from top to bottom. PostgreSQL uses the first record matching the connection's type, database, user, and address. It does not continue searching after an authentication failure. Therefore, place narrow application rules above broad rules.
Reload and validate
After saving the file, reload the configuration. A reload changes authentication rules without restarting the server:
SELECT pg_reload_conf();
SELECT line_number, type, database, user_name, address, auth_method, error
FROM pg_hba_file_rules
ORDER BY line_number;An empty error value indicates that PostgreSQL parsed the record. Check the line order as well as the syntax.
Exercise
A role has an SCRAM verifier, but a broader trust rule appears before its specific scram-sha-256 rule. Which rule applies?
Show answer
The earlier trust rule applies. Move the specific rule above the trust rule, or remove the unsafe rule.