DBAtlas · Database operations atlas

Enable SSL/TLS and verify encrypted connections (pg_stat_ssl)

PostgreSQLSecurity

Command

# Server certificate (self-signed for testing; use a corporate CA in production)
openssl req -new -x509 -days 365 -nodes -subj "/CN=db.example.com" -keyout server.key -out server.crt
chmod 600 server.key    # in the data directory, owned by postgres

-- Enable SSL (a reload is enough)
ALTER SYSTEM SET ssl = on;
ALTER SYSTEM SET ssl_cert_file = 'server.crt';
ALTER SYSTEM SET ssl_key_file = 'server.key';
ALTER SYSTEM SET ssl_min_protocol_version = 'TLSv1.2';
SELECT pg_reload_conf();

-- Which connections are encrypted?
SELECT a.pid, a.usename, a.client_addr, a.application_name,
       s.ssl, s.version, s.cipher, s.bits
FROM pg_stat_ssl s
JOIN pg_stat_activity a USING (pid)
WHERE a.backend_type = 'client backend'
ORDER BY s.ssl, a.usename;

# On the client, verify the server identity as well
psql "host=db.example.com dbname=postgres user=postgres sslmode=verify-full sslrootcert=root.crt"

What it does

Enables TLS with a server certificate without a restart, sets the minimum protocol version, and lists whether current connections are encrypted, with TLS version and cipher.

When to use it

For security audit/compliance requirements (PCI, GDPR), to protect passwords and data in transit over the network.

Caution

ssl = on alone does not enforce encryption; clients can still connect unencrypted with sslmode=prefer/disable. To enforce it, use hostssl instead of host in pg_hba.conf (and add hostnossl ... reject). sslmode=require does not verify the server identity (open to MITM); use verify-full for certificate verification. The key file must be owned by the postgres user with mode 0600 (or root-owned with 0640); otherwise SSL is not loaded, so check the log and SHOW ssl after the reload. Certificate renewals are also picked up by a reload.

Open in DBAtlas →

Related