PostgreSQL Exposure & Hardening Guide: Self-Hosted and Managed (2026)
How to keep PostgreSQL off the internet and hard to abuse: listen_addresses and pg_hba.conf rules, TLS with verify-full and SCRAM-SHA-256, least-privilege roles without superuser apps, encrypted backups, pgAdmin and RDS exposure checks, and how to detect a public port 5432, with lessons from exposed ClickHouse and MongoDB servers, pgAdmin 9.19 and Babelfish for Aurora PostgreSQL.
// key takeaways
- Network reachability is the first control. DeepSeek's exposed ClickHouse instances and MongoBleed both show that a database answering on the internet turns one mistake or one bug into a data leak.
- pg_hba.conf decides who may even try to log in. Use hostssl lines, specific CIDRs, scram-sha-256, and end with an explicit reject; never use trust outside a local socket.
- Applications should not connect as a superuser. COPY ... TO PROGRAM runs shell commands for superusers and members of pg_execute_server_program.
- Admin tools are part of the database's attack surface. pgAdmin 4 before 9.19 let an ordinary database role run commands on the pgAdmin host through Import/Export.
- Backups are a second copy of the database. Encrypt them with keys that are not stored next to them, and test restores.
How databases actually get exposed
The most common database incident is not an exploit. It is a server that accepts connections from anywhere. In January 2025 Wiz found two DeepSeek ClickHouse instances open to the internet without authentication, with a query interface that allowed arbitrary SQL and a log table containing plaintext chat history, API keys and backend details. DeepSeek locked it down within an hour of being told, but anyone who found it first had the data.
When a reachable database does have a bug, exposure decides who can use it. MongoBleed let an unauthenticated client read uninitialized heap memory from MongoDB through zlib message decompression; CISA confirmed exploitation, and the advice included keeping MongoDB off the internet. ClickHouse fixed an unauthenticated remote code execution flaw in October 2026. PostgreSQL deserves the same assumption: if 5432 is reachable from the internet, the next pre-authentication bug or a weak password is all that stands between an attacker and the data.
Credential reuse is the third path. In the Snowflake customer account thefts, the group Mandiant tracks as UNC5537 logged in with credentials stolen by infostealers on accounts without MFA or network allow lists. Database passwords that live in developer laptops, CI variables and dotfiles leak the same way.
Step 1: listen_addresses, firewalls and the public 5432 check
PostgreSQL's listen_addresses setting in postgresql.conf controls which interfaces the server binds. The compiled default is localhost, but many container images and installers set it to '*' so the server works out of the box. Bind only to the private interface the application uses, and enforce the same rule in the network layer: a security group, cloud firewall or nftables rule that allows 5432 only from application subnets and bastion hosts.
Then check from the outside, because configuration and reality drift. Scan your public IP ranges for 5432 from a host outside your network. On AWS, list RDS instances with PubliclyAccessible set to true and check the security groups attached to them. Docker deserves a special look: publishing a port with -p 5432:5432 binds to all host interfaces by default, and Docker's own iptables rules can bypass a host firewall such as ufw. Use -p 127.0.0.1:5432:5432 or keep the database on an internal Docker network.
- Set listen_addresses to the private IP (or localhost when the app is on the same host).
- Allow 5432 only from application subnets and bastions in security groups and host firewalls.
- Scan your own public ranges for open 5432 from outside on a schedule.
- Set PubliclyAccessible to false on RDS and Aurora instances that do not need it.
- Never publish the database port on 0.0.0.0 in Docker compose files.
# On the server: which addresses is postgres bound to?
ss -ltnp | grep 5432
psql -Atc "SHOW listen_addresses"
# From a host OUTSIDE your network: is 5432 open on your public range?
nmap -Pn -p 5432 --open 203.0.113.0/24
# AWS: RDS and Aurora instances marked publicly accessible
aws rds describe-db-instances \
--query 'DBInstances[?PubliclyAccessible==`true`].[DBInstanceIdentifier,Endpoint.Address,VpcSecurityGroups[].VpcSecurityGroupId]' \
--output table
# Docker: containers publishing 5432 on all interfaces
docker ps --format '{{.Names}} {{.Ports}}' | grep '0.0.0.0:5432'Step 2: pg_hba.conf, TLS and SCRAM-SHA-256
pg_hba.conf is evaluated top to bottom and the first matching line wins. Use hostssl instead of host so non-TLS connections never match, list specific databases, roles and CIDRs instead of all and 0.0.0.0/0, and finish with a reject line so anything unexpected fails closed. The trust method skips authentication entirely; keep it out of every line that is not a local Unix socket for maintenance, and prefer peer there.
Use scram-sha-256 for password authentication. It has been the default password_encryption since PostgreSQL 14, but roles created on older versions may still have MD5 hashes, which are weaker and can be replayed by anyone who obtains the stored hash. Find them in pg_authid, set password_encryption to scram-sha-256, and reset those passwords. Then remove md5 from pg_hba.conf.
Turn on TLS with ssl = on and a certificate from a CA your clients trust; ssl_min_protocol_version defaults to TLSv1.2 since PostgreSQL 12. TLS only protects against interception if clients verify the server: libpq's default sslmode is prefer, which falls back to plaintext and does not check the certificate. Clients should use sslmode=verify-full with the CA certificate, which checks both the chain and the host name. Managed services publish their CA bundles for exactly this.
# TYPE DATABASE USER ADDRESS METHOD
local all postgres peer
hostssl appdb app_rw 10.20.0.0/24 scram-sha-256
hostssl appdb app_ro 10.20.0.0/24 scram-sha-256
hostssl all dba 10.99.0.10/32 scram-sha-256
host all all 0.0.0.0/0 reject
host all all ::/0 reject
# postgresql.conf
# listen_addresses = '10.20.0.5'
# password_encryption = 'scram-sha-256'
# ssl = on
# ssl_min_protocol_version = 'TLSv1.2'
# Client connection string
# postgresql://app_rw@db.internal:5432/appdb?sslmode=verify-full&sslrootcert=/etc/ssl/db-ca.pemStep 3: least-privilege roles
A superuser can read every table, change any setting, load untrusted procedural languages, and run operating-system commands with COPY ... TO PROGRAM or FROM PROGRAM. Since PostgreSQL 11 that ability is also granted by the predefined role pg_execute_server_program. An application that connects as postgres turns every SQL injection into command execution on the database host. Applications should own nothing they do not need: a migration role that owns the schema, a read-write role for the service, and a read-only role for reporting.
Lock down the public schema. Before PostgreSQL 15 every role could create objects in public by default, which lets a low-privileged role plant functions or tables that shadow names other roles use. PostgreSQL 15 removed CREATE on public from PUBLIC for new databases, but databases upgraded from older versions keep the old grant. Revoke it explicitly, and revoke CONNECT on databases from PUBLIC so roles only reach the databases they are granted.
- No application connects as a superuser or as a member of pg_execute_server_program.
- Separate migration, read-write and read-only roles; use predefined roles such as pg_read_all_data only for reporting.
- REVOKE CREATE ON SCHEMA public FROM PUBLIC and REVOKE ALL ON DATABASE appdb FROM PUBLIC.
- Set statement_timeout and a CONNECTION LIMIT on application roles.
- Log connections and role changes (log_connections, log_disconnections, and pgAudit where you need statement audit).
-- Who can do everything?
SELECT rolname FROM pg_roles WHERE rolsuper;
-- Who can run shell commands via COPY ... PROGRAM?
SELECT r.rolname FROM pg_auth_members m
JOIN pg_roles g ON g.oid = m.roleid
JOIN pg_roles r ON r.oid = m.member
WHERE g.rolname = 'pg_execute_server_program';
-- Passwords still stored as MD5 (requires superuser)
SELECT rolname FROM pg_authid WHERE rolpassword LIKE 'md5%';
-- Lock down defaults
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON DATABASE appdb FROM PUBLIC;
GRANT CONNECT ON DATABASE appdb TO app_rw, app_ro;
ALTER ROLE app_rw CONNECTION LIMIT 50;
ALTER ROLE app_rw SET statement_timeout = '30s';Step 4: pgAdmin, managed-service features and patching
Database administration tools run with database credentials and usually sit closer to the internet than the database. pgAdmin 4 9.19, released October 29, 2026, fixed a batch of vulnerabilities in all earlier versions. The worst let an ordinary database role escape psql's \copy wrapper in the Import/Export Data tool so that a TO PROGRAM clause ran on the pgAdmin host as the account running pgAdmin; another let an unauthenticated attacker in server mode bypass the failed-login lockout and guess passwords for any internal account. Upgrade to 9.19 or later and keep pgAdmin behind a VPN or SSO proxy rather than on a public URL.
Managed services add their own protocol surfaces. On November 6, 2026 AWS published a bulletin for two memory-safety issues in the TDS protocol layer of Babelfish for Aurora PostgreSQL, the SQL Server wire-protocol endpoint; one was reachable without authentication during the connection handshake. AWS fixed them in Babelfish for PostgreSQL extension versions 4.10, 5.6 and 6.1 and advised restricting the TDS port, 1433 by default, to trusted sources until upgraded. If you do not use a feature like Babelfish, do not enable it; if you do, give its port the same network rules as 5432.
For self-hosted servers, follow the PostgreSQL minor release schedule. Minor releases contain only bug and security fixes and do not change the on-disk format, so upgrading within a major version is a package update and a restart.
Step 5: encrypt and isolate backups
A pg_dump file or base backup contains every row and every password hash. Backups stored unencrypted in object storage, on a shared NFS mount or in a CI artifact are a second database with weaker access control. Encrypt them before they leave the host: pgBackRest supports repository encryption with repo1-cipher-type=aes-256-cbc and a passphrase, WAL-G supports libsodium and OpenPGP keys, and a plain pg_dump can be piped through age or gpg to a public key.
Keep the decryption key out of the backup location and out of the database host's routine access, store backups in a bucket or account the database host can write to but not delete from, and restore one regularly. An untested backup is not a recovery plan, and an encrypted backup whose key lived only on the compromised server is not a backup.
# Logical backup encrypted to a public key (private key stays offline)
pg_dump -Fc -d appdb | age -r age1examplepublickey... > appdb-$(date +%F).dump.age
# Restore
age -d -i backup-key.txt appdb-2026-12-07.dump.age | pg_restore -d appdb_restore
# /etc/pgbackrest/pgbackrest.conf
# [global]
# repo1-cipher-type=aes-256-cbc
# repo1-cipher-pass=<long random passphrase from your secret store>
# repo1-retention-full=4// actionable engineering checklist
Not reachable from the internet
listen_addresses on a private interface, 5432 firewalled, RDS PubliclyAccessible false, no 0.0.0.0:5432 in Docker.
pg_hba.conf fails closed
hostssl only, specific CIDRs and roles, scram-sha-256, explicit reject at the end, no trust.
MD5 hashes gone
password_encryption = scram-sha-256 and every role with an md5 hash has reset its password.
Clients verify TLS
sslmode=verify-full with the server CA in every connection string.
No superuser apps
Apps use non-superuser roles outside pg_execute_server_program; public schema CREATE revoked.
Admin tools patched and private
pgAdmin 9.19+ behind VPN or SSO; Babelfish extension 4.10, 5.6 or 6.1+ and TDS port restricted if enabled.
Backups encrypted and tested
Encrypted before upload, key stored separately, delete-protected storage, a restore tested recently.
Exposure monitored
Scheduled external scan for 5432 and alerts on new public RDS instances or security group changes.
// connected pwn.watch tools & live trackers
SSL Certificate Decoder →
Inspect the PostgreSQL server certificate's SANs and expiry before switching clients to verify-full.
Bcrypt Generator →
Hash application user passwords properly in the tables your database stores.
chmod Calculator →
PostgreSQL refuses a server key file readable by group or others; check it is 0600.
CVSS v3.1 & v4.0 Calculator →
Re-score database and admin-tool CVEs for a server that is not reachable from the internet.
Stack & Tag CVE Trackers
Security Hubs & Feeds
Related Incidents
- pgAdmin 4 9.19 fixes command execution through Import/Export and a login lockout bypass →
- AWS Babelfish for Aurora PostgreSQL TDS parser issues →
- DeepSeek leaves ClickHouse database open: chat logs and API keys exposed →
- MongoBleed: pre-auth heap memory leak in MongoDB Server →
- ClickHouse Server: unauthenticated remote code execution →
- Snowflake customer accounts raided with infostealer credentials →
Frequently Asked Questions
- Is it safe to expose PostgreSQL on port 5432 if it has a strong password?
- It is much riskier than keeping it private. A strong password does not protect against pre-authentication bugs or leaked credentials, and it invites constant password guessing. Keep 5432 on a private network and reach it through a VPN, bastion or private link.
- Should I use md5 or scram-sha-256 in pg_hba.conf?
- scram-sha-256. It has been the default password_encryption since PostgreSQL 14. Find roles that still have md5 hashes, reset their passwords with password_encryption set to scram-sha-256, then remove md5 from pg_hba.conf.
- What sslmode should applications use?
- verify-full with the server's CA certificate. The libpq default, prefer, can silently fall back to plaintext and does not check the certificate, so it does not stop interception.
- Why should the application not connect as postgres?
- Superusers can run operating-system commands through COPY ... TO PROGRAM, read every table and change server settings. A SQL injection in an app that uses a superuser becomes command execution on the database host.
Get an email when a new major security incident drops. No spam, unsubscribe any time.