Writing a secure pg_hba.conf

A secure pg_hba.conf limits who can connect, from where, to which databases and with which method. This page explains how to design and roll out those rules on self-hosted PostgreSQL.

On this page

Why a secure pg_hba.conf is the first control on PostgreSQL access

Most self-hosted PostgreSQL clusters have a pg_hba.conf file that grew one exception at a time, and it now holds broad address ranges, trust lines left from a early setup, and md5 entries nobody remembers adding. The file decides, for each connection attempt, whether a client is admitted at all, over which connection type, from which address, to which database and as which user, and by which authentication method. Anything the file allows is admitted before roles, privileges or row-level policies get a say, so a loose rule here undermines controls further in. Read the file as an access policy, not as configuration you set once.

Teams should redesign the file on specific triggers: a security audit or review, a new application that needs its own database and role, a mandate to encrypt every client connection, or a move to SCRAM password hashing or to login through a directory. PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM, so any remaining md5 entries are now a planned migration item rather than a safe default. The pg_hba.conf file is the place where that migration is enforced, because the method on each line decides how a password is checked. Before editing, confirm which server version you run and which client libraries connect to it, since older drivers may not support SCRAM.

A redesign starts with an inventory of who connects today: applications, batch jobs, replication users, administrators and monitoring agents, along with their source addresses. Ask your team or partner to produce that inventory from server logs and connection statistics rather than from memory, because the rules that are hardest to remove are the ones nobody can explain. The sibling topics on TLS, certificates, directory login and roles build on the rules you define here, so settle the structure of the file first. Check the official PostgreSQL client authentication documentation for the methods your version supports before you commit to a design.

Which pg_hba.conf connection types and methods fit which access

This table compares the connection types and authentication methods a designer chooses between in pg_hba.conf, with the situations each suits and its main trade-off. Read each row as a question: which client is connecting, over what path, and what proof of identity the server should require.

Type or methodWhen it fitsMain trade-off
hostAny TCP client where the connection method itself is then forced to use TLS by a separate rule, so it is rarely the right final choice on its ownMatches plaintext and TLS connections alike, so it cannot guarantee encryption without a paired hostssl rule
hostsslRemote clients, including applications and admins, where traffic must be encrypted before any password or token is exchangedClients and any connection poolers in the path must support TLS and be configured to use it
hostnosslA narrow, deliberate case such as a legacy client that cannot negotiate TLS, kept on a tightly limited address rangeSends credentials in clear text, so it should be a short, documented exception with a planned removal date
scram-sha-256 (password)Database users who sign in with a password, applications without a directory or certificate optionSecurity depends on password strength and rotation, and the server must hold a SCRAM verifier for each role
certServices and admins who hold client certificates from an internal CA, with names mapped to rolesRequires a certificate lifecycle (issuance, rotation, revocation) and a clear mapping in pg_ident.conf
gss (Kerberos)Sites that already run Active Directory or FreeIPA and want passwordless sign-in for people and servicesNeeds keytabs, correct service principals and DNS, and clients that support GSSAPI
ldapSites that check database passwords against a directory without KerberosTies login to directory availability and the bind method chosen, and roles must still exist in PostgreSQL
oauth (PostgreSQL 18)Users who sign in with tokens from an OAuth provider, where the provider holds the identityRequires a validator library, issuer matching and role mapping, and PostgreSQL 18 or later
peer or ident (local sockets)Operating system users connecting over a local Unix socket for administration on the same hostTrusts the operating system account on the server, so account control on the host becomes database access control
trustAlmost never in production, only in a short isolated test setupAllows any client matching the rule to connect without proof of identity
md5Legacy compatibility only, where older clients cannot yet use SCRAMPostgreSQL 18 deprecates MD5 password authentication in favor of SCRAM, so plan its removal

Narrowing addresses, databases and users in each rule

The address column decides which network sources a rule matches. A rule that lists a single host or a narrow subnet limits who can even attempt a login for that database and role, so a stolen password is less useful when it is presented from an unexpected machine. Broad ranges such as a whole private /8 or an entire data center block make every workstation and tenant in that range a potential attacker. Write each rule against the smallest set of sources that really originate the traffic, and keep application servers, administrators and monitoring hosts in separate rules.

  • Use host or CIDR entries: Name the application subnet or specific hosts instead of 0.0.0.0/0 or all.
  • Keep administrative sources apart: Allow admin logins only from a bastion or management network.
  • Check the apparent source: Load balancers, NAT gateways and connection poolers replace the client address, so the server sees the proxy, not the application.
  • Account for Kubernetes and overlay networks: Pod or service addresses may change, so confirm which address the server receives before writing a fixed entry.
  • Test from every legitimate path: A client outside the expected range fails with an authentication error that looks like a bad password.

Before you change any address entry, confirm with a test connection from each intended path which address PostgreSQL logs for the session.

Rewriting pg_hba.conf safely on a running cluster

This sequence replaces a permissive client authentication file with a reviewed rule set, applied without downtime and checked at each stage so that every rule matches what the team intended before clients depend on it.

  1. Inventory every current connection source

    Start by listing who connects to the cluster today. Pull client addresses, users, databases and application names from the PostgreSQL server logs and from the pg_stat_activity view, sampling across business hours, batch windows and failover tests so that periodic jobs are not missed. Cross-check the list with the owners of each application, administrators' jump hosts, monitoring agents, backup tools and replication consumers. Done means every connection source is named, has an owner and is recorded in a single inventory. Any source you cannot attribute is treated as a finding to resolve before the rules are narrowed.

  2. Write the target rule set in intended order

    Draft the new pg_hba.conf as a written rule set, with the most specific rules first because PostgreSQL reads records top to bottom and applies the first match. Give separate rules for application roles, administrator access, batch jobs and replication, each limited to the specific databases, users and address ranges from the inventory, and use hostssl for any remote connection that must be encrypted. Remove trust entries and move password-based entries to scram-sha-256. Have a second engineer review the draft against the inventory. Done means every inventory entry maps to exactly one rule and the reviewer has signed off on the order.

  3. Set scram-sha-256 and confirm stored password hashes

    Set password_encryption to scram-sha-256 in postgresql.conf, reload the configuration, and then reset passwords for roles that still hold older hashes, since a change to the setting does not rewrite existing passwords. Confirm the result by querying pg_authid for the password hash prefix of each login role, which should begin with SCRAM-SHA-256 for every role that has a password. Review the md5 entries in the draft rule set and replace them with scram-sha-256. Done means no role that logs in with a password still has an md5 hash, and the draft contains no md5 method. Note that PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM.

  4. Test each rule from a client in staging

    Load the draft file into a staging cluster that mirrors production roles, databases and TLS configuration. For each rule, connect with a representative client for that connection source, and also attempt a connection that should be refused, such as a wrong database, a wrong address or a non-encrypted connection to a hostssl-only rule. Record the client, the expected result and the actual result in a test log. Done means every allowed path succeeds, every denied path fails with the expected error, and the log has no unexplained result. Any mismatch goes back to the draft in step two before the file moves forward.

  5. Keep a rollback copy of the live file

    Before changing production, copy the current pg_hba.conf to a dated backup in the same directory or in your configuration management system, and record its checksum. Confirm the copy opens and matches the live file byte for byte. Also record the file's location, as shown by SHOW hba_file, and the operator who will perform the reload. Done means a restorable copy exists, its checksum is logged, and the team knows how to put it back and reload. Rollback then means restoring this copy and reloading, not restarting the server.

  6. Reload the configuration without restarting

    Install the reviewed file and ask the server to reread its configuration with SELECT pg_reload_conf(); or the equivalent pg_ctl reload command. Authentication rules are read on reload, so existing sessions are not disrupted and a restart is not needed. Watch the server log for parse errors, since a syntax problem causes the reload to be rejected and the previous rules to remain in force. Done means the function returns true, the log shows the configuration was reloaded without errors, and a test connection from each major source still succeeds. If a source fails, restore the rollback copy and reload again.

  7. Verify parsed rules match intent with pg_hba_file_rules

    Query the pg_hba_file_rules view, which shows how the server parsed each line, including the line number, type, databases, users, addresses, auth method and any error. Compare each parsed row with the target rule set from step two, confirming that the order, address masks, hostssl or host type, and method are exactly as intended. Check that the error column is empty for every row. Done means the parsed view matches the reviewed draft, no row carries an error, and the result is saved with the change record. Repeat this check after any future edit to the file.

Separate rules for replication, administrators and applications

Give replication, administrators and applications their own rules in pg_hba.conf, because each group has a different reason to connect and a different blast radius if its credentials leak. The replication pseudo-database exists for this purpose: a standby's streaming connection is not a database session, so it should match a rule that names only replication and no application database. Keeping that rule separate means a standby can be allowed from the standby's own address while an application pool that happens to use the same user name is still refused. Confirm in the PostgreSQL authentication docs how the replication keyword interacts with your address and method choices before you write the rule.

Administrator access deserves its own address range, ideally a bastion or management network rather than any workstation that can reach the database port. A rule that admits administrative roles from the application subnet gives a compromised web tier a path to superuser-level sessions. Limit admin rules to the bastion's address, pair them with a method that requires strong authentication, and keep the number of roles allowed through them small. Ask your network team to confirm which subnets can route to the database host, because a rule is only as narrow as the network path behind it.

Application rules should name the application roles that the software actually logs in with, not a shared superuser account or a generic postgres login. Each application gets its own role, its own database and its own rule, so a pool serving one service cannot be used to reach another. When you review the file, check that no application rule uses the all keyword for either database or user, and that replication, admin and application rules do not overlap in the order they are read. Record the owner of each rule so that a change to one group is reviewed by the people responsible for that group.

How a connection attempt moves through pg_hba.conf

A client connection starts at the listener and is compared against the records in pg_hba.conf from top to bottom. Each record is tested for connection type, database, user and address, and the first record that matches decides the authentication method. If that method fails, or if no record matches at all, the connection is rejected, so record order is a security control. Check each path to confirm that the intended record is the one that answers.

First matching record decides the outcome; no match means rejection.

Security risks in pg_hba.conf and how to avoid them

The pg_hba.conf file decides who can connect, from where, to which database, and with what proof of identity. Most authentication weaknesses in self-hosted PostgreSQL come from a few recurring entries and habits, and each card below pairs one risk with the control that closes it.

Trust entries admit anyone

A trust method accepts a connection without asking for a password or any other proof of identity, so anyone who can reach the listening address and claim a role name gets in. Such entries often survive from initial setup or testing. Check every rule for trust, confirm which addresses it matches, and replace it with scram-sha-256 or a certificate method. Treat any remaining trust line as a finding to close before go-live.

Authentication methods docs

MD5 entries kept after SCRAM

The md5 method still works, but PostgreSQL 18 deprecated MD5 password authentication in favor of SCRAM. Rules that stay on md5 also keep the server from relying on the stronger password hashing you intended. Set password_encryption to scram-sha-256, reset passwords so they are stored in SCRAM form, and change each md5 rule to scram-sha-256. Confirm that older client libraries in your estate support SCRAM before the change.

PostgreSQL 18 release notes

Plaintext credentials over host connections

A host rule does not require TLS, so a password sent by a client can cross the network unencrypted when the connection is not protected. Use hostssl for every rule that carries a password, and reject non-SSL connections for remote addresses. Pair this with the server certificate setup and sslmode=verify-full on clients. Check it by attempting a non-SSL connection from a remote host and confirming that PostgreSQL refuses it.

Broad addresses and all-database rules

Entries such as all all 0.0.0.0/0 let every role reach every database from any network. The rule is often written this way to avoid debugging a narrow match, then never tightened. Name the database, role and the exact subnet or host of each application server or administrator workstation. Put the most specific rules first, and keep a final reject line for anything unmatched. Ask the team to justify any range wider than a single subnet.

Shared superuser logins

When administrators and applications connect as the postgres superuser through a shared password, no one can tell who ran a change, and a leaked secret grants full control. Give each administrator a named role, route application access through least-privilege roles, and limit superuser use to break-glass procedures. Use client certificate or directory-backed methods for named people where possible, and check that the rules for postgres are narrower than the rules for application roles.

Unreviewed changes to the file

The pg_hba.conf file is read in order, and a single line added above a restrictive rule can open access without any failed test. Store the file in version control, require review for each change, and check the effective rules after every edit with pg_hba_file_rules before reloading. Use pg_ctl reload or SELECT pg_reload_conf(); so existing sessions stay up, and keep a tested rollback copy.

Reloading the file and managing change control

Changes to pg_hba.conf take effect when the server reloads the file, not when it restarts, so a new rule can be live within seconds of a reload. That is useful for rolling out a narrowed rule without downtime, but it also means a typo, a wrong record order or a mistaken address range can block every new session immediately. Treat each reload as a production change with a rollback plan, and confirm before you start how your team reloads the server (for example, through pg_ctl reload, SELECT pg_reload_conf() or your service manager) so the same step is used every time.

Keep the file in version control and review edits with the same rigor you would give firewall rules. Each change should show the record added, removed or moved, the reason, a named reviewer and the ticket that authorized it. Record who changed which record and why in the commit message rather than relying on memory or on the server's own history, which does not capture intent. Store the reviewed file in configuration management so a rebuilt server gets the same rules, and check that the deployed file matches the approved copy after every reload. Also check whether your team has a documented way to restore the last known good file quickly.

Before reloading, open a second administrative session that is already authenticated and leave it open. If the new rules reject your ordinary login, that session lets you revert the file and reload again. Test the change from a client on the path you expect, including the hostssl or host variant, the database and user combinations, and at least one replication connection if your rules cover it. A reload does not necessarily terminate sessions that were already authenticated under the old rules, so review active connections separately, for example in pg_stat_activity, and decide whether to end sessions that no longer match policy. Confirm this behavior against the version you run, since it is documented in the client authentication pages.

Limits to confirm in your environment before you rely on these rules

The rules in a pg_hba.conf file only match what PostgreSQL actually sees. Proxies, poolers, directories and replication paths can change the address, identity or availability that the rules depend on, so confirm each of these in your own environment before you treat a rule set as final.

Client address as seen by PostgreSQL

Address-based rules match the source address PostgreSQL receives, not the address of the application that opened the session. If PgBouncer, a load balancer or a sidecar proxy sits in the path, every client may appear as the pooler's address, and a rule written for application subnets could match too broadly or not at all. Check which address reaches the server in logs and in pg_stat_activity, and confirm whether the proxy preserves the original address and how. Behavior depends on the installed version and configuration of each component.

PgBouncer docs

Method support in your version and packaging

Not every authentication method is available in every build. Some distributions compile out or package separately the GSSAPI, LDAP, RADIUS, PAM or OAuth support that a planned rule depends on. Confirm that your PostgreSQL version and packaging accept each method and the options you intend to use, and test that the server starts with the final file. Methods deprecated in a given release should be replaced in the plan, not carried forward silently.

OAuth method added
18
Authentication methods

Directory, certificate and OAuth failure behavior

A rule that delegates login to LDAP, Kerberos, a certificate authority or an OAuth issuer inherits that system's availability. When the directory or issuer is down, logins can fail for every user, including administrators who need a fallback path. Decide in advance which local accounts remain available, how certificate revocation or expiry is handled, and what happens to existing sessions. Test these failure paths in a lab before a rule goes live.

Reachability of replication hosts

Replication rules in the replication pseudo-database only work if standbys connect from addresses you can name in the file. Dynamic addresses, NAT, or standbys behind a different network path can fail to match and stop replication without any change to the primary's configuration. Confirm the source address each standby presents, whether it changes after a failover, and how a promoted standby will be added to the rules before failover is needed.

High availability docs

Audit and change record requirements

Editing pg_hba.conf changes who can connect, so your audit process may require a record of who changed the file, when, why and who approved it. PostgreSQL reloads the file but does not keep a change history of its own. Confirm whether your change control requires version control of the file, an approval step, and retention of the prior version. Check which connection events your logging captures, since a rejected or accepted login is only evidence if it is logged.

Questions teams ask before writing their own pg_hba.conf

Can our own team write a secure pg_hba.conf without outside help?

Yes, if one or two engineers understand PostgreSQL authentication, can read the server logs, and have a complete list of every application, user, host and tool that connects. The file itself is short, but the work is in the inventory: which clients connect, from which networks, to which databases, and whether they need TLS or a directory login. Teams without that knowledge usually get the file right for the applications they remember and break the ones they forgot. Plan a test window, keep a rollback copy of the old file, and check the reload result in the server log before closing the change.

What makes a pg_hba.conf rewrite take longer?

The main drivers are the number of applications and clients, how many distinct networks and hosts they come from, whether replication, backup tools and administrators each need their own rules, and whether directory integration such as LDAP, Kerberos or certificates is part of the target design. Each environment (development, test, production, disaster recovery) multiplies the review. Duration depends most on inventory quality. A team with a current connection map moves faster than one that has to discover connections by reading logs over several weeks. Ask any partner to show how they will build that inventory before agreeing a timeline.

What does a partner need from us before starting?

A partner needs working access to the database servers and their configuration, read access to the current pg_hba.conf and postgresql.conf, and the ability to test changes in non-production environments first. They also need a connection inventory, meaning application names, service accounts, client hosts or subnets, target databases and the authentication method each one uses today. Each application needs a named owner who can confirm its behavior and approve the cutover window. Without owners, rules are guesses, and the change stalls at the first unknown client.

Do we have to change application code to move from md5 to SCRAM?

Usually not in the application code itself, but the change touches the database and client side. The server must store new passwords as SCRAM hashes, which happens when a password is set again after password_encryption is set to scram-sha-256. Existing md5-hashed passwords keep working until they are reset, so the rule change in pg_hba.conf must wait until every role has a SCRAM hash. Older client libraries or drivers may not support SCRAM, and those clients need an upgrade or a different method. The PostgreSQL 18 release announcement notes that MD5 password authentication is deprecated in favor of SCRAM, so plan the move rather than postponing it.

Which parts of a pg_hba.conf project cost money, and what recurs?

Costs fall into three groups: discovery (inventory, log review and owner interviews), design and testing (rules, rollout plan, non-production validation) and cutover support (reload, verification and fixing unexpected failures). Discovery and design are mostly one-time. Recurring work appears when new applications, new networks or new administrators arrive, because every new client needs a rule and a review. Ask a partner to separate one-time work from any ongoing review arrangement, and to state who performs testing in each environment.

What should a quote for this work contain?

A quote should follow from a written scope and list the systems in scope, the number of environments, the authentication methods to be implemented (for example, SCRAM, TLS-based certificates or directory login), and the assumptions about access and owner availability. It should state the deliverables, such as the revised file, a rule-by-rule explanation, a test script or checklist, a rollback procedure and a reload runbook. It should also name what is excluded, such as TLS certificate issuance or directory administration, and how changes after sign-off are handled. DeployOpen does not publish a price list, and its engagements are fixed-scope, so the quote is built from that written scope.

How do we avoid locking ourselves out when we reload the rules?

Keep an existing administrative session open while you test, and test the new file on a non-production server first. Make changes in small groups, reload with pg_ctl reload or SELECT pg_reload_conf();, and confirm each change with a test connection from the expected client. PostgreSQL applies rules in file order and uses the first match, so a broad rule placed too early can override a narrow one. Keep a copy of the previous file, and verify that a failed rule appears in the server log before you close the window.

How DeployOpen scopes and delivers pg_hba.conf hardening

DeployOpen plans, implements and documents PostgreSQL client authentication inside your own infrastructure. We start from an inventory of every client, service and admin path that reaches the database, then replace broad rules with narrow, tested ones and hand over the files and runbooks your team needs to operate them.

How we scope

  • Inventory every client, application, replica and admin path that connects to each PostgreSQL cluster in scope.
  • Record which hosts, subnets, databases and roles currently rely on trust, md5 or broad address ranges.
  • Agree in writing which clusters, environments and pg_hba.conf files are covered, and what testing is included.

How we build

  • Draft ordered rules with specific databases, users and address ranges, with a final reject line for everything else.
  • Require hostssl for remote connections and apply SCRAM-based password rules or certificate methods where the environment supports them.
  • Separate replication and administrator rules from application rules, then test each allowed and denied connection path before rollout.

How we hand over

  • Deliver the final pg_hba.conf with comments explaining each rule, its owner and the reason it exists.
  • Provide a reload procedure with a validation query, a rollback copy of the previous file and a check of active sessions.
  • Document the connection test matrix so your team can rerun it after changes, upgrades or new applications are added.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Ongoing rule reviews, upgrades and retesting after new applications or network changes are available as a retainer.
  • Ask any provider to confirm which environments, PostgreSQL versions and access paths are included in their quote.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.