c77_secure_db/SECURITY.md

461 lines
17 KiB
Markdown

# Security Policy
## 🛡️ **Our Security Commitment**
The c77_secure_db extension is designed with security as the primary concern. This document outlines our security policies, vulnerability reporting procedures, and the security architecture of the extension.
## 🚨 **Reporting Security Vulnerabilities**
### **Please DO NOT report security vulnerabilities through public GitHub issues.**
If you discover a security vulnerability in c77_secure_db, please report it responsibly:
### **Preferred Reporting Method**
- **Email**: [security@yourcompany.com](mailto:security@yourcompany.com)
- **Subject**: `[SECURITY] c77_secure_db Vulnerability Report`
- **Encryption**: Use our PGP key if possible (key ID: YOUR_PGP_KEY_ID)
### **What to Include**
1. **Description**: Clear description of the vulnerability
2. **Steps to Reproduce**: Detailed steps to reproduce the issue
3. **Impact Assessment**: Your assessment of the potential impact
4. **Proof of Concept**: If available, a proof-of-concept (responsibly disclosed)
5. **Suggested Fix**: If you have ideas for remediation
6. **Contact Information**: How we can reach you for follow-up
### **Response Timeline**
- **Initial Response**: Within 24 hours of report
- **Vulnerability Assessment**: Within 72 hours
- **Fix Development**: Timeline varies based on severity
- **Security Advisory**: Published after fix is available
### **Responsible Disclosure**
We request that you:
- Give us reasonable time to address the issue before public disclosure
- Avoid accessing or modifying data that doesn't belong to you
- Don't perform actions that could harm the availability of the service
- Only test against your own installations
## 🔐 **Security Architecture**
### **Multi-Layer Security Model**
c77_secure_db implements defense-in-depth with multiple security layers:
#### **Layer 1: Trigger Protection**
- **Purpose**: Prevent all direct database modifications
- **Mechanism**: PostgreSQL triggers on all protected tables
- **Coverage**: INSERT, UPDATE, DELETE operations
- **Bypass Prevention**: Cannot be disabled without superuser access
#### **Layer 2: Token Authorization**
- **Purpose**: Authorize legitimate operations
- **Mechanism**: Short-lived, single-use authorization tokens
- **Token Lifespan**: 5 seconds maximum
- **Session Binding**: Tokens tied to specific database sessions
- **Replay Prevention**: Single-use tokens prevent replay attacks
#### **Layer 3: Content Integrity**
- **Purpose**: Detect unauthorized data modifications
- **Mechanism**: SHA-256 cryptographic hashing
- **Coverage**: All business data (excluding system columns)
- **Verification**: On-demand and scheduled integrity checks
#### **Layer 4: Audit Trail**
- **Purpose**: Complete operation logging for forensics
- **Coverage**: All secure operations, successes and failures
- **Retention**: Configurable retention periods for compliance
- **Immutability**: Audit logs protected by same security layers
#### **Layer 5: Access Control (Optional)**
- **Purpose**: Role-based permission enforcement
- **Integration**: c77_rbac extension for advanced permissions
- **Granularity**: Feature-based and scope-based access control
- **Fallback**: Secure operation without RBAC if not available
### **Threat Model**
#### **Threats Mitigated**
| Threat Category | Mitigation Strategy | Security Layer |
|----------------|-------------------|----------------|
| **SQL Injection** | Trigger protection blocks direct SQL | Layer 1 |
| **Application Bypass** | Token validation required for all operations | Layer 2 |
| **Data Tampering** | Content hash verification detects changes | Layer 3 |
| **Replay Attacks** | Single-use, time-limited tokens | Layer 2 |
| **Session Hijacking** | Session-specific token binding | Layer 2 |
| **Privilege Escalation** | Controlled function execution with SECURITY DEFINER | All Layers |
| **Audit Log Tampering** | Audit data protected by same security layers | Layer 4 |
| **Unauthorized Access** | RBAC integration with scope-based permissions | Layer 5 |
#### **Assumptions**
Our security model assumes:
- PostgreSQL superuser access is properly controlled
- Database network communication is encrypted (TLS)
- Application servers are reasonably secure
- System administrators follow security best practices
- Regular security updates are applied
#### **Known Limitations**
- **PostgreSQL Superuser**: Can bypass all protections (by design)
- **Physical Access**: Direct file system access can compromise data
- **Memory Dumps**: Active tokens might be visible in memory dumps
- **Time Synchronization**: Token expiration depends on accurate system time
- **Extension Dependencies**: Security depends on pgcrypto extension integrity
### **Cryptographic Details**
#### **Content Hashing**
- **Algorithm**: SHA-256
- **Input**: Sorted key-value pairs of business data
- **Salt**: None (deterministic hashing for verification)
- **Exclusions**: System columns (timestamps, hashes, etc.)
- **Performance**: Optimized for production workloads
#### **Token Generation**
- **Source**: PostgreSQL's `gen_random_uuid()` function
- **Entropy**: Based on system randomness
- **Format**: UUID v4 standard
- **Storage**: Temporary database table with automatic cleanup
## 🔒 **Security Controls**
### **Access Controls**
#### **Installation Requirements**
- **Superuser Required**: Initial installation requires PostgreSQL superuser
- **Post-Installation**: Regular users can operate with granted roles
#### **Runtime Permissions**
- **c77_secure_db_readonly**: Read-only operations (freshness checks, health monitoring)
- **c77_secure_db_user**: Standard secure operations (insert, update, delete)
- **c77_secure_db_admin**: Administrative functions (hash verification, schema management)
#### **RBAC Integration**
- **Optional**: Works with or without c77_rbac extension
- **Granular**: Feature-based permissions (secure_db_insert, secure_db_update, etc.)
- **Scoped**: Department, region, or custom scope-based access
- **Audited**: All RBAC decisions logged in audit trail
### **Data Protection**
#### **Data at Rest**
- **Database Files**: Protected by PostgreSQL's standard file permissions
- **Hash Storage**: Content hashes stored alongside data in same security context
- **Audit Logs**: Subject to same database security as operational data
- **Tokens**: Automatically purged expired tokens (default: daily cleanup)
#### **Data in Transit**
- **Application to Database**: Use PostgreSQL TLS connections
- **Token Transmission**: Tokens transmitted via secure database session
- **Audit Data**: Logged locally within database, no network transmission
#### **Data Processing**
- **Hash Calculation**: Performed within database using pgcrypto
- **Token Validation**: Atomic database operations with automatic cleanup
- **Operation Logging**: Immediate logging within same transaction context
### **Monitoring and Alerting**
#### **Security Monitoring**
```sql
-- Key security metrics to monitor
SELECT
'Error Rate' as metric,
count(*) FILTER (WHERE success = false)::numeric / count(*) * 100 as percentage
FROM c77_secure_db_operation_audit
WHERE created_at > now() - interval '1 hour';
-- Token anomalies
SELECT count(*) as active_tokens
FROM c77_secure_db_auth_tokens
WHERE expires_at > now();
-- Unusual access patterns
SELECT user_name, count(*) as operations
FROM c77_secure_db_operation_audit
WHERE created_at > now() - interval '1 hour'
GROUP BY user_name
HAVING count(*) > 100;
```
#### **Recommended Alerts**
- **Error Rate > 5%**: Indicates potential security issues or attacks
- **Active Tokens > 100**: May indicate token cleanup problems
- **Hash Mismatches**: Critical security alert requiring immediate investigation
- **Off-Hours Activity**: Unusual activity outside business hours
- **Repeated Failures**: Multiple failed operations from same user
## 🔄 **Security Update Process**
### **Severity Classification**
#### **Critical (CVSS 9.0-10.0)**
- **Timeline**: Patch within 24-48 hours
- **Examples**: Authentication bypass, data corruption, privilege escalation
- **Response**: Emergency release, immediate security advisory
#### **High (CVSS 7.0-8.9)**
- **Timeline**: Patch within 1 week
- **Examples**: Information disclosure, denial of service
- **Response**: Priority release, security advisory
#### **Medium (CVSS 4.0-6.9)**
- **Timeline**: Patch within 30 days
- **Examples**: Less severe information disclosure, limited DoS
- **Response**: Regular release cycle, documented in changelog
#### **Low (CVSS 0.1-3.9)**
- **Timeline**: Next regular release
- **Examples**: Minor information disclosure, edge cases
- **Response**: Standard release process
### **Update Distribution**
#### **Security Advisories**
- **Format**: GitHub Security Advisories
- **Content**: CVE ID, affected versions, mitigation steps, upgrade instructions
- **Distribution**: GitHub, mailing list, website
#### **Patch Releases**
- **Naming**: Increment patch version (e.g., 2.0 → 2.0.1)
- **Content**: Security fixes only, minimal functional changes
- **Testing**: Automated security test suite must pass
- **Backwards Compatibility**: Maintained unless security requires breaking changes
#### **Upgrade Instructions**
```sql
-- Security update process
-- 1. Backup your database
pg_dump your_database > backup_before_security_update.sql
-- 2. Install new extension files
sudo cp c77_secure_db--2.0.1.sql $(pg_config --sharedir)/extension/
-- 3. Update extension
ALTER EXTENSION c77_secure_db UPDATE TO '2.0.1';
-- 4. Verify security update
SELECT c77_secure_db_run_all_tests();
-- Must return: "overall_status": "ALL_TESTS_PASSED"
-- 5. Check health after update
SELECT c77_secure_db_health_check();
```
## 📋 **Compliance and Standards**
### **Security Standards Alignment**
#### **NIST Cybersecurity Framework**
- **Identify**: Asset inventory, risk assessment procedures
- **Protect**: Access controls, data security, protective technology
- **Detect**: Security monitoring, anomaly detection
- **Respond**: Incident response procedures, forensic capabilities
- **Recover**: Recovery planning, backup and restore procedures
#### **OWASP Guidelines**
- **A01 Broken Access Control**: Prevented by trigger protection and RBAC
- **A02 Cryptographic Failures**: SHA-256 hashing with proper implementation
- **A03 Injection**: SQL injection prevented by trigger layer
- **A08 Software Integrity Failures**: Content hash verification
- **A09 Security Logging**: Comprehensive audit trail
#### **Database Security Best Practices**
- **Principle of Least Privilege**: Granular role-based permissions
- **Defense in Depth**: Multiple security layers
- **Audit Logging**: Complete operation trail
- **Data Integrity**: Cryptographic verification
- **Access Controls**: Authentication and authorization
### **Regulatory Considerations**
#### **HIPAA (Healthcare)**
- **Administrative Safeguards**: Access management, audit procedures
- **Physical Safeguards**: Database server protection (external to extension)
- **Technical Safeguards**: Access controls, audit logs, data integrity
#### **SOX (Financial)**
- **Internal Controls**: Automated security controls, segregation of duties
- **Audit Trail**: Complete transaction logging with timestamps
- **Data Integrity**: Hash verification for financial data
#### **GDPR (Privacy)**
- **Data Protection**: Encryption at rest and in transit (implementation-dependent)
- **Audit Requirements**: Complete processing logs
- **Right to Deletion**: Secure deletion capabilities (soft delete support)
## 🔍 **Security Testing**
### **Automated Security Tests**
The extension includes comprehensive security tests:
```sql
-- Run complete security test suite
SELECT c77_secure_db_run_all_tests();
-- Specific security tests
SELECT c77_secure_db_test_security();
-- RBAC integration tests
SELECT c77_secure_db_test_rbac_integration();
```
#### **Test Coverage**
- **Bypass Prevention**: Attempts to circumvent trigger protection
- **Token Security**: Token expiration, single-use validation, session binding
- **Hash Integrity**: Content hash calculation and verification
- **RBAC Integration**: Permission enforcement, scope validation
- **Error Handling**: Security-relevant error conditions
- **Performance**: Security overhead measurement
### **Security Validation Requirements**
#### **Pre-Release Testing**
- [ ] All security tests pass with 100% success rate
- [ ] No bypass vulnerabilities identified
- [ ] Performance impact within acceptable limits
- [ ] RBAC integration functions correctly
- [ ] Error handling doesn't leak sensitive information
- [ ] Audit logging captures all required events
#### **Production Deployment Validation**
```sql
-- Mandatory post-deployment security check
DO $
DECLARE
v_test_results jsonb;
BEGIN
-- Run security tests
SELECT c77_secure_db_run_all_tests() INTO v_test_results;
-- Verify all tests passed
IF (v_test_results->>'overall_status') != 'ALL_TESTS_PASSED' THEN
RAISE EXCEPTION 'DEPLOYMENT FAILED: Security tests did not pass. Status: %',
v_test_results->>'overall_status'
USING HINT = 'Do not use in production until all security tests pass';
END IF;
RAISE NOTICE 'Security validation passed - extension ready for production use';
END $;
```
## 🚨 **Incident Response**
### **Security Incident Classifications**
#### **P0 - Critical Security Breach**
- **Definition**: Active exploitation, data compromise, or system compromise
- **Response Time**: Immediate (< 1 hour)
- **Actions**:
- Isolate affected systems
- Preserve forensic evidence
- Notify security team and management
- Begin incident response procedures
#### **P1 - High Security Risk**
- **Definition**: Vulnerability discovered, attempted exploitation, or suspicious activity
- **Response Time**: Within 4 hours
- **Actions**:
- Assess impact and risk
- Implement temporary mitigations
- Begin patch development
- Monitor for exploitation attempts
#### **P2 - Medium Security Issue**
- **Definition**: Lower-risk vulnerability or security concern
- **Response Time**: Within 24 hours
- **Actions**:
- Document and prioritize
- Plan remediation
- Schedule fix in next release cycle
### **Forensic Capabilities**
#### **Audit Trail Analysis**
```sql
-- Incident investigation queries
-- Identify suspicious activity patterns
SELECT
user_name,
operation_type,
count(*) as frequency,
min(created_at) as first_occurrence,
max(created_at) as last_occurrence,
array_agg(DISTINCT error_message) FILTER (WHERE success = false) as errors
FROM c77_secure_db_operation_audit
WHERE created_at BETWEEN 'incident_start_time' AND 'incident_end_time'
GROUP BY user_name, operation_type
ORDER BY frequency DESC;
-- Hash verification for tampered data
SELECT c77_secure_db_verify_content_hashes('affected_schema', 'affected_table');
-- Token analysis during incident window
SELECT
session_id,
operation_type,
count(*) as token_count,
min(created_at) as first_token,
max(expires_at) as last_expiry
FROM c77_secure_db_auth_tokens
WHERE created_at BETWEEN 'incident_start_time' AND 'incident_end_time'
GROUP BY session_id, operation_type;
```
#### **Evidence Preservation**
- **Audit Logs**: Immutable record of all operations
- **Hash Values**: Cryptographic proof of data state
- **Token Records**: Authorization trail for forensic analysis
- **System Logs**: PostgreSQL logs with detailed operation information
## 📞 **Security Contacts**
### **Security Team**
- **Primary Contact**: security@yourcompany.com
- **Response Time**: 24 hours maximum
- **Escalation**: Available for critical issues
### **Development Team**
- **Technical Contact**: developers@yourcompany.com
- **Availability**: Business hours
- **Expertise**: Extension architecture and implementation
### **Emergency Contacts**
- **After Hours**: emergency@yourcompany.com
- **Critical Issues**: Available 24/7
- **Response**: Within 1 hour for P0 incidents
## 📚 **Additional Resources**
### **Security Documentation**
- **[BEST_PRACTICES.md](BEST_PRACTICES.md)**: Comprehensive security best practices
- **[USAGE.md](USAGE.md)**: Security-focused usage examples
- **[EXAMPLES.md](EXAMPLES.md)**: Secure implementation patterns
### **External Resources**
- **PostgreSQL Security**: https://www.postgresql.org/docs/current/security.html
- **OWASP Database Security**: https://owasp.org/www-project-database-security/
- **NIST Cybersecurity Framework**: https://www.nist.gov/cyberframework
### **Security Tools**
- **pgaudit**: PostgreSQL auditing extension
- **pg_stat_statements**: Query performance and security monitoring
- **log_statement**: PostgreSQL statement logging for security analysis
---
## 📄 **Security Policy Updates**
This security policy is reviewed quarterly and updated as needed to reflect:
- New threats and vulnerabilities
- Changes in security best practices
- Updates to compliance requirements
- Lessons learned from security incidents
**Last Updated**: January 2025
**Next Review**: April 2025
**Version**: 2.0