DBAtlas · 数据库运维图谱

启用 SSL/TLS 并验证加密连接(pg_stat_ssl)

PostgreSQL安全

命令

# 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"

作用

无需重启即可使用服务器证书启用 TLS,设置最低协议版本,并列出当前连接是否已加密以及 TLS 版本和加密套件。

适用场景

用于安全审计/合规要求(PCI、GDPR),保护网络传输中的密码和数据。

注意

仅 ssl = on 并不强制加密;客户端仍可用 sslmode=prefer/disable 进行未加密连接。要强制加密,请在 pg_hba.conf 中用 hostssl 代替 host(并添加 hostnossl ... reject)。sslmode=require 不验证服务器身份(易受 MITM 攻击);证书验证请使用 verify-full。密钥文件的属主必须是 postgres 用户且权限为 0600(或属主为 root 且权限为 0640);否则 SSL 不会加载,因此 reload 后请检查日志和 SHOW ssl。证书续期也可通过 reload 生效。

在 DBAtlas 中打开 →

相关内容