使用 pgaudit 保留角色级和对象级审计日志
PostgreSQL安全命令
-- Prerequisite: shared_preload_libraries = 'pgaudit' + restart, then:
CREATE EXTENSION pgaudit;
-- Session auditing: server-wide, only DDL and role/privilege changes
ALTER SYSTEM SET pgaudit.log = 'ddl, role';
ALTER SYSTEM SET pgaudit.log_relation = on;
ALTER SYSTEM SET pgaudit.log_parameter = off;
SELECT pg_reload_conf();
-- All reads/writes of a specific application role
ALTER ROLE web_app SET pgaudit.log = 'read, write';
-- Object auditing: privileges granted to the auditor role = operations to log
CREATE ROLE auditor NOLOGIN;
ALTER SYSTEM SET pgaudit.role = 'auditor';
SELECT pg_reload_conf();
GRANT SELECT, DELETE ON customer TO auditor;
GRANT UPDATE (balance) ON customer TO auditor;作用
记录服务器范围的 DDL 和权限变更、特定角色的所有读写,以及对授予 auditor 角色的敏感表/列的访问,输出为以 'AUDIT:' 为前缀的结构化日志行。
适用场景
用于在 GDPR、PCI-DSS 或 SOX 等合规审计中证明谁访问了敏感数据。
注意
在服务器范围启用 pgaudit.log = 'all' 或 'read' 会大幅增加日志量和 I/O;请用角色审计或对象审计缩小范围。超级用户可以关闭审计(ALTER SYSTEM/ALTER ROLE);请将记录发送到集中日志系统(syslog/SIEM),并独立于数据库服务器存储。log_parameter = on 也会记录绑定参数(个人数据)。角色设置在新会话中生效。pgaudit 的大版本必须与 PostgreSQL 的大版本一致(pgaudit 17.x = PG17)。