Databases hold the data attackers actually want, yet many are still reachable from the internet, protected by shared or default accounts, and queried by applications that connect with administrator rights. Most database breaches do not need an exotic exploit: an open port, a reused application password or an injectable query is enough. This guide covers the database threat model, network exposure, authentication, least privilege for people and application service accounts, encryption at rest, in transit and at field level, auditing and database activity monitoring, hardening baselines, backups and cloud managed databases. It uses documented settings from PostgreSQL, SQL Server, Oracle, MySQL, MongoDB and Redis as examples and is written for DBAs, platform engineers and security teams.
Key takeaways
- Never expose a database port to the internet. Databases belong on a private segment reachable only from the application tier and an administrative jump path.
- Every connection needs a named identity. One account per application or service, no use of sa, root or SYS, and integrated or token-based authentication where the platform supports it.
- Application accounts are non-human identities. They should not own schemas or hold DBA rights, and their credentials belong in a vault with rotation, not in source code or config files.
- Know what each encryption layer protects. TDE protects files and backups, TLS protects the wire, and only field-level encryption or tokenisation keeps data from a privileged DBA or a stolen application session.
- Audit the access that matters. Native audit or database activity monitoring should capture privileged actions, failed logins, permission changes and bulk reads of sensitive tables, and send them off the database server.
The database threat model
Start from how databases are actually compromised, then map each path to a control owner.
| Threat | Typical path | Primary controls | ATT&CK (v20) |
|---|---|---|---|
| Internet exposure | Database port or admin console reachable without authentication | Private network, firewall allowlists, authentication enforced | T1190 Exploit Public-Facing Application |
| Credential misuse | Default, shared or leaked application credentials | Named accounts, vaulted and rotated secrets, MFA for admins | T1078 Valid Accounts |
| Injection | SQL, NoSQL or LDAP injection through the application | Parameterised queries, least-privilege app account | T1190 |
| Over-privileged access | Application or analyst account reads far more than it needs | Roles, row and column security, views | T1213.006 Data from Information Repositories: Databases |
| Unpatched engine | Known vulnerability in the database server or a bundled tool | Patching, vulnerability assessment, reduced exposure | T1190 |
| Destruction and extortion | Tables dropped or encrypted after access is gained | Separated, immutable backups; restricted DROP and TRUNCATE rights | T1485 Data Destruction |
| Insider and privileged misuse | DBA or support account bulk-exports sensitive data | Separation of duties, field-level encryption, activity monitoring | T1213.006 |
Network exposure: keep databases off the internet
Redis's own documentation says it "is designed to be accessed by trusted clients inside trusted environments", and the same is true of every mainstream database. The DeepSeek database exposure (an open ClickHouse database leaking chat logs and API secrets) and the Moltbook database exposure (an open Supabase database exposing 1.5 million AI agent API keys) show how quickly open data stores are found.
- Bind to private interfaces: MongoDB's
net.bindIp, Redisbind 127.0.0.1(Redis enters protected mode since 3.2.0 when bound to all interfaces without a password) and PostgreSQLlisten_addressesshould list only the interfaces the application uses. - Allowlist sources: firewall or security group rules that admit only application servers and the admin jump host. MongoDB adds
security.clusterIpSourceAllowlistand per-userauthenticationRestrictions; MySQL warns "Never grant privileges to all hosts". - Test from outside: MySQL's guidelines suggest scanning your own ports from the internet with nmap; port 3306 "should not be accessible from untrusted hosts". Do the same for 1433 (SQL Server), 1521 (Oracle listener), 5432 (PostgreSQL), 27017 (MongoDB), 6379 (Redis) and 9200 (Elasticsearch).
- No direct client connections: OWASP states that "Direct connections should never be made from a thick client to the backend database"; put an API with access control in between.
- Protect admin consoles: phpMyAdmin, pgAdmin and similar tools need authentication, HTTPS and network restriction too.
Feed database hosts and cloud database endpoints into external attack surface scanning. See the Attack Surface Management Guide.
Authentication: no shared or default accounts
Require authentication for every connection, including local ones, and remove default and sample accounts at build time. The JADEPUFFER agentic ransomware case used harvested and default credentials to destroy a production database.
| Platform | Prefer | Avoid or remove |
|---|---|---|
| PostgreSQL | scram-sha-256, cert or GSSAPI in pg_hba.conf; hostssl records to force TLS | trust, which lets anyone who can connect log in as any user; password (clear text); md5, which is deprecated |
| SQL Server | Windows or Active Directory authentication through AD groups mapped to roles; contained users where databases move between instances | The sa login (Microsoft: should not be used or enabled); Mixed Mode unless required |
| MySQL and MariaDB | Accounts scoped to a host; run mysql_secure_installation | Root without a password (test with mysql -u root); accounts on '%' |
| MongoDB | Access control enabled, SCRAM or X.509; LDAP or Kerberos in Enterprise and Atlas | Instances started without authorisation enabled |
| Redis | ACL users (Redis 6 and later) with command restrictions | A single shared requirepass for every client |
| Amazon RDS (MySQL, MariaDB, PostgreSQL) | IAM database authentication: short-lived tokens valid for 15 minutes, no password stored in the database | Applications using the master user |
PostgreSQL uses the first pg_hba.conf record that matches, with no fall-through, so a broad trust line near the top silently overrides stricter rules below it. Order rules from most to least specific and review the file under change control. Hard-coded vendor credentials are a separate class of risk: the SAP SQL Anywhere Monitor hard-coded credentials flaw scored a maximum 10.0.
Least privilege and application service accounts
The application's database account is a non-human identity with standing access to all the data the application can reach, so it deserves the same governance as any privileged service account.
- One account per application and environment: separate accounts for development, test and production, each limited to its own database. OWASP: "DO NOT ASSIGN DBA OR ADMIN TYPE ACCESS TO YOUR APPLICATION ACCOUNTS".
- Do not let the application own the schema: ownership allows privilege escalation and, in PostgreSQL, lets the owner bypass row-level security unless
FORCE ROW LEVEL SECURITYis set. Run migrations with a separate deployment account that is used only during releases. - Grant only required statements: most applications need SELECT, INSERT, UPDATE and DELETE on specific tables, not DROP, ALTER or GRANT. Restrict the FILE privilege in MySQL and avoid database links and linked servers.
- Vault and rotate credentials: never in source code or committed config files. Use dynamic, short-lived credentials or platform identity (IAM database authentication, managed identities, gMSA for SQL Server service accounts, which have their passwords managed by Windows) where available. See the Secrets Management Guide.
- Scope automation tokens too: CI pipelines, AI coding agents and platform tokens that can reach production databases need the same limits. The PocketOS database deletion happened when an AI coding agent used an over-privileged Railway token to wipe production. See the Service Account Security Guide.
- Separate DBA duties: Microsoft recommends granting DBAs
CONTROL SERVERrather than sysadmin membership, because sysadmin "doesn't respect DENY while CONTROL SERVER does", and limiting DBA rights to modify audit logs. Use MFA and a privileged access workflow for DBA logins. See the Privileged Access Management Guide. - Restrict rows and columns: PostgreSQL
ALTER TABLE ... ENABLE ROW LEVEL SECURITYwithCREATE POLICY(default deny when no policy exists; superusers andBYPASSRLSroles always bypass), SQL Server row-level security withSESSION_CONTEXTfor middle-tier apps that share one login, and column grants or restricted views for sensitive fields.
Encryption at rest, in transit and at field level
| Control | Protects against | Does not protect against | Examples |
|---|---|---|---|
| Transparent data encryption (TDE) or storage encryption | Stolen disks, data files and backup files | Anyone who can query the database, including an attacker with app credentials; data on the wire | SQL Server and Oracle TDE, MongoDB WiredTiger encryption at rest, RDS AES-256 encryption of instances and snapshots |
| TLS in transit | Eavesdropping and credential capture on the network | Data at rest; compromised endpoints | PostgreSQL hostssl; MongoDB TLS for all connections; Redis optional TLS |
| Client-side field encryption | DBAs, database compromise and backups exposing specific fields | A compromised application holding the keys | SQL Server Always Encrypted (decrypted only in client libraries); MongoDB Queryable Encryption and CSFLE |
| Tokenisation | Exposure of card numbers or identifiers in downstream systems | The token vault itself, which becomes the high-value target | Payment and identifier vaults |
| Dynamic data masking | Casual over-viewing in reports and support screens | Determined users with query access; it is presentation, not encryption | SQL Server DDM (Microsoft: prefer Always Encrypted where possible) |
- TDE scope limits: in SQL Server, TDE covers data and log files, backups and tempdb, but not FILESTREAM data, buffer pool extension files, or communication channels.
- Back up the keys: Microsoft warns that without a backup of the TDE certificate and private key "you can't open the database" after a restore on another server. Store keys in an HSM or external key manager where possible. See the Cryptographic Key Management Guide.
- Clients must verify: OWASP recommends TLS 1.2 or later with clients verifying the server certificate; encryption without verification still allows interception.
Choosing: TDE is the baseline for every production database. Add field-level encryption or tokenisation for a small set of high-impact fields (payment data, national identifiers, health data) where you must keep data from DBAs or hosting providers, accepting limits on querying and indexing.
Auditing and database activity monitoring
Native audit features are the foundation; database activity monitoring (DAM) tools add independent capture, analytics and blocking. Both should send events off the database host so a DBA or attacker cannot quietly delete them.
- SQL Server: SQL Server Audit with a server-level policy inherited by all databases, plus database-level audits on tables and columns with sensitive data. Microsoft: if data is important enough to protect, it "should be considered important enough to audit".
- Oracle: unified auditing, read through
UNIFIED_AUDIT_TRAIL.ORA_SECURECONFIGis enabled by default on databases created from 12.2 andORA_LOGIN_LOGOUTfrom 26ai, but not on upgraded databases. Traditional auditing is desupported in Oracle AI Database 26ai. - PostgreSQL:
log_connections,log_disconnectionsand the pgAudit extension for statement and object audit. - MongoDB: the Enterprise auditing facility, filtered to authentication and privileged events.
- Cloud: check what the platform does not log. AWS notes that CloudWatch and CloudTrail do not log IAM database authentication.
What to alert on: failed logins and logins from new hosts, use of superuser or break-glass accounts, GRANT, ALTER ROLE and audit policy changes, DROP or TRUNCATE in production, application accounts running ad hoc queries or connecting outside the application tier, and unusually large result sets from sensitive tables. Correlate in the SIEM. See the SIEM Guide.
Hardening, patching and backups
- Baselines: CIS publishes consensus Benchmarks for major database engines, assessable with CIS-CAT; DISA publishes STIGs for products including Microsoft SQL Server, Oracle Database and PostgreSQL. Pick one baseline per engine and track deviations.
- SQL Server: disable
xp_cmdshell,xp_dirtreeand other unused extended procedures, CLR execution and the SQL Browser service; remove Northwind and AdventureWorks. - MongoDB: disable server-side JavaScript with
--noscriptingif$where,mapReduce,$accumulatorand$functionare unused; run under a dedicated OS user. - Redis: restrict
CONFIG,FLUSHALLand similar commands with ACL rules (renaming commands is deprecated);CONFIGcan redirect dump files to arbitrary paths and lead to code execution. - Elasticsearch: since 8.0, security is "enabled and configured by default"; never disable it to fix a connection problem.
- Patching: database engines and drivers need a tracked patch cadence. MongoBleed (CVE-2025-14847) let remote clients read secrets from MongoDB server memory, a reminder that exposure turns an engine bug into a breach. See the Patch Management Guide.
- Vulnerability assessment: run configuration scans (for example SQL vulnerability assessment in Microsoft Defender for SQL) alongside OS hardening. See the Linux Server Hardening Guide.
Backups and recovery
Backups are a second copy of the database and need equal protection: restricted permissions, encryption, and storage the database credentials cannot delete. Keep encryption keys and certificates recoverable separately from the database server, keep transaction logs on a separate disk, and test restores, including point-in-time recovery, at least quarterly. Restrict who can run DROP DATABASE or delete snapshots, since attackers target both. See the Backup Security and Immutable Backup Guide.
Cloud managed databases and shared responsibility
AWS describes the split as security "of" the cloud (the provider) versus security "in" the cloud (the customer). Managed services patch the engine and run backups, but the customer still owns most of the decisions that cause breaches.
| Area | Provider (managed service) | Customer |
|---|---|---|
| Engine patching and host OS | Applies patches, often in customer-chosen maintenance windows | Choose windows, track major version end of support |
| Network exposure | Provides VPC, private endpoints and security groups | Keeps instances private and security groups narrow |
| Identity | Offers IAM database authentication and secrets integration | Retires master user use, scopes IAM policies, rotates secrets |
| Encryption | Provides encryption at rest and TLS endpoints | Enables them, manages keys, enforces TLS on clients |
| Data access and audit | Provides audit and log export options | Grants, row and column security, log review |
Developer platforms that expose the database through an auto-generated API (as Supabase does over PostgreSQL) make row-level security the main access control, so every exposed table needs RLS enabled and tested. See the CNAPP Guide for posture checks across cloud database services.
Injection: an application-layer control
SQL injection is fixed in application code, not the database. OWASP's primary defences are prepared statements with parameterised queries, properly constructed stored procedures and allow-list input validation; escaping user input is "STRONGLY DISCOURAGED". The database's part is least privilege, so a successful injection reads one schema rather than the whole server. The McKinsey AI platform hack shows SQL injection in unauthenticated APIs is still being found. LDAP injection follows the same logic: escape distinguished names and search filters with the correct encoding and limit the bind account's rights.
Implementation and measurement
A phased rollout
- Inventory: list every database instance, engine, version, owner, data classification and network exposure, including cloud and developer-created instances. See the Data Security Guide.
- Close exposure first: remove internet reachability and admin console exposure; this is the fastest risk reduction and rarely breaks applications that run in the same network.
- Turn on auditing in log-only mode: collect two to four weeks of connections and queries to learn which accounts and hosts actually use each database before tightening anything.
- Fix accounts: remove default and orphaned accounts, split shared accounts, move application credentials to a vault, then reduce grants based on observed usage. Pilot on one non-critical application, keep the previous grant script for rollback, and watch error rates after each change.
- Encrypt: enable TDE and enforce TLS (start with
hostsslor equivalent alongside the old rule, then remove the non-TLS path), with key backups verified before rollout. - Baseline and monitor: apply CIS or STIG baselines with documented exceptions, schedule configuration scans and connect audit events to the SIEM.
Small and large estates: a small organisation on managed cloud databases gets most value from private networking, IAM or vaulted credentials and provider audit logs. A large estate with Oracle and SQL Server on-premises usually needs a DAM platform, a privileged access workflow for DBAs and field-level encryption for regulated data.
Measuring progress
- Number of database endpoints reachable from the internet (target zero).
- Percentage of application accounts that are unique, vaulted and rotated, and without DBA or owner rights.
- Percentage of production databases with TDE enabled and TLS enforced.
- Percentage of sensitive databases sending audit events to the SIEM, and mean time to review privileged-activity alerts.
- Number of baseline deviations without an approved exception, and time from database patch release to deployment.
- Restore tests completed successfully in the last quarter.
Common failure patterns
- Open by default: a test or analytics database launched without authentication on a public IP, as in the DeepSeek and Moltbook exposures.
- The application as DBA: one powerful login used by the app, migrations and support staff, so every injection or leaked config file becomes full compromise.
- Credentials in code and images: connection strings in repositories, container images and engagement reports, as in the Red Hat Consulting GitLab breach, which exposed tokens and connection strings.
- Treating TDE as access control: data is encrypted on disk but fully readable to anyone with a login.
- Audit on, nobody watching: audit logs stored on the same server, never forwarded or reviewed, and deletable by the DBA.
- Unrecoverable encryption: TDE certificates or keys not backed up, so a restore fails when it matters.
Framework mapping
| Control area | NIST SP 800-53 Rev. 5 | CIS Controls v8.1 | ISO/IEC 27001:2022 Annex A |
|---|---|---|---|
| Least privilege and accounts | AC-2, AC-6, IA-5 | 5.4, 6.8 | A.5.15, A.5.18, A.8.2 |
| Encryption at rest and in transit | SC-28, SC-8 | 3.11, 3.10 | A.8.24 |
| Secure configuration | CM-6, CM-7 | 4.1 | A.8.9 |
| Audit logging | AU-2, AU-12 | 8.2, 8.5 | A.8.15, A.8.16 |
| Backups | CP-9 | 11.3 | A.8.13 |
| Injection defence | SI-10 | 16.1 | A.8.28 |
Practitioner checklist
- Confirm no database port or admin console is reachable from the internet, and scan to prove it.
- Remove default, sample and orphaned accounts; disable sa, root and SYS for routine use.
- Give each application its own account per environment, without ownership or DBA rights.
- Move database credentials into a vault, or replace them with IAM tokens, managed identities or gMSA.
- Enforce TLS with certificate verification and enable TDE with tested key backups.
- Apply row, column or field-level protection to the most sensitive data.
- Forward native audit or DAM events off the server and alert on privileged and bulk access.
- Apply a CIS Benchmark or STIG per engine and patch on a tracked cadence.
- Test restores, including encrypted backups, every quarter.
Standards and references
- OWASP: Database Security Cheat Sheet
- OWASP: SQL Injection Prevention Cheat Sheet
- Microsoft: SQL Server security best practices
- Microsoft: Transparent data encryption (TDE)
- PostgreSQL: The pg_hba.conf File
- MongoDB: Security Checklist for Self-Managed Deployments
- Oracle: Introduction to Auditing
- AWS: IAM database authentication for MariaDB, MySQL, and PostgreSQL
Related NHI Mgmt Group resources: Data Security Guide · Service Account Security Guide · Secrets Management Guide · Encryption Guide · Backup Security and Immutable Backup Guide