Configure Tor to forward PostgreSQL's port through a hidden service, then restrict access with Tor client authorization:
# /etc/tor/torrc - PostgreSQL hidden service
HiddenServiceDir /var/lib/tor/db_service/
HiddenServicePort 5432 127.0.0.1:5432
HiddenServiceVersion 3
# Require client auth - only authorized keys can connect
HiddenServiceAuthorizeClient stealth db-admin# /etc/postgresql/16/main/postgresql.conf
listen_addresses = '127.0.0.1'
port = 5432
ssl = on
ssl_cert_file = '/etc/ssl/certs/pg.crt'
ssl_key_file = '/etc/ssl/private/pg.key'
# /etc/postgresql/16/main/pg_hba.conf
# Only allow SSL connections from localhost (Tor)
hostssl all db_user 127.0.0.1/32 scram-sha-256With this configuration, PostgreSQL only listens on localhost and requires SSL even for local connections. The Tor hidden service provides network-level access control, while PostgreSQL's own authentication provides application-level security. This defense-in-depth approach means an attacker needs both a valid Tor auth key and valid database credentials.