Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 70 ยท Security

Securing a Deployment

Harden a MongoDB deployment: bind to private networks, require TLS, encrypt data at rest and in fields, audit access and keep tested backups. Includes a checklist.

Users and roles (Authentication and Role-Based Access) answer who may do what once a client is connected. Hardening is about everything around that: who can reach the server at all, whether traffic can be read in transit, whether stolen disks or backups reveal your data, whether you would notice misuse, and whether you can recover. Real incidents involving MongoDB have mostly been boring ones: a database listening on the public internet with no authentication, a default port left open, a backup bucket set to public. A short, repeated checklist prevents nearly all of them.

This lesson is a checklist with explanations. The commands and configuration are real and read-only, because the site has no server to run them on. The two TryIts are stand-ins that model a configuration review and an audit-log filter in plain JavaScript; they teach the reasoning, they do not talk to MongoDB.

Layers of defence

Network Private address, firewall.
Transport TLS on every connection.
At rest Encrypted disks and backups.
Visibility Audit logs and monitoring.

No single layer is enough. Assume one will fail.

1 / 2

Network exposure

Start with the simplest and most important rule: the database should not be reachable from the public internet. MongoDB's net.bindIp setting controls which local addresses the server listens on. Binding only to 127.0.0.1 accepts local connections only; binding to a private interface lets application servers on the same network connect.

YAML
# mongod.conf
net:
  port: 27017
  bindIp: 127.0.0.1,10.0.1.12     # loopback plus one private address

Avoid bindIp: 0.0.0.0 unless a firewall is certain to protect the port. Then layer controls on top of the bind address:

  • A firewall or security group that allows port 27017 only from your application servers' addresses.
  • A private network (VPC, VPN, peering or private endpoints) between application and database, so the database has no public address at all. On Atlas, use the IP access list and private connectivity options rather than "allow access from anywhere".
  • Running mongod as an unprivileged operating-system user, never as root.

If a port scan from outside your network can see 27017, treat that as an incident to fix today, even if authentication is on.

Transport encryption with TLS

Without TLS, anything on the network path between client and server (queries, results, even SCRAM exchange data) travels in clear text. Enable TLS so that every connection is encrypted and the client can verify that it is really talking to your server.

YAML
# mongod.conf
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb/server.pem
    CAFile: /etc/ssl/mongodb/ca.pem

requireTLS rejects plain connections, while weaker modes allow them for migrations only. Clients then connect with tls=true (Atlas connection strings already include it) and must trust the certificate's issuer. Never switch off certificate validation in production to "make the error go away": options such as tlsAllowInvalidCertificates defeat the point of TLS and belong only in throwaway local tests. Rotate certificates before they expire; an expired certificate is a common cause of surprise outages.

Encryption at rest

TLS protects data on the wire. Encryption at rest protects it on disk, so a stolen drive, a discarded server or a copied snapshot is not readable. There are three common routes:

  1. Disk or volume encryption provided by the operating system or cloud (for example encrypted block storage). This is the easiest and is on by default on many managed services.
  2. Native encrypted storage engine in MongoDB Enterprise, with keys held in an external key manager (KMIP) or a local key file.
  3. Atlas, which encrypts storage by default and can use your own keys held in a cloud key-management service.

Backups and exports matter just as much as the live database. A mongodump archive is a plain copy of your data, so store it encrypted, restrict who can read the bucket, and keep it out of public locations.

Field-level encryption and Queryable Encryption

Encryption at rest still lets anyone with database access, including a curious administrator, read sensitive values through normal queries. Client-side field level encryption (CSFLE) moves the encryption into the driver: chosen fields (a national ID, a medical code, a card number) are encrypted before leaving the application, so the server only ever stores ciphertext and never holds the keys. You describe which fields to encrypt in a schema, and the driver encrypts and decrypts transparently. Equality search is possible with deterministic encryption, at the cost of leaking which values are equal.

Queryable Encryption is a newer MongoDB feature that goes further: the field stays encrypted and the server can still run certain queries on it (equality, and in newer versions range queries) without seeing plaintext. Both features need driver support, a key management setup and careful planning of which queries you need, so treat them as design decisions for genuinely sensitive fields, not defaults for every field. Check the current documentation for supported query types and server requirements.

Client-side encryption in practice

The previous section described what client-side field level encryption (CSFLE) and Queryable Encryption are. This one explains how the pieces fit, because the design decisions come from the key hierarchy and the encryption type you pick for each field.

The key hierarchy. Encryption uses two layers of keys so that the database never holds anything it could decrypt with:

  • Data encryption keys (DEKs) encrypt your field values. They are stored, themselves encrypted, in a normal collection called the key vault (by convention encryption.__keyVault).
  • A customer master key (CMK) encrypts the DEKs. The CMK lives outside MongoDB, in a key management service such as AWS KMS, Azure Key Vault, Google Cloud KMS, a KMIP server, or (for development only) a local key file.

The driver asks the KMS to unwrap a DEK, uses it to encrypt or decrypt, and never sends the plaintext key or the plaintext field to the server. Rotating the CMK re-wraps the DEKs without touching your data.

Choosing an encryption type per field:

Type Same value, same ciphertext? Server can query it? Use for
Deterministic (CSFLE) Yes Equality only ({ ssn: "123-45-6789" }) Identifiers you must look up exactly. Leaks which values are equal, so avoid it for low-variety fields such as a yes/no flag.
Random (CSFLE) No, each encryption differs No Values you only store and read back by _id, such as notes or medical details. The strongest option.
Queryable Encryption No, but the server can match it Equality, and in newer versions ranges, through special encrypted indexes Sensitive fields that you must search, without the equality leak of deterministic encryption.

Configuration is declared in the driver, either with an automatic encryption schema (the driver encrypts and decrypts fields matching a JSON schema; this needs MongoDB Enterprise or Atlas) or with explicit calls such as clientEncryption.encrypt(value, options), which also work with Community Edition. A schema fragment looks like this:

JavaScript
{
  bsonType: "object",
  encryptMetadata: { keyId: [UUID("...")] },
  properties: {
    ssn: { encrypt: { bsonType: "string", algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" } },
    notes: { encrypt: { bsonType: "string", algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random" } }
  }
}

Practical consequences: encrypted fields cannot be used in range queries, sorts, $regex or most aggregation expressions (unless you use Queryable Encryption features that support them), indexes on them reveal only ciphertext order, and you must back up the key vault and keep CMK access safe, because losing the keys means losing the data permanently. Plan which queries you need before choosing a type.

The model below uses a toy cipher (not secure; it only shows the behavior) to demonstrate why deterministic encryption allows equality lookups and random encryption does not.

JS Deterministic versus random encryption

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Deterministic encryption gives the equality search, and its cost is visible in the output: anyone reading the database can see that Ann and Cy have the same value. Random encryption hides that, and the price is that you cannot search for it.

X.509 certificates and the default port

TLS (see above) encrypts traffic. X.509 authentication uses the same certificates to prove who is connecting, with no password. It has two uses:

  1. Client authentication. An application presents a certificate signed by your certificate authority. MongoDB maps the certificate's subject (its distinguished name) to a user in the $external database:
JavaScript
db.getSiblingDB("$external").runCommand({
  createUser: "CN=orders-service,OU=apps,O=Example Corp",
  roles: [{ role: "readWrite", db: "shop" }]
})
Terminal
mongosh "mongodb://db1.internal:27017/?tls=true&authMechanism=MONGODB-X509&authSource=%24external" \
  --tlsCertificateKeyFile orders-service.pem --tlsCAFile ca.pem
  1. Internal member authentication. The members of a replica set or sharded cluster must also authenticate to each other. The simple method is a shared keyfile; the stronger one is X.509, set with security.clusterAuthMode: x509, where every member holds a certificate whose subject shares the same organization fields (O, OU, DC) and which lists the server's host name in its subject alternative names.
YAML
# mongod.conf (replica set member using X.509 for both clients and members)
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb/member1.pem
    CAFile: /etc/ssl/mongodb/ca.pem
security:
  clusterAuthMode: x509
  authorization: enabled

Certificates expire, so monitor their dates, automate renewal, and rotate them before the deadline: an expired member certificate stops replication. The lifetimes you choose are a trade-off between safety (short) and operational effort (long).

Changing the default port. MongoDB listens on 27017 (shard servers conventionally on 27018 and config servers on 27019). You can change it with net.port in mongod.conf, or --port:

YAML
net:
  port: 28017
  bindIp: 127.0.0.1

A different port does not secure the server. Scanners find any open port within minutes. It helps only to avoid conflicts when several mongod processes share a host, or to reduce log noise. The real protections are the ones in this lesson: a private network, a firewall, authentication, TLS and least-privilege roles. Remember to update connection strings, firewall rules and monitoring when the port changes.

The model below shows how a certificate subject is matched to a database user, and how the member certificate rule works.

JS Mapping certificate subjects to users

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Auditing and monitoring

Auditing means keeping a record of who did what: logins and failures, user and role changes, schema changes, and optionally reads and writes. MongoDB Enterprise and Atlas include an audit system that writes events (as JSON, BSON or to syslog) and can filter by event type, user or namespace to keep volume under control.

YAML
# mongod.conf (Enterprise)
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{ atype: { $in: ["authenticate", "createUser", "dropUser", "createCollection", "dropCollection"] } }'

Even with Community Edition you can reduce blind spots: ship mongod logs to a central place, alert on repeated authentication failures, and watch connection counts. Alert on the events that signal trouble: a new user created at 3 a.m., a burst of failed logins, a role changed on a production database.

The first stand-in filters a small sample audit log the way an alert rule would, looking for suspicious patterns.

JS Scanning an audit log for suspicious events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sample is deliberately small, but the pattern is real: group by a key, count, compare to a threshold. In production the same rules would run in your log platform over audit output.

Backups and recovery

Security includes surviving a mistake or an attack such as ransomware. A backup you have never restored is a hope, not a backup. Good practice is:

  • Take backups on a schedule that matches how much data you can afford to lose (your RPO), and keep several generations.
  • Keep at least one copy separate from the production account and network, with write access limited so an intruder cannot delete it.
  • Restore regularly into a test environment and time it (your RTO).
  • Encrypt backups and protect the storage location.

Tools and strategies are covered in Backup, Restore and Import/Export.

A deployment review

This second stand-in turns the checklist into code: it reads a description of a deployment and lists every gap. Edit the object, for example set bindIp to "0.0.0.0" or turn TLS off, and watch the findings change.

JS A hardening checklist as code

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A short pre-launch checklist

  • Access control enabled, one least-privilege user per service.
  • bindIp limited to loopback and private addresses; firewall or private networking in front.
  • TLS required, with valid certificates and a rotation plan.
  • Disk and backup encryption on; field-level encryption considered for the most sensitive fields.
  • Auditing or at least central log shipping with alerts on failed logins and administrative changes.
  • Software kept up to date; run a supported MongoDB version and apply security patches.
  • Backups scheduled, stored apart from production, and restored in a drill.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A MongoDB server has authentication enabled but bindIp is 0.0.0.0 with no firewall. What is the best description of the risk?

    Authentication is one layer. An internet-reachable port still invites attacks, so restrict the network path too.
  2. 2. What does requireTLS do?

    requireTLS refuses plain connections, protecting data in transit. Disk and field encryption are separate features.
  3. 3. Which feature keeps selected fields encrypted so the server never sees their plaintext?

    With client-side field level encryption the driver encrypts chosen fields before sending them, and the server stores ciphertext only.
  4. 4. Why should you restore backups into a test environment on a schedule?

    An untested backup may be corrupt or incomplete. Drills confirm that recovery works and show your real recovery time.

Summary

  • Keep the server off the public internet: bind to loopback or private addresses, add a firewall or private networking.
  • Require TLS and never disable certificate validation outside local tests.
  • Encrypt at rest with disk or storage-engine encryption; protect backups equally.
  • Field-level encryption and Queryable Encryption protect chosen fields even from people with database access.
  • Audit logins, user changes and schema changes, and alert on unusual patterns.
  • Take backups, keep a separate copy, and test restores.

Next, learn what happens when untrusted input becomes part of a query in NoSQL Injection and Safe Queries.