Securing PostgreSQL using Host Based Authentication (HBA)

The pg_hba.conf file

Client authentication in PostgreSQL is controlled using a system known as Host Based Authentication using a configuration file called pg_hba.conf which is usually located in the database cluster's data directory. This file should be located at /mnt/databases/postgres/9.0/pg_hba.conf in our example installation.

The pg_hba.conf file we created during installation is shown below.

/mnt/databases/postgres/9.0/pg_hba.conf
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD

# "local" is for Unix domain socket connections only
local all pgadmin trust
local all all md5

# IPv4 local connections:
host all all 127.0.0.1/32 md5

# IPv6 local connections:
host all all ::1/128 md5

# IPv4 remote connections:
host all all 10.0.0.0/8 md5
host all all 192.168.0.0/16 md5

As you can see there are various entries, each on a separate line, with some comments prefixed by the # character. A full explanation of the pg_hba.conf file can be found in the pg_hba.conf file section of the PostgreSQL Documentation however we shall provide a brief overview here also.

The first field of each pg_hba.conf file entry consists of the connection type described by the rest of the entry. In our example above we only use the local (connections made using unix sockets) and host (connections made using TCP/IP sockets) types. Other interesting connection types include hostssl which, as the name implies, requires that the connection is secured using SSL encryption.

The second and third fields contain, respectively, a list of the databases and users to which this entry should apply. Both can use the special entry all which, as expected, allows access to all users or databases. As you can see in our example above we have allowed, for local connections, all databases to be accessed by the pgadmin user using trust authentication (explained below) and all databases to be accessed by all users supplying an MD5 encrypted password.

If the connection type is not a local connection then the next entry consists of either a CIDR-address (such as 192.168.0.0/16) or an IP address and subnet mask (such as 192.168.0.0 255.255.0.0). As you can see from our example above a CIDR-address can be used to specify IPv6 addresses such as ::1/128. We have not used any IP address and subnet mask style entries.

The final column in each entry contains the authentication method which should be used by connections matching the criteria specified in the previous components of the entry. As you can see in our example we have so far only used two authentication method specifiers so far. The first of those is the trust specifier which allows the connection unconditionally. In our example this allows the administrator, using the pgadmin local unix account, to access any database without specifying a password. All other entries specify md5 which requires an MD5 encrypted password to be supplied.