Join our Newsletter — 33% off our NHI Course
Home› Guides› MongoDB Security Guide: Authentication, Network Exposure and Encryption
Guide Data Security

MongoDB Security Guide: Authentication, Network Exposure and Encryption

PDF for newsletter subscribers · free to read online

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

Self-managed MongoDB deployments are still found on the internet with access control switched off, unencrypted connections and application accounts holding cluster-wide roles. MongoDB ships the controls to prevent all of this, but most of them are opt-in settings in mongod.conf, and several (auditing, the encrypted storage engine, Kerberos) depend on the edition you run. This guide goes engine-deep on self-managed MongoDB Community and Enterprise: authentication and the localhost exception, role design, network exposure, TLS, encryption at rest and in use, auditing, patching and incident lessons. It is written for database engineers, platform teams and security architects who already know the general database controls covered in the Database Security Guide and need the MongoDB specifics. Atlas credential handling is covered separately in the MongoDB Atlas Credentials Security Guide.

Key takeaways

  • Turn on access control explicitly. Set security.authorization: enabled, create a user administrator through the localhost exception, then close the exception on every shard as well as on mongos.
  • Bind to private interfaces only. MongoDB binds to localhost by default; the exposure usually comes from someone setting bindIp: 0.0.0.0 or --bind_ip_all without a firewall or source allowlist behind it.
  • Give every application its own least-privilege user. Custom roles scoped to named databases and collections beat readWriteAnyDatabase, dbOwner or root, and roles that manage users are as powerful as root.
  • Know which encryption layer does what. TLS protects the wire, WiredTiger encryption at rest (Enterprise) or disk encryption protects files and backups, and Queryable Encryption or CSFLE keeps fields unreadable even to a database administrator.
  • Patch fast and assume exposure means compromise. MongoBleed (CVE-2025-14847) leaked server memory to unauthenticated clients and entered the CISA KEV catalogue ten days after disclosure; reachable unpatched servers need credential rotation, not only an upgrade.

How MongoDB deployments get exposed

MongoDB listens on TCP 27017 by default and speaks its own wire protocol, so any host that can reach the port can attempt authentication, or, if access control is off, read and drop every database. The common attack paths map to a small set of ATT&CK techniques.

ExposureHow it happensATT&CK techniquePrimary control
Open instance, no authenticationAccess control never enabled, port reachable from the internet or a flat network; found by mass scanningT1046 Network Service Discovery, T1190 Exploit Public-Facing Applicationsecurity.authorization: enabled, private bindIp, firewall
Wipe-and-ransomAutomated scripts read, drop and replace databases with a ransom note on unauthenticated instancesT1485 Data Destruction, T1657 Financial TheftAuthentication, network allowlists, tested backups
Credential guessing and reuseWeak or shared passwords on SCRAM users, credentials reused from leaked connection stringsT1110.003 Password Spraying, T1078 Valid AccountsUnique strong secrets, X.509 for services, authenticationRestrictions
Leaked connection stringsmongodb://user:password@host URIs committed to code, .env files or CI logsT1552.001 Credentials In FilesSecrets manager, rotation, secret scanning
Server vulnerabilityUnpatched mongod (MongoBleed) or exposed admin tools such as mongo-express (CVE-2019-10758, in the KEV catalogue)T1190 Exploit Public-Facing ApplicationPatch SLA, no admin UIs on public networks
Bulk exfiltrationmongodump or large find calls by a valid but over-privileged accountT1213 Data from Information RepositoriesLeast privilege, auditing, egress control

Automated wipe-and-ransom campaigns against unauthenticated MongoDB instances have recurred for years. They need no exploit at all: the attacker simply uses the database as designed. That is why the first two controls in this guide matter more than anything else.

Authentication: mechanisms, the localhost exception and internal auth

SCRAM is the default authentication mechanism, and MongoDB supports both SCRAM-SHA-1 and SCRAM-SHA-256. Which other mechanisms you can use depends on edition.

MechanismAvailable inBest used forNotes
SCRAM-SHA-256Community, Enterprise, AtlasHuman users and applications where certificates are impracticalRestrict accepted mechanisms with the authenticationMechanisms server parameter so legacy SCRAM-SHA-1 is not offered unless needed
X.509 certificatesCommunity, Enterprise, AtlasService accounts and cluster membersRequires TLS and CA-signed certificates; no shared password to leak
Kerberos (GSSAPI)Enterprise onlyWindows and Active Directory estatesCentral credential lifecycle
LDAP proxyEnterprise, Atlas M10+Directory-backed usersDeprecated from MongoDB 8.0 and due for removal; plan a move to OIDC or Kerberos
OpenID Connect (OIDC)Enterprise, Atlas M10+Workforce SSO to the databaseBrings MFA and joiner-mover-leaver from the identity provider
AWS IAMAtlas onlyWorkloads running on AWSShort-lived credentials instead of stored passwords

Close the localhost exception

When access control is on but no users or roles exist, a connection from the localhost interface may create the first user or role, initiate a replica set and run a few replica set commands. Creating the first user or role ends the exception on that mongod. In a sharded cluster the exception applies per shard as well as to the cluster: creating a user administrator through mongos does not protect the individual shards. For each shard, either create a user administrator on the shard primary or start the shard with --setParameter enableLocalhostAuthBypass=0. Forgotten shards are a quiet way to leave an unauthenticated door open to anyone with a shell on the host.

Authenticate cluster members

Replica set members and shards should authenticate to each other. A keyfile (security.keyFile) is a single shared secret on every member, acceptable for small clusters if the file is permission-locked and rotated. X.509 member certificates (security.clusterAuthMode: x509) remove the shared secret and suit larger or regulated estates. Use security.clusterIpSourceAllowlist to limit which addresses may present themselves as cluster members.

Authorisation: built-in roles, custom roles and service accounts

MongoDB authorisation is role-based: a user holds roles, roles hold privileges (actions on resources). MongoDB's checklist asks for a user administrator first, then a unique user for each person and each application, each with only the roles it needs.

Built-in roleScopeRisk if over-assignedUse instead
read, readWriteOne databaseLow to medium; still exposes every collection in that databaseCustom role on named collections for sensitive data
dbAdmin, dbOwnerOne databasedbOwner includes user administration on that databaseSeparate schema-change account used only by migrations
userAdmin, userAdminAnyDatabaseOne or all databasesCan grant any role, including to itself: effectively rootHold in PAM, check out for user changes only
readAnyDatabase, readWriteAnyDatabaseAll databasesOne leaked app secret reads the whole deploymentPer-database or per-collection roles
clusterAdmin, clusterMonitorClusterclusterAdmin can reconfigure and shut down; monitoring agents rarely need itclusterMonitor for monitoring agents
backup, restoreAll dataBackup reads everything; restore writes everything, including user dataDedicated backup identity, network-restricted
rootEverythingFull controlBreak-glass only, vaulted, alerted on use
  • Custom roles: build application roles with db.createRole() listing only the actions needed (for example find, insert, update) on specific { db, collection } resources. Keep role definitions in version control and apply them through automation.
  • Network-bound users: add authenticationRestrictions (clientSource and serverAddress) when creating application users, so a stolen password only works from the application subnet.
  • Application identities are non-human identities: each service account needs an owner, a rotation date and an inventory entry. See the Service Account Security Guide and the Database Credential and Access Security Guide.
  • Connection strings are secrets: fetch them from a secrets manager at runtime, never from the repository. Short-lived dynamic database users issued by a secrets manager reduce the value of any single leak. See the Secrets Management Guide.
  • Review regularly: MongoDB's own production checklist includes reviewing database users and rotating them periodically. Query db.getUsers() and db.getRoles({showPrivileges: true}) per database and diff against the inventory.

Network exposure and server hardening

mongod and mongos bind to localhost by default. Production nodes must listen on something else, which is the moment exposure is introduced. Bind only to the private interface (net.bindIp: 127.0.0.1,10.0.0.5), and treat 0.0.0.0 or net.bindIpAll as a change that needs a firewall rule and a review.

SettingRecommended valueWhy
security.authorizationenabledWithout it, any client that connects has full access
net.bindIpLocalhost plus the private interface onlyKeeps 27017 off public interfaces
net.tls.moderequireTLSRejects plaintext clients and members
security.clusterAuthModex509 (or keyFile for small clusters)Members prove identity to each other
security.javascriptEnabled / --noscriptingfalse unless neededDisables server-side JavaScript in $where, mapReduce, $accumulator and $function
net.compression.compressorssnappy,zstd (omit zlib on unpatched builds)The MongoBleed workaround removed zlib from the compressor list
enableLocalhostAuthBypass0 after bootstrapCloses the localhost exception, including on shards
Service account (OS)Dedicated unprivileged user owning storage.dbPathLimits blast radius of a server compromise
  • Firewall and security groups: allow 27017 only from application subnets, other cluster members and backup hosts. Inbound and outbound rules both matter: a database server rarely needs general internet egress.
  • Admin tools: never publish web admin consoles (such as mongo-express) or monitoring exporters on public addresses. Put them behind a VPN or zero trust access proxy.
  • Endpoint security interaction: MongoDB advises excluding storage.dbPath and systemLog.path from antivirus and EDR file scanning, because quarantining data files can corrupt the database. Compensate with host-level controls and file integrity monitoring on configuration and key files.
  • Baselines: use the CIS Benchmark for MongoDB or the DISA STIG (MongoDB provides it on request for US Department of Defense deployments) as the configuration baseline, and scan for drift. See the Network Segmentation Guide.

Encryption in transit, at rest and in use

MongoDB's checklist asks for TLS on every incoming and outgoing connection, including between mongod and mongos and from every application. It uses OpenSSL on Linux, Secure Channel on Windows and Secure Transport on macOS, so protocol and cipher policy follows the platform library.

LayerMongoDB featureEditionProtects againstDoes not protect against
In transitTLS (net.tls.*), certificate validation on clientsAllNetwork sniffing, member spoofingA valid but malicious client
At rest (engine)WiredTiger native encryption at rest, local keyfile or KMIP key managerEnterprise (Atlas encrypts storage)Stolen disks, data files, backups copied from the hostAnyone who can query the running database
At rest (platform)Filesystem or volume encryption (for example dm-crypt) plus file permissionsAnyLost media, decommissioned disksRoot on the running host
In useQueryable EncryptionSee current MongoDB compatibility tableAdministrators, logs and memory dumps seeing sensitive fieldsAn application identity that holds the keys
In useClient-Side Field Level Encryption (CSFLE)See current MongoDB compatibility tableSame as above; deterministic mode supports equality matchesSame as above
  • Scope at rest properly: MongoDB lists data files, configuration files, audit logs and key files as data to protect. A KMIP key manager keeps the master key off the database host.
  • Queryable Encryption and CSFLE: both use envelope encryption, with a data encryption key per field wrapped by a customer master key held in a KMS. They can coexist in one deployment but not in the same collection. Use them for the few fields where a database administrator or a memory leak must not see plaintext, such as national identifiers or health data.
  • Keys are the new crown jewels: the identity that can call the KMS decrypt operation is now the gatekeeper. See the Cryptographic Key Management Guide and the Encryption Guide.
  • Certificates: X.509 member and client certificates expire. Track them in the certificate inventory. See the Machine Identity, PKI and Certificate Lifecycle Guide.

Auditing, detection and measurement

The auditing facility is part of MongoDB Enterprise and Atlas (M10 and larger); Community Edition has no native audit log, so Community estates rely on the server log (which records authentication attempts and source IP addresses) plus network telemetry. Enterprise writes audit events to the console, syslog, a JSON file or a BSON file, configured with auditLog.destination or --auditDestination.

  • What to capture: authentication success and failure, user and role changes (createUser, grantRolesToUser, createRole), schema events such as dropDatabase and dropCollection, and replica set or shard changes. CRUD events are only recorded when auditAuthorizationSuccess is true, which is costly; enable it with a filter scoped to sensitive collections.
  • Know the failure mode: if the server cannot write to the audit destination it terminates, and buffered events can be lost on a crash. Size the volume, monitor free space and forward to the SIEM.
  • Alert on: authentication failures from new sources, any use of root or user-admin roles, role grants outside change windows, dropDatabase bursts, large getMore volumes or mongodump-style reads by application users, and connections from outside the expected subnets.
  • External attack surface: scan your own address space for 27017 and for admin UIs; compare against the inventory. See the Attack Surface Management Guide.

Metrics that show it is working

  1. Internet-reachable MongoDB endpoints: target zero, measured by external scan weekly.
  2. Percentage of nodes with security.authorization: enabled and net.tls.mode: requireTLS, from configuration scanning.
  3. Percentage of application users that are unique, owned, vaulted and hold no AnyDatabase or root role.
  4. Median days from a MongoDB security alert to patched production (target set by severity, with KEV entries fastest).
  5. Audit coverage: share of Enterprise nodes forwarding audit events to the SIEM, and alerts reviewed within SLA.
  6. Last successful restore test date per production cluster.

Implementation: a phased rollout

  1. Inventory and exposure check (week 1): list every mongod and mongos, version, edition, owner and whether access control is on. Scan externally and internally for 27017. Any open, unauthenticated instance is an incident, not a backlog item.
  2. Close network exposure: set private bindIp, apply firewall allowlists, remove public admin consoles. Roll back by restoring the previous rule set, which should be kept in version control.
  3. Enable authentication without downtime: on replica sets, use MongoDB's rolling procedure (security.transitionToAuth during transition), create users, update application connection strings, then remove the transition flag. Test in a staging replica set first; the rollback is to restart members with the transition setting still on.
  4. Fix accounts: create custom least-privilege roles, issue one user per application, move secrets to the vault, add authenticationRestrictions, and retire shared and default accounts.
  5. Encrypt: enforce TLS (start with allowTLS or preferTLS, move to requireTLS once all clients connect over TLS), enable encryption at rest, then apply Queryable Encryption or CSFLE to the most sensitive fields in new collections.
  6. Audit and monitor: enable auditing with a filter, forward to the SIEM, build the alerts above and baseline normal behaviour for two to four weeks before tuning.
  7. Sustain: subscribe to MongoDB security alerts and end-of-life dates, set a patch SLA, review users quarterly and test restores.

Small versus large estates: a small team on Community Edition gets most of the risk reduction from authentication, private binding, TLS, disk encryption and unique vaulted users, and can lean on server logs for detection. Larger or regulated estates usually justify Enterprise or Atlas for auditing, Kerberos or OIDC, KMIP-backed encryption at rest and centralised policy, and should automate configuration checks across clusters. Choosing between self-managed and Atlas shifts patching and storage encryption to the provider but not user design, network access lists or key ownership.

Common failure patterns

  • Access control never enabled: a development cluster promoted to production with no users, bound to all interfaces. This is the root cause of most wipe-and-ransom incidents against MongoDB.
  • Patching without rotating: MongoBleed let unauthenticated clients read uninitialised heap memory, which could hold passwords, keys and session tokens, and left little trace. Teams that only upgraded kept using secrets that may already have leaked. See the MongoBleed (CVE-2025-14847) breach analysis.
  • Shard-level localhost exception left open: the user administrator was created through mongos only, so individual shards still accept unauthenticated localhost administration.
  • Applications running as root: one connection string with root or readWriteAnyDatabase shared by several services, often committed to a repository, so any leak exposes every database.
  • Encryption mistaken for access control: encryption at rest is on, so the team assumes data is protected, while every application user can still read every field. Field-level encryption, not storage encryption, addresses that.
  • Audit log that kills the server: auditing enabled to a local file on the data volume without monitoring; the disk fills, the audit write fails and mongod terminates.

Lessons from incidents

MongoBleed (CVE-2025-14847) is the clearest recent lesson. A flaw in zlib network message decompression let any client that could reach the port receive server memory before authentication. Censys counted more than 87,000 potentially vulnerable internet-facing instances, exploitation was reported in the wild days after a public proof of concept, and CISA added it to the KEV catalogue on 29 December 2025. Fixed releases are 8.2.3, 8.0.17, 7.0.28, 6.0.27, 5.0.32 and 4.4.30; 4.2 and earlier have no fix. Three controls would have contained it: no internet exposure of 27017, a patch SLA keyed to KEV, and a rotation runbook for every credential the server could have held in memory. The same pattern, an internet-reachable data store with no authentication, is visible in the DeepSeek Database Exposure 2025, where an open ClickHouse instance leaked logs containing API keys.

Framework mapping

MongoDB controlNIST SP 800-53 Rev. 5NIST CSF 2.0CIS Controls v8.1ISO/IEC 27001:2022 Annex A
Access control on, unique users, X.509 / OIDCIA-2, IA-5PR.AA-015, 6A.5.16, A.8.5
Custom least-privilege rolesAC-6PR.AA-056A.5.15, A.8.2
Private binding, firewall, IP allowlistsSC-7PR.PS-014, 12A.8.20, A.8.22
Hardened configuration, scripting offCM-6, CM-7PR.PS-014A.8.9
TLS everywhereSC-8PR.DS-023A.8.24
Encryption at rest and in useSC-28PR.DS-013A.8.24
Auditing to SIEMAU-2, AU-12DE.CM-018A.8.15, A.8.16
Patching, KEV-driven SLARA-5, SI-2ID.RA-017A.8.8
Backups and restore testsCP-9PR.DS-1111A.8.13

See the NIST SP 800-53 Guide and CIS Controls Guide for the wider control sets.

Practitioner checklist

  • Confirm every mongod and mongos runs with security.authorization: enabled, and that no port 27017 is reachable from the internet.
  • Close the localhost exception on every shard and set enableLocalhostAuthBypass=0 after bootstrap.
  • Authenticate cluster members with X.509 or a permission-locked keyfile, and restrict member sources with clusterIpSourceAllowlist.
  • Replace shared and AnyDatabase application accounts with one custom-role user per application, vaulted, owned and bound with authenticationRestrictions.
  • Hold root and user-admin roles in PAM and alert on every use.
  • Enforce requireTLS, enable encryption at rest (WiredTiger or volume), and apply Queryable Encryption or CSFLE to the most sensitive fields.
  • Disable server-side JavaScript unless an application needs it.
  • Enable auditing (Enterprise or Atlas) with a scoped filter, forward to the SIEM and monitor the audit destination's free space.
  • Track MongoDB security alerts and end-of-life dates, patch KEV entries first, and rotate credentials after any memory-disclosure flaw.
  • Back up with a dedicated identity, store copies immutably and test a restore each quarter.

Standards and references

Related NHI Mgmt Group resources: Database Security Guide · MongoDB Atlas Credentials Security Guide · PostgreSQL Security Guide · Elasticsearch and OpenSearch Security Guide · Redis Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

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
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 26 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.