Enable TLS for MongoDB
/etc/mongod.confnet: tls: mode: requireTLS certificateKeyFile: /etc/ssl/mongodb/server.pem CAFile: /etc/ssl/mongodb/ca.pemsudo systemctl restart mongodWhy it matters
Section titled “Why it matters”Without TLS, every document you read, every document you write and the authentication exchange itself cross the network in cleartext. MongoDB’s SCRAM authentication resists replay of the stored credential, but it does nothing for the data — and the data is the entire point of a database.
The four modes, and the one that catches people
Section titled “The four modes, and the one that catches people”| Mode | Accepts plaintext | Accepts TLS |
|---|---|---|
disabled |
yes | no |
allowTLS |
yes | yes |
preferTLS |
yes | yes |
requireTLS |
no | yes |
allowTLS and preferTLS both still accept unencrypted connections. The
difference between them is only what the server prefers for internal
replication traffic — neither turns anything away.
This is the same trap as Postgres and
MySQL, with an extra edge: preferTLS reads like it’s
doing something protective, and it is a popular half-step. A server on
preferTLS will report TLS working, show encrypted connections in your testing,
and quietly accept the one legacy client still connecting in the clear.
requireTLS is the only mode that requires anything.
The certificate is one combined file
Section titled “The certificate is one combined file”MongoDB wants the certificate and its private key concatenated into a single PEM, which is unusual enough to be a common first stumble:
cat server.crt server.key > /etc/ssl/mongodb/server.pemsudo chown mongodb:mongodb /etc/ssl/mongodb/server.pemsudo chmod 600 /etc/ssl/mongodb/server.pemcertificateKeyFile points at that combined file, not at a cert. If MongoDB
refuses to start with a TLS error, this is the first thing to check.
The client half
Section titled “The client half”A server requiring TLS stops eavesdropping. Only the client decides whether it verifies which server it reached:
mongodb://app:secret@db.internal:27017/appdb?authSource=admin&tls=true&tlsCAFile=/etc/ssl/ca.pemtls=true encrypts and validates against the CA by default — MongoDB drivers
verify certificates unless you tell them not to. The options that turn that off
(tlsAllowInvalidCertificates, tlsAllowInvalidHostnames) exist for
self-signed certificates and are frequently pasted in to “fix” a connection
error. Each one gives up exactly the protection you enabled TLS for.
If a driver only connects with tlsAllowInvalidCertificates=true, the
certificate is wrong. Fix the certificate.
Related
Section titled “Related”- Grant least privilege roles — the credential this protects.
- Enable authorization — do that first; it matters more.