68%
of data breaches involve a database as the primary target system (Verizon DBIR 2025)
32 days
average time to detect a database compromise without activity monitoring in place
41%
of organizations have at least one publicly exposed database (Rapid7 2025)

Databases are the crown jewel of every enterprise environment. Customer PII, financial records, health data, authentication credentials -- it all ends up in a database. Yet database security consistently lags behind endpoint and network security in organizational maturity. Misconfigurations, default credentials, excessive privileges, and missing encryption combine to make databases one of the most reliably exploitable targets in modern breaches.

This guide walks through the practical controls that matter: hardening by platform, database activity monitoring (DAM), encryption choices, network isolation, and building an access model that assumes breach. It applies to SQL Server, Oracle, MySQL, PostgreSQL, and cloud-managed variants (RDS, Cloud SQL, Azure SQL).

Why Databases Stay Breached for Weeks

The average time to detect a database compromise is significantly longer than endpoint compromises -- and the reason is structural. Most organizations funnel endpoint telemetry to their SIEM but treat database logs as an operations concern. Database error logs, audit trails, and connection records sit in the database itself or a separate logging destination that security operations never monitors.

The result: an attacker who gains access via a compromised application service account can run SELECT * FROM users for 30 days before anyone notices. The access pattern looks identical to legitimate application queries because it uses the same credential.

The fix requires three concurrent efforts: reduce who can access databases and from where (access control), make illegitimate access look different from legitimate access (monitoring), and encrypt data so that even exfiltrated records are useless without the key (encryption at rest and in transit).

Database Hardening Checklist by Platform

SQL Server

  • Disable the sa account and rename it; use Windows Authentication for internal services where possible
  • Disable xp_cmdshell, Ole Automation Procedures, and Ad Hoc Distributed Queries unless explicitly required
  • Enable Transparent Data Encryption (TDE) for all databases containing sensitive data
  • Set CLR enabled to 0 unless CLR assemblies are required
  • Enable SQL Server Audit and ship logs to your SIEM; audit logins, schema changes, and SELECT on sensitive tables
  • Apply SQL Server patches within your SLA -- SQL Server has a dedicated patch track separate from Windows Update
  • Disable named pipes and shared memory protocols if the application connects over TCP only
  • Run SQL Server service accounts with minimum OS privileges; never SYSTEM or local Administrator

PostgreSQL

  • Edit pg_hba.conf to restrict connections by IP range and authentication method (scram-sha-256 for all non-local connections; never trust)
  • Set ssl = on in postgresql.conf and configure ssl_cert_file, ssl_key_file, and ssl_ca_file
  • Use row-level security (RLS) to enforce data-level access control beyond schema-level grants
  • Enable pgaudit extension for granular DDL and DML auditing
  • Restrict pg_stat_activity access -- it reveals all active queries including queries from other users' sessions
  • Set log_connections = on, log_disconnections = on, and log_statement = ddl at minimum
  • Remove the PUBLIC schema CREATE privilege: REVOKE CREATE ON SCHEMA public FROM PUBLIC

MySQL / MariaDB

  • Remove anonymous users and the test database immediately after install (mysql_secure_installation)
  • Disable LOAD DATA INFILE unless required; it can be used for file read attacks
  • Enable the validate_password plugin with complexity requirements
  • Set bind-address to listen only on required interfaces; 0.0.0.0 exposes MySQL to all interfaces
  • Enable binary logging with binlog_format = ROW for replication and forensic audit trail
  • Use REQUIRE SSL on user grants for any account that connects over the network
  • Enable general_log during incident investigations; it records every SQL statement

Oracle

  • Apply the Oracle Critical Patch Update (CPU) quarterly; Oracle databases are heavily targeted in exploit campaigns
  • Enable Oracle Audit Vault or Unified Auditing and ship to a separate audit repository the database admins cannot modify
  • Remove default schemas (SCOTT, HR, OE) in production environments
  • Set REMOTE_OS_AUTHENT = FALSE to prevent OS-authenticated login bypasses
  • Encrypt tablespaces containing PII using Oracle TDE
  • Enable Oracle Database Vault to restrict DBA access to application data -- separates the DBA role from data access
  • Use Oracle Label Security for multi-tenancy environments requiring row-level classification
Free daily briefing

Briefings like this, every morning before 9am.

Threat intel, active CVEs, and campaign alerts, distilled for practitioners. 50,000+ subscribers. No noise.

Database Activity Monitoring (DAM)

Database Activity Monitoring intercepts SQL traffic at the network or agent level and analyzes it for anomalous patterns -- high-volume SELECT statements, unusual off-hours access, lateral movement from unexpected source IPs, and schema enumeration queries.

Deployment models

  • Network-based DAM: Passively captures SQL traffic from a network tap or span port. Does not require database agents, low performance impact, but cannot see local/loopback connections (which shared hosting and applications on the same host use frequently).
  • Agent-based DAM: Installs an agent on the database host, captures all SQL including local connections, higher fidelity but introduces an agent dependency.
  • Native audit log integration: Uses the database's built-in audit trail (SQL Server Audit, pgaudit, Oracle Unified Auditing) forwarded to the SIEM. Lowest cost, highest coverage gap -- the database itself can be tampered with to suppress audit records.

Key detection use cases

BehaviorWhat to Alert On
Bulk SELECT> 10,000 rows returned in a single session in a short window
Schema enumerationQueries against information_schema, sys.tables, pg_catalog from non-DBA accounts
Credential dumpingSELECT from user/password tables from application accounts
Unusual source IPDatabase connection from a new IP not in the application server whitelist
Privilege escalationGRANT or ALTER USER statements outside change window
Off-hours accessInteractive logins between 11 PM and 5 AM from non-DBA accounts

Commercial DAM vendors: IBM Guardium, Imperva Data Security Fabric, Solarwinds DAM, McAfee Database Security (now Trellix). Most CSPM tools also surface misconfigured RDS/Cloud SQL instances with public exposure.

Encryption: At Rest, In Transit, and at the Column Level

Encryption at rest

Transparent Data Encryption (TDE) encrypts the entire database data file at the storage layer. It protects against an attacker who steals the physical disk or backup file -- but it does NOT protect against a compromised database account or application credential that can query data normally. TDE is a compliance checkbox that addresses a specific threat (physical media theft or backup exfiltration) rather than logical access threats.

Encryption in transit

All database connections should use TLS 1.2 or 1.3. Verify this is enforced:

  • SQL Server: ENCRYPT = yes in the connection string; enforce via SQL Server Configuration Manager
  • PostgreSQL: ssl = on plus hostssl entries in pg_hba.conf (not host)
  • MySQL: --ssl-mode=REQUIRED in client configuration
  • Cloud SQL / RDS: Enable SSL enforcement via the instance settings; do not rely on application defaults

Column-level encryption (CLE)

For the highest sensitivity fields (SSNs, payment card numbers, health record identifiers), column-level encryption means the data is encrypted before storage and the database engine never sees plaintext. This protects against compromised DBA accounts and bulk SELECT exfiltration.

  • SQL Server: Always Encrypted stores keys client-side; the database engine processes ciphertext only
  • PostgreSQL: pgcrypto extension provides pgp_sym_encrypt / pgp_sym_decrypt functions
  • Application-layer encryption: Encrypt in the application before INSERT; keys stored in a secrets manager (Vault, AWS KMS, Azure Key Vault)

CLE introduces query limitations -- you cannot use ORDER BY, LIKE, or range predicates on encrypted columns without deterministic encryption (which weakens security). Design your encryption scheme around which fields need searchability vs. maximum confidentiality.

Least-Privilege Access Model for Databases

The single most impactful database security control is removing excessive privileges. The vast majority of breached databases were accessed using legitimate credentials -- either stolen application service account credentials or over-permissioned developer/DBA accounts.

Service account model

Each application should have its own dedicated database user with only the permissions it needs:

  • A read-heavy reporting application needs only SELECT on specific tables
  • A transactional application needs SELECT, INSERT, UPDATE, DELETE on its schema only
  • No application service account should have CREATE TABLE, DROP TABLE, GRANT, or access to system schemas
  • Schema migration accounts (Flyway, Liquibase) should be separate from runtime accounts, with privileges revoked or credentials rotated after migrations complete

Privilege review workflow

Run privilege audits quarterly. For PostgreSQL:

SELECT grantee, table_schema, table_name, privilege_type
FROM information_schema.role_table_grants
WHERE grantee NOT IN ('pg_catalog', 'information_schema')
ORDER BY grantee, table_schema, table_name;

For SQL Server:

SELECT dp.name AS principal, o.name AS object_name,
       p.type_desc AS permission, p.state_desc AS state
FROM sys.database_permissions p
JOIN sys.database_principals dp ON p.grantee_principal_id = dp.principal_id
JOIN sys.objects o ON p.major_id = o.object_id
ORDER BY dp.name, o.name;

DBA access controls

  • DBAs should not have standing access to production data; use just-in-time (JIT) privilege elevation with approval workflow and session recording
  • Separate the DBA role from data access in Oracle using Database Vault; DBAs can manage schema but cannot SELECT from application tables
  • All DBA access should be via a PAM tool (CyberArk, BeyondTrust) that records the full session

Network isolation

  • Database servers should never be accessible from the internet. Place them in a dedicated subnet with no public IP
  • Application servers connect to databases; databases should not initiate outbound connections
  • Security groups / firewall rules should whitelist specific application server IPs on specific ports -- not 0.0.0.0/0:5432
  • Cloud databases: Disable public access at the instance level, even if a security group would block it. Defense in depth.

Cloud-Managed Database Security (RDS, Cloud SQL, Azure SQL)

Cloud-managed databases shift patching and infrastructure management to the provider but do not shift security responsibility for configuration, access, and data handling.

AWS RDS

  • Enable deletion protection and automated backups
  • Use IAM database authentication for MySQL and PostgreSQL RDS -- eliminates static database passwords for IAM-authenticated services
  • Enable Performance Insights only for authorized roles; it exposes query text
  • Enable Enhanced Monitoring and ship logs to CloudWatch; configure CloudWatch alarms for unusual connection spikes
  • Enable RDS encryption at rest using a customer-managed KMS key (not the AWS default key) for regulatory compliance
  • Disable publicly_accessible flag; use RDS Proxy for connection pooling from Lambda without exposing the database endpoint

Cloud SQL (GCP)

  • Disable the default postgres or root user after setup
  • Use Cloud SQL Auth Proxy for all application connections -- it handles TLS and IAM authentication automatically
  • Enable audit logging via Cloud Audit Logs; export to BigQuery or a centralized logging sink
  • Set authorized_networks to an empty list and use the Auth Proxy instead of IP allowlisting

Azure SQL

  • Enable Microsoft Defender for SQL for anomaly detection and vulnerability assessment
  • Use Azure Active Directory authentication instead of SQL authentication where possible
  • Enable Auditing to a Log Analytics workspace and configure alerts for suspicious activities
  • Enable Always Encrypted for columns containing highly sensitive PII
  • Use Private Endpoints for Azure SQL; disable public network access at the server level

Backup Security and Recovery Testing

Database backups are themselves sensitive data targets. An attacker who cannot exfiltrate 100 GB from a production database may target the backup storage where the same data sits in a tar file without DAM coverage.

Backup protection requirements

  • Encrypt all database backups. For on-premises: use SQL Server backup encryption or compress-and-encrypt with a key stored separately from the backup
  • Store backups in a separate storage account or S3 bucket with its own access controls, separate from production credentials
  • Enable immutable storage (WORM) for backup destinations to prevent ransomware from encrypting or deleting backups
  • Use cross-region or cross-account backup replication for critical databases

Recovery testing

A backup that has never been tested is not a backup. Run quarterly restore drills:

  • Restore to a non-production environment and verify row counts and data integrity
  • Measure recovery time objective (RTO) -- most organizations discover their RTO is 4-6x their assumed value on first test
  • Document the recovery runbook step-by-step; a database restore under incident pressure is not the time to figure out the procedure
  • Test point-in-time recovery (PITR) for critical databases, not just full restores

The bottom line

Database security is not glamorous, but it is where breaches materialize. Hardening defaults, enforcing TLS, monitoring activity, applying least-privilege access, encrypting sensitive columns, and isolating databases in private network segments addresses the overwhelming majority of real-world database compromise vectors. Start with the hardening checklist for your platform, get database logs into your SIEM, and run a privilege audit -- those three steps will surface more risk than any penetration test.

Frequently asked questions

What is the most common way databases get compromised?

The most common paths are: (1) compromised application service account credentials -- attackers steal the credentials the application uses to connect and then query freely; (2) SQL injection via an unparameterized application query that lets attackers inject their own SQL; (3) exposed database ports -- databases with public IP addresses or overly broad firewall rules that let attackers connect directly; and (4) default or weak DBA credentials that were never changed from installation defaults.

Does Transparent Data Encryption (TDE) protect against a data breach?

TDE protects against physical media theft and backup file exfiltration only. It does not protect against a compromised database account, SQL injection, or any attack that accesses data through the database engine itself -- because TDE decrypts data transparently before returning query results. For protection against compromised accounts and insider threats, you need column-level encryption, database activity monitoring, and least-privilege access controls.

What is database activity monitoring (DAM) and do I need it?

DAM intercepts SQL traffic and alerts on anomalous behavior: bulk data exports, schema enumeration, off-hours access, privilege escalation statements, and connections from unexpected sources. If your databases contain regulated data (PCI, HIPAA, SOC 2) or high-value business data, DAM significantly reduces detection time for data exfiltration in progress. Without it, you may not detect a database compromise until the stolen data appears for sale or a regulator notifies you.

How do I find over-privileged database users?

Query the database's permission catalog for your platform (information_schema.role_table_grants in PostgreSQL; sys.database_permissions in SQL Server; DBA_TAB_PRIVS in Oracle). Look for application service accounts with DDL privileges (CREATE, DROP, ALTER), accounts with access to schemas they should not need, and any account with DBA or SYSDBA role. Compare what each account has against what the application actually uses -- the gap is almost always significant.

Should cloud-managed databases (RDS, Cloud SQL) be treated differently?

The cloud provider handles OS patching, hardware management, and some encryption defaults, but configuration security remains your responsibility. The most common cloud database security failures are: public accessibility enabled on RDS instances (surprisingly common), overly permissive security groups, using static database passwords instead of IAM authentication, missing audit logging, and no encryption for backup storage. Use your CSPM tool to continuously audit these settings -- they drift quickly as developers provision new instances.

What compliance frameworks require database security controls?

PCI DSS requires encryption of cardholder data at rest (Requirement 3), access controls with least privilege (Requirement 7), and audit logging (Requirement 10). HIPAA requires encryption of ePHI at rest and in transit and access controls with audit trails. SOC 2 Trust Services Criteria covers logical access and availability, both of which require documented database access controls and monitoring. GDPR's Article 32 requires technical measures to ensure data security, which regulators interpret to include encryption, access control, and monitoring for databases holding EU personal data.

How often should database backups be tested?

At minimum quarterly for full restore testing, and monthly for backup integrity verification (verifying the backup file is not corrupted and can be read). For critical databases, test point-in-time recovery separately from full restores -- PITR uses the transaction log, not just the backup, and has its own failure modes. Document your measured RTO and RPO from each test; the numbers are almost always worse than assumed and should drive investment in faster recovery infrastructure.

Sources & references

  1. Verizon Data Breach Investigations Report 2025
  2. CIS Microsoft SQL Server Benchmarks
  3. PostgreSQL Security Documentation
  4. Oracle Database Security Guide
  5. AWS RDS Security Best Practices
  6. NIST SP 800-111: Guide to Storage Encryption Technologies

Free resources

25
Free download

Critical CVE Reference Card 2025–2026

25 actively exploited vulnerabilities with CVSS scores, exploit status, and patch availability. Print it, pin it, share it with your SOC team.

No spam. Unsubscribe anytime.

Free download

Ransomware Incident Response Playbook

Step-by-step 24-hour IR checklist covering detection, containment, eradication, and recovery. Built for SOC teams, IR leads, and CISOs.

No spam. Unsubscribe anytime.

Free newsletter

Get threat intel before your inbox does.

50,000+ security professionals read Decryption Digest for early warnings on zero-days, ransomware, and nation-state campaigns. Free, weekly, no spam.

Unsubscribe anytime. We never sell your data.

Eric Bang
Author

Founder & Cybersecurity Evangelist, Decryption Digest

Cybersecurity professional with expertise in threat intelligence, vulnerability research, and enterprise security. Covers zero-days, ransomware, and nation-state operations for 50,000+ security professionals weekly.

Free Brief

The Mythos Brief is free.

AI that finds 27-year-old zero-days. What it means for your security program.

Joins Decryption Digest. Unsubscribe anytime.

Daily Briefing

Get briefings like this every morning

Actionable threat intelligence for working practitioners. Free. No spam. Trusted by 50,000+ SOC analysts, CISOs, and security engineers.

Unsubscribe anytime.

Mythos Brief

Anthropic's AI finds zero-days your scanners miss.