392 lines
11 KiB
Markdown
392 lines
11 KiB
Markdown
# c77_secure_db
|
|
|
|
**Enterprise-grade PostgreSQL extension for secure database operations with tamper detection and transaction control.**
|
|
|
|
[](https://www.postgresql.org/)
|
|
[](LICENSE)
|
|
[](CHANGELOG.md)
|
|
|
|
## 🔒 **Security-First Database Protection**
|
|
|
|
c77_secure_db provides database-level security that cannot be bypassed by application bugs or SQL injection attacks. All data modifications go through secure, audited operations with cryptographic tamper detection.
|
|
|
|
### **Why c77_secure_db?**
|
|
|
|
- **🛡️ Unbypassable Security**: Token-based authorization prevents all unauthorized access
|
|
- **🔍 Tamper Detection**: SHA-256 content hashing detects any unauthorized data changes
|
|
- **📊 Complete Audit Trail**: Every operation logged with user context and performance metrics
|
|
- **🔗 RBAC Integration**: Seamless integration with c77_rbac extension for advanced permissions
|
|
- **⚡ Production Ready**: Optimized for high-performance enterprise workloads
|
|
- **🏗️ Framework Agnostic**: Works with Laravel, Django, Node.js, and any PostgreSQL client
|
|
|
|
## 🚀 **Quick Start**
|
|
|
|
### Installation
|
|
|
|
```bash
|
|
# Copy files to PostgreSQL extension directory
|
|
sudo cp c77_secure_db.control $(pg_config --sharedir)/extension/
|
|
sudo cp c77_secure_db--1.0.sql $(pg_config --sharedir)/extension/
|
|
```
|
|
|
|
```sql
|
|
-- Install extension (requires superuser)
|
|
sudo -u postgres psql
|
|
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
|
CREATE EXTENSION c77_secure_db;
|
|
|
|
-- Verify installation (CRITICAL - must pass!)
|
|
SELECT c77_secure_db_run_all_tests();
|
|
|
|
-- Set up application user
|
|
CREATE USER myapp_user WITH PASSWORD 'secure_password';
|
|
GRANT c77_secure_db_user TO myapp_user;
|
|
```
|
|
|
|
### Basic Usage
|
|
|
|
```sql
|
|
-- Create secure schema
|
|
CREATE SCHEMA myapp;
|
|
SELECT c77_secure_db_manage_secure_schemas('add', 'myapp');
|
|
|
|
-- Create secure table
|
|
CREATE TABLE myapp.users (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
email TEXT UNIQUE NOT NULL,
|
|
-- Required security columns
|
|
content_hash TEXT,
|
|
hash_version INTEGER DEFAULT 1,
|
|
created_at TIMESTAMPTZ DEFAULT NOW(),
|
|
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
|
deleted_at TIMESTAMPTZ
|
|
);
|
|
|
|
-- Secure operations (direct SQL is automatically blocked)
|
|
SELECT c77_secure_db_operation(jsonb_build_object(
|
|
'schema_name', 'myapp',
|
|
'table_name', 'users',
|
|
'operation', 'insert',
|
|
'data', jsonb_build_object(
|
|
'name', 'John Doe',
|
|
'email', 'john@example.com'
|
|
)
|
|
));
|
|
```
|
|
|
|
## ✨ **Key Features**
|
|
|
|
### **Token-Based Security**
|
|
- **5-second expiring tokens** prevent replay attacks
|
|
- **Single-use authorization** - tokens cannot be reused
|
|
- **Session-specific** - tied to database connection
|
|
- **Automatic cleanup** - no token buildup
|
|
|
|
### **Content Hash Verification**
|
|
- **SHA-256 cryptographic hashing** for tamper detection
|
|
- **Configurable exclusions** - exclude frequently changing columns
|
|
- **Automatic calculation** - hashes computed transparently
|
|
- **Bulk verification** - check entire tables for integrity
|
|
|
|
### **Comprehensive Audit Logging**
|
|
- **Every operation logged** with complete context
|
|
- **Performance metrics** - execution time tracking
|
|
- **User attribution** - who did what, when
|
|
- **Error tracking** - detailed failure analysis
|
|
|
|
### **RBAC Integration**
|
|
- **Optional c77_rbac integration** - works standalone or with advanced permissions
|
|
- **Feature-based security** - granular permission control
|
|
- **Scope-based access** - department, region, or custom scopes
|
|
- **Graceful degradation** - works without RBAC if not needed
|
|
|
|
## 🔧 **Advanced Features**
|
|
|
|
### **Bulk Operations**
|
|
```sql
|
|
-- Verify multiple records at once
|
|
SELECT c77_secure_db_check_freshness_bulk(
|
|
'myapp', 'users',
|
|
'[{"id":1,"name":"John"},{"id":2,"name":"Jane"}]'::jsonb
|
|
);
|
|
```
|
|
|
|
### **Hash Verification**
|
|
```sql
|
|
-- Check all records in a table
|
|
SELECT c77_secure_db_verify_content_hashes('myapp', 'users');
|
|
|
|
-- Fix any hash mismatches
|
|
SELECT c77_secure_db_verify_content_hashes('myapp', 'users', true);
|
|
```
|
|
|
|
### **RBAC-Protected Operations**
|
|
```sql
|
|
-- Set user context
|
|
SET "c77_rbac.external_id" TO '123';
|
|
|
|
-- Use operation with permission checking
|
|
SELECT c77_secure_db_operation(
|
|
jsonb_build_object(...),
|
|
true, -- check RBAC
|
|
'secure_db_insert' -- required permission
|
|
);
|
|
```
|
|
|
|
## 🏗️ **Framework Integration**
|
|
|
|
### **Laravel**
|
|
```php
|
|
// Service class integration
|
|
class SecureDbService {
|
|
public function insert(string $table, array $data): array {
|
|
$result = DB::selectOne('SELECT c77_secure_db_operation(?) as result', [
|
|
json_encode([
|
|
'schema_name' => 'myapp',
|
|
'table_name' => $table,
|
|
'operation' => 'insert',
|
|
'data' => $data
|
|
])
|
|
]);
|
|
|
|
return json_decode($result->result, true);
|
|
}
|
|
}
|
|
```
|
|
|
|
### **Node.js**
|
|
```javascript
|
|
// Express integration
|
|
const secureDb = {
|
|
async insert(table, data) {
|
|
const result = await pool.query(
|
|
'SELECT c77_secure_db_operation($1) as result',
|
|
[JSON.stringify({
|
|
schema_name: 'myapp',
|
|
table_name: table,
|
|
operation: 'insert',
|
|
data: data
|
|
})]
|
|
);
|
|
|
|
return JSON.parse(result.rows[0].result);
|
|
}
|
|
};
|
|
```
|
|
|
|
### **Django**
|
|
```python
|
|
# Django service integration
|
|
class SecureDbService:
|
|
def insert(self, table, data):
|
|
with connection.cursor() as cursor:
|
|
cursor.execute(
|
|
"SELECT c77_secure_db_operation(%s) as result",
|
|
[json.dumps({
|
|
'schema_name': 'myapp',
|
|
'table_name': table,
|
|
'operation': 'insert',
|
|
'data': data
|
|
})]
|
|
)
|
|
result = cursor.fetchone()[0]
|
|
return json.loads(result)
|
|
```
|
|
|
|
## 📊 **Monitoring & Maintenance**
|
|
|
|
### **Health Monitoring**
|
|
```sql
|
|
-- System health check
|
|
SELECT c77_secure_db_health_check();
|
|
|
|
-- Performance monitoring
|
|
SELECT
|
|
operation_type,
|
|
avg(execution_time_ms) as avg_time,
|
|
count(*) as operation_count
|
|
FROM c77_secure_db_operation_audit
|
|
WHERE created_at > now() - interval '1 hour'
|
|
GROUP BY operation_type;
|
|
```
|
|
|
|
### **Maintenance**
|
|
```sql
|
|
-- Daily cleanup
|
|
SELECT c77_secure_db_cleanup_expired_tokens();
|
|
|
|
-- Weekly integrity check
|
|
SELECT c77_secure_db_verify_content_hashes('myapp', 'users');
|
|
```
|
|
|
|
## 🛡️ **Security Architecture**
|
|
|
|
### **Multi-Layer Protection**
|
|
|
|
1. **Trigger Layer**: Prevents all direct SQL modifications
|
|
2. **Token Layer**: Authorizes legitimate operations with expiring tokens
|
|
3. **Hash Layer**: Detects unauthorized data tampering
|
|
4. **Audit Layer**: Logs all operations for compliance
|
|
5. **RBAC Layer**: Optional permission-based access control
|
|
|
|
### **Threat Mitigation**
|
|
|
|
- ✅ **SQL Injection**: Cannot bypass trigger protection
|
|
- ✅ **Data Tampering**: Detected by content hash verification
|
|
- ✅ **Unauthorized Access**: Blocked by token validation
|
|
- ✅ **Replay Attacks**: Prevented by single-use tokens
|
|
- ✅ **Session Hijacking**: Mitigated by session-specific tokens
|
|
- ✅ **Application Bugs**: Cannot bypass database-level security
|
|
|
|
## 🔄 **Migration from v1.x**
|
|
|
|
**⚠️ BREAKING CHANGES**: Version 2.0 is a complete security rewrite.
|
|
|
|
The vulnerable session variable approach has been completely removed:
|
|
|
|
```sql
|
|
-- ❌ v1.x had this vulnerability (NEVER use this approach)
|
|
SET "myapp.allow_direct_modification" TO 'true'; -- Could bypass security!
|
|
|
|
-- ✅ v2.0 uses secure token-based authorization (unbypassable)
|
|
-- All security is handled internally by the extension
|
|
```
|
|
|
|
**Migration Steps:**
|
|
1. Backup your data
|
|
2. Drop old extension: `DROP EXTENSION c77_secure_db CASCADE;`
|
|
3. Install v2.0: `CREATE EXTENSION c77_secure_db;`
|
|
4. Re-register secure schemas
|
|
5. Run security tests: `SELECT c77_secure_db_run_all_tests();`
|
|
|
|
## 📚 **Documentation**
|
|
|
|
- **[USAGE.md](USAGE.md)** - Comprehensive usage guide with examples
|
|
- **[INSTALL.md](INSTALL.md)** - Detailed installation instructions
|
|
- **[CHANGELOG.md](CHANGELOG.md)** - Version history and changes
|
|
- **[SECURITY.md](SECURITY.md)** - Security policies and reporting
|
|
|
|
## ⚡ **Performance**
|
|
|
|
Designed for production workloads:
|
|
|
|
- **Optimized hash calculations** - Efficient SHA-256 implementation
|
|
- **Indexed operations** - Fast token lookups and audit queries
|
|
- **Bulk processing** - Handle thousands of records efficiently
|
|
- **Minimal overhead** - < 10ms typical operation time
|
|
- **Scalable architecture** - Tested with millions of records
|
|
|
|
## 🧪 **Testing**
|
|
|
|
Built-in comprehensive test suite:
|
|
|
|
```sql
|
|
-- Run all tests (must pass before production use)
|
|
SELECT c77_secure_db_run_all_tests();
|
|
|
|
-- Security-specific tests
|
|
SELECT c77_secure_db_test_security();
|
|
|
|
-- RBAC integration tests
|
|
SELECT c77_secure_db_test_rbac_integration();
|
|
```
|
|
|
|
## 🏢 **Production Use Cases**
|
|
|
|
### **Healthcare**
|
|
- HIPAA compliance with audit trails
|
|
- Patient data integrity verification
|
|
- Role-based access by department
|
|
|
|
### **Financial Services**
|
|
- Transaction integrity protection
|
|
- Regulatory audit requirements
|
|
- Multi-level approval workflows
|
|
|
|
### **E-commerce**
|
|
- Customer data protection
|
|
- Order processing security
|
|
- Payment data integrity
|
|
|
|
### **Government**
|
|
- Classification-based access control
|
|
- Data integrity verification
|
|
- Complete audit trails
|
|
|
|
## 🤝 **Contributing**
|
|
|
|
Contributions are welcome! Please:
|
|
|
|
1. Fork the repository
|
|
2. Create a feature branch
|
|
3. Add tests for new functionality
|
|
4. Ensure all tests pass
|
|
5. Submit a pull request
|
|
|
|
### **Development Setup**
|
|
|
|
```bash
|
|
# Clone repository
|
|
git clone https://github.com/yourusername/c77_secure_db.git
|
|
cd c77_secure_db
|
|
|
|
# Install in development PostgreSQL
|
|
make install
|
|
|
|
# Run tests
|
|
make test
|
|
```
|
|
|
|
## 📋 **Requirements**
|
|
|
|
- **PostgreSQL**: 14 or later
|
|
- **Extensions**: pgcrypto (required), c77_rbac (optional)
|
|
- **Installation**: Superuser privileges required for installation
|
|
- **Usage**: Regular database users (with granted roles)
|
|
- **Platform**: Linux, macOS, Windows (with PostgreSQL)
|
|
|
|
## 📝 **License**
|
|
|
|
MIT License - see [LICENSE](LICENSE) file for details.
|
|
|
|
## 🆘 **Support**
|
|
|
|
- **Documentation**: Check [USAGE.md](USAGE.md) for comprehensive guides
|
|
- **Issues**: Report bugs via GitHub Issues
|
|
- **Security**: See [SECURITY.md](SECURITY.md) for vulnerability reporting
|
|
- **Discussions**: Use GitHub Discussions for questions
|
|
|
|
## 🔗 **Related Projects**
|
|
|
|
- **[c77_rbac](https://github.com/yourusername/c77_rbac)** - Role-Based Access Control extension
|
|
- **PostgreSQL Extensions** - Part of the c77_ extension family
|
|
|
|
## ⭐ **Why Choose c77_secure_db?**
|
|
|
|
> "Traditional application-level security can be bypassed by bugs, SQL injection, or direct database access. c77_secure_db provides unbypassable database-level protection with cryptographic integrity verification."
|
|
|
|
### **Before c77_secure_db**
|
|
```sql
|
|
-- ❌ Vulnerable to bypasses
|
|
INSERT INTO users (name) VALUES ('Hacker'); -- Could work!
|
|
```
|
|
|
|
### **After c77_secure_db**
|
|
```sql
|
|
-- ❌ Automatically blocked
|
|
INSERT INTO users (name) VALUES ('Hacker');
|
|
-- ERROR: Direct modifications not allowed
|
|
|
|
-- ✅ Must use secure API
|
|
SELECT c77_secure_db_operation(...); -- Audited, authorized, verified
|
|
```
|
|
|
|
---
|
|
|
|
**Get started today and secure your PostgreSQL database with enterprise-grade protection!**
|
|
|
|
```sql
|
|
CREATE EXTENSION c77_secure_db;
|
|
SELECT c77_secure_db_run_all_tests(); -- Must pass!
|
|
``` |