MongoDB Security
Comprehensive Database Hardening
TLS/SSL, SCRAM, x.509, Field-Level Encryption, Client-Side Field Level Encryption, LDAP, Kerberos, Auditing & SOC 2/ISO 27001 Compliance
MongoDB Security Architecture Overview
MongoDB Enterprise bietet ein mehrschichtiges Sicherheitsmodell: Netzwerkverschlüsselung durch TLS/SSL, starke Authentifizierung über SCRAM-SHA-256 oder x.509-Zertifikate, Autorisierung durch rollenbasierte Zugriffskontrolle (RBAC), und zusätzlich Feld- und dokumentenbasierte Verschlüsselung für sensible Daten. Für Enterprise-Umgebungen unterstützt MongoDB zudem LDAP-Integration und Kerberos-Authentifizierung.
Transport Encryption
TLS 1.3 für alle Verbindungen
Authentication
SCRAM, x.509, LDAP, Kerberos
Authorization
RBAC mit built-in & custom roles
Encryption
At-rest & Client-Side Field Level
TLS/SSL Configuration (mongod.conf)
# mongod.conf - Comprehensive TLS/SSL Configuration
net:
port: 27017
bindIp: 127.0.0.1,10.0.0.10 # Restrict binding
tls:
mode: requireTLS # Enforce TLS for all connections
certificateKeyFile: /etc/ssl/mongodb-server.pem
certificateKeyFilePassword: $TLS_KEY_PASSWORD # Via environment variable
CAFile: /etc/ssl/ca.pem
clusterFile: /etc/ssl/mongodb-cluster.pem # For replica set communication
clusterCAFile: /etc/ssl/ca.pem
# TLS 1.3 only (disable older protocols)
disabledProtocols: "TLS1_0,TLS1_1,TLS1_2"
# Allow connections without client certificates initially
# Then transition to requireClientCertificate
allowConnectionsWithoutCertificates: false
# Certificate validation
allowInvalidCertificates: false
allowInvalidHostnames: false
# OCSP stapling (Enterprise)
ocspEnabled: true
# Alternative: x.509 Certificate Authentication
security:
authorization: enabled
clusterAuthMode: x509 # Use certificates for internal auth
# JavaScript execution disabled
javascriptEnabled: false
# Redact client IP in logs (GDPR compliance)
redactClientLogData: false
# KMIP for encryption key management (Enterprise)
kmip:
serverName: kmip.hsm.internal
port: 5696
clientCertificateFile: /etc/ssl/kmip-client.pem
clientCertificatePassword: $KMIP_PASSWORD
serverCAFile: /etc/ssl/kmip-ca.pemSCRAM-SHA-256 Authentication Deep Dive
SCRAM (Salted Challenge Response Authentication Mechanism) ist die Standard-Authentifizierung in MongoDB 4.0+. Es bietet Schutz vor Passwort-Abhören und Replay-Attacken durch Challenge-Response mit Salting.
# Create user with SCRAM-SHA-256 (recommended)
use admin
db.createUser({
user: "appUser",
pwd: "ComplexP@ssw0rd123!",
mechanisms: ["SCRAM-SHA-256"], # Explicit, not SCRAM-SHA-1
roles: [
{ role: "readWrite", db: "application" },
{ role: "dbAdmin", db: "application" }
],
passwordDigestor: "server" # Server hashes password
})
# Create read-only analyst user
use reporting
db.createUser({
user: "analyst",
pwd: "An@lyst2026Secure!",
mechanisms: ["SCRAM-SHA-256"],
roles: [
{
role: "read",
db: "reporting",
collection: "analytics" # MongoDB 6.0+ granular permissions
}
]
})
# Verify authentication mechanism
db.runCommand({
connectionStatus: 1
}).authInfo.authenticatedUsers[0].mechanisms
# Output: [ "SCRAM-SHA-256" ]x.509 Certificate Authentication (Enterprise)
x.509-Zertifikate bieten die stärkste Authentifizierung. Keine Passwörter nötig - nur PKI-basierte Identität. Ideal für Service-Accounts und Microservices.
# Create x.509 user (certificate subject as username)
use $external
db.createUser({
user: "CN=app-service,O=Company,OU=Production,L=Berlin,ST=Berlin,C=DE",
roles: [
{ role: "readWrite", db: "app_production" },
{ role: "read", db: "app_cache" }
],
writeConcern: { w: "majority" }
})
# Connection string with x.509
mongodb://app-server.mongodb.internal:27017/?authMechanism=MONGODB-X509&tls=true&tlsCertificateKeyFile=/certs/app.pem
# Validate certificate chain
openssl verify -CAfile /etc/ssl/ca.pem -untrusted /etc/ssl/intermediate.pem /etc/ssl/client.pem
# Check certificate expiry (monitoring script)
#!/bin/bash
EXPIRY=$(openssl x509 -in /etc/ssl/mongodb-server.pem -noout -enddate | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s)
NOW_EPOCH=$(date +%s)
DAYS_UNTIL_EXPIRY=$(( ($EXPIRY_EPOCH - $NOW_EPOCH) / 86400 ))
if [ $DAYS_UNTIL_EXPIRY -lt 30 ]; then
echo "WARNING: Certificate expires in $DAYS_UNTIL_EXPIRY days"
# Trigger renewal or alert
fiRole-Based Access Control (RBAC) Design
# Create custom roles for application tiers
# 1. Application Read-Only (for caching layer)
db.createRole({
role: "appReadOnly",
privileges: [
{
resource: { db: "app", collection: "" },
actions: ["find", "collStats", "dbHash", "listCollections", "listIndexes"]
},
{
resource: { db: "app", collection: "system.indexes" },
actions: ["find"]
}
],
roles: []
})
# 2. Data Processor (can insert/update but not delete)
db.createRole({
role: "dataProcessor",
privileges: [
{
resource: { db: "app", collection: "events" },
actions: ["insert", "update", "find"]
},
{
resource: { db: "app", collection: "events" },
actions: ["update"],
query: { status: { $ne: "archived" } } # Cannot update archived
}
],
roles: [{ role: "appReadOnly", db: "app" }]
})
# 3. Backup Operator (Enterprise Ops Manager integration)
db.createRole({
role: "backupOperator",
privileges: [
{ resource: { cluster: true }, actions: ["backup", "restore"] },
{ resource: { db: "", collection: "" }, actions: ["find"] },
{ resource: { db: "config", collection: "" }, actions: ["find"] }
],
roles: []
})
# 4. Security Officer (can view users/roles, not data)
db.createRole({
role: "securityOfficer",
privileges: [
{ resource: { cluster: true }, actions: ["viewUser", "viewRole", "listDatabases"] },
{ resource: { db: "", collection: "" }, actions: ["collStats"] }
],
roles: []
})
# Grant roles to users
db.grantRolesToUser("app-service", [{ role: "dataProcessor", db: "app" }])Field-Level Encryption (FLE) Implementation
Feld-Level-Verschlüsselung schützt sensible Daten auch vor Datenbank-Admins. Die Anwendung verschlüsselt vor dem Senden, MongoDB speichert nur Ciphertext.
// Node.js Client-Side Field Level Encryption (CSFLE)
const { MongoClient, ClientEncryption } = require('mongodb');
const { getCredentials } = require('./vault');
async function createEncryptedClient() {
// Get master key from external HSM/Vault
const masterKey = await getCredentials('mongodb-master-key');
const keyVaultNamespace = 'encryption.__keyVault';
const kmsProviders = {
local: {
key: Binary.createFromBase64(masterKey, 0)
}
};
// Automatic Encryption Schema
const schema = {
"bsonType": "object",
"encryptMetadata": {
"keyId": [new Binary(Buffer.from(dataKeyId, "base64"), 4)]
},
"properties": {
"ssn": {
"encrypt": {
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
},
"bloodType": {
"encrypt": {
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random" // Queryable
}
},
"medicalHistory": {
"encrypt": {
"bsonType": "array",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random" // Not queryable
}
}
}
};
const client = new MongoClient(uri, {
autoEncryption: {
keyVaultNamespace,
kmsProviders,
schemaMap: { 'medical.records': schema },
// Disable auto encryption for certain operations
bypassAutoEncryption: false,
// Extra options for mongocryptd
extraOptions: {
mongocryptdSpawnPath: '/usr/bin/mongocryptd',
mongocryptdBypassSpawnVerification: false
}
}
});
return client;
}
// Query encrypted fields (deterministic encryption only)
const patients = await db.collection('records').find({
ssn: "123-45-6789" // Can query because deterministic
}).toArray();
// Cannot query random-encrypted fields directly
// This will NOT work:
// db.collection('records').find({ bloodType: "O+" }) // Error!LDAP & Active Directory Integration
# mongod.conf - LDAP Authorization (Enterprise)
security:
authorization: enabled
ldap:
servers: "ldap.company.internal:636"
bind:
queryUser: "CN=mongo-service,OU=ServiceAccounts,DC=company,DC=internal"
queryPassword: $LDAP_PASSWORD
transportSecurity: tls
# User to Distinguished Name mapping
userToDNMapping:
- match: "(.+)"
ldapQuery: "DC=company,DC=internal??sub?(userPrincipalName={0}@company.internal)"
# Cache for performance
authz:
queryTemplate: "{USER}?memberOf?base"
cache:
ttl: 300 # 5 minutes
size: 1000
# Map LDAP groups to MongoDB roles
# Group: CN=MongoDB-ReadOnly,OU=Groups,DC=company,DC=internal
# Maps to: readAnyDatabase@admin
# Group: CN=MongoDB-DBA,OU=Groups,DC=company,DC=internal
# Maps to: dbAdminAnyDatabase@admin + clusterMonitor@adminAuditing & Compliance Logging
# mongod.conf - Comprehensive Audit Configuration (Enterprise)
auditLog:
destination: file
format: JSON # or BSON for binary
path: /var/log/mongodb/audit.log
# Filter events by type
filter: '{
atype: { $in: ["authCheck", "authenticate", "insert", "update", "delete"] },
"param.command": { $in: ["find", "insert", "update", "delete", "drop", "createUser"] }
}'
# HIPAA/SOC 2: Log all access to PHI collections
filter: '{
atype: "authCheck",
"param.ns": { $regex: /^medical\.patients$/ }
}'
# Alternative: Send to syslog for SIEM integration
auditLog:
destination: syslog
# Filter specific users (exclude monitoring)
auditLog:
filter: '{ "user": { $ne: "monitoring-agent" } }'
# Enable system activity auditing
setParameter:
auditAuthorizationSuccess: true # Log successful ops tooEnterprise Deployment: Replica Set Security
# Replica Set with Full Security Stack
# Primary + 2 Secondaries + Arbiter
# Keyfile for internal authentication (minimum requirement)
# Generate: openssl rand -base64 756 > /etc/mongodb-keyfile
# chmod 400 /etc/mongodb-keyfile
# chown mongod:mongod /etc/mongodb-keyfile
# Primary Node Configuration
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 8
encryptionOptions:
keyStorage:
local:
keyIdentifier: "mongodb-key"
keyPath: "/etc/mongodb-keyfile"
replication:
replSetName: "rs0-production"
sharding:
clusterRole: shardsvr
security:
keyFile: /etc/mongodb-keyfile
authorization: enabled
clusterAuthMode: keyFile
# Encryption at Rest (Enterprise)
enableEncryption: true
encryptionKeyFile: /etc/mongodb-encryption-key
# KMIP for key management
kmip:
serverName: kmip-server.internal
port: 5696
serverCAFile: /etc/ssl/kmip-ca.pem
clientCertificateFile: /etc/ssl/kmip-client.pem
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pemSecurity Checklist: Production Readiness
Network Security
Access Control
Encryption
Monitoring & Compliance
MongoDB Enterprise Security Assessment
Validieren Sie Ihre MongoDB-Installation gegen Enterprise Security Best Practices und Compliance-Standards.
Security Assessment Starten