pgsqlite implements defense-in-depth security with multiple layers of protection against common attack vectors. This document details the security features, configuration options, and best practices for deploying pgsqlite in production environments.
- SQL Injection Protection
- Security Audit Logging
- Rate Limiting & DoS Protection
- Memory Safety
- Input Validation
- Network Security
- Configuration Best Practices
- Security Monitoring
pgsqlite employs a sophisticated two-tier SQL injection detection system:
-
AST-based Analysis (Primary)
- Parses SQL using
sqlparser
with PostgreSQL dialect - Builds Abstract Syntax Tree for structural analysis
- Detects injection patterns at the semantic level
- Parses SQL using
-
Pattern Matching (Fallback)
- Activates when SQL parsing fails
- High-confidence pattern detection
- Zero false positives for legitimate queries
Identifies always-true conditions commonly used in SQL injection:
- Numeric tautologies:
1=1
,2=2
,1<>0
- String tautologies:
'a'='a'
,"x"="x"
- Complex tautologies:
1=1 AND 2=2
Blocks execution of high-risk functions:
- System commands:
exec
,execute
,system
,shell
- Microsoft SQL Server:
xp_cmdshell
,sp_executesql
- Generic:
eval
,cmd
- Limits UNION operations (default: 5)
- Detects suspicious UNION with sensitive tables
- Blocks
UNION SELECT password FROM admin
patterns
- Limits statement count per query (default: 3)
- Prevents statement stacking attacks
- Blocks
; DROP TABLE users; --
patterns
The SQL injection detector is always active but can be tuned:
// In code - for embedded use
let detector = SqlInjectionDetector::new()
.with_max_depth(10) // Maximum query nesting depth
.with_max_statements(3) // Maximum statements per query
.with_max_unions(5); // Maximum UNION operations
Location: /src/security/sql_injection_detector.rs
Key components:
SqlInjectionDetector
: Main detection engineSqlAnalysisResult
: Analysis output with detailed findings- Integration with
DbHandler
for query validation - Automatic security event logging
Comprehensive logging of security-relevant events:
- Authentication Events: Login attempts, successes, failures
- SQL Injection Attempts: Detailed analysis of blocked queries
- Permission Violations: Unauthorized access attempts
- Rate Limit Violations: DoS attempt detection
- System Anomalies: Unexpected errors, resource exhaustion
Environment variables for audit configuration:
# Enable/disable audit logging
PGSQLITE_AUDIT_ENABLED=true
# Minimum severity level (debug, info, warning, error, critical)
PGSQLITE_AUDIT_SEVERITY=info
# Specific event types
PGSQLITE_AUDIT_LOG_AUTH=true # Authentication events
PGSQLITE_AUDIT_LOG_QUERIES=true # Query execution
PGSQLITE_AUDIT_LOG_ERRORS=true # System errors
PGSQLITE_AUDIT_LOG_ADMIN=true # Administrative actions
# Output configuration
PGSQLITE_AUDIT_BUFFER_SIZE=1000 # Event buffer size
PGSQLITE_AUDIT_MAX_QUERY_LENGTH=1000 # Query truncation
Audit events are logged as structured JSON:
{
"timestamp": 1758931844607131,
"event_type": "SqlInjectionAttempt",
"severity": "High",
"client_ip": "192.168.1.100",
"session_id": "abc123",
"database": "production",
"username": "webapp",
"query": "SELECT * FROM users WHERE id = 1 OR 1=1",
"message": "SQL injection attempt detected: tautology",
"metadata": {
"detected_pattern": "tautology",
"detection_method": "ast_analysis"
},
"process_id": 1234,
"thread_id": 5678
}
High-severity events trigger immediate alerts:
- SQL injection attempts
- Authentication failures (repeated)
- Rate limit violations
- System resource exhaustion
Multi-layered protection against denial-of-service attacks:
-
Per-Client Rate Limiting
- Token bucket algorithm
- Configurable limits per IP
- Sliding window tracking
-
Circuit Breaker Pattern
- Automatic client isolation
- Failure threshold detection
- Graduated recovery
-
Resource Protection
- Query size limits
- Nesting depth limits
- Statement count limits
# Rate limiting
PGSQLITE_RATE_LIMIT_ENABLED=true
PGSQLITE_RATE_LIMIT_REQUESTS=1000 # Requests per window
PGSQLITE_RATE_LIMIT_WINDOW=1 # Window in seconds
PGSQLITE_RATE_LIMIT_BURST=100 # Burst capacity
# Circuit breaker
PGSQLITE_CIRCUIT_BREAKER_ENABLED=true
PGSQLITE_CIRCUIT_BREAKER_THRESHOLD=0.5 # Failure rate threshold
PGSQLITE_CIRCUIT_BREAKER_WINDOW=60 # Evaluation window (seconds)
PGSQLITE_CIRCUIT_BREAKER_COOLDOWN=300 # Recovery time (seconds)
# Resource limits
PGSQLITE_MAX_QUERY_SIZE=1048576 # 1MB max query
PGSQLITE_MAX_QUERY_DEPTH=100 # Max nesting
PGSQLITE_MAX_STATEMENTS=10 # Max statements per query
Location: /src/security/rate_limiter.rs
Features:
- Lock-free atomic operations for performance
- Memory-efficient sliding window
- Automatic cleanup of old entries
- Statistics and metrics collection
pgsqlite leverages Rust's ownership system for memory safety:
- No buffer overflows: Bounds checking at compile time
- No use-after-free: Ownership tracking prevents dangling pointers
- No data races: Send/Sync traits ensure thread safety
- No null pointer dereferences: Option types for nullable values
Advanced memory management for performance:
-
Copy-on-Write Strings (
Cow<str>
)- Avoids unnecessary allocations
- Reduces memory fragmentation
- Improves cache locality
-
Arena Allocators
- Bulk allocation for related objects
- Reduced allocation overhead
- Improved cleanup performance
-
TTL-based Caching
- Automatic eviction of stale entries
- Memory pressure handling
- Configurable size limits
- Smart pointers (
Arc
,Rc
) for reference counting - RAII pattern for resource management
- Automatic cleanup on scope exit
- No manual memory management
All PostgreSQL wire protocol messages are validated:
- Message size limits
- Type checking
- Format verification
- Sequence validation
- Type safety for prepared statements
- Length validation for strings
- Range checking for numerics
- Format validation for specialized types
- Authentication verification
- SSL/TLS certificate validation
- Client IP allowlisting (optional)
- Connection limit enforcement
Full TLS 1.2+ support for encrypted connections:
# Generate certificates
pgsqlite --generate-certs --cert-dir ./certs
# Run with TLS
pgsqlite --ssl --cert ./certs/server.crt --key ./certs/server.key
Features:
- Certificate-based authentication
- Perfect forward secrecy
- Modern cipher suites only
- Optional client certificate verification
For local connections with enhanced security:
# Use Unix socket (more secure for local connections)
pgsqlite --unix-socket /var/run/pgsqlite.sock
Benefits:
- No network exposure
- File system permissions
- Lower latency
- Reduced attack surface
#!/bin/bash
# Production configuration example
# Core settings
export PGSQLITE_DATABASE="/secure/path/database.db"
export PGSQLITE_BIND_ADDRESS="127.0.0.1" # Local only
export PGSQLITE_PORT=5432
# Security
export PGSQLITE_SSL=true
export PGSQLITE_SSL_CERT="/secure/certs/server.crt"
export PGSQLITE_SSL_KEY="/secure/certs/server.key"
export PGSQLITE_REQUIRE_SSL=true # Force SSL connections
# Audit logging
export PGSQLITE_AUDIT_ENABLED=true
export PGSQLITE_AUDIT_SEVERITY=info
export PGSQLITE_AUDIT_LOG_AUTH=true
export PGSQLITE_AUDIT_LOG_QUERIES=false # Only for debugging
# Rate limiting
export PGSQLITE_RATE_LIMIT_ENABLED=true
export PGSQLITE_RATE_LIMIT_REQUESTS=100
export PGSQLITE_RATE_LIMIT_WINDOW=1
# Resource limits
export PGSQLITE_MAX_CONNECTIONS=100
export PGSQLITE_CONNECTION_TIMEOUT=300
# Start with restricted permissions
umask 077
pgsqlite
- Enable SSL/TLS for network connections
- Configure audit logging
- Set appropriate rate limits
- Use Unix sockets for local connections
- Restrict file permissions on database files
- Enable connection limits
- Configure firewall rules
- Monitor audit logs
- Regular security updates
- Backup strategy in place
-
Authentication Metrics
- Failed login attempts
- Successful authentications
- Authentication latency
-
SQL Injection Metrics
- Blocked queries count
- Detection method distribution
- Attack pattern trends
-
Rate Limiting Metrics
- Rate limit violations
- Circuit breaker trips
- Client distribution
-
Resource Metrics
- Memory usage
- Connection count
- Query execution time
Export metrics to monitoring systems:
# Prometheus metrics endpoint (planned)
PGSQLITE_METRICS_ENABLED=true
PGSQLITE_METRICS_PORT=9090
# StatsD integration (planned)
PGSQLITE_STATSD_HOST=localhost
PGSQLITE_STATSD_PORT=8125
Critical alerts to configure:
- High SQL injection attempt rate (> 10/min)
- Authentication failure spike (> 50/min)
- Circuit breaker activation
- Memory usage > 90%
- Connection pool exhaustion
Stay informed about security updates:
- Watch the GitHub repository for security advisories
- Enable GitHub security alerts
- Subscribe to release notifications
- Review the changelog for security fixes
If you discover a security vulnerability:
- Do not create a public GitHub issue
- Email security details to the maintainers
- Include:
- Description of the vulnerability
- Steps to reproduce
- Potential impact
- Suggested fix (if available)
pgsqlite's security features support compliance with:
- PCI DSS: SQL injection protection, audit logging
- HIPAA: Encryption in transit, audit trails
- GDPR: Data protection, audit logging
- SOC 2: Security controls, monitoring
Note: pgsqlite itself is not certified for these standards. Compliance depends on your overall implementation and controls.
Planned security improvements:
- Row-level security (RLS) support
- Column-level encryption
- Advanced threat detection with ML
- Security scanning integration
- Automated security testing
- Certificate rotation support
- OAuth/SAML authentication
- Audit log shipping to SIEM
pgsqlite provides comprehensive security features suitable for production deployments. By following the configuration guidelines and best practices in this document, you can deploy pgsqlite with confidence in security-sensitive environments.
Remember: Security is a shared responsibility. While pgsqlite provides the tools, proper configuration, monitoring, and operational practices are essential for maintaining a secure deployment.