MongoDB Security Hardening: Authentication, TLS, and Replica Set Security

Retool's new app builder is where AI-generated code ships safely
Building apps with AI is easy. Getting them to production safely is another story.
MongoDB's default configuration was designed for rapid local development, not production deployment. Authentication is disabled, the server binds to all interfaces, TLS is off, and no audit logging is configured. This combination made MongoDB the most-ransomed database type of the 2016-2019 period, with over 50,000 publicly exposed instances discovered by security researchers. The hardening steps required are documented in MongoDB's own security checklist but are not applied automatically. This guide covers each hardening layer in order of criticality: network binding, authentication enablement, TLS configuration, role-based access control, audit logging, and replica set internal authentication security.
Restrict Network Binding Before Any Other Configuration
Network binding is the highest-priority hardening step because it reduces attack surface before authentication is even configured. An internet-exposed MongoDB with authentication enabled is still a higher risk than one bound to private interfaces only.
Set net.bindIp to private interface only
In mongod.conf, set `net: {bindIp: 127.0.0.1,10.0.1.5}` replacing `10.0.1.5` with the private IP of the server's network interface. For replica sets, bind to the localhost interface and the private replication network interface -- members communicate over private interfaces, not public ones. Restart mongod after the change. Verify with `ss -tlnp | grep mongod` that mongod is listening on 27017 only on the expected interfaces, not 0.0.0.0.
Configure firewall rules as defense in depth
Even with net.bindIp restricted, add firewall rules to port 27017 (and 27018-27019 for replica sets/sharding) allowing only application server IP ranges. For AWS deployments, use security group inbound rules scoped to application server security group IDs. For on-premises, use iptables: `iptables -A INPUT -p tcp --dport 27017 -s <app-server-cidr> -j ACCEPT; iptables -A INPUT -p tcp --dport 27017 -j DROP`. Document firewall rules alongside the mongod.conf configuration to prevent drift.
Disable direct internet exposure for Atlas clusters
For MongoDB Atlas, disable public cluster endpoints and use VPC peering or private endpoints (AWS PrivateLink, Azure Private Link) to restrict cluster access to your VPC. In Atlas, go to Network Access and remove any IP access list entry of 0.0.0.0/0. Configure Network Peering to your application VPC. Use Atlas Private Endpoints for the strictest isolation -- traffic never leaves AWS/Azure/GCP infrastructure. Verify no public endpoint is accessible: `nmap -p 27017 <atlas-cluster-hostname>` from outside the VPC should time out.
Enable Authentication and Configure RBAC
MongoDB authentication must be explicitly enabled in mongod.conf. After enabling, create administrative and application users with appropriate built-in or custom roles.
Enable authorization in mongod.conf
Set `security: {authorization: enabled}` in mongod.conf. For a standalone instance, connect from localhost before restarting to create the initial admin user (the localhost exception). For a replica set, configure keyfile authentication simultaneously with authorization to prevent replica set members from losing connectivity: `security: {authorization: enabled, keyFile: /etc/mongodb/keyfile}`. Generate a keyfile: `openssl rand -base64 756 > /etc/mongodb/keyfile; chmod 400 /etc/mongodb/keyfile`. Copy the identical keyfile to all replica set members.
Create the admin user via localhost exception
Immediately after enabling auth on a fresh instance, connect from localhost: `mongosh --host 127.0.0.1`. Create the admin user: `use admin; db.createUser({user: 'dba_admin', pwd: passwordPrompt(), roles: ['userAdminAnyDatabase', 'clusterAdmin', 'readWriteAnyDatabase']})`. The `passwordPrompt()` function avoids echoing the password to the shell. After creating the admin user, the localhost exception closes -- all subsequent connections require valid credentials.
Create per-service application users with minimum roles
Create dedicated users for each application service: `use myapp_db; db.createUser({user: 'api_service', pwd: passwordPrompt(), roles: [{role: 'readWrite', db: 'myapp_db'}]})`. For read-only reporting services: use the `read` role. For ETL services that need to create and drop collections: use `dbOwner` scoped to a specific database (not any database). Never use the `root` role or `*AnyDatabase` roles for application connections -- these grant access to all databases including admin.
Implement custom roles for fine-grained collection-level access
MongoDB supports collection-level and action-level custom roles: `db.createRole({role: 'payments_reader', privileges: [{resource: {db: 'myapp', collection: 'payments'}, actions: ['find']}], roles: []})`. This grants SELECT-equivalent access only on the payments collection in the myapp database. Assign to users with `db.grantRolesToUser('reporting_user', [{role: 'payments_reader', db: 'myapp'}])`. Collection-level roles are appropriate for multi-team environments where different teams own different MongoDB collections within the same database.
Briefings like this, every morning before 9am.
Threat intel, active CVEs, and campaign alerts, distilled for practitioners. 50,000+ subscribers. No noise.
Configure TLS for All Connections
TLS encryption protects credentials and data in transit between clients and MongoDB, and between replica set members. requireTLS mode is the only mode that provides a security guarantee.
Generate or obtain TLS certificates
For internal deployments, use your organization's PKI to issue a server certificate for the MongoDB host (with the hostname in the SAN field). For development or smaller deployments, use an internal CA: `openssl genrsa -out ca.key 4096; openssl req -new -x509 -key ca.key -out ca.crt -days 3650 -subj '/CN=MongoDB-CA'`. Issue a server certificate signed by this CA. Create a combined PEM file: `cat server.crt server.key > /etc/ssl/mongodb.pem; chmod 600 /etc/ssl/mongodb.pem`. For client x.509 authentication, issue separate client certificates with unique subject DNs.
Configure mongod.conf for requireTLS
In mongod.conf: `net: {tls: {mode: requireTLS, certificateKeyFile: /etc/ssl/mongodb.pem, CAFile: /etc/ssl/ca.pem, allowConnectionsWithoutCertificates: true}}`. Set `allowConnectionsWithoutCertificates: true` if using SCRAM password authentication (not x.509 client certs) -- this requires TLS encryption but does not require a client certificate. Set `allowConnectionsWithoutCertificates: false` if enforcing x.509 client certificate authentication for all connections.
Update client connection strings to include TLS parameters
Update MongoDB connection strings to specify TLS: `mongodb://user:password@host:27017/db?tls=true&tlsCAFile=/etc/ssl/ca.pem`. For drivers using URI options, set `tls=true` and `tlsAllowInvalidCertificates=false`. Never set `tlsInsecure=true` in production -- this disables certificate verification and makes TLS encryption only (no authentication of the server identity). Verify the server certificate CN or SAN matches the hostname in the connection string to prevent man-in-the-middle attacks.
Enable Audit Logging and Monitor for Anomalous Access
MongoDB audit logging captures the authentication events, authorization failures, and administrative operations required for incident response and compliance. Available in MongoDB Enterprise and Atlas.
Configure security.auditLog in mongod.conf
For MongoDB Enterprise, add to mongod.conf: `security: {auditLog: {destination: file, format: JSON, path: /var/log/mongodb/auditLog.json, filter: '{atype: {$in: ["authenticate", "authCheck", "createUser", "dropUser", "grantRolesToUser", "createCollection", "dropCollection", "find", "insert", "update", "delete"]}}' }}`. The filter limits audit events to authentication and CRUD operations on sensitive collections. Adjust the filter based on compliance requirements -- PCI DSS requires capturing all access to cardholder data collections.
Ship audit logs to centralized SIEM
Configure Filebeat or Fluentd to tail the MongoDB audit log file and forward to your SIEM. Parse the JSON `atype` field to categorize events. Create SIEM alerts for: multiple failed authentication events from a single IP within 5 minutes (credential stuffing), `createUser` or `grantRolesToUser` events outside change window hours (unauthorized privilege escalation), and `dropCollection` or `dropDatabase` events on production databases (ransomware or insider threat).
The bottom line
MongoDB security hardening follows a strict sequence: restrict network binding before enabling auth, enable auth before opening any port, require TLS before any credential traverses the network, then add audit logging and RBAC cleanup. The highest-impact single control is net.bindIp restricted to private interfaces -- it eliminates the entire class of internet-exposed database incidents that affected tens of thousands of MongoDB deployments. Pair it with security.authorization: enabled and net.tls.mode: requireTLS and you have closed the three most exploited MongoDB attack vectors.
Frequently asked questions
How do you enable authentication on a running MongoDB instance without downtime?
For a replica set, use the localhost exception: when authentication is first enabled, MongoDB allows one connection from localhost without credentials to create the first admin user. The process: (1) add `security.authorization: enabled` to mongod.conf, (2) restart mongod, (3) immediately connect from localhost and create the admin user: `db.createUser({user: 'admin', pwd: '<password>', roles: ['userAdminAnyDatabase', 'clusterAdmin']})`. For replica sets, enable auth on one member at a time during a rolling maintenance window. Replica set members must have keyfile or x.509 auth configured before enabling authorization or the replica set will lose quorum.
What is the difference between SCRAM and x.509 MongoDB authentication?
SCRAM (Salted Challenge Response Authentication Mechanism) is MongoDB's default password-based authentication protocol. SCRAM-SHA-256 is the current version. x.509 authentication uses TLS client certificates instead of passwords -- the client presents a certificate signed by the MongoDB deployment's CA, and MongoDB extracts the subject DN from the certificate as the user identifier. x.509 eliminates password management for service accounts: no passwords to rotate, no passwords in connection strings, no password exposure risk. x.509 requires a PKI infrastructure to issue and manage client certificates but is the recommended authentication method for service-to-service connections.
How do you configure TLS for MongoDB?
In mongod.conf, configure the net.tls block: `net: {tls: {mode: requireTLS, certificateKeyFile: /etc/ssl/mongodb.pem, CAFile: /etc/ssl/ca.pem}}`. The `requireTLS` mode rejects any connection without TLS -- use `allowTLS` only during migration. The `certificateKeyFile` must be a PEM file containing both the server certificate and private key concatenated. For replica set internal TLS, add `clusterAuthMode: x509` to use client certificates for member authentication. Verify TLS is active: `openssl s_client -connect <host>:27017 -tls1_2` should return the server certificate without error.
What MongoDB built-in roles should you use for application access?
MongoDB's built-in roles for application use: `read` grants find, listCollections, listIndexes on a specific database; `readWrite` adds insert, update, delete, createCollection, createIndex. For most application services, grant `readWrite` on the specific database and collection namespace only -- not on the entire deployment. Never use `dbOwner`, `userAdmin`, or any `*AnyDatabase` role for application service accounts. Create a dedicated MongoDB user per application service with the minimum role required: `db.createUser({user: 'paymentservice', pwd: '<pw>', roles: [{role: 'readWrite', db: 'payments'}]})`.
How do you secure MongoDB replica set internal communication?
Replica set members authenticate to each other using either keyfile authentication or x.509 certificates. Keyfile authentication requires each member to have the same keyfile (a shared secret of 6-1024 characters) referenced in mongod.conf: `security: {keyFile: /etc/mongodb/keyfile}`. The keyfile must have permissions 400 (owner read-only). x.509 internal auth requires each member to have a certificate with a common subject DN prefix and uses the member certificate for both connection encryption and member identity verification. x.509 is preferred because keyfile is a shared secret (compromise of one member exposes the keyfile to all) while x.509 uses unique certificates per member.
How does MongoDB audit logging work and what does it capture?
MongoDB audit logging (available in MongoDB Enterprise and Atlas) writes a JSON or BSON log of database operations to a file or syslog. Configure in mongod.conf: `security: {auditLog: {destination: file, format: JSON, path: /var/log/mongodb/auditLog.json}}`. Use the filter field to scope what is audited: `{atype: {$in: ['authenticate', 'authCheck', 'createCollection', 'dropCollection', 'createUser', 'dropUser', 'grantRolesToUser', 'revokeRolesFromUser']}}`. Capturing authentication, authorization check failures, and administrative operations is the minimum for compliance. Full DML auditing (insert, update, delete) produces significant log volume -- evaluate selectively by collection sensitivity.
Should MongoDB ever bind to 0.0.0.0 in production?
No. MongoDB should never bind to 0.0.0.0 (all interfaces) in production environments, even with authentication enabled. The correct configuration is `net.bindIp: 127.0.0.1,<private-interface-ip>` to bind only to the localhost interface and the private network interface. Even with strong authentication, binding to all interfaces exposes MongoDB to network-level attack surface: amplification attacks, connection exhaustion, and future authentication bypasses. Use firewall rules (iptables, cloud security groups) as a defense-in-depth layer in addition to the bind restriction, not as a replacement for it.
Sources & references
Free resources
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.
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.
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, daily, no spam.
Unsubscribe anytime. We never sell your data.

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 every morning.
Win a $2,495 Black Hat pass.
Full-access to Black Hat USA 2026 in Las Vegas. Subscribe free to enter.
