Skip to main content

MongoDB Security Checklist

MongoDB is a powerful NoSQL database that powers countless applications worldwide. However, an insecure MongoDB deployment can expose sensitive data and leave your application vulnerable to attacks. This comprehensive security checklist will guide you through essential steps to secure your MongoDB installations.

Introduction

Security is not a one-time task but an ongoing process. MongoDB provides several security features that should be enabled and properly configured to protect your data. This checklist covers authentication, authorization, network security, encryption, and other security best practices.

Let's start by understanding why MongoDB security is critical:

  1. Data Protection: MongoDB often stores sensitive user data
  2. Preventing Unauthorized Access: Avoiding data breaches
  3. Compliance Requirements: Meeting regulatory standards like GDPR, HIPAA, etc.
  4. Business Continuity: Preventing disruptions due to security incidents

1. Authentication and Authorization

Enable Authentication

By default, MongoDB doesn't require authentication. This is convenient for development but dangerous in production.

To enable authentication, start MongoDB with the --auth option or set it in your configuration file:

javascript
// In mongod.conf
security:
authorization: enabled

Create Administrative User

Before enabling authentication, create an administrative user:

javascript
use admin
db.createUser(
{
user: "adminUser",
pwd: "securePassword123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

After enabling authentication, you'll need to authenticate to perform operations:

javascript
// Connect and authenticate
mongo --port 27017 -u adminUser -p securePassword123 --authenticationDatabase admin

Use Role-Based Access Control (RBAC)

MongoDB provides built-in roles for common use cases. Assign the minimum required privileges to each user:

javascript
// Create a read-only user for a specific database
use myApp
db.createUser(
{
user: "readOnlyUser",
pwd: "anotherSecurePassword",
roles: [ { role: "read", db: "myApp" } ]
}
)

Common built-in roles include:

  • read: Read-only access to specified database
  • readWrite: Read and write access to specified database
  • dbAdmin: Administrative tasks on specified database
  • userAdmin: User and role management on specified database
  • dbOwner: Combines readWrite, dbAdmin, and userAdmin roles

2. Network Security

Bind to Localhost Only

For development environments or when using an SSH tunnel, bind MongoDB to localhost:

javascript
// In mongod.conf
net:
bindIp: 127.0.0.1

For production with remote access needs, specify authorized IPs:

javascript
net:
bindIp: 127.0.0.1,192.168.1.100

Enable TLS/SSL

Secure data in transit by enabling TLS/SSL:

javascript
// In mongod.conf
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem

To connect to a TLS/SSL-enabled MongoDB instance:

bash
mongo --tls --tlsCAFile /path/to/ca.pem --host mongodb.example.com

Use IP Whitelisting or VPC

Restrict access to your MongoDB servers by using:

  • Firewall rules (iptables, ufw, Windows Firewall)
  • Cloud provider security groups
  • VPC (Virtual Private Cloud) networks

Example of firewall rule using ufw on Ubuntu:

bash
sudo ufw allow from 192.168.1.0/24 to any port 27017

3. Encryption

Encrypt Data at Rest

MongoDB Enterprise provides encryption at rest using:

  1. WiredTiger Encryption:
javascript
// In mongod.conf
security:
enableEncryption: true
encryptionKeyFile: "/path/to/key/file"
  1. Full Disk Encryption: Use operating system solutions like:
    • Linux: dm-crypt and LUKS
    • Windows: BitLocker
    • macOS: FileVault

Encrypt Application Data

For sensitive fields, use client-side field level encryption:

javascript
// Node.js example using MongoDB Client-Side Field Level Encryption
const { ClientEncryption } = require('mongodb-client-encryption');
const { MongoClient } = require('mongodb');

const connection = new MongoClient('mongodb://localhost:27017');
const encryption = new ClientEncryption(connection, {
keyVaultNamespace: 'encryption.__keyVault',
kmsProviders: {
local: {
key: Buffer.from('...') // Your encryption key
}
}
});

// Encrypt a field
const encryptedSSN = await encryption.encrypt('123-45-6789', {
algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic',
keyAltName: 'myKey'
});

// Store in database with encrypted field
await db.collection('users').insertOne({
name: 'John Doe',
ssn: encryptedSSN
});

4. Auditing and Monitoring

Enable Audit Logging (MongoDB Enterprise)

javascript
// In mongod.conf
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.log
filter: '{ atype: { $in: ["authenticate", "createUser", "dropUser"] } }'

Monitor Database Activities

Set up monitoring using:

  1. MongoDB Atlas monitoring (for cloud deployments)
  2. MongoDB Ops Manager (Enterprise)
  3. Open-source monitoring tools like:
    • Prometheus with MongoDB exporter
    • Grafana dashboards

Example Prometheus MongoDB exporter setup:

bash
# Install and run MongoDB exporter
docker run --name mongodb_exporter -d \
-p 9216:9216 \
-e MONGODB_URI=mongodb://user:password@mongodb:27017/ \
bitnami/mongodb-exporter

Log Rotation

Configure log rotation to prevent disk space exhaustion:

javascript
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logRotate: rename
logAppend: true

5. Regular Updates and Patching

Stay Current with MongoDB Versions

Check the current version:

bash
mongod --version

Subscribe to the MongoDB security mailing list and regularly apply security patches.

Use a Vulnerability Scanner

Regularly scan your MongoDB deployment for vulnerabilities using tools like:

  • MongoDB built-in security checks
  • OpenVAS
  • Nessus

6. Backup and Recovery

Secure Backup Strategy

Implement regular backups using MongoDB tools:

bash
# Create a backup
mongodump --uri="mongodb://user:password@localhost:27017" --out=/backup/mongodump-$(date +"%Y-%m-%d")

# Restore from backup
mongorestore --uri="mongodb://user:password@localhost:27017" /backup/mongodump-2023-04-15

Encrypt your backups:

bash
# Encrypt backup using gpg
tar -czf - /backup/mongodump-2023-04-15 | gpg -e -r [email protected] > mongodump-2023-04-15.tar.gz.gpg

7. Docker and Container Security

If using MongoDB with Docker:

dockerfile
FROM mongo:latest

# Don't run as root
USER mongodb

# Set proper permissions
RUN chown -R mongodb:mongodb /data/db

# Add custom configuration
COPY --chown=mongodb:mongodb mongod.conf /etc/mongod.conf

# Use secure default configuration
CMD ["mongod", "--config", "/etc/mongod.conf", "--auth"]

8. MongoDB Security Checklist Quick Reference

Here's a quick reference checklist you can use to audit your MongoDB deployment:

Real-World Security Implementation Example

Let's walk through a complete example of securing a MongoDB deployment for a web application:

Step 1: Secure Configuration File

javascript
// /etc/mongod.conf
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true

storage:
dbPath: "/var/lib/mongodb"

net:
bindIp: 127.0.0.1
port: 27017
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem

security:
authorization: enabled

processManagement:
timeZoneInfo: /usr/share/zoneinfo

Step 2: Create SSL Certificates

bash
# Generate self-signed certificate (for development only)
openssl req -newkey rsa:4096 -nodes -keyout mongodb.key -x509 -days 365 -out mongodb.crt

# Combine key and certificate
cat mongodb.key mongodb.crt > mongodb.pem

# Move to appropriate location with correct permissions
sudo mv mongodb.pem /etc/ssl/
sudo chmod 600 /etc/ssl/mongodb.pem
sudo chown mongodb:mongodb /etc/ssl/mongodb.pem

Step 3: Initialize MongoDB with Security

bash
# Start MongoDB with the secure configuration
sudo systemctl start mongod

# Connect to MongoDB
mongo --tls --tlsAllowInvalidCertificates

# Create administrator account
use admin
db.createUser({
user: "dbAdmin",
pwd: "strongPassword123!",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})

# Exit and reconnect with authentication
exit
mongo --tls --tlsAllowInvalidCertificates -u dbAdmin -p strongPassword123! --authenticationDatabase admin

Step 4: Create Application User with Limited Permissions

javascript
use myAppDatabase
db.createUser({
user: "myAppUser",
pwd: "appSpecificPassword456!",
roles: [
{ role: "readWrite", db: "myAppDatabase" }
]
})

Step 5: Application Connection String

In your application code, use a secure connection string:

javascript
// Node.js example
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://myAppUser:appSpecificPassword456!@localhost:27017/myAppDatabase?ssl=true&authSource=myAppDatabase";

MongoClient.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
tls: true,
tlsCAFile: '/path/to/ca.pem'
})
.then(client => {
const db = client.db('myAppDatabase');
// Your database operations here
})
.catch(error => console.error(error));

Summary

Implementing MongoDB security is essential for protecting your data and applications. This checklist covers the crucial aspects:

  1. Authentication and Authorization: Enable authentication and use role-based access control
  2. Network Security: Restrict access using IP binding, TLS/SSL, and firewalls
  3. Encryption: Encrypt data at rest and in transit
  4. Auditing and Monitoring: Track database activities and detect suspicious behavior
  5. Regular Updates: Keep your MongoDB deployment patched and current
  6. Backup Strategy: Maintain secure, regular backups
  7. Container Security: Apply security best practices in containerized environments

Remember that security is a continuous process. Regularly review your security measures and stay updated with the latest security best practices and vulnerabilities.

Additional Resources

Practice Exercises

  1. Security Audit: Perform a security audit of your current MongoDB deployment using this checklist.
  2. Penetration Testing: Try to identify security vulnerabilities in a test MongoDB instance (never on production).
  3. Secure Deployment Plan: Create a deployment plan for a new MongoDB instance with all security features enabled.
  4. Incident Response: Develop a plan for responding to potential MongoDB security breaches.
  5. Security Monitoring: Set up a monitoring system for your MongoDB deployment with alerts for suspicious activities.

Implementing these security measures will significantly reduce the risk of unauthorized access and data breaches in your MongoDB deployments.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)