### Install cracklib packages on apt-based systems Source: https://github.com/hexacluster/credcheck/blob/master/README.md Install required cracklib packages on Debian/Ubuntu using apt. ```bash sudo apt install libpam-cracklib libcrack2-dev ``` -------------------------------- ### Install cracklib packages on yum-based systems Source: https://github.com/hexacluster/credcheck/blob/master/README.md Install required cracklib packages on RHEL/CentOS/Fedora using yum. ```bash sudo yum -y install cracklib cracklib-devel cracklib-dicts words ``` -------------------------------- ### Query pg_lastlog view Source: https://github.com/hexacluster/credcheck Example query showing the last 5 user sessions with login time, duration, and state, ordered by login time descending. The view includes boot/shutdown/crash markers in addition to user sessions. ```sql SELECT username, login_time, duration, state FROM pg_lastlog WHERE type = 'user' ORDER BY login_time DESC LIMIT 5; ``` -------------------------------- ### Query pg_banned_role view with output Source: https://github.com/hexacluster/credcheck Example query listing roles with authentication failures, their failure counts, and ban dates. The output shows a role with failure_count 2 and a banned_date, while NULL banned_date indicates not yet banned. ```sql SELECT roleid, failure_count, banned_date FROM pg_banned_role; -- roleid | failure_count | banned_date -- -----------+---------------+---------------------------- -- toban_user | 2 | 2023-06-09 20:33:58.490273 ``` -------------------------------- ### Password reuse history example Source: https://github.com/hexacluster/credcheck/blob/master/README.md Sets password reuse history to 2, creates a user, changes password, and queries the history. Shows that reusing a recent password fails with an error, and resets the history with pg_password_history_reset(). ```sql SET credcheck.password_reuse_history = 2; CREATE USER credtest WITH PASSWORD 'H8Hdre=S2'; ALTER USER credtest PASSWORD 'J8YuRe=6O'; SELECT rolename, password_hash FROM pg_password_history WHERE rolename = 'credtest' ORDER BY password_date; rolename | password_hash ----------+------------------------------------------------------------------ credtest | 7488570b80076cf9da26644d5eeb316c4768ff5bee7bf319344e7bb328032098 credtest | e61e58c22aa6bf31a92b385932f7d0e4dbaba24fa3fdb2982510d6c72a961335 (2 rows) -- fail, the credential is still in the history ALTER USER credtest PASSWORD 'J8YuRe=6O'; ERROR: Cannot use this credential following the password reuse policy -- Reset the password history SELECT pg_password_history_reset(); pg_password_history_reset --------------------------- 2 (1 row) ``` -------------------------------- ### Query pg_password_history view Source: https://github.com/hexacluster/credcheck Lists a role's password history by querying the public view. The example filters for role 'credtest' and orders by password_date. The output shows the role, timestamp, and hex-encoded hash. ```sql SELECT rolename, password_date, password_hash FROM pg_password_history WHERE rolename = 'credtest' ORDER BY password_date; -- rolename | password_date | password_hash -- ----------+-------------------------------+------------------------------------------------------------------ -- credtest | 2022-12-15 13:41:06.736775+03 | c38cf85ca6c3e5ee72c09cf0bfb42fb29b0f0a3e8ba335637941d60f86512508 -- (1 row) ``` -------------------------------- ### psql example of policy violation error Source: https://github.com/hexacluster/credcheck Shows the error output when a policy check fails inside CREATE ROLE. The client sees a statement error with SQLSTATE 28000, as demonstrated by the ERROR message about username length. ```sql CREATE USER abc WITH PASSWORD 'pass'; -- ERROR: username length should match the configured credcheck.username_min_length (4) ``` -------------------------------- ### Query pg_password_history view Source: https://github.com/hexacluster/credcheck Example query showing password reuse history for a specific role, ordered by password date descending. The view shows committed password hashes only; uncommitted mutations are not visible. ```sql CREATE VIEW credcheck password history usage SELECT rolename, password_date FROM pg_password_history WHERE rolename = 'credtest' ORDER BY password_date DESC; ``` -------------------------------- ### Background worker registration for lastlog flusher Source: https://github.com/hexacluster/credcheck Registers the background worker entry point for the lastlog flusher. Sets flags for shared memory access, start time at postmaster start, restart time of 5 seconds, and names the library, function, and worker. Used when lastlog is enabled. ```c worker.bgw_flags = BGWORKER_SHMEM_ACCESS; worker.bgw_start_time = BgWorkerStart_PostmasterStart; worker.bgw_restart_time = 5; snprintf(worker.bgw_library_name, BGW_MAXLEN, "credcheck"); snprintf(worker.bgw_function_name, BGW_MAXLEN, "lastlog_bgworker_main"); snprintf(worker.bgw_name, BGW_MAXLEN, "credcheck lastlog flusher"); worker.bgw_main_arg = (Datum) 0; ``` -------------------------------- ### Authentication failure ban example with psql Source: https://github.com/hexacluster/credcheck/blob/master/README.md Shows three consecutive failed login attempts for user 'toban_user'. After the configured maximum failures, the server rejects the connection with 'user has been banned'. ```shell $ psql -h localhost -U toban_user -d gilles Password for user toban_user: psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" $ psql -h localhost -U toban_user -d gilles Password for user toban_user: psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" $ psql -h localhost -U toban_user -d gilles Password for user toban_user: psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: rejecting connection, user 'toban_user' has been banned connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: rejecting connection, user 'toban_user' has been banned ``` -------------------------------- ### Password reuse interval example Source: https://github.com/hexacluster/credcheck/blob/master/README.md Sets password reuse history to 1 and interval to 365 days. Uses pg_password_history_timestamp() to adjust password age, showing that a password younger than the interval fails, while an older one succeeds and is removed from history. ```sql SET credcheck.password_reuse_history = 1; SET credcheck.password_reuse_interval = 365; -- Add a new password in the history and set its age to 100 days ALTER USER credtest PASSWORD 'J8YuRe=6O'; SELECT pg_password_history_timestamp('credtest', now()::timestamp - '100 days'::interval); pg_password_history_timestamp ------------------------------- 1 (1 row) SELECT * FROM pg_password_history WHERE rolename = 'credtest'; rolename | password_date | password_hash ----------+-------------------------------+------------------------------------------------------------------ credtest | 2022-12-15 13:41:06.736775+03 | c38cf85ca6c3e5ee72c09cf0bfb42fb29b0f0a3e8ba335637941d60f86512508 (1 row) -- fail, the password is in the history for less than 1 year ALTER USER credtest PASSWORD 'J8YuRe=6O'; ERROR: Cannot use this credential following the password reuse policy -- Change the age of the password to exceed the 1 year interval SELECT pg_password_history_timestamp('credtest', now()::timestamp - '380 days'::interval); pg_password_history_timestamp ------------------------------- 2 (1 row) -- success, the old password present in the history has expired and will be removed ALTER USER credtest PASSWORD 'J8YuRe=6O'; SELECT rolename, password_hash FROM pg_password_history WHERE rolename = 'credtest'; rolename | password_date | password_hash ----------+-------------------------------+------------------------------------------------------------------ credtest | 2023-03-25 13:42:37.387629+03 | c38cf85ca6c3e5ee72c09cf0bfb42fb29b0f0a3e8ba335637941d60f86512508 (1 row) ``` -------------------------------- ### Clear full password history with pg_password_history_reset() Source: https://github.com/hexacluster/credcheck Basic call to clear the entire password reuse history. Requires the extension to be in shared_preload_libraries. Returns the number of removed records (4 in the example), and a subsequent count shows 0 remaining entries. ```sql CREATE EXTENSION credcheck; -- must also be in shared_preload_libraries -- after several password changes SELECT pg_password_history_reset(); -- pg_password_history_reset -- -------------------------- -- 4 -- (1 row) SELECT count(*) FROM pg_password_history; -- count -- ------- -- 0 ``` -------------------------------- ### Set password_valid_min and password_valid_until for new roles and password changes Source: https://github.com/hexacluster/credcheck/blob/master/README.md Use these settings to give newly created roles a shorter VALID UNTIL window than existing roles when they change passwords. When credcheck.password_valid_min is greater than zero, it overrides credcheck.password_valid_until for CREATE ROLE statements only. The example shows setting the values and then creating a user and altering a password, with comments explaining the resulting expiration windows. ```sql postgres=# SET credcheck.password_valid_min = 5; -- new roles: 5 days postgres=# SET credcheck.password_valid_until = 365; -- password changes: 1 year postgres=# SET credcheck.password_valid_max = 370; -- never beyond ~1 year -- new role, no VALID UNTIL given: automatically set to now() + 5 days postgres=# CREATE USER remi PASSWORD 'FirstPass1'; -- when remi later changes its password without a VALID UNTIL clause, -- credcheck sets it to now() + 365 days instead of 5. postgres=# ALTER USER remi PASSWORD 'ChosenPass1'; ``` -------------------------------- ### Build cracklib dictionary with mkdict Source: https://github.com/hexacluster/credcheck/blob/master/README.md Build the cracklib dictionary using mkdict and packer, typically for yum-based systems. ```bash mkdict /usr/share/dict/* | sudo packer /usr/lib/cracklib_dict ``` -------------------------------- ### Masked password in server log Source: https://github.com/hexacluster/credcheck/blob/master/README.md When credcheck.no_password_logging is enabled (default), passwords in logged statements are masked with dots. This example shows a CREATE ROLE statement with the password replaced by dots. ```log LOG: statement: CREATE ROLE alice LOGIN PASSWORD '............'; ``` -------------------------------- ### Build cracklib dictionary with cracklib-format Source: https://github.com/hexacluster/credcheck/blob/master/README.md Build the cracklib dictionary using cracklib-format and cracklib-packer, typically for apt-based systems. ```bash cracklib-format /usr/share/dict/* | sudo cracklib-packer /usr/lib/cracklib_dic ``` -------------------------------- ### Enforce policy with SET and test candidates Source: https://github.com/hexacluster/credcheck Sets password policy parameters (min_length=12, min_digit=1, min_special=1, contain_username=on) and tests three candidates. Shows errors for too-short and username-containing passwords, and success for a valid one. ```sql SET credcheck.password_min_length = 12; SET credcheck.password_min_digit = 1; SET credcheck.password_min_special = 1; SET credcheck.password_contain_username = on; SELECT pg_check_password('alice', 'weakpass'); -- too short -- ERROR: password length should match the configured credcheck.password_min_length (12) SELECT pg_check_password('alice', 'alicePassw0rd!'); -- contains the username -- ERROR: password should not contain username SELECT pg_check_password('alice', 'S3cur3Passw0rd!'); -- ok -- pg_check_password -- ------------------ -- t ``` -------------------------------- ### CREATE FUNCTION pg_password_history_reset() signatures Source: https://github.com/hexacluster/credcheck Two overloads: one with no arguments to clear the whole history, and one with a username parameter to clear a single role's history. The second overload is STRICT, so a NULL username returns NULL instead of running. ```sql CREATE FUNCTION pg_password_history_reset( ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C VOLATILE; CREATE FUNCTION pg_password_history_reset( IN username name ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### Create user with plain text password Source: https://github.com/hexacluster/credcheck/blob/master/README.md Shows a successful CREATE USER with a plain text password. The extension only works for plain text passwords. ```sql postgres=# CREATE USER user1 PASSWORD 'this is some plain text'; CREATE ROLE ``` -------------------------------- ### Basic call to pg_banned_role Source: https://github.com/hexacluster/credcheck Shows how to inspect the ban cache with SELECT * FROM pg_banned_role and how to cast roleid to regrole as the view does. The output includes failure_count and banned_date for each role. ```sql SELECT * FROM pg_banned_role; -- roleid | failure_count | banned_date -- ---------+---------------+---------------------------- -- 250362 | 2 | 2023-06-09 20:33:58.490273 -- (1 row) SELECT roleid::regrole, failure_count FROM pg_banned_role; -- what the view does -- roleid | failure_count -- -----------+--------------- -- toban_user | 2 ``` -------------------------------- ### Basic call accepting a valid password Source: https://github.com/hexacluster/credcheck With default settings (username_min_length = 1, password_min_length = 1), returns true for a valid password. Output shows 't'. ```sql -- defaults: username_min_length = 1, password_min_length = 1 SELECT pg_check_password('alice', 'S3cur3-Passw0rd!'); -- pg_check_password -- ------------------ -- t -- (1 row) ``` -------------------------------- ### Query with tracking enabled Source: https://github.com/hexacluster/credcheck Shows configuration settings in postgresql.conf to enable query tracking, then queries pg_lastlog for user sessions with non-null query, ordering by login_time descending and limiting to 3 rows. Requires restart after setting shared_preload_libraries, credcheck.lastlog, credcheck.lastlog_track_query, and credcheck.lastlog_query_size. ```sql -- postgresql.conf (restart required): -- shared_preload_libraries = 'credcheck' -- credcheck.lastlog = on -- credcheck.lastlog_track_query = on -- credcheck.lastlog_query_size = 4096 SELECT username, login_time, duration, query FROM pg_lastlog WHERE type = 'user' AND query IS NOT NULL ORDER BY login_time DESC LIMIT 3; ``` -------------------------------- ### CREATE FUNCTION pg_banned_role_reset() signatures Source: https://github.com/hexacluster/credcheck Defines the two overloads of pg_banned_role_reset: one with no arguments to clear the entire cache, and one with a username parameter to clear a single role's entry. The second overload is STRICT, so NULL input returns NULL. ```sql CREATE FUNCTION pg_banned_role_reset( ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C VOLATILE; CREATE FUNCTION pg_banned_role_reset( IN username name ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### Query pg_lastlog view Source: https://github.com/hexacluster/credcheck/blob/master/README.md Displays the last-login history ring, including user sessions, boot, and shutdown records. Output shows columns for type, username, pid, client address/port, login/logout times, duration, state, and query. ```sql contrib_regression=# select * from pg_lastlog; type | username | pid | client_addr | client_port | login_time | logout_time | duration | state | query ----------+----------+--------+-------------+-------------+-------------------------------+-------------------------------+-----------------+-----------------+------- user | gilles | 148483 | [local] | 0 | 2026-09-09 16:59:07.765016+02 | | 00:00:14.202368 | still connected | user | gilles | 148481 | [local] | 0 | 2026-09-09 16:59:07.171284+02 | 2026-09-09 16:59:07.174723+02 | 00:00:00.003439 | disconnected | [...] user | gilles | 145047 | [local] | 0 | 2026-09-09 15:36:34.346523+02 | 2026-09-09 15:36:34.368934+02 | 00:00:00.022411 | disconnected | user | postgres | 144982 | [local] | 0 | 2026-09-09 15:36:30.786325+02 | 2026-09-09 15:36:30.788083+02 | 00:00:00.001758 | disconnected | user | postgres | 144977 | [local] | 0 | 2026-09-09 15:36:30.273365+02 | 2026-09-09 15:36:30.275044+02 | 00:00:00.001679 | disconnected | user | postgres | 144974 | [local] | 0 | 2026-09-09 15:36:29.757562+02 | 2026-09-09 15:36:29.762573+02 | 00:00:00.005011 | disconnected | boot | | 144960 | | | 2026-09-09 15:36:28.674986+02 | | | boot | shutdown | | | | | 2026-09-09 15:36:28.490285+02 | | | shutdown | ``` -------------------------------- ### Basic query on pg_lastlog Source: https://github.com/hexacluster/credcheck Selects recent login history from the pg_lastlog view, ordering by login_time descending and limiting to 5 rows. The output shows user sessions with state 'still connected' or 'disconnected', plus boot and shutdown markers. ```sql SELECT type, username, pid, login_time, state FROM pg_lastlog ORDER BY login_time DESC LIMIT 5; -- type | username | pid | login_time | state -- ---------+----------+--------+-------------------------------+----------------- -- user | gilles | 148483 | 2026-09-09 16:59:07.765016+02 | still connected -- user | gilles | 148481 | 2026-09-09 16:59:07.171284+02 | disconnected -- user | postgres | 144974 | 2026-09-09 16:59:07.757562+02 | disconnected -- boot | | 144960 | 2026-09-09 15:36:28.674986+02 | boot -- shutdown| | | 2026-09-09 15:36:28.490285+02 | shutdown -- (5 rows) ``` -------------------------------- ### Catch policy violations in PL/pgSQL with EXCEPTION WHEN Source: https://github.com/hexacluster/credcheck Use this PL/pgSQL block to catch policy violations inside a database session. It handles SQLSTATE 28000 (invalid_authorization_specification) and 42501 (insufficient_privilege) errors raised by CREATE ROLE or ALTER ROLE. Note that ban rejections are FATAL and cannot be caught this way. ```sql DO $$ BEGIN ALTER USER alice PASSWORD 'weak'; EXCEPTION WHEN invalid_authorization_specification THEN RAISE NOTICE 'policy violation: %', SQLERRM; WHEN insufficient_privilege THEN RAISE NOTICE 'not allowed: %', SQLERRM; END $$; ``` -------------------------------- ### fail2ban action calling via psql injection-safely Source: https://github.com/hexacluster/credcheck Typical integration in /etc/fail2ban/action.d/credcheck-report.conf. Uses psql with -v ON_ERROR_STOP=1 and -v u="" to pass the username safely via :'u' placeholder. ```ini # /etc/fail2ban/action.d/credcheck-report.conf [Definition] actionban = psql "host=PGHOST port=5432 user=f2b_reporter dbname=postgres" \ -X -q -v ON_ERROR_STOP=1 \ -c "SELECT credcheck_record_auth_failure(:'u')" -v u="" actionunban = ``` -------------------------------- ### Error handling in PL/pgSQL with WHEN clause Source: https://github.com/hexacluster/credcheck DO block that catches invalid_authorization_specification and raises a notice with the error message. Output shows the notice for a too-short password. ```sql DO $$ BEGIN IF NOT (SELECT pg_check_password('alice', 'weakpass')) THEN RAISE NOTICE 'rejected by return value'; END IF; EXCEPTION WHEN invalid_authorization_specification THEN RAISE NOTICE 'rejected by error: %', SQLERRM; END $$; -- NOTICE: rejected by error: password length should match the configured credcheck.password_min_length (12) ``` -------------------------------- ### Create reporter role and grant EXECUTE Source: https://github.com/hexacluster/credcheck/blob/master/README.md Creates a login role for fail2ban and grants EXECUTE on credcheck_record_auth_failure so it can report failures. ```sql CREATE ROLE f2b_reporter LOGIN PASSWORD '...'; GRANT EXECUTE ON FUNCTION credcheck_record_auth_failure(name) TO f2b_reporter; ``` -------------------------------- ### Makefile optional cracklib support Source: https://github.com/hexacluster/credcheck Build-time switch for optional cracklib support in the Makefile. Uncomment these lines to enable cracklib password checking. ```makefile #PG_CPPFLAGS = -DUSE_CRACKLIB '-DCRACKLIB_DICTPATH="/usr/lib/cracklib_dict"' #SHLIB_LINK = -lcrack ``` -------------------------------- ### fail2ban filter for PgBouncer log Source: https://github.com/hexacluster/credcheck/blob/master/README.md Regex to match PgBouncer login failures. Adjust to your PgBouncer version's log format. ```ini # /etc/fail2ban/filter.d/pgbouncer-credcheck.conf [Definition] failregex = login failed: .*"?[^"@ ]+"?@ password authentication failed for user "?[^"]+"? ``` -------------------------------- ### CREATE FUNCTION pg_password_history Source: https://github.com/hexacluster/credcheck Defines the set-returning function that lists password reuse history. It takes no arguments and returns a SETOF record with columns rolename, password_date, and password_hash. The function is STRICT and VOLATILE, implemented in C. ```sql CREATE FUNCTION pg_password_history ( OUT rolename name, OUT password_date timestamp with time zone, OUT password_hash text ) RETURNS SETOF record AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### Login attempt after reset Source: https://github.com/hexacluster/credcheck/blob/master/README.md After resetting the banned cache, a new login attempt is allowed but still fails due to wrong password. ```shell $ psql -h localhost -U toban_user -d gilles Password for user toban_user: psql: error: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "toban_user" ``` -------------------------------- ### Configure auth_query in pgbouncer.ini Source: https://github.com/hexacluster/credcheck/blob/master/README.md Sets PgBouncer's auth_query to use the pgbouncer_auth function. PgBouncer caches results, so enforcement takes effect on next cache refresh or reconnect. ```ini auth_query = SELECT uname, phash FROM public.pgbouncer_auth($1) ``` -------------------------------- ### Basic usage of pg_password_history_timestamp Source: https://github.com/hexacluster/credcheck Backdates a role's password history to exceed the reuse interval. Shows that a 100-day-old entry still blocks reuse, while a 380-day-old entry allows it. Requires superuser privileges. ```sql -- password must not be reusable for 365 days SET credcheck.password_reuse_history = 1; SET credcheck.password_reuse_interval = 365; ALTER USER credtest PASSWORD 'J8YuRe=6O'; SELECT pg_password_history_timestamp('credtest', now()::timestamp - '100 days'::interval); -- pg_password_history_timestamp -- ------------------------------- -- 1 -- (1 row) -- still blocked: entry is only 100 days old ALTER USER credtest PASSWORD 'J8YuRe=6O'; -- ERROR: Cannot use this credential following the password reuse policy SELECT pg_password_history_timestamp('credtest', now()::timestamp - '380 days'::interval); -- pg_password_history_timestamp -- ------------------------------- -- 2 -- (1 row) -- now allowed: the old entry has expired ALTER USER credtest PASSWORD 'J8YuRe=6O'; -- ALTER ROLE ``` -------------------------------- ### Create pg_password_history view Source: https://github.com/hexacluster/credcheck Defines the pg_password_history view that wraps the pg_password_history() set-returning function. The view is revoked from PUBLIC and granted SELECT to pg_read_all_stats. ```sql CREATE VIEW pg_password_history AS SELECT * FROM pg_password_history(); ``` -------------------------------- ### Whitelist users from authentication failure ban Source: https://github.com/hexacluster/credcheck/blob/master/README.md Configuration directive to exclude specific usernames from the authentication failure ban behavior. ```ini credcheck.whitelist_auth_failure = 'appuser1,appuser2' ``` -------------------------------- ### Graceful no-op when feature disabled Source: https://github.com/hexacluster/credcheck With credcheck.max_auth_failure = 0, the function returns 0 without recording. Also returns 0 for whitelisted or unknown roles, or when cache is full. ```sql SET credcheck.max_auth_failure = 0; SELECT credcheck_record_auth_failure('nobody'); -- credcheck_record_auth_failure -- ------------------------------- -- 0 -- (1 row) ``` -------------------------------- ### Create user with forced password change on first login Source: https://github.com/hexacluster/credcheck/blob/master/README.md Creates a PostgreSQL user with a password and validity period. When `credcheck.password_change_first_login` is enabled, the user must change their password upon first login. ```sql CREATE USER user1 PASSWORD 'Rkd89,34' VALID UNTIL '2050-12-31'; ``` -------------------------------- ### Query banned roles and reset cache with pg_banned_role_reset() Source: https://github.com/hexacluster/credcheck/blob/master/README.md Shows the pg_banned_role view with a banned user, then calls pg_banned_role_reset() to clear the cache, and verifies the view is empty. ```sql test=# SELECT * FROM pg_banned_role; roleid | failure_count | banned_date --------+---------------+---------------------------- 250362 | 2 | 2023-06-09 20:33:58.490273 (1 row) test=# SELECT pg_banned_role_reset(); pg_banned_role_reset ---------------------- 1 (1 row) test=# SELECT * FROM pg_banned_role; roleid | failure_count | banned_date --------+---------------+------------- (0 rows) ``` -------------------------------- ### Connect as new user and observe forced password change error Source: https://github.com/hexacluster/credcheck/blob/master/README.md Connecting with the new user triggers an error requiring a password change. The user must execute `ALTER USER` to set a new password before running other queries. ```bash $ psql -h localhost -d test -U user1 Password for user user1: psql (17.5 (Ubuntu 17.5-1.pgdg24.04+1)) SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off, ALPN: postgresql) Type "help" for help. test=> SELECT count(1) FROM pg_stat_activity; ERROR: you must change your password first. test=> ALTER USER user1 PASSWORD 'Zkd89,34'; ALTER ROLE test=> test=> SELECT count(1) FROM pg_stat_activity; count ------- 6 (1 row) ``` -------------------------------- ### Basic call reporting failures for toban_user Source: https://github.com/hexacluster/credcheck Reports two authentication failures for role 'toban_user' from a fail2ban action. The reporter role (f2b_reporter) must be granted EXECUTE by the DBA. Each call returns the new failure count (1, then 2). ```sql -- reporter role (not superuser) granted by the DBA: -- GRANT EXECUTE ON FUNCTION credcheck_record_auth_failure(name) TO f2b_reporter; -- initial failures SELECT credcheck_record_auth_failure('toban_user'); -- credcheck_record_auth_failure -- ------------------------------- -- 1 -- (1 row) SELECT credcheck_record_auth_failure('toban_user'); -- credcheck_record_auth_failure -- ------------------------------- -- 2 -- (1 row) ``` -------------------------------- ### Error when extension not preloaded Source: https://github.com/hexacluster/credcheck Shows the error raised when calling pg_password_history() without the extension being in shared_preload_libraries. The error message is 'credcheck must be loaded via shared_preload_libraries to use password history'. ```sql -- extension installed but shared_preload_libraries does not contain credcheck SELECT * FROM pg_password_history(); -- ERROR: credcheck must be loaded via shared_preload_libraries to use password history ``` -------------------------------- ### Create pg_lastlog view Source: https://github.com/hexacluster/credcheck Defines the pg_lastlog view that wraps the credcheck_lastlog() function. The view is revoked from PUBLIC and granted SELECT to pg_read_all_stats. Requires the credcheck.lastlog configuration to be enabled. ```sql CREATE VIEW pg_lastlog AS SELECT * FROM credcheck_lastlog(); ``` -------------------------------- ### CREATE FUNCTION pg_password_history_timestamp Source: https://github.com/hexacluster/credcheck Exact SQL definition from sql/credcheck--6.0.0.sql. The function is STRICT and VOLATILE, returns integer, and is implemented in C. ```sql CREATE FUNCTION pg_password_history_timestamp( IN username name, IN new_timestamp timestamp with time zone) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### Unban a single role with pg_banned_role_reset Source: https://github.com/hexacluster/credcheck Shows a basic call to unban a single role. First query the pg_banned_role view to see the banned role, then call pg_banned_role_reset('toban_user') which returns the number of removed entries (1). ```sql SELECT * FROM pg_banned_role; -- roleid | failure_count | banned_date -- ---------+---------------+---------------------------- -- 250362 | 2 | 2023-06-09 20:33:58.490273 -- (1 row) SELECT pg_banned_role_reset('toban_user'); -- pg_banned_role_reset -- ---------------------- -- 1 -- (1 row) ``` -------------------------------- ### Create and rename user with password (username checks invoked) Source: https://github.com/hexacluster/credcheck/blob/master/README.md Username checks are invoked on both the CREATE USER and the subsequent ALTER USER RENAME statement when the user has a password. ```sql postgres=# CREATE USER user1 PASSWORD 'this is some plain text'; CREATE ROLE postgres=# ALTER USER user1 RENAME to test_user; ``` -------------------------------- ### Ignore case in password username check with credcheck.password_ignore_case Source: https://github.com/hexacluster/credcheck/blob/master/README.md Demonstrates enabling credcheck.password_ignore_case. With it 'on', a password that contains the username in a different case now fails, while a password without the username succeeds. ```sql postgres=# SHOW credcheck.password_ignore_case; credcheck.password_ignore_case -------------------------------- on (1 row) postgres=# CREATE USER abcd$ WITH PASSWORD 'ABCD$xyz'; ERROR: password should not contain username postgres=# CREATE USER abcd$ WITH PASSWORD 'A$xyz'; CREATE ROLE ``` -------------------------------- ### credcheck_lastlog() Source: https://github.com/hexacluster/credcheck Set-returning function (SRF) exposing the last-login history, including user sessions and PostgreSQL boot/shutdown/crash markers. It returns a set of records with session details and is used by the public view pg_lastlog. ```APIDOC ## credcheck_lastlog() ### Description Set-returning function (SRF) exposing the last-login history (modelled on Unix `last(1)`/wtmp): user sessions plus PostgreSQL boot/shutdown/crash markers. The public view `pg_lastlog` is built on top of it. ### Signature ```sql CREATE FUNCTION credcheck_lastlog ( OUT type text, OUT username text, OUT pid integer, OUT client_addr text, OUT client_port integer, OUT login_time timestamp with time zone, OUT logout_time timestamp with time zone, OUT duration interval, OUT state text, OUT query text ) RETURNS SETOF record AS 'MODULE_PATHNAME', 'credcheck_lastlog' LANGUAGE C VOLATILE; ``` ### Parameters None. ### Return Type `SETOF record` with the following OUT columns: | Column | Type | Description | |--------|------|-------------| | `type` | `text` | `user`, `boot`, `shutdown` or `crash` | | `username` | `text` | Role name (NULL for boot/shutdown/crash markers) | | `pid` | `integer` | Backend PID (`PostmasterPid` for boot records; NULL/0 for markers without PID) | | `client_addr` | `text` | Source host, or `[local]` for local connections (NULL for markers) | | `client_port` | `integer` | Source port (0 for local connections; NULL for markers) | | `login_time` | `timestamp with time zone` | Session start (or marker time) | | `logout_time` | `timestamp with time zone` | Session end; NULL while still connected | | `duration` | `interval` | `logout_time - login_time` (still-connected sessions: age from now); NULL for markers | | `state` | `text` | `still connected` for live sessions, `disconnected` for finalized user records, else the marker type | | `query` | `text` | Last executed SQL query when `credcheck.lastlog_track_query` is on; NULL otherwise | Live sessions (from anonymous shared memory `lastlog->active[]`) are emitted first, then the history ring from the mmap file, newest first. ### Behavior Notes - Requires `credcheck.lastlog = on` (shared_preload) — otherwise: `ERROR: credcheck.lastlog is disabled` (SQLSTATE 55000). - Requires `SFRM_Materialize` support, else `ERROR: set-valued function called in context that cannot accept a set` (SQLSTATE 0A000). - The `query` column always masks password literals (masking applies regardless of `credcheck.no_password_logging`). - The history ring defaults to 1024 records (`credcheck.lastlog_max`), with per-record stride depending on `credcheck.lastlog_query_size`. ### Throws | Error | Condition | Location | |-------|-----------|----------| | `credcheck.lastlog is disabled` (SQLSTATE 55000) | `credcheck.lastlog` not enabled in `shared_preload_libraries` | `credcheck.c:2697` | | `set-valued function called in context that cannot accept a set` (SQLSTATE 0A000) | Caller does not support set results | `credcheck.c:2700` | ### Request Example Basic call — look at the login history: ```sql SELECT type, username, pid, login_time, state FROM pg_lastlog ORDER BY login_time DESC LIMIT 5; -- type | username | pid | login_time | state -- ---------+----------+--------+-------------------------------+----------------- -- user | gilles | 148483 | 2026-09-09 16:59:07.765016+02 | still connected -- user | gilles | 148481 | 2026-09-09 16:59:07.171284+02 | disconnected -- user | postgres | 144974 | 2026-09-09 16:59:07.757562+02 | disconnected -- boot | | 144960 | 2026-09-09 15:36:28.674986+02 | boot -- shutdown| | | 2026-09-09 15:36:28.490285+02 | shutdown -- (5 rows) ``` Non-trivial use — with query tracking enabled: ```sql -- postgresql.conf (restart required): -- shared_preload_libraries = 'credcheck' -- credcheck.lastlog = on -- credcheck.lastlog_track_query = on -- credcheck.lastlog_query_size = 4096 SELECT username, login_time, duration, query FROM pg_lastlog WHERE type = 'user' AND query IS NOT NULL ORDER BY login_time DESC LIMIT 3; ``` Error handling — the feature is off: ```sql SELECT * FROM credcheck_lastlog(); -- ERROR: credcheck.lastlog is disabled ``` ``` -------------------------------- ### Create pgbouncer_auth function to enforce bans via auth_query Source: https://github.com/hexacluster/credcheck/blob/master/README.md SQL function that returns the password hash for a user only if the role is not banned. SECURITY DEFINER requires the owner to have EXECUTE on credcheck_is_banned if not superuser. Grant EXECUTE to the PgBouncer auth user. ```sql -- owned by a role allowed to read pg_authid (SECURITY DEFINER) CREATE FUNCTION public.pgbouncer_auth(i_user text) RETURNS TABLE(uname text, phash text) LANGUAGE sql SECURITY DEFINER AS $$ SELECT rolname::text, rolpassword::text FROM pg_authid WHERE rolname = i_user AND rolcanlogin AND NOT credcheck_is_banned(i_user::name) $$; REVOKE ALL ON FUNCTION public.pgbouncer_auth(text) FROM PUBLIC; GRANT EXECUTE ON FUNCTION public.pgbouncer_auth(text) TO ; ``` -------------------------------- ### Enforce minimum username length with credcheck.username_min_length Source: https://github.com/hexacluster/credcheck/blob/master/README.md Shows the effect of setting credcheck.username_min_length to 4. Creating a user with a shorter username fails with an error, while a username of length 4 succeeds. ```sql postgres=# SHOW credcheck.username_min_length; credcheck.username_min_length ------------------------------- 4 (1 row) postgres=# CREATE USER abc WITH PASSWORD 'pass'; ERROR: username length should match the configured credcheck.username_min_length postgres=# CREATE USER abcd WITH PASSWORD 'pass'; CREATE ROLE ``` -------------------------------- ### CREATE FUNCTION credcheck_record_auth_failure signature Source: https://github.com/hexacluster/credcheck Exact function signature from sql/credcheck--6.0.0.sql. Takes a role name and returns the new failure count as integer. STRICT means NULL input returns NULL. ```sql CREATE FUNCTION credcheck_record_auth_failure( IN username name ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### CREATE FUNCTION pg_check_password signature Source: https://github.com/hexacluster/credcheck Exact SQL definition from sql/credcheck--6.0.0.sql. Declares the function as STRICT and VOLATILE, returning boolean. ```sql CREATE FUNCTION pg_check_password( IN username name, IN password text ) RETURNS boolean AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` -------------------------------- ### Error handling for pg_banned_role Source: https://github.com/hexacluster/credcheck Checks if credcheck is in shared_preload_libraries and shows the error when it is absent. The error message is 'credcheck must be loaded via shared_preload_libraries to use auth failure feature'. ```sql -- credcheck in shared_preload_libraries? check: SHOW shared_preload_libraries; -- if credcheck is absent: SELECT * FROM pg_banned_role(); -- ERROR: credcheck must be loaded via shared_preload_libraries to use auth failure feature ``` -------------------------------- ### Create user without password (no username check) Source: https://github.com/hexacluster/credcheck/blob/master/README.md Username checks are not enforced when creating a user without a password. ```sql postgres=# CREATE USER user1; ``` -------------------------------- ### pg_banned_role_reset() Source: https://github.com/hexacluster/credcheck Removes entries from the authentication-failure ban cache. Two overloads: one clears the whole cache, one clears the cache for a single role. Only superusers may call it. ```APIDOC ## pg_banned_role_reset() ### Description Removes entries from the authentication-failure ban cache. Two overloads: one clears the whole cache, one clears the cache for a single role. Only superusers may call it. ### Signatures ```sql CREATE FUNCTION pg_banned_role_reset( ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C VOLATILE; CREATE FUNCTION pg_banned_role_reset( IN username name ) RETURNS integer AS 'MODULE_PATHNAME' LANGUAGE C STRICT VOLATILE; ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `username` | `name` | no (overload 2) | — | Only remove the cache entry of this role. Omitted (overload 1) clears the entire cache. | Overload 2 is `STRICT`: NULL returns NULL. ### Return Type `integer` — the number of cache entries removed (`num_removed`). Returns `0` when the shared state is not initialized (`!pgaf || !pgaf_hash`) or no entry matches. ### Behavior - Only superusers may call it: otherwise `ERROR: only superuser can reset banned roles cache`. - Takes the auth-failure cache LWLock exclusively and removes matching entries from the `pgaf_hash` dynahash table (`hash_search(..., HASH_REMOVE, NULL)`). - The cache is memory-only: a PostgreSQL restart clears it too (per the README, the failure history is deliberately not persisted). - Non-transactional: effective immediately. ### Throws | Error | Condition | Location | |-------|-----------|----------| | `only superuser can reset banned roles cache` | Caller is not a superuser | `credcheck.c:5235` | ### Examples Basic call — unban a single role: ```sql SELECT * FROM pg_banned_role; -- roleid | failure_count | banned_date -- ---------+---------------+---------------------------- -- 250362 | 2 | 2023-06-09 20:33:58.490273 -- (1 row) SELECT pg_banned_role_reset('toban_user'); -- pg_banned_role_reset -- ---------------------- -- 1 -- (1 row) ``` Clear the whole cache and show the error case: ```sql SELECT pg_banned_role_reset(); -- pg_banned_role_reset -- ---------------------- -- 3 -- (1 row) SET ROLE regular_user; SELECT pg_banned_role_reset(); -- ERROR: only superuser can reset banned roles cache ``` ``` -------------------------------- ### Check ban status with credcheck_is_banned after threshold Source: https://github.com/hexacluster/credcheck After setting credcheck.max_auth_failure = 2 and reporting two failures, verifies the role is banned at the pooler edge. Returns 't' when banned. ```sql SELECT credcheck_is_banned('toban_user'); -- credcheck_is_banned -- -------------------- -- t ``` -------------------------------- ### Error message when password is easily cracked by cracklib Source: https://github.com/hexacluster/credcheck/blob/master/README.md When cracklib is enabled to check password easiness, attempting to create a user with a weak password like 'pass123' results in an ERROR: password is easily cracked. ```sql postgres=# CREATE USER my_easy_password with password 'pass123'; ERROR: password is easily cracked ``` -------------------------------- ### Clear whole cache and show superuser error Source: https://github.com/hexacluster/credcheck Clears the entire ban cache with pg_banned_role_reset() returning the number of removed entries (3). Then demonstrates the error when a non-superuser attempts the call: 'ERROR: only superuser can reset banned roles cache'. ```sql SELECT pg_banned_role_reset(); -- pg_banned_role_reset -- ---------------------- -- 3 -- (1 row) SET ROLE regular_user; SELECT pg_banned_role_reset(); -- ERROR: only superuser can reset banned roles cache ``` -------------------------------- ### Create user with encrypted password error Source: https://github.com/hexacluster/credcheck/blob/master/README.md Attempting to create a user with an encrypted password results in an error: 'password type is not a plain text'. Enable credcheck.encrypted_password_allowed to allow encrypted passwords. ```sql postgres=# CREATE USER user1 PASSWORD 'md55e4cc86d2d6a8b73bbefc4d5b91baa45'; ERROR: password type is not a plain text ``` -------------------------------- ### Create pg_banned_role view Source: https://github.com/hexacluster/credcheck Defines the pg_banned_role view that wraps the pg_banned_role() function, casting roleid to regrole for display as role name. The view is revoked from PUBLIC and granted SELECT to pg_read_all_stats. ```sql CREATE VIEW pg_banned_role AS SELECT roleid::regrole, failure_count, banned_date FROM pg_banned_role(); ```