How to Connect to PostgreSQL in SSL Mode

Shihab Sikder Feb 02, 2024
How to Connect to PostgreSQL in SSL Mode

Postgres uses the SSL to verify the connection’s security when we are trying to connect a database. It’s disabled by default in HTTP, but in HTTPS, we need the SSL mode of the connection to perform any operation in the Postgres database.

There can be multiple attack parameters if the connection is not private. Anyone can easily use the sniffing tools over the database request-response.

What Are the SSL Modes in PostgreSQL

Postgres provides different types of SSL modes. First, let’s look at the general connection string for Postgres.

const connectionString =
    'postgres://<database_username>:<database_userpassword>@<hostaddress>:<port_no>/<database_name>'

Now, we can add the parameter sslmode like the following.

const connectionString =
    'postgres://<database_username>:<database_userpassword>@<hostaddress>:<port_no>/<database_name>?sslmode=<ssl_mode>'

Here’s the list of SSL modes provided by Postgres.

sslmode Eavesdropping Protection MITM Protection Description
disable No No It will not care about the security. No data will be encrypted.
allow Maybe No It will not care about security and encrypt the connection.
prefer Maybe No It will not force to use encryption; if the server supports the overhead of the encryption, then it will encrypt.
require Yes No Encrypt the data, it will face some overhead of the encryption, and the network ensures the correct server that the user wants to connect to.
verify-ca Yes Depends on the CA policy Encrypt the data, the overhead of encryption and always connect to the trusted server.
verify-full Yes Yes Data will be encrypted, the user accepts the overhead, network and server both are trusted and only connect to the specific server that’s been asked.

You can also set this flag in the environment variable.

PGSSLMODE=verify-full PGSSLROOTCERT=ca.pem

Here, ca.pem is the key. You need to collect it from a CA; CA stands for certificate authority.

To fully configure the server with the Postgres SSL mode, you can follow the steps from this blog.

Here’s a note from Postgres official documentation regarding the SSL mode.

Using NULL-SHA or NULL-MD5 ciphers, authentication can be done without any encryption overhead. A man-in-the-middle, on the other hand, might read and pass communications between the client and the server. In addition, as compared to the overhead of authentication, encryption has a low overhead. NULL ciphers are not recommended for these reasons.

Also, you can look at the official documentation here. They showed how to self-sign a certificate while using the SSL mode.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website