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 onmongos. - Bind to private interfaces only. MongoDB binds to localhost by default; the exposure usually comes from someone setting
bindIp: 0.0.0.0or--bind_ip_allwithout 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,dbOwnerorroot, 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.
| Exposure | How it happens | ATT&CK technique | Primary control |
|---|---|---|---|
| Open instance, no authentication | Access control never enabled, port reachable from the internet or a flat network; found by mass scanning | T1046 Network Service Discovery, T1190 Exploit Public-Facing Application | security.authorization: enabled, private bindIp, firewall |
| Wipe-and-ransom | Automated scripts read, drop and replace databases with a ransom note on unauthenticated instances | T1485 Data Destruction, T1657 Financial Theft | Authentication, network allowlists, tested backups |
| Credential guessing and reuse | Weak or shared passwords on SCRAM users, credentials reused from leaked connection strings | T1110.003 Password Spraying, T1078 Valid Accounts | Unique strong secrets, X.509 for services, authenticationRestrictions |
| Leaked connection strings | mongodb://user:password@host URIs committed to code, .env files or CI logs | T1552.001 Credentials In Files | Secrets manager, rotation, secret scanning |
| Server vulnerability | Unpatched mongod (MongoBleed) or exposed admin tools such as mongo-express (CVE-2019-10758, in the KEV catalogue) | T1190 Exploit Public-Facing Application | Patch SLA, no admin UIs on public networks |
| Bulk exfiltration | mongodump or large find calls by a valid but over-privileged account | T1213 Data from Information Repositories | Least 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.
| Mechanism | Available in | Best used for | Notes |
|---|---|---|---|
| SCRAM-SHA-256 | Community, Enterprise, Atlas | Human users and applications where certificates are impractical | Restrict accepted mechanisms with the authenticationMechanisms server parameter so legacy SCRAM-SHA-1 is not offered unless needed |
| X.509 certificates | Community, Enterprise, Atlas | Service accounts and cluster members | Requires TLS and CA-signed certificates; no shared password to leak |
| Kerberos (GSSAPI) | Enterprise only | Windows and Active Directory estates | Central credential lifecycle |
| LDAP proxy | Enterprise, Atlas M10+ | Directory-backed users | Deprecated 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 database | Brings MFA and joiner-mover-leaver from the identity provider |
| AWS IAM | Atlas only | Workloads running on AWS | Short-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 role | Scope | Risk if over-assigned | Use instead |
|---|---|---|---|
read, readWrite | One database | Low to medium; still exposes every collection in that database | Custom role on named collections for sensitive data |
dbAdmin, dbOwner | One database | dbOwner includes user administration on that database | Separate schema-change account used only by migrations |
userAdmin, userAdminAnyDatabase | One or all databases | Can grant any role, including to itself: effectively root | Hold in PAM, check out for user changes only |
readAnyDatabase, readWriteAnyDatabase | All databases | One leaked app secret reads the whole deployment | Per-database or per-collection roles |
clusterAdmin, clusterMonitor | Cluster | clusterAdmin can reconfigure and shut down; monitoring agents rarely need it | clusterMonitor for monitoring agents |
backup, restore | All data | Backup reads everything; restore writes everything, including user data | Dedicated backup identity, network-restricted |
root | Everything | Full control | Break-glass only, vaulted, alerted on use |
- Custom roles: build application roles with
db.createRole()listing only the actions needed (for examplefind,insert,update) on specific{ db, collection }resources. Keep role definitions in version control and apply them through automation. - Network-bound users: add
authenticationRestrictions(clientSourceandserverAddress) 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()anddb.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.
| Setting | Recommended value | Why |
|---|---|---|
security.authorization | enabled | Without it, any client that connects has full access |
net.bindIp | Localhost plus the private interface only | Keeps 27017 off public interfaces |
net.tls.mode | requireTLS | Rejects plaintext clients and members |
security.clusterAuthMode | x509 (or keyFile for small clusters) | Members prove identity to each other |
security.javascriptEnabled / --noscripting | false unless needed | Disables server-side JavaScript in $where, mapReduce, $accumulator and $function |
net.compression.compressors | snappy,zstd (omit zlib on unpatched builds) | The MongoBleed workaround removed zlib from the compressor list |
enableLocalhostAuthBypass | 0 after bootstrap | Closes the localhost exception, including on shards |
| Service account (OS) | Dedicated unprivileged user owning storage.dbPath | Limits 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.dbPathandsystemLog.pathfrom 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.
| Layer | MongoDB feature | Edition | Protects against | Does not protect against |
|---|---|---|---|---|
| In transit | TLS (net.tls.*), certificate validation on clients | All | Network sniffing, member spoofing | A valid but malicious client |
| At rest (engine) | WiredTiger native encryption at rest, local keyfile or KMIP key manager | Enterprise (Atlas encrypts storage) | Stolen disks, data files, backups copied from the host | Anyone who can query the running database |
| At rest (platform) | Filesystem or volume encryption (for example dm-crypt) plus file permissions | Any | Lost media, decommissioned disks | Root on the running host |
| In use | Queryable Encryption | See current MongoDB compatibility table | Administrators, logs and memory dumps seeing sensitive fields | An application identity that holds the keys |
| In use | Client-Side Field Level Encryption (CSFLE) | See current MongoDB compatibility table | Same as above; deterministic mode supports equality matches | Same 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 asdropDatabaseanddropCollection, and replica set or shard changes. CRUD events are only recorded whenauditAuthorizationSuccessistrue, 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
rootor user-admin roles, role grants outside change windows,dropDatabasebursts, largegetMorevolumes ormongodump-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
- Internet-reachable MongoDB endpoints: target zero, measured by external scan weekly.
- Percentage of nodes with
security.authorization: enabledandnet.tls.mode: requireTLS, from configuration scanning. - Percentage of application users that are unique, owned, vaulted and hold no
AnyDatabaseorrootrole. - Median days from a MongoDB security alert to patched production (target set by severity, with KEV entries fastest).
- Audit coverage: share of Enterprise nodes forwarding audit events to the SIEM, and alerts reviewed within SLA.
- Last successful restore test date per production cluster.
Implementation: a phased rollout
- Inventory and exposure check (week 1): list every
mongodandmongos, 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. - 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. - Enable authentication without downtime: on replica sets, use MongoDB's rolling procedure (
security.transitionToAuthduring 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. - 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. - Encrypt: enforce TLS (start with
allowTLSorpreferTLS, move torequireTLSonce all clients connect over TLS), enable encryption at rest, then apply Queryable Encryption or CSFLE to the most sensitive fields in new collections. - 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.
- 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
mongosonly, so individual shards still accept unauthenticated localhost administration. - Applications running as root: one connection string with
rootorreadWriteAnyDatabaseshared 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
mongodterminates.
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 control | NIST SP 800-53 Rev. 5 | NIST CSF 2.0 | CIS Controls v8.1 | ISO/IEC 27001:2022 Annex A |
|---|---|---|---|---|
| Access control on, unique users, X.509 / OIDC | IA-2, IA-5 | PR.AA-01 | 5, 6 | A.5.16, A.8.5 |
| Custom least-privilege roles | AC-6 | PR.AA-05 | 6 | A.5.15, A.8.2 |
| Private binding, firewall, IP allowlists | SC-7 | PR.PS-01 | 4, 12 | A.8.20, A.8.22 |
| Hardened configuration, scripting off | CM-6, CM-7 | PR.PS-01 | 4 | A.8.9 |
| TLS everywhere | SC-8 | PR.DS-02 | 3 | A.8.24 |
| Encryption at rest and in use | SC-28 | PR.DS-01 | 3 | A.8.24 |
| Auditing to SIEM | AU-2, AU-12 | DE.CM-01 | 8 | A.8.15, A.8.16 |
| Patching, KEV-driven SLA | RA-5, SI-2 | ID.RA-01 | 7 | A.8.8 |
| Backups and restore tests | CP-9 | PR.DS-11 | 11 | A.8.13 |
See the NIST SP 800-53 Guide and CIS Controls Guide for the wider control sets.
Practitioner checklist
- Confirm every
mongodandmongosruns withsecurity.authorization: enabled, and that no port 27017 is reachable from the internet. - Close the localhost exception on every shard and set
enableLocalhostAuthBypass=0after bootstrap. - Authenticate cluster members with X.509 or a permission-locked keyfile, and restrict member sources with
clusterIpSourceAllowlist. - Replace shared and
AnyDatabaseapplication accounts with one custom-role user per application, vaulted, owned and bound withauthenticationRestrictions. - Hold
rootand 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
- MongoDB: Security Checklist for Self-Managed Deployments
- MongoDB: Authentication on Self-Managed Deployments
- MongoDB: Localhost Exception
- MongoDB: In-Use Encryption
- MongoDB: Auditing
- CISA: Known Exploited Vulnerabilities Catalog
- NIST: SP 800-53 Rev. 5
- MITRE ATT&CK: Exploit Public-Facing Application
Related NHI Mgmt Group resources: Database Security Guide · MongoDB Atlas Credentials Security Guide · PostgreSQL Security Guide · Elasticsearch and OpenSearch Security Guide · Redis Security Guide