Join our Newsletter — 33% off our NHI Course
Home› Guides› Database Security Guide
Guide Data Security & Privacy

Database Security Guide

← All guides
By Lalit Choda, NHI Mgmt Group Updated 17 October 2026 16 min read
On this page

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.

ThreatTypical pathPrimary controlsATT&CK (v20)
Internet exposureDatabase port or admin console reachable without authenticationPrivate network, firewall allowlists, authentication enforcedT1190 Exploit Public-Facing Application
Credential misuseDefault, shared or leaked application credentialsNamed accounts, vaulted and rotated secrets, MFA for adminsT1078 Valid Accounts
InjectionSQL, NoSQL or LDAP injection through the applicationParameterised queries, least-privilege app accountT1190
Over-privileged accessApplication or analyst account reads far more than it needsRoles, row and column security, viewsT1213.006 Data from Information Repositories: Databases
Unpatched engineKnown vulnerability in the database server or a bundled toolPatching, vulnerability assessment, reduced exposureT1190
Destruction and extortionTables dropped or encrypted after access is gainedSeparated, immutable backups; restricted DROP and TRUNCATE rightsT1485 Data Destruction
Insider and privileged misuseDBA or support account bulk-exports sensitive dataSeparation of duties, field-level encryption, activity monitoringT1213.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, Redis bind 127.0.0.1 (Redis enters protected mode since 3.2.0 when bound to all interfaces without a password) and PostgreSQL listen_addresses should 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.clusterIpSourceAllowlist and per-user authenticationRestrictions; 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.

PlatformPreferAvoid or remove
PostgreSQLscram-sha-256, cert or GSSAPI in pg_hba.conf; hostssl records to force TLStrust, which lets anyone who can connect log in as any user; password (clear text); md5, which is deprecated
SQL ServerWindows or Active Directory authentication through AD groups mapped to roles; contained users where databases move between instancesThe sa login (Microsoft: should not be used or enabled); Mixed Mode unless required
MySQL and MariaDBAccounts scoped to a host; run mysql_secure_installationRoot without a password (test with mysql -u root); accounts on '%'
MongoDBAccess control enabled, SCRAM or X.509; LDAP or Kerberos in Enterprise and AtlasInstances started without authorisation enabled
RedisACL users (Redis 6 and later) with command restrictionsA 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 databaseApplications 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 SECURITY is 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 SERVER rather 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 SECURITY with CREATE POLICY (default deny when no policy exists; superusers and BYPASSRLS roles always bypass), SQL Server row-level security with SESSION_CONTEXT for 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

ControlProtects againstDoes not protect againstExamples
Transparent data encryption (TDE) or storage encryptionStolen disks, data files and backup filesAnyone who can query the database, including an attacker with app credentials; data on the wireSQL Server and Oracle TDE, MongoDB WiredTiger encryption at rest, RDS AES-256 encryption of instances and snapshots
TLS in transitEavesdropping and credential capture on the networkData at rest; compromised endpointsPostgreSQL hostssl; MongoDB TLS for all connections; Redis optional TLS
Client-side field encryptionDBAs, database compromise and backups exposing specific fieldsA compromised application holding the keysSQL Server Always Encrypted (decrypted only in client libraries); MongoDB Queryable Encryption and CSFLE
TokenisationExposure of card numbers or identifiers in downstream systemsThe token vault itself, which becomes the high-value targetPayment and identifier vaults
Dynamic data maskingCasual over-viewing in reports and support screensDetermined users with query access; it is presentation, not encryptionSQL 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_SECURECONFIG is enabled by default on databases created from 12.2 and ORA_LOGIN_LOGOUT from 26ai, but not on upgraded databases. Traditional auditing is desupported in Oracle AI Database 26ai.
  • PostgreSQL: log_connections, log_disconnections and 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_dirtree and other unused extended procedures, CLR execution and the SQL Browser service; remove Northwind and AdventureWorks.
  • MongoDB: disable server-side JavaScript with --noscripting if $where, mapReduce, $accumulator and $function are unused; run under a dedicated OS user.
  • Redis: restrict CONFIG, FLUSHALL and similar commands with ACL rules (renaming commands is deprecated); CONFIG can 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.

AreaProvider (managed service)Customer
Engine patching and host OSApplies patches, often in customer-chosen maintenance windowsChoose windows, track major version end of support
Network exposureProvides VPC, private endpoints and security groupsKeeps instances private and security groups narrow
IdentityOffers IAM database authentication and secrets integrationRetires master user use, scopes IAM policies, rotates secrets
EncryptionProvides encryption at rest and TLS endpointsEnables them, manages keys, enforces TLS on clients
Data access and auditProvides audit and log export optionsGrants, 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

  1. Inventory: list every database instance, engine, version, owner, data classification and network exposure, including cloud and developer-created instances. See the Data Security Guide.
  2. 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.
  3. 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.
  4. 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.
  5. Encrypt: enable TDE and enforce TLS (start with hostssl or equivalent alongside the old rule, then remove the non-TLS path), with key backups verified before rollout.
  6. 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 areaNIST SP 800-53 Rev. 5CIS Controls v8.1ISO/IEC 27001:2022 Annex A
Least privilege and accountsAC-2, AC-6, IA-55.4, 6.8A.5.15, A.5.18, A.8.2
Encryption at rest and in transitSC-28, SC-83.11, 3.10A.8.24
Secure configurationCM-6, CM-74.1A.8.9
Audit loggingAU-2, AU-128.2, 8.5A.8.15, A.8.16
BackupsCP-911.3A.8.13
Injection defenceSI-1016.1A.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

Related NHI Mgmt Group resources: Data Security Guide · Service Account Security Guide · Secrets Management Guide · Encryption Guide · Backup Security and Immutable Backup Guide

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Written and reviewed by Lalit Choda, NHI Mgmt Group. Last updated 17 October 2026.
NHI Mgmt Group — the #1 independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org