06 Database Security
Table of Contents
Overview
Database security encompasses the tools, controls, and measures designed to protect database management systems (DBMS) from threats and vulnerabilities. Databases are high-value targets containing sensitive information, making their security critical to organizational risk management.
Security Objectives for Databases
Confidentiality
Protect sensitive data from unauthorized disclosure
Encryption, access control, data masking
Integrity
Prevent unauthorized modification or corruption
Constraints, triggers, checksums, backups
Availability
Ensure database accessible to authorized users
Redundancy, backup/recovery, DDoS protection
Accountability
Track database operations for audit
Logging, auditing, change tracking
Database Security Fundamentals
The Database Threat Landscape
Common Database Threats:
SQL Injection
Malicious SQL code injection through inputs
Data breach, manipulation, deletion
Privilege Escalation
Unauthorized elevation of user privileges
Full database compromise
Credential Theft
Stolen database credentials
Unauthorized access
Insider Threats
Malicious or negligent insiders
Data exfiltration, sabotage
Weak Authentication
Poor password policies, no MFA
Easy unauthorized access
Unpatched Vulnerabilities
Missing security patches
Exploitation of known flaws
Excessive Privileges
Users with unnecessary permissions
Larger attack surface
Backup Exposure
Unsecured database backups
Offline data access
Inference Attacks
Deducing sensitive data from queries
Privacy violations
DoS/DDoS
Overwhelming database resources
Service unavailability
Defense in Depth for Databases
Multiple security layers: Network Security (Firewalls, Segmentation) → Authentication (Strong credentials, MFA) → Authorization (RBAC, least privilege) → Encryption (TDE, column encryption) → Auditing (Logs, monitoring) → Secure Configuration
Database Access Control
Database-Specific Access Control Models
Discretionary Access Control (DAC) in Databases
Users control access to objects they own.
SQL Example (PostgreSQL):
Advantages: Flexible, users control data, granular permissions
Disadvantages: Hard to enforce policies, users may grant excessive permissions, difficult auditing
Mandatory Access Control (MAC) in Databases
Access based on security labels and clearance levels.
Implementation:
Oracle Label Security
Row-level security with classification labels
Enforced by DBMS, users cannot override
Example Scenario:
Role-Based Access Control (RBAC)
Permissions assigned to roles, users assigned to roles.
RBAC Hierarchy Example:
Role Hierarchy:
Advantages: Easier management, aligns with org structure, simplifies auditing, reduces overhead
Row-Level Security (RLS)
Fine-grained access control at the row level based on user context.
PostgreSQL Example:
Use Cases:
Multi-tenant SaaS applications
Departmental data segregation
Security clearance enforcement
Data sovereignty requirements
Column-Level Security
Restrict access to specific columns.
SQL Server Example:
Principle of Least Privilege in Databases
Implementation:
Grant minimum necessary permissions (e.g., SELECT/INSERT/UPDATE on specific tables, not ALL PRIVILEGES)
Separate accounts: Admin (DBA tasks), Application (limited data access), Read-only (reporting), Backup (backup ops)
Avoid root/superuser: Never use sa/postgres/root for applications, create dedicated accounts
Database Authentication
Database User Authentication
Password-Based Authentication
Best Practices:
Minimum password length: 12-16 characters
Password complexity: Enforce strong password requirements
Password expiration: Balance security with usability (90-180 days)
Account lockout: Temporarily lock after N failed attempts (e.g., 5)
Password history: Prevent reuse of recent passwords
SQL Server Example:
Storing Database Passwords:
Never: Hardcode in source code or store in plain text
Use: Environment variables, secret management services (HashiCorp Vault, AWS Secrets Manager), encrypted config files
External Authentication
LDAP/Active Directory Integration:
Kerberos Authentication:
Benefits: Centralized user management, SSO, consistent password policies, automated provisioning/deprovisioning
Certificate-Based Authentication
PostgreSQL SSL Certificate Authentication:
Advantages: Strong cryptographic authentication, no password management, suitable for service-to-service, HSM support
Multi-Factor Authentication for Databases
Implementation Strategies: Database + External MFA (Duo/Okta), VPN + Database (MFA required), Bastion Host (jump server with MFA), Application-Level MFA
Database Encryption
Encryption at Rest
Transparent Data Encryption (TDE)
Encrypts entire database files at the storage level.
SQL Server TDE:
Characteristics: Transparent (no code changes), minimal performance overhead (hardware AES), encrypts data/log files and backups, critical key management
Key Hierarchy:
File-Level Encryption
Operating system or storage-level encryption.
Examples:
Linux: LUKS (dm-crypt)
Windows: BitLocker
Cloud: AWS EBS encryption, Azure Disk Encryption
Advantages: Protects against physical theft, easier than TDE, OS-level key management
Disadvantages: Performance impact, no fine-grained control
Application-Level Encryption
Encrypt data before inserting into database.
Example (Python):
Advantages: Fine-grained control, end-to-end encryption, no DB encryption support needed
Disadvantages: Complex logic, cannot query encrypted data directly, application manages keys
Column-Level Encryption
Encrypt specific sensitive columns.
SQL Server Always Encrypted:
Encryption Types:
Deterministic: Same plaintext → same ciphertext (allows equality comparisons)
Randomized: Same plaintext → different ciphertext (stronger security, no queries)
Encryption in Transit
TLS/SSL for Database Connections:
PostgreSQL:
MySQL:
Importance: Prevents eavesdropping, protects credentials in transit, ensures data integrity
Key Management
Key Management Best Practices:
Separate key storage from data (use dedicated key management systems)
Hardware Security Modules (HSMs) (FIPS 140-2 Level 2+: AWS CloudHSM, Azure Key Vault, Thales HSM)
Key Rotation (annually or after breach, maintain version history)
Access Control for Keys (strict permissions, audit access)
Backup Key Material Securely (encrypted backups, separate location)
SQL Injection
SQL Injection is a code injection attack where malicious SQL statements are inserted into input fields, manipulating database queries.
SQL Injection Attack Types
1. Classic (In-Band) SQL Injection
Vulnerable Code:
Attack:
Another Attack:
2. Union-Based SQL Injection
Attacker uses UNION to combine malicious query with legitimate one.
Attack:
3. Blind SQL Injection
No direct output, but attacker infers information from application behavior.
Boolean-Based:
Time-Based:
4. Second-Order SQL Injection
Malicious data stored in database, executed later.
5. Out-of-Band SQL Injection
Data exfiltrated through alternative channels (DNS, HTTP requests).
SQL Server Example:
Result: Database makes DNS/SMB request to attacker.com, leaking password in domain name.
6. NoSQL Injection
NoSQL databases also vulnerable to injection.
MongoDB Example (Vulnerable):
SQL Injection Prevention
1. Parameterized Queries (Prepared Statements)
SECURE - Always use this approach:
Python (psycopg2):
Java (JDBC):
PHP (PDO):
Node.js (pg):
Why It Works:
Database treats parameters as data, not executable code
No possibility of SQL code injection
Works for all user inputs
2. Stored Procedures (with Proper Parameterization)
Note: Stored procedures alone don't prevent SQL injection if you concatenate strings inside them!
3. Input Validation
Whitelist Validation:
Pattern Matching:
Note: Input validation is a defense-in-depth measure, NOT a replacement for parameterized queries.
4. Escaping (Last Resort)
If parameterized queries are impossible (rare cases), escape special characters.
Warning: Escaping is error-prone and should be avoided. Use parameterized queries instead.
5. Principle of Least Privilege
Limit database user permissions:
Even if SQL injection occurs, damage is limited.
6. Web Application Firewall (WAF)
Deploy WAF to detect and block SQL injection attempts.
WAF Rules:
Detect SQL keywords in unexpected parameters
Block suspicious patterns (UNION, --, /*, xp_, etc.)
Rate limiting to prevent automated attacks
Example (ModSecurity Rule):
Note: WAF is defense-in-depth, not a substitute for secure coding.
7. Error Handling
Don't expose database errors to users:
Bad:
Good:
Log detailed errors server-side for debugging, show generic errors to users.
SQL Injection Testing
Manual Testing:
Automated Tools:
sqlmap: Powerful SQL injection exploitation tool
OWASP ZAP: Web application security scanner
Burp Suite: Intercepting proxy with scanner
Acunetix: Commercial web vulnerability scanner
Testing Command (sqlmap):
Database Auditing and Compliance
Database Auditing
Auditing tracks and logs database activities for security analysis and compliance.
What to Audit:
Authentication attempts (successful and failed)
Privileged operations (DDL statements)
Data access (sensitive tables)
Data modifications (INSERT, UPDATE, DELETE)
Schema changes
Permission changes
SQL Server Audit Example:
PostgreSQL Auditing (pgAudit):
Compliance Requirements
GDPR (General Data Protection Regulation):
Data encryption (at rest and in transit)
Access controls
Audit logs (who accessed what data, when)
Data minimization
Right to erasure (ability to delete user data)
Breach notification (72 hours)
HIPAA (Health Insurance Portability and Accountability Act):
Encryption of Protected Health Information (PHI)
Access controls and audit logs
Business Associate Agreements (BAAs)
Breach notification
Data backup and disaster recovery
PCI DSS (Payment Card Industry Data Security Standard):
Encrypt cardholder data
Restrict access to cardholder data
Maintain audit logs
Regularly test security systems
Maintain vulnerability management program
SOX (Sarbanes-Oxley Act):
Audit trails for financial data
Change control
Access controls
Data integrity verification
Secure Database Configuration
Secure Installation
Initial Security Steps:
Change default passwords immediately
Remove/disable default accounts
Remove sample/test databases
Database Hardening
Network Security:
Bind to specific IP address (not 0.0.0.0)
Use non-standard ports (security through obscurity - minor benefit)
Firewall rules: Allow only necessary IPs
Disable remote root/admin login
PostgreSQL Example:
Service Configuration:
File System Permissions:
Patch Management
Best Practices:
Subscribe to database vendor security advisories
Test patches in development/staging before production
Maintain patch schedule (critical: immediate, high: monthly, low: quarterly)
Automate patching where possible
Document patching procedures
Example CVE Tracking:
PostgreSQL: https://www.postgresql.org/support/security/
MySQL: https://www.mysql.com/support/security/
SQL Server: Microsoft Security Response Center (MSRC)
Oracle: Critical Patch Updates (CPU)
Database-Specific Threats
Inference Attacks
Inference attack: Deducing sensitive information by analyzing query results and database responses.
Example Scenario:
Mitigation Strategies:
Query result size restrictions
Data perturbation/noise injection
Add random noise to aggregate results
Balance privacy with utility
Query auditing
Monitor for sequences of related queries
Detect inference attack patterns
Differential privacy
Mathematical framework for privacy-preserving queries
Add calibrated noise to query results
Privilege Escalation
Attacker gains higher privileges than authorized.
Attack Vectors:
SQL injection → access to higher-privilege procedures
Exploiting weak permissions on stored procedures
Default/weak admin credentials
Vulnerabilities in database software
Example (SQL Server):
Prevention:
Principle of least privilege for all accounts
Avoid EXECUTE AS OWNER unless necessary
Regular privilege audits
Disable unused features/procedures
Backup Security
Backup Risks:
Backup files contain full database (including sensitive data)
Often stored with weak permissions
May be forgotten on old servers/tapes
Backup Security Best Practices:
Encrypt backups
Secure backup storage
Separate storage from production database
Encrypted file system or cloud storage
Access controls on backup files
Regular backup testing
Verify backups can be restored
Test restore procedures
Check backup integrity
Backup retention policy
Define retention periods based on compliance requirements
Securely destroy old backups
Document retention policy
NoSQL Security
NoSQL databases (MongoDB, Cassandra, Redis) have different security considerations.
MongoDB Security
Authentication:
Authorization:
NoSQL Injection Prevention:
Network Security:
Bind to localhost or specific IP
Enable TLS/SSL
Firewall rules
Redis Security
Authentication:
Network Security:
Best Practices
Database Security Checklist
Access Control:
Implement role-based access control (RBAC)
Enforce principle of least privilege
Use row-level and column-level security where needed
Regular access reviews and audits
Disable/remove unused accounts
Authentication:
Enforce strong password policies
Implement multi-factor authentication for privileged accounts
Use external authentication (LDAP/AD) for centralized management
Never use default credentials
Encryption:
Encrypt data at rest (TDE or file-level encryption)
Encrypt data in transit (TLS/SSL for all connections)
Encrypt backups
Implement secure key management
Application Security:
Always use parameterized queries / prepared statements
Never concatenate user input into SQL queries
Validate and sanitize all inputs
Implement proper error handling (don't expose details)
Use Web Application Firewall (WAF)
Auditing and Monitoring:
Enable database auditing
Log all authentication attempts
Monitor for suspicious activity
Implement alerting for security events
Regular security assessments
Configuration:
Change default passwords immediately
Remove sample/test databases
Disable unnecessary features
Apply principle of least functionality
Keep database software patched and updated
Backup and Recovery:
Regular automated backups
Encrypt backups
Secure backup storage
Test restore procedures regularly
Documented disaster recovery plan
Network Security:
Firewall rules restricting database access
Network segmentation (DMZ, private subnets)
VPN for remote database access
Intrusion detection/prevention systems
Security Testing
Regular Security Assessments:
Vulnerability Scanning
Tools: Nessus, OpenVAS, Qualys
Identify missing patches and misconfigurations
Schedule: Monthly or after changes
Penetration Testing
Simulated attacks to find vulnerabilities
Test SQL injection, privilege escalation, etc.
Schedule: Annually or after major changes
Code Review
Review database access code for security issues
Focus on SQL injection, access control, error handling
Audit Review
Analyze audit logs for suspicious activity
Verify compliance with policies
Last updated