Database Connector

PostgreSQL Connector

Connect DB Audit to your PostgreSQL databases for comprehensive activity monitoring, query auditing, and compliance reporting. Zero performance impact with our lightweight collector.

Native Deep Integration

Zero Agent Architecture

No software to install on your database servers

pgaudit & pg_stat_statements

Leverages native PostgreSQL extensions

<1% Performance Impact

Lightweight read-only collection

What You Can Monitor

Real-Time Query Monitoring

Capture every SQL query executed against your PostgreSQL database with microsecond precision timestamps.

User Activity Tracking

Track all user sessions, login attempts, privilege escalations, and role changes.

Schema Change Detection

Detect and alert on DDL operations including CREATE, ALTER, DROP, and GRANT statements.

Data Access Patterns

Analyze query patterns to identify unusual data access or potential data exfiltration.

Requirements

PostgreSQL Version 9.6 or higher (12+ recommended)
Network Access TCP port 5432 (or custom port)
Authentication Password, MD5, SCRAM-SHA-256, or SSL certificate
Required Privileges pg_read_all_stats, pg_read_all_settings

Configuration Reference

Basic Connection

Field Type Required Description
name string Yes A unique name to identify this connection
host string Yes PostgreSQL server hostname or IP address
port number Yes PostgreSQL server port
database_name string Yes Name of the database to connect to
username string Yes Database username for authentication
password password Yes Database password (stored encrypted)

SSL/TLS Configuration

Field Type Default Description
ssl_mode select prefer SSL connection mode
ssl_ca_cert string - CA certificate for server verification
ssl_client_cert string - Client certificate for mutual TLS
ssl_client_key password - Client private key (stored encrypted)

Log Collection

Field Type Default Description
log_collection_type select native_audit Method for collecting audit logs
polling_interval number 5 Seconds between log collection polls
batch_size number 100 Maximum events per batch
min_query_duration_ms number 0 Minimum query duration to capture (ms)

Log Collection Methods

DB Audit supports multiple methods for collecting audit logs from PostgreSQL.

Native Audit (pgaudit)

Recommended

Direct integration with PostgreSQL pg_stat_statements and pgaudit extensions for comprehensive query logging.

Real-time event capture
Full query text with parameters
Session-level tracking
Zero external dependencies

CloudWatch Logs

Collect PostgreSQL logs from AWS CloudWatch for RDS and Aurora instances.

No database configuration required
Works with RDS/Aurora
Centralized log management
Automatic log rotation
1

Create Audit User

Create a dedicated read-only user for DB Audit. This user only needs access to system statistics and query logs—never grant write permissions.

-- Create a dedicated audit user with minimal privileges
CREATE USER dbaudit_reader WITH PASSWORD 'your_secure_password';

-- Grant access to read system statistics
GRANT pg_read_all_stats TO dbaudit_reader;
GRANT pg_read_all_settings TO dbaudit_reader;

-- For PostgreSQL 10+, grant access to pg_stat_statements
GRANT EXECUTE ON FUNCTION pg_stat_statements_reset() TO dbaudit_reader;

-- Allow connection to the target database
GRANT CONNECT ON DATABASE your_database TO dbaudit_reader;
Security Best Practice

Use a strong, unique password and store it in environment variables or a secrets manager. Never commit credentials to version control.

2

Enable Query Tracking

For comprehensive query auditing, enable the pg_stat_statements extension. Optionally, add pgaudit for detailed audit logging.

-- Enable pg_stat_statements for query tracking
-- Add to postgresql.conf:
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all
pg_stat_statements.max = 10000

-- Then restart PostgreSQL and run:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Enable pgaudit for comprehensive audit logging (optional but recommended)
CREATE EXTENSION IF NOT EXISTS pgaudit;
Note

Enabling pg_stat_statements requires a PostgreSQL restart. Plan this during a maintenance window.

3

Configure SSL (Recommended)

For production deployments, always use SSL/TLS encryption. DB Audit supports all PostgreSQL SSL modes including certificate-based authentication.

require
Encrypted connection
verify-ca
+ CA verification
verify-full
+ hostname check
Recommended
# Generate client certificate (if using certificate auth)
openssl genrsa -out client.key 2048
openssl req -new -key client.key -out client.csr
openssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \
  -CAcreateserial -out client.crt -days 365

# Set correct permissions
chmod 600 client.key

# PostgreSQL pg_hba.conf entry for SSL
hostssl  all  dbaudit_reader  0.0.0.0/0  scram-sha-256  clientcert=verify-full
4

Configure DB Audit Collector

Add your PostgreSQL connection to the DB Audit configuration file. Store sensitive credentials in environment variables.

databases:
  - name: production-postgres
    type: postgresql
    host: db.example.com
    port: 5432
    database: your_database
    username: dbaudit_reader
    password: ${PG_PASSWORD}

    # SSL Configuration (recommended for production)
    ssl: true
    ssl_mode: verify-full
    ssl_cert: /etc/dbaudit/certs/client.crt
    ssl_key: /etc/dbaudit/certs/client.key
    ssl_root_cert: /etc/dbaudit/certs/ca.crt

    # Connection settings
    connect_timeout: 10
    statement_timeout: 30000

    # Monitoring options
    options:
      track_queries: true
      track_connections: true
      track_ddl: true
      track_dml: true
      track_errors: true
      sample_rate: 1.0  # 100% of queries
5

Test Connection

Verify your configuration before deploying. The collector includes built-in connection testing.

# Test connection with psql
PGPASSWORD='your_password' psql -h db.example.com -U dbaudit_reader -d your_database -c "SELECT version();"

# Test with SSL
psql "host=db.example.com user=dbaudit_reader dbname=your_database sslmode=verify-full sslcert=client.crt sslkey=client.key sslrootcert=ca.crt"

# Verify DB Audit collector can connect
dbaudit-collector test-connections --config /etc/dbaudit/config.yaml

AWS RDS PostgreSQL & CloudWatch

Managed PostgreSQL with CloudWatch Logs Integration

Amazon RDS for PostgreSQL can publish logs to CloudWatch Logs, enabling centralized log management and integration with DB Audit. This section covers how to configure pgAudit on RDS PostgreSQL and connect it to DB Audit via CloudWatch.

pgAudit Extension

RDS PostgreSQL supports the pgAudit extension for comprehensive audit logging. Unlike native PostgreSQL logging, pgAudit provides detailed session and object-level auditing with structured output. Set shared_preload_libraries = 'pgaudit' in your parameter group.

Key Parameter Group Settings

Parameter Value Restart Description
shared_preload_libraries pgaudit Yes Load pgAudit extension at startup
pgaudit.log all No Log all statement classes (read, write, ddl, role, etc.)
log_statement all No Log all SQL statements
log_connections 1 No Log each successful connection
log_disconnections 1 No Log end of each session

1. Configure RDS Parameter Group

Create a custom parameter group and enable pgaudit in the shared_preload_libraries parameter. Configure audit logging settings.

# Create a custom parameter group for PostgreSQL with pgAudit
aws rds create-db-parameter-group \
  --db-parameter-group-name postgres-audit-params \
  --db-parameter-group-family postgres15 \
  --description "PostgreSQL parameter group with pgAudit enabled"

# Enable pgAudit shared library and configure logging
aws rds modify-db-parameter-group \
  --db-parameter-group-name postgres-audit-params \
  --parameters \
    "ParameterName=shared_preload_libraries,ParameterValue=pgaudit,ApplyMethod=pending-reboot" \
    "ParameterName=pgaudit.log,ParameterValue=all,ApplyMethod=immediate" \
    "ParameterName=log_statement,ParameterValue=all,ApplyMethod=immediate" \
    "ParameterName=log_connections,ParameterValue=1,ApplyMethod=immediate" \
    "ParameterName=log_disconnections,ParameterValue=1,ApplyMethod=immediate"

# Apply the parameter group to your instance
aws rds modify-db-instance \
  --db-instance-identifier my-postgres-instance \
  --db-parameter-group-name postgres-audit-params \
  --apply-immediately
Reboot Required

Changes to shared_preload_libraries require a database reboot to take effect. Plan this during a maintenance window.

2. Enable CloudWatch Logs Export

Configure your RDS instance to publish PostgreSQL logs to CloudWatch Logs.

# Enable CloudWatch Logs export for PostgreSQL logs
aws rds modify-db-instance \
  --db-instance-identifier my-postgres-instance \
  --cloudwatch-logs-export-configuration '{"EnableLogTypes":["postgresql","upgrade"]}'

# Create a new instance with CloudWatch logging enabled
aws rds create-db-instance \
  --db-instance-identifier my-postgres-instance \
  --db-instance-class db.m5.large \
  --engine postgres \
  --engine-version 15.4 \
  --master-username admin \
  --manage-master-user-password \
  --allocated-storage 100 \
  --db-parameter-group-name postgres-audit-params \
  --cloudwatch-logs-export-configuration '["postgresql","upgrade"]'

# Verify CloudWatch Logs export is enabled
aws rds describe-db-instances \
  --db-instance-identifier my-postgres-instance \
  --query 'DBInstances[0].EnabledCloudwatchLogsExports'

CloudWatch Log Group Structure

PostgreSQL logs are published to: /aws/rds/instance/<instance-id>/postgresql

Upgrade logs are published to: /aws/rds/instance/<instance-id>/upgrade

3. Configure pgAudit Extension

After the parameter group is applied and the instance rebooted, connect to your database and configure pgAudit.

-- Connect to your RDS PostgreSQL instance and enable pgAudit
-- Note: shared_preload_libraries must be set in parameter group first

-- Create the pgAudit extension
CREATE EXTENSION IF NOT EXISTS pgaudit;

-- Configure pgAudit for comprehensive logging
-- Log all statement types
ALTER SYSTEM SET pgaudit.log = 'all';

-- Log catalog access for role and privilege queries
ALTER SYSTEM SET pgaudit.log_catalog = on;

-- Include parameter values in log entries
ALTER SYSTEM SET pgaudit.log_parameter = on;

-- Include the fully-qualified object name
ALTER SYSTEM SET pgaudit.log_relation = on;

-- Configure session-based audit logging
ALTER SYSTEM SET pgaudit.log_statement_once = off;

-- Reload configuration
SELECT pg_reload_conf();

-- Verify pgAudit is active
SHOW shared_preload_libraries;
SELECT * FROM pg_extension WHERE extname = 'pgaudit';

-- Create role-based audit policy for specific users
CREATE ROLE auditor NOLOGIN;
ALTER ROLE dbaudit_reader SET pgaudit.role = 'auditor';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO auditor;

4. Configure IAM Permissions

Grant DB Audit permission to read CloudWatch Logs for your PostgreSQL instances.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:DescribeLogGroups",
        "logs:DescribeLogStreams",
        "logs:GetLogEvents",
        "logs:FilterLogEvents"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/rds/instance/*/postgresql:*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "rds:DescribeDBInstances",
        "rds:DescribeDBLogFiles",
        "rds:DownloadDBLogFilePortion"
      ],
      "Resource": "*"
    }
  ]
}
Use IAM Roles

If running DB Audit on EC2 or ECS, attach an IAM role instead of using access keys. This is more secure and handles credential rotation automatically.

5. Configure DB Audit for RDS PostgreSQL

Configure DB Audit to collect logs from CloudWatch and optionally query pg_stat_statements directly.

# DB Audit configuration for RDS PostgreSQL via CloudWatch
databases:
  - name: production-rds-postgres
    type: postgresql

    # RDS endpoint
    host: my-postgres-instance.xxxx.us-east-1.rds.amazonaws.com
    port: 5432
    database: mydb
    username: dbaudit_reader
    password: ${RDS_POSTGRES_PASSWORD}

    # SSL is enabled by default for RDS
    ssl: true
    ssl_mode: require

    options:
      # Use CloudWatch as the log source
      log_source: cloudwatch

      # CloudWatch configuration
      cloudwatch:
        region: us-east-1
        log_group: /aws/rds/instance/my-postgres-instance/postgresql

        # AWS credentials (use IAM role if running on EC2/ECS)
        # access_key_id: ${AWS_ACCESS_KEY_ID}
        # secret_access_key: ${AWS_SECRET_ACCESS_KEY}

        # Or use IAM role (recommended)
        use_iam_role: true

      # Polling interval for CloudWatch logs
      polling_interval: 30

      # Also query pg_stat_statements directly for real-time metrics
      query_pg_stat_statements: true
      track_queries: true
      track_connections: true

6. Query Audit Logs in CloudWatch

Use CloudWatch Logs Insights to analyze audit data directly in the AWS Console.

# View PostgreSQL logs in CloudWatch Logs Insights
# Log group: /aws/rds/instance/<instance-id>/postgresql

# Query for failed login attempts
fields @timestamp, @message
| filter @message like /FATAL|authentication failed/
| sort @timestamp desc
| limit 100

# Query for DDL operations
fields @timestamp, @message
| filter @message like /CREATE|DROP|ALTER|TRUNCATE/
| sort @timestamp desc
| limit 100

# Query for specific user activity
fields @timestamp, @message
| filter @message like /user=admin/
| sort @timestamp desc
| limit 50

# Query pgAudit logs specifically
fields @timestamp, @message
| filter @message like /AUDIT:/
| parse @message "AUDIT: *,*,*,*,*,*,*" as session_id, statement_id, substatement_id, class, command, object_type, object_name
| sort @timestamp desc
| limit 100

# Query for slow queries (log_min_duration_statement)
fields @timestamp, @message
| filter @message like /duration:/
| parse @message "duration: * ms" as duration_ms
| filter duration_ms > 1000
| sort @timestamp desc
| limit 50

RDS PostgreSQL Log Retention

RDS Instance Storage

PostgreSQL logs are retained on the RDS instance based on available storage. Logs older than 7 days are automatically rotated.

CloudWatch Logs

Configure retention in CloudWatch (1 day to 10 years). Set based on your compliance requirements.

Log Volume Considerations

Setting log_statement = 'all' and pgaudit.log = 'all' can generate significant log volume. Consider using more specific settings in high-traffic environments or filtering by role.

Compliance Support

DB Audit's PostgreSQL connector helps you meet audit requirements for major compliance frameworks.

SOC 2
Access logging
HIPAA
PHI access audit
PCI DSS
Cardholder data
GDPR
Data access rights

Troubleshooting

Connection refused

Check that PostgreSQL is accepting connections on the configured host and port. Verify pg_hba.conf allows connections from the collector's IP address.

Authentication failed

Verify the username and password are correct. Check that the authentication method in pg_hba.conf matches your configuration (md5, scram-sha-256, etc.).

SSL connection required

If the server requires SSL, ensure ssl: true is set in your configuration and the correct certificates are provided.

Permission denied for pg_stat_statements

Grant the pg_read_all_stats role to your audit user, or ensure pg_stat_statements.track is set to 'all' in postgresql.conf.

Ready to Audit Your PostgreSQL Database?

Start monitoring your PostgreSQL databases in minutes. No agents to install on your database servers.