Skip to content

sendtoshailesh/postgresql-security-toolkit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PostgreSQL Security Toolkit

A comprehensive security toolkit for PostgreSQL applications, featuring production-ready defense mechanisms against SQL injection attacks, secure client libraries, and security monitoring tools.

πŸ›‘οΈ Features

  • Secure Client Library: Production-ready PostgreSQL client with comprehensive SQL injection protection
  • Input Validation: Multi-layered validation against PostgreSQL-specific attack patterns
  • Parameterized Queries: Safe database operations using proper parameterization
  • Security Configuration: Hardened PostgreSQL configuration templates
  • Monitoring Tools: Scripts for security auditing and threat detection
  • Comprehensive Testing: Full test suite validating security measures

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • PostgreSQL 12+
  • pip3

Installation

  1. Clone the repository:
git clone https://github.com/yourusername/postgresql-security-toolkit.git
cd postgresql-security-toolkit
  1. Run the setup script:
chmod +x scripts/setup.sh
./scripts/setup.sh
  1. Configure your environment:
cp .env.example .env
# Edit .env with your database settings

Basic Usage

from secure_postgresql_client import SecurePostgreSQLClient

# Initialize the secure client
client = SecurePostgreSQLClient({
    'host': 'localhost',
    'database': 'myapp',
    'user': 'app_user',
    'password': 'secure_password'
})

# Safe user search (prevents SQL injection)
users = client.safe_user_search('john_doe')

# Safe JSON search (prevents JSON injection)
products = client.safe_json_search({
    'category': 'electronics',
    'price_max': 1000
})

# Safe array search (prevents array injection)
tagged_products = client.safe_array_search(['laptop', 'portable'])

# Get security metrics
metrics = client.get_security_metrics()
print(f"Threats blocked: {metrics['threats_blocked']}")

πŸ“ Repository Structure

postgresql-security-toolkit/
β”œβ”€β”€ secure-client/
β”‚   └── python/
β”‚       └── secure_postgresql_client.py    # Main secure client library
β”œβ”€β”€ database-config/
β”‚   β”œβ”€β”€ postgresql.conf.template           # Hardened PostgreSQL config
β”‚   └── pg_hba.conf.template              # Secure authentication config
β”œβ”€β”€ tests/
β”‚   └── test_secure_client.py             # Comprehensive test suite
β”œβ”€β”€ scripts/
β”‚   β”œβ”€β”€ setup.sh                          # Setup and installation script
β”‚   └── security-audit.sh                 # Security audit script
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ SECURITY_GUIDE.md                 # Detailed security guide
β”‚   └── API_REFERENCE.md                  # API documentation
└── examples/
    └── vulnerable_vs_secure.py           # Before/after examples

πŸ”’ Security Features

Input Validation

The toolkit provides multi-layered input validation:

  • Pattern Detection: Identifies SQL injection patterns specific to PostgreSQL
  • Type Validation: Enforces data type constraints (usernames, emails, UUIDs, etc.)
  • Length Limits: Prevents buffer overflow and DoS attacks
  • JSON Structure Validation: Whitelist-based validation for JSON inputs
  • Array Validation: Size limits and content validation for arrays

Attack Prevention

Protects against various attack vectors:

  • Traditional SQL injection (UNION, DROP, etc.)
  • PostgreSQL-specific attacks (pg_read_file, pg_sleep, etc.)
  • JSON injection attacks using PostgreSQL operators
  • Array manipulation attacks
  • Comment injection attempts
  • Boolean-based blind injection
  • Time-based attacks

Secure Query Patterns

  • Parameterized Queries: All database operations use proper parameterization
  • Whitelist Validation: Dynamic queries validated against allowed tables/columns
  • Safe Error Handling: Prevents information disclosure through error messages
  • Connection Security: Secure connection management with proper cleanup

πŸ§ͺ Testing

Run the comprehensive test suite:

# Activate virtual environment
source venv/bin/activate

# Run all tests with coverage
python -m pytest tests/ -v --cov=secure-client/python/

# Run specific test categories
python -m pytest tests/test_secure_client.py::TestSecurePostgreSQLClient -v

πŸ“Š Security Monitoring

The toolkit includes built-in security metrics:

metrics = client.get_security_metrics()
print(f"""
Security Metrics:
- Queries executed: {metrics['queries_executed']}
- Validation failures: {metrics['validation_failures']}
- Threats blocked: {metrics['threats_blocked']}
- Threat block rate: {metrics['threat_block_rate']:.2f}%
""")

βš™οΈ Configuration

Database Configuration

Use the provided PostgreSQL configuration template:

# Copy template to your PostgreSQL config directory
cp database-config/postgresql.conf.template /etc/postgresql/13/main/postgresql.conf

# Review and customize settings
sudo nano /etc/postgresql/13/main/postgresql.conf

# Restart PostgreSQL
sudo systemctl restart postgresql

Authentication Configuration

Configure secure client authentication:

# Copy pg_hba template
cp database-config/pg_hba.conf.template /etc/postgresql/13/main/pg_hba.conf

# Customize IP addresses and authentication methods
sudo nano /etc/postgresql/13/main/pg_hba.conf

# Reload configuration
sudo systemctl reload postgresql

πŸ” Security Audit

Run the security audit script to check your PostgreSQL installation:

./scripts/security-audit.sh

This script checks for:

  • Weak authentication configurations
  • Insecure connection settings
  • Missing security patches
  • Dangerous configuration options
  • User privilege issues

πŸ“š Documentation

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

  1. Fork the repository
  2. Create a feature branch
  3. Install development dependencies:
pip install -r requirements-dev.txt
  1. Run tests before submitting:
python -m pytest tests/ -v
python -m flake8 secure-client/
python -m mypy secure-client/

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

🚨 Security Reporting

If you discover a security vulnerability, please send an email to security@yourcompany.com. All security vulnerabilities will be promptly addressed.

πŸ™ Acknowledgments

  • PostgreSQL Security Documentation
  • OWASP SQL Injection Prevention Guidelines
  • Python Security Best Practices
  • Community feedback and contributions

πŸ“ˆ Roadmap

  • Support for additional databases (MySQL, SQLite)
  • Web application firewall integration
  • Real-time threat detection dashboard
  • Machine learning-based anomaly detection
  • Integration with popular ORMs (SQLAlchemy, Django ORM)
  • Kubernetes deployment templates
  • Performance benchmarking tools

⚠️ Important Security Notice: This toolkit provides defense-in-depth security measures, but security is an ongoing process. Always keep your PostgreSQL installation updated, follow security best practices, and regularly audit your systems.

About

A comprehensive PostgreSQL security toolkit with best practices, monitoring, and secure client implementations

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published