Five Critical MongoDB Security Configurations You Must Implement Now

Secure MongoDB with authentication, least-privilege roles, network binding, TLS, and audit logging checks.

Five Critical MongoDB Security Configurations You Must Implement Now

MongoDB security problems usually start with a simple mistake: a database listens where it should not, accepts users it should not, or sends traffic without encryption. Your MongoDB configuration needs explicit authentication, narrow roles, private network exposure, TLS, and useful audit records.

This guide shows five production checks that reduce the chance of unauthorized access and make suspicious activity easier to investigate.


1. Enable Mandatory Access Control and Strong Authentication

Start by making sure authorization is enabled. Without it, a client that can reach the server may be able to read or change data depending on how the deployment was started and configured.

How to Enable Authentication

Authentication is typically enabled via the configuration file (mongod.conf) or command line flags during startup.

Configuration File (/etc/mongod.conf):

# /etc/mongod.conf snippet
security:
  authorization: enabled

Command Line:

mongod --auth --dbpath /var/lib/mongodb

Creating the Administrator User

Create the first administrative user before you enable authorization, or use MongoDB's localhost exception during initial setup. After the first user exists, restart with authorization enabled and use named accounts for all access.

Example: Creating the Root User via mongosh

First, connect to the database (if already running without auth, or using localhost exception):

use admin
db.createUser(
  {
    user: "mongoAdmin",
    pwd: passwordPrompt(), // Prompts for password securely
    roles: [ { role: "root", db: "admin" } ]
  }
)

Warning: Always use strong passwords stored in a secrets manager. Never hardcode sensitive credentials in scripts or configuration files.

2. Implement Granular Role-Based Access Control (RBAC)

After enabling authentication, the next step is establishing the Principle of Least Privilege (PoLP). This means every user, application, and service account should only have the minimum permissions necessary to perform its required tasks.

Avoid using the root or readWriteAnyDatabase roles for application connections. Instead, define custom roles that grant specific permissions on specific databases or collections.

Practical RBAC Steps

  1. Define Custom Roles: If built-in roles (read, readWrite) are insufficient, create roles with fine-grained access actions (e.g., only insert and find on a specific collection).
  2. Separate Application Users: Create dedicated users for different application tiers (e.g., app_rw for the backend, reporting_ro for analytics).
  3. Limit External Tool Access: Ensure administration tools only connect using privileged accounts when absolutely necessary.

Example: Creating a Read-Only User for a Specific Database

use users_db
db.createUser(
  {
    user: "reporting_svc",
    pwd: passwordPrompt(),
    roles: [ { role: "read", db: "users_db" } ] // Only read access to users_db
  }
)

3. Configure Strict Network Binding and Firewalls

Network configuration is the perimeter defense for your database. Many packaged MongoDB installations bind to localhost by default, but container images, custom command lines, and copied configuration files can expose 0.0.0.0. Always verify the effective bindIp instead of assuming the default is safe.

Restrict bindIp

The primary security measure is defining the bindIp setting in your configuration file. This explicitly tells MongoDB which IP addresses or hostnames it should listen on.

Configuration File (/etc/mongod.conf):

# List of IPs or hostnames to bind to
# Use 127.0.0.1 for local access only
# Use internal IP(s) for access from application servers only
net:
  port: 27017
  bindIp: 127.0.0.1, 10.0.1.5, localhost

Implement External Firewalls (Security Groups)

In addition to bindIp (which restricts the MongoDB process), you must use an external firewall (like iptables, AWS Security Groups, or Azure Network Security Groups) to filter traffic before it reaches the server.

Best Practice: Only allow inbound traffic on the MongoDB port (default 27017) from your application servers, load balancers, and administrative jump boxes.

4. Enforce Encryption for Data In Transit (TLS)

Data transmitted between clients, shells, drivers, and MongoDB should be encrypted with Transport Layer Security (TLS). Sending credentials, queries, and results over unencrypted connections exposes data to eavesdropping and man-in-the-middle attacks.

MongoDB supports native TLS configuration for both encrypted traffic and optional client certificate validation.

Enabling TLS

To enable encryption, you must generate or obtain valid TLS certificates and specify their location in the configuration file.

Configuration File (/etc/mongod.conf):

net:
  tls:
    mode: requireTLS
    # Path to the combined certificate and key file
    certificateKeyFile: /etc/ssl/mongodb.pem
    # Path to the Certificate Authority file (for client validation)
    CAFile: /etc/ssl/ca.pem

Client Connection with TLS

Once the server requires TLS, all clients must connect using the appropriate secure flags:

mongosh "mongodb://[email protected]/admin?authSource=admin" --tls --tlsCAFile /path/to/ca.pem

Tip: Use mode: requireTLS in production to ensure all connections are secured. The preferTLS mode is generally only used during migration or testing.

5. Enable Auditing and Monitor Activity Logs

Even with strong access control and encryption, security threats can arise from compromised internal accounts or privilege escalation. Enabling comprehensive auditing provides a historical record of actions, which is crucial for compliance, forensic analysis, and detecting suspicious behavior.

MongoDB's auditing facility can log administrative actions, authentication attempts, authorization failures, and selected data operations. Availability depends on your MongoDB edition or platform; for example, auditing is available in MongoDB Enterprise and MongoDB Atlas, while self-managed Community deployments need other logging and monitoring approaches.

Configuration for Auditing

Auditing is configured via the auditLog section in the configuration file. You can specify the destination (file, syslog, console) and the filter criteria.

Configuration File (/etc/mongod.conf):

auditLog:
  destination: file
  path: /var/log/mongodb/audit.log
  format: JSON
  # Focus on key security events like authentication and administrative changes
  filter: '{ atype: { $in: [ "authenticate", "authCheck", "createCollection", "createUser", "dropDatabase" ] } }'

Essential Monitoring Focus Areas

  • Failed Authentication Attempts: A sudden spike indicates a potential brute-force attack.
  • User/Role Creation/Deletion: All privilege changes must be logged and reviewed.
  • Database or Collection Drops: Immediate alerts are required for destructive operations.

Integrate MongoDB audit logs with centralized log management systems such as Splunk, the Elastic Stack, or Datadog for alerting and retention.

Takeaway

Review these five controls during every MongoDB deployment: authorization is enabled, application users have narrow roles, bindIp and firewalls limit network access, clients require TLS, and security events flow into your monitoring system. These checks do not replace backups, patching, or secret rotation, but they close the most common configuration gaps first.