pg_hba.conf

On this page 7

pg_hba.conf is the PostgreSQL host-based authentication configuration file that decides which clients may connect, to which databases, as which roles, and which authentication method each connection must pass. In database security, it is the first gate a connection meets, evaluated before any privilege, row-level security policy or audit rule applies.

The file is plain text, usually stored in the data directory, and its location can be changed with the hba_file parameter. Every connection attempt is matched against its rules from top to bottom, and the first matching line wins.

How pg_hba.conf evaluates connection attempts

PostgreSQL evaluates pg_hba.conf by comparing each incoming connection with the rules in file order and applying the first rule that matches the connection type, database, user and client address. If no rule matches, the connection is rejected by default, so the file works as an allow list.

There is no fall-through: when a matching rule requires a password and the password is wrong, PostgreSQL does not try later lines. This makes rule order the most important design decision, with specific rules placed above general ones.

Each record has the same columns, summarized in the following table.

FieldMeaningExample values
TypeConnection transportlocal, host, hostssl, hostnossl, hostgssenc
DatabaseTarget database or keywordall, sameuser, replication, app_db
UserRole name or groupall, app_user, +readonly
AddressClient IP range or host name10.0.0.0/8, 192.168.1.20/32
MethodAuthentication methodscram-sha-256, cert, reject
OptionsMethod-specific settingsclientcert=verify-full, map=ldapmap
Fields of a pg_hba.conf record

Changes take effect only after a configuration reload, for example with SELECT pg_reload_conf() or pg_ctl reload. The pg_hba_file_rules view shows how the server parsed the file and reports syntax errors before they cause an outage.

Authentication methods available in pg_hba.conf

The method column determines how a client proves its identity, and the choice largely defines the security of the whole server. Modern deployments should prefer SCRAM-SHA-256, certificates or an enterprise identity system over older password methods.

MethodHow it worksSecurity levelTypical use
trustNo authenticationNoneIsolated test only
peerMatches OS user on local socketHigh on local hostAdministrative access
scram-sha-256Salted challenge-response passwordHighDefault for applications
md5Hashed password challengeLegacy, weakerOld clients only
certTLS client certificateVery highService-to-service
ldap, gss, radiusExternal identity systemDepends on setupEnterprise sign-on
rejectAlways deniesNot applicableExplicit block rules
Common authentication methods and their suitability

Since PostgreSQL 14, password_encryption defaults to scram-sha-256, and the md5 method is deprecated in recent releases. Using hostssl rather than host ensures that password exchanges and data travel only over TLS-encrypted connections.

Writing a secure rule set

A secure pg_hba.conf follows the principle of least access: each rule names the narrowest database, role and network that a client needs. Broad entries such as all all 0.0.0.0/0 are the most common cause of unintended network exposure.

OrderRule purposeExample line
1Local administrator via OS identitylocal all postgres peer
2Replication from standbyhostssl replication replicator 10.0.2.15/32 scram-sha-256
3Application servers to one databasehostssl app_db app_user 10.0.1.0/24 scram-sha-256
4Block plaintext connectionshostnossl all all 0.0.0.0/0 reject
5Deny everything elsehost all all 0.0.0.0/0 reject
Example rule layout from specific to general
  • Combine with listen_addresses so the server listens only on the interfaces that rules expect.
  • Use group roles with the plus prefix so access follows role membership, not long user lists.
  • Keep the file under version control and review every change like application code.
  • Add a firewall or security group as an independent network layer, never as a replacement.

pg_hba.conf compared with other access controls

pg_hba.conf controls who may establish a session, while other PostgreSQL mechanisms control what a session may do. Effective database access control needs all layers, because each one stops a different kind of misuse.

LayerQuestion it answersConfigured with
Host-based authenticationMay this client connect at allpg_hba.conf
Database privilegeMay this role use this objectGRANT and REVOKE
Row-level securityWhich rows may this role seeCREATE POLICY
Database auditWhat did this role dopgAudit, server logs
Layers of PostgreSQL access control

A related file, pg_ident.conf, maps external identities such as OS users or certificate names to database roles. Rules in pg_hba.conf reference these mappings through the map option.

Managed cloud services often hide or restrict direct file editing. In those environments, the same decisions are expressed through provider settings such as allowed networks, enforced TLS and identity integration, so the underlying model of ordered, first-match rules still applies conceptually.

Common mistakes and failure modes

Most pg_hba.conf incidents come from rule order errors, overly broad addresses and forgotten reloads. Their symptoms are either unexpected rejections or, more dangerously, connections that succeed when they should not.

  • trust left in production lets anyone who reaches the port connect as any role, including a superuser.
  • A broad rule above a narrow one silently overrides the stricter method placed below it.
  • Edits without reload give a false sense of protection until the next restart.
  • Container defaults in some images allow wide access and must be reviewed before exposure.
  • Error messages such as no pg_hba.conf entry for host help diagnosis but should not prompt hasty wildcard rules.

Put simply

pg_hba.conf is like the guest list at the door of a PostgreSQL database. It says who may enter, from which address, and what proof each visitor must show.

The guard reads the list from the top and follows the first line that fits. Anyone who is not on the list is turned away. The key takeaway is simple: a short, precise list is safer than a long or vague one.

In practice

A health-care software provider runs PostgreSQL 16 for a patient scheduling application. A security review finds a pg_hba.conf line allowing host all all 0.0.0.0/0 md5, added years earlier during a migration, so any network that can reach port 5432 can attempt password logins.

The database team replaces it with hostssl rules for the two application subnets using scram-sha-256, a certificate-based rule for the replication standby, peer authentication for local administration and a final reject line. They rehash all passwords to SCRAM, check the result in pg_hba_file_rules, and reload the configuration during a quiet period.

A follow-up scan shows that connections from outside the approved subnets are now refused before any password exchange, and all remaining traffic is encrypted. The change also satisfies an audit requirement for encrypted database connections.