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:
- Data Protection: MongoDB often stores sensitive user data
- Preventing Unauthorized Access: Avoiding data breaches
- Compliance Requirements: Meeting regulatory standards like GDPR, HIPAA, etc.
- 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:
// In mongod.conf
security:
authorization: enabled
Create Administrative User
Before enabling authentication, create an administrative user:
use admin
db.createUser(
{
user: "adminUser",
pwd: "securePassword123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
After enabling authentication, you'll need to authenticate to perform operations:
// 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:
// 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 databasereadWrite
: Read and write access to specified databasedbAdmin
: Administrative tasks on specified databaseuserAdmin
: User and role management on specified databasedbOwner
: 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:
// In mongod.conf
net:
bindIp: 127.0.0.1
For production with remote access needs, specify authorized IPs:
net:
bindIp: 127.0.0.1,192.168.1.100
Enable TLS/SSL
Secure data in transit by enabling TLS/SSL:
// 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:
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:
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:
- WiredTiger Encryption:
// In mongod.conf
security:
enableEncryption: true
encryptionKeyFile: "/path/to/key/file"
- 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:
// 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)
// 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:
- MongoDB Atlas monitoring (for cloud deployments)
- MongoDB Ops Manager (Enterprise)
- Open-source monitoring tools like:
- Prometheus with MongoDB exporter
- Grafana dashboards
Example Prometheus MongoDB exporter setup:
# 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:
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:
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:
# 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:
# 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:
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
// /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
# 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
# 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
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:
// 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:
- Authentication and Authorization: Enable authentication and use role-based access control
- Network Security: Restrict access using IP binding, TLS/SSL, and firewalls
- Encryption: Encrypt data at rest and in transit
- Auditing and Monitoring: Track database activities and detect suspicious behavior
- Regular Updates: Keep your MongoDB deployment patched and current
- Backup Strategy: Maintain secure, regular backups
- 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
- Security Audit: Perform a security audit of your current MongoDB deployment using this checklist.
- Penetration Testing: Try to identify security vulnerabilities in a test MongoDB instance (never on production).
- Secure Deployment Plan: Create a deployment plan for a new MongoDB instance with all security features enabled.
- Incident Response: Develop a plan for responding to potential MongoDB security breaches.
- 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! :)