Skip to content

PSonar is an grade security auditing tool for PostgreSQL databases. It performs comprehensive **read-only** security assessments aligned with **CIS PostgreSQL Benchmark** and **MITRE ATT&CK** framework.

License

Notifications You must be signed in to change notification settings

cumakurt/psonar

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ PSonar - PostgreSQL Security Auditor

PostgreSQL 12+ Python 3.11+ License GPL-3.0 CIS Benchmark MITRE ATT&CK

πŸ‡ΉπŸ‡· TΓΌrkΓ§e README

PSonar is an enterprise-grade security auditing tool for PostgreSQL databases. It performs comprehensive read-only security assessments aligned with CIS PostgreSQL Benchmark and MITRE ATT&CK framework.

✨ Features

πŸ”’ Core Security

  • Read-Only Operations: All operations are strictly read-only - no data modification
  • CIS Benchmark Compliance: 20+ security controls from CIS PostgreSQL Benchmark
  • MITRE ATT&CK Mapping: Findings mapped to relevant attack techniques
  • Risk Scoring: Comprehensive risk analysis with prioritized recommendations

πŸ” Advanced Auditing

  • Vulnerability Scanner: CVE detection, version EOL checks, risky extensions
  • Configuration Audit: Best practices comparison, 20+ setting validations
  • Sensitive Data Discovery: PII, financial data, credentials detection (GDPR, PCI-DSS, HIPAA, KVKK)
  • User & Privilege Audit: Superuser detection, privilege escalation paths, password policies
  • Session Monitoring: Active sessions, blocking queries, suspicious activities
  • Schema Security: SECURITY DEFINER functions, triggers, views (SECURITY BARRIER), FDW credential exposure
  • Database Health: Connection stats, cache ratios, bloat detection, vacuum status

πŸ“Š Enterprise Features

  • Enterprise Security Controls: pgaudit, RLS, encryption, replication, backup checks
  • Compliance Scoring: CIS, PCI-DSS, SOC2, HIPAA, GDPR readiness scores
  • Beautiful Reports: Professional HTML reports with dark mode support
  • Multi-Database Support: Scan multiple databases from config file
  • SSL Support: Full SSL/TLS support for secure connections

πŸš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/cumakurt/psonar.git
cd psonar

# Install dependencies
pip install -r requirements.txt

# Or install as package
pip install -e .

PyPI Installation (Coming Soon)

pip install psonar

Docker

# Build
docker build -t psonar .

# Run (reports stay inside container unless you mount a volume)
docker run -it psonar scan -h your-db-host -d mydb -U postgres

Saving Reports on the Host (Volume Mount)

By default, reports are written inside the container at /app/reports. To get them on your host machine, mount a volume with -v.

Recommended: Save reports to host /tmp (avoids permission issues):

docker run -it -v /tmp:/app/reports -e PGPASSWORD=yourpassword psonar scan -h your-db-host -d mydb -U postgres
# Report will appear on host at: /tmp/psonar_<host>_<port>_<db>_<timestamp>.html

Save reports to current directory (if you get "Permission denied", add --user root):

docker run -it -v "$(pwd):/app/reports" --user root -e PGPASSWORD=yourpassword psonar scan -h your-db-host -d mydb -U postgres

Save reports to a reports folder on the host:

mkdir -p reports
docker run -it -v "$(pwd)/reports:/app/reports" --user root -e PGPASSWORD=yourpassword psonar scan -h your-db-host -d mydb -U postgres

Note: The container runs as non-root user psonar. If the mounted directory is not writable by that user, use --user root or mount a writable path such as /tmp.

Basic Usage

# Scan a single database
psonar scan -h localhost -d mydb -U postgres

# Scan with password prompt
psonar scan -h localhost -d mydb -U postgres -W

# Scan multiple databases from config
psonar scan -c config/databases.yaml

# Run specific checks only
psonar scan -h localhost -d mydb -U postgres --checks CIS-3.1,CIS-4.1,CIS-6.1

# Skip health or CIS checks
psonar scan -h localhost -d mydb -U postgres --skip-health
psonar scan -h localhost -d mydb -U postgres --skip-cis

# Output format: html (default) or json
psonar scan -h localhost -d mydb -U postgres -o ./reports -f html

# Generate sample config file
psonar init-config -o my-config.yaml

# List available checks
psonar list-checks

Python API

from psonar import PSonarScanner

# Using context manager
with PSonarScanner(
    host="localhost",
    database="mydb",
    username="postgres",
    password="secret"
) as scanner:
    scanner.run_health_checks()
    scanner.run_cis_checks()
    scanner.calculate_risk_scores()

# Or run full scan
from psonar.main import scan_database

report = scan_database(
    host="localhost",
    database="mydb",
    username="postgres",
    password="secret",
    output_path="./report.html"
)

print(f"Compliance: {report.compliance_score['compliance_percentage']}%")

πŸ“‹ Security Checks

Audit Modules

Module Description Checks
πŸ”“ Vulnerability Scanner CVE detection, version support 8+ known CVEs, EOL checks
βš™οΈ Configuration Audit Best practices comparison 20+ settings validation
πŸ‘₯ User & Privilege Audit Access control analysis Superusers, privileges, passwords
πŸ” Sensitive Data Discovery PII/secrets detection Email, CC, SSN, API keys
πŸ“Š Session Monitoring Real-time session analysis Blocking, long queries
πŸ—οΈ Schema Security Object security audit SECURITY DEFINER functions, triggers, views, FDW credentials
πŸ—„οΈ Database Health Performance & health Connections, cache, bloat
🏒 Enterprise Security Compliance controls pgaudit, RLS, encryption
πŸ“œ CIS Benchmark Industry standard 21 CIS controls
🎯 MITRE ATT&CK Threat mapping Attack technique correlation

CIS PostgreSQL Benchmark Controls

ID Category Control Severity
CIS-3.1 Authentication Password encryption HIGH
CIS-3.2 Authentication Password expiration policy MEDIUM
CIS-4.1 Privilege Management Superuser role count HIGH
CIS-4.2 Privilege Management Public schema privileges HIGH
CIS-4.3 Privilege Management Default privileges MEDIUM
CIS-5.1 Privilege Management Dangerous extensions MEDIUM
CIS-5.2 Privilege Management Untrusted procedural languages HIGH
CIS-6.1 Connection Security SSL enabled CRITICAL
CIS-6.2 Connection Security SSL required for remote HIGH
CIS-6.3 Authentication Trust authentication CRITICAL
CIS-6.4 Authentication Password auth method HIGH
CIS-7.1 Logging Log connections MEDIUM
CIS-7.2 Logging Log disconnections MEDIUM
CIS-7.3 Logging Log statement MEDIUM
CIS-7.4 Logging Log statement duration LOW
CIS-7.5 Logging Log hostname LOW
CIS-8.1 Network Listen addresses MEDIUM
CIS-8.2 Network Port configuration LOW
CIS-9.1 Data Protection Data checksums MEDIUM
CIS-10.1 Maintenance Autovacuum HIGH
CIS-10.2 Maintenance Backup configuration MEDIUM

Sensitive Data Types Detected

Category Types
PII Email, Phone, SSN, National ID, Passport, Name, Address, DOB
Financial Credit Card, Bank Account, IBAN
Credentials Password, API Key, Secret Key, Token, Private Key
Health Medical records, Patient ID
Other IP Address, Geolocation, Biometric

Vulnerability Checks

  • PostgreSQL version EOL status
  • Known CVEs (CVE-2024-7348, CVE-2024-0985, CVE-2023-5869, etc.)
  • Security update availability
  • Risky extensions (plpythonu, file_fdw, dblink, adminpack)

🎯 MITRE ATT&CK Mapping

Findings are mapped to relevant MITRE ATT&CK techniques:

Tactic Techniques
Credential Access T1110 (Brute Force), T1552 (Unsecured Credentials), T1040 (Network Sniffing)
Privilege Escalation T1068 (Exploitation), T1078 (Valid Accounts)
Persistence T1098 (Account Manipulation), T1505 (Server Software Component)
Defense Evasion T1562 (Impair Defenses), T1070 (Indicator Removal)

πŸ“Š Risk Scoring

PSonar calculates risk scores based on:

  • Base Severity: CIS benchmark severity (Low to Critical)
  • Exposure Factor: Category-based multiplier
  • MITRE Factor: Attack technique relevance

Risk Levels:

  • 🟒 Low (0-3.9): Minor issues
  • 🟑 Medium (4-6.9): Should be addressed
  • 🟠 High (7-8.9): Prioritize remediation
  • πŸ”΄ Critical (9-10): Immediate action required

πŸ“„ Configuration

YAML Configuration

# psonar.yaml
databases:
  - name: "production"
    host: "prod-db.example.com"
    port: 5432
    database: "myapp"
    username: "auditor"
    password: "${DB_PASSWORD}"  # Environment variable
    ssl_mode: "require"

settings:
  connect_timeout: 10
  query_timeout: 30

output:
  directory: "./reports"
  format: "html"

Environment Variables

export DB_PASSWORD="your-secure-password"
export STAGING_DB_PASSWORD="staging-password"

πŸ”’ Security Considerations

Read-Only Guarantee

PSonar enforces strict read-only operations:

  1. Transaction Mode: All connections use transaction_read_only = on
  2. Query Validation: All queries are validated before execution
  3. Forbidden Operations: INSERT, UPDATE, DELETE, DROP, etc. are blocked
  4. Catalog Only: Queries only access pg_catalog and information_schema

Recommended Audit User

Create a dedicated read-only user for auditing:

-- Create audit role
CREATE ROLE security_auditor WITH LOGIN PASSWORD 'secure_password';

-- Grant read access to system catalogs (already available)
GRANT CONNECT ON DATABASE mydb TO security_auditor;

-- Grant pg_read_all_settings for configuration access
GRANT pg_read_all_settings TO security_auditor;

-- Grant pg_read_all_stats for statistics access  
GRANT pg_read_all_stats TO security_auditor;

-- For pg_hba.conf access (PostgreSQL 10+)
GRANT pg_read_all_data TO security_auditor;

SSL Configuration

Always use SSL for production scans:

psonar scan -h prod-db.example.com --ssl-mode require

πŸ“ˆ Report Output

Reports can be generated in HTML (default) or JSON format (-f html or -f json). HTML reports are self-contained, support dark mode, and include developer information in the footer.

Report sections include:

  1. Executive Summary: Compliance score, key findings, risk overview
  2. Vulnerability Scan: CVEs, version status, risky extensions
  3. Configuration Audit: Settings compliance, best practices
  4. User & Privilege Audit: Access control analysis, risk users
  5. Sensitive Data Discovery: PII/credential locations (GDPR, PCI-DSS, HIPAA, KVKK)
  6. Session Monitoring: Active sessions, blocking analysis
  7. Schema Security: SECURITY DEFINER functions, triggers, views, FDW credential exposure
  8. Database Health: Performance metrics and warnings
  9. Enterprise Security: Compliance controls status
  10. CIS Compliance Table: All 21 checks with status and evidence
  11. MITRE ATT&CK Mapping: Techniques and tactics coverage
  12. Risk Analysis: Scored findings with prioritization
  13. Recommendations: Actionable remediation steps

Sample Output

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     Scan Results Summary                         β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Compliance Score   β”‚ 75.0%                                       β”‚
β”‚ Checks Passed      β”‚ 15                                          β”‚
β”‚ Checks Failed      β”‚ 5                                           β”‚
β”‚ Warnings           β”‚ 3                                           β”‚
β”‚ Overall Risk       β”‚ Medium                                      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   πŸ”“ Vulnerability Scan                          β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ PostgreSQL Version β”‚ 14.5                                        β”‚
β”‚ Support Status     β”‚ βœ“ Supported                                 β”‚
β”‚ CVEs Found         β”‚ 2                                           β”‚
β”‚ Risky Extensions   β”‚ 1                                           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                   πŸ‘₯ User & Privilege Audit                      β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Total Users        β”‚ 12                                          β”‚
β”‚ Superusers         β”‚ 2                                           β”‚
β”‚ Critical Risk      β”‚ 1                                           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ› οΈ Development

Project Structure

psonar/
β”œβ”€β”€ psonar/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ cli.py                  # CLI interface
β”‚   β”œβ”€β”€ config.py               # Configuration handling
β”‚   β”œβ”€β”€ main.py                 # Main entry point
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”œβ”€β”€ connection.py       # Database connection
β”‚   β”‚   └── safe_query.py       # Safe query execution
β”‚   β”œβ”€β”€ checks/
β”‚   β”‚   β”œβ”€β”€ cis.py              # CIS benchmark checks
β”‚   β”‚   β”œβ”€β”€ health.py           # Health checks
β”‚   β”‚   β”œβ”€β”€ users.py            # User & privilege audit
β”‚   β”‚   β”œβ”€β”€ databases.py        # Database health audit
β”‚   β”‚   β”œβ”€β”€ enterprise.py       # Enterprise security
β”‚   β”‚   β”œβ”€β”€ sensitive_data.py   # PII/secrets discovery
β”‚   β”‚   β”œβ”€β”€ sessions.py         # Session monitoring
β”‚   β”‚   β”œβ”€β”€ configuration.py    # Config audit
β”‚   β”‚   β”œβ”€β”€ vulnerabilities.py  # CVE scanner
β”‚   β”‚   └── schema_security.py  # Schema security
β”‚   β”œβ”€β”€ analysis/
β”‚   β”‚   β”œβ”€β”€ risk_scoring.py     # Risk calculation
β”‚   β”‚   └── mitre_mapping.py    # MITRE ATT&CK mapping
β”‚   └── reporting/
β”‚       β”œβ”€β”€ html_report.py      # HTML report generation
β”‚       └── templates/          # Jinja2 templates
β”œβ”€β”€ config/
β”‚   └── example.yaml            # Example configuration
β”œβ”€β”€ tests/
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ pyproject.toml
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ docker-compose.yaml
└── README.md

Running Tests

# Install dev dependencies
pip install -e ".[dev]"

# Run tests
pytest tests/

# Run with coverage
pytest --cov=psonar tests/

# Lint
black psonar/
mypy psonar/

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Run tests (pytest tests/)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

πŸ“ License

GNU General Public License v3.0 (GPL-3.0) - see LICENSE file for details.

⚠️ Disclaimer

This tool is for security assessment purposes only. Always:

  • Get proper authorization before scanning
  • Use dedicated audit accounts
  • Review findings before remediation
  • Test changes in non-production first

πŸ‘€ Author

Cuma KURT


Made with ❀️ for PostgreSQL security
Β© 2024-2026 Cuma KURT. All rights reserved.

About

PSonar is an grade security auditing tool for PostgreSQL databases. It performs comprehensive **read-only** security assessments aligned with **CIS PostgreSQL Benchmark** and **MITRE ATT&CK** framework.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages