pg-harden — PostgreSQL Security Audit and Hardening with Rollback Plan

pg-harden is an open-source security audit and hardening tool for PostgreSQL (as of November 2026, version 0.4.1). It checks a PostgreSQL instance against 86 security rules (74 for the server, 12 for the client machine) and writes a change plan with rollback SQL. Only when you explicitly run apply --execute does it apply selected fixes — with a backup upfront and a login check after reloading.

The tool runs on PHP 8.3 or newer with no Composer dependencies (requires pdo_pgsql and mbstring). It is tested on PostgreSQL 14 through 18 plus 19rc1 on Debian 13, and on PostgreSQL 18 on Windows 11. It is intended for your own systems or systems you are explicitly authorized to harden.

pg-harden workflow: check, plan, apply safely, and roll back if needed 1. check Read 86 rules 2. plan Plan & rollback 3. apply Journal & test 4. rollback Restore prior state
Figure 1: From read-only inspection to controlled execution with a tested rollback path.

Open Source on GitHub

Licensed under MIT, pg-harden audits postgresql.conf, pg_hba.conf, TLS, passwords, roles, and privileges. The README is available in full in German and as an English summary; tool output is currently in German.

View on GitHub

Training: PostgreSQL Security & Hardening

Learn the operational background behind the rules: authentication, pg_hba.conf, TLS, roles, privileges, and day-to-day operations for DBAs and security engineers.

View Training (German)

Why plain checklists are not enough

A checklist spots common misconfigurations, but it cannot tell you what will break in production once you change a setting. A single mistake in pg_hba.conf can lock out every user. pg-harden therefore pairs read-only auditing with a structured change plan, a dry run, and a tested rollback path.

In our PostgreSQL Security and Hardening training (German) and real-world reviews, the same four gaps show up repeatedly across files and system catalogs:

  • pg_hba.conf: Entries using trust, md5, or password, network access without TLS, or all open to every address.
  • Passwords: Roles using their own role name, postgres, or Passwort1. Looking at pg_authid will not reveal this because PostgreSQL only stores hashes.
  • Privileges: PUBLIC allowed to create objects in public, connect to every database, and create temporary tables, or SECURITY DEFINER functions without a fixed search_path.
  • Operating system: Overly permissive file modes on the data directory, configuration, TLS keys, and socket, or plaintext passwords in environment variables, scripts, and .pgpass files. For the OS layer underneath, see The Operating System Beneath PostgreSQL (German).
Comparison: plain checklist vs. pg-harden A plain checklist only lists findings without lockout protection or rollback. pg-harden checks 86 rules read-only, generates a change plan with rollback SQL, tests login after reload, and restores automatically on failure. Plain Checklist Lists findings only No lockout protection No automated rollback With pg-harden 86 rules read-only Plan, dry run & login test Journal & rollback per change
Figure 2: A checklist finds issues; pg-harden also safeguards the remediation.

What pg-harden does

pg-harden strictly separates inspection from changes. The check, plan, client, and rules commands never modify the server; they only read state. Only apply --execute and rollback write configuration files or execute SQL, recording every step in a journal.

  1. Audit (check): Checks 86 rules and reports severity, rationale, and remediation for each finding. Every database query runs individually inside a read-only transaction (BEGIN TRANSACTION READ ONLY … ROLLBACK). Output is printed to the terminal or saved with -o as JSON and HTML files (including overview and print view).
  2. Plan (plan): Writes a change plan to disk without touching the server: conf.d parameters, per-database SQL fixes with rollback comments, and a list of manual items.
  3. Compare (check -f, client -f): Compares the current run against a previous report for both server and client machines. A finding only counts as resolved if that exact check ran again.
  4. Apply (apply) and roll back (rollback): Without --execute, apply runs a dry run only. With --execute, it backs up existing files to a journal, lets PostgreSQL validate the new configuration, and tests its own login after reload. If anything fails, it automatically restores the prior files and writes an HTML log to the journal. pg-harden never restarts the PostgreSQL server. Keep two limits in mind: the login test verifies the tool's connection, not your applications, and rollback overwrites later third-party edits to the same files.
  5. Password check without login attempts: Recomputes stored SCRAM-SHA-256 and MD5 verifiers against a short list of obvious candidates, optionally extended with up to 100 organization-specific terms. Reports only output the role name, never the password.
  6. OS and client checks: When run on the database host, check inspects permissions on the data directory, configuration, TLS keys, and socket, as well as the service account on Linux and Windows. client inspects the connecting machine without a database connection for password files, environment variables, scripts, cron jobs, and services. Scanning other users' accounts (--user) requires authorization and, for employees, a legal basis.
  7. Run without superuser: Nearly all rules work with a non-superuser role. Any rule lacking privileges is marked as skipped in the report.

Hiding database names from other roles

By default, any authenticated role can list all database and role names (\l, \du, GUI clients) — even for databases it cannot connect to. The db.catalog_visibility rule revokes PUBLIC read access on eight system catalogs, but it does not replace true tenant isolation.

Testing across PostgreSQL 14 through 19rc1 (October 2026, Docker on Debian 13) showed the following limits:

  • The privilege applies per database. You must also revoke it in template1 so newly created databases inherit it.
  • Afterwards, \l, \du, and pg_dump fail for non-superusers unless the role is granted explicit SELECT. Monitoring tools, backup scripts such as pg-clusterbackup, and drivers that query these catalogs need targeted grants beforehand.
  • In tests, the revocation survived both pg_upgrade (17 to 18 and 14 to 19rc1) and pg_dumpall restore, though you should re-verify after any upgrade or restore. Databases created with TEMPLATE template0 do not inherit the revocation, but the next check run flags them.
  • Not true isolation: Role names can still be inferred via OIDs, connection error messages reveal whether a database exists, and pg_stat_activity exposes active sessions. Use separate clusters when strict tenant isolation is required.

Sample output

The repository includes genuine, unedited output from all commands run against an intentionally weak example instance. You can inspect text and HTML reports, change-plan files, dry runs, journaled execution, before/after diffs, rollback output, the rule catalog, client checks, and lockout protection. Only a fictional instance is published because real audit reports are confidential; a script in the repository regenerates all examples at any time.

Excerpt from a check report — findings are grouped by severity with each affected item below:

BEFUNDE — HOCH (7)
  tls.ssl_enabled               TLS ist eingeschaltet
                                - ssl: ist 'off', erwartet 'on'
  auth.md5_passwords            Keine Rolle hat noch ein MD5-Passwort
                                - reporting: Passwort als MD5-Hash gespeichert
  auth.weak_passwords           Kein Passwort einer anmeldefähigen Rolle stammt aus der Prüfliste
                                (naheliegende Werte, optional Betreiberbegriffe)
                                → Geprüft wurde nur eine kurze Liste naheliegender Werte — das sagt nichts
                                  über die Stärke der übrigen Passwörter.
                                - reporting: Passwort stammt aus der Prüfliste (wird nicht ausgegeben)
                                - shop_app: Passwort stammt aus der Prüfliste (wird nicht ausgegeben)

Excerpt from the change plan (harden_shop.sql) — every fix includes its rollback command:

-- code.secdef_search_path: public.order_total(p_id bigint)
-- BESTÄTIGEN: ALTER ROUTINE public.order_total(p_id bigint) SET search_path = public, pg_temp;
-- Rückweg: ALTER ROUTINE public.order_total(p_id bigint) RESET search_path;

Lockout protection: apply refuses to switch trust to scram-sha-256 if roles without a SCRAM password could no longer log in, leaving pg_hba.conf untouched:

NICHT AUSGEFÜHRT
  hba.trust                     Rollen ohne SCRAM-Passwort würden sich nicht mehr anmelden können: postgres,
                                reporting — erst Passwörter neu setzen

All sample outputs in the GitHub repository


Tested versions

pg-harden v0.4.1 is tested on PostgreSQL 14 through 18 and 19rc1 on Debian 13, and on PostgreSQL 18 on Windows 11 (as of November 2026). Rules for parameters introduced in newer releases are automatically skipped on older servers.

PostgreSQL Tested on
14, 15, 16, 17, 18 Docker, Debian 13
19rc1 (Release Candidate) Docker, Debian 13 — pre-release check
18 Windows 11

The test matrix verifies that pg-harden runs on these versions and documents version differences; it does not measure detection accuracy for every individual rule. See the version matrix on GitHub (German).


Quick start

You need PHP 8.3 or newer with pdo_pgsql and mbstring, plus pcntl and posix on Linux for write runs (apply --execute, rollback). Pass the password via PGPASSWORD or a .pgpass file, never on the command line. Four steps take you from the first audit to verified remediation:

Quick start with pg-harden in four steps 1 check (audit) 2 plan (SQL & conf) 3 apply (dry run) 4 apply --execute
Figure 3: Recommended workflow from read-only audit to verified execution.
git clone --branch v0.4.1 https://github.com/glueck-it/pg-harden.git
cd pg-harden
php pg-harden.php check --host=db1 --user=postgres --sslmode=verify-full                       # terminal report
php pg-harden.php check --host=db1 --user=postgres --sslmode=verify-full -o audit              # writes audit.json and audit.html
php pg-harden.php plan  --host=db1 --user=postgres --sslmode=verify-full --dir=plan-1          # change plan files
php pg-harden.php apply --host=db1 --user=postgres --sslmode=verify-full                       # dry run

Version 0.4.0 fixes a security vulnerability when running as Administrator on Windows (affecting 0.3.0 through 0.3.2). If you use one of those versions as Administrator on Windows, upgrade to 0.4.1, which also fixes several pg_hba.conf checks. See the Changelog on GitHub for details.

Write runs (apply --execute, rollback) and password checks require --sslmode=verify-full over remote connections. To audit without superuser privileges, create a dedicated role:

CREATE ROLE pgharden LOGIN;                                 -- pg_ prefix is reserved for system roles
GRANT pg_monitor TO pgharden;
GRANT EXECUTE ON FUNCTION pg_hba_file_rules() TO pgharden;
GRANT SELECT ON pg_hba_file_rules TO pgharden;
-- after db.catalog_visibility, also grant in each database (otherwise the run aborts):
-- GRANT SELECT ON TABLE pg_catalog.pg_database, pg_catalog.pg_roles TO pgharden;

Frequently Asked Questions (FAQ)

Which PostgreSQL versions are supported?

pg-harden is tested on PostgreSQL 14, 15, 16, 17, 18, and 19rc1 (Release Candidate) on Debian 13, and on PostgreSQL 18 on Windows 11. Tool output and the version matrix are currently in German. Rules for parameters added in newer PostgreSQL releases are skipped on older servers.

Does pg-harden modify the server?

The check, plan, client, and rules commands are read-only and never modify the server. Only apply and rollback make changes, and apply without --execute only previews what it would do. Configuration files are modified only when apply runs locally on the database host.

Is pg-harden a benchmark scanner?

No. pg-harden does not implement any published benchmark and does not replace a benchmark or a review of your own requirements. Its focus is combining a change plan with rollback SQL, client-machine checks, and a safeguarded execution step.

Does my system comply with ISO 27001 afterwards?

No. The tool produces technical check results you can use as audit evidence. It ships with a verified mapping to BSI IT-Grundschutz module APP.4.3 "Relationale Datenbanken" (Edition 2023) and a preliminary, unverified mapping to ISO/IEC 27001:2022 Annex A. A clean run only means the rule catalog found no issues — it does not certify compliance.

How should audit reports be handled?

Reports can contain role, object, and network names that may identify individuals. Treat them as confidential, use them solely for remediation, and delete them after a defined retention period. Restrict access if you keep them as audit evidence, and observe data protection and co-determination rules where roles map to employees.

Where can I find the source code and documentation?

The full project with changelog, tests, and documentation in German and English is hosted on GitHub: https://github.com/glueck-it/pg-harden.

A release archive is also available on the PostgreSQL Extension Network: pg-harden on PGXN. pg-harden is a command-line tool, not a server extension; there is no CREATE EXTENSION.


Related Training & Consulting

If you want to deepen the concepts or get hands-on help hardening your PostgreSQL environment, I support teams in the Cologne/Leverkusen area on-site as well as remotely or in-house across Germany — see Database Consulting in the Rhineland (German) and PostgreSQL Maintenance (German):