Networking Security: Self-Managed / TLS for Self-Managed Deployments
Code Summary: TLS for Self-Managed Deployments
The following provides a summary of the code to configure TLS/SSL for Self-Managed MongoDB deployments.
Prerequisites
- MongoDB
- Linux (Ubuntu)
Usage
Generate a Self-Signed CA Certificate:
The following generates a 4096-bit private key and then creates a self-signed CA certificate valid for 365 days using that key. The key and certificate are saved in the /tmp directory.
openssl genrsa -out /tmp/ca.key 4096
openssl req -x509 -new -nodes -key /tmp/ca.key -sha256 -days 365 -out /tmp/ca.crt
Generate Certificates for each Node:
The following generates a 4096-bit private key and then creates a certificate signing request (CSR) using that key. The key and CSR are saved as mongod0.key and mongod0.csr. You’ll have to repeat this process for each node in the cluster.
openssl genrsa -out mongod0.key 4096
openssl req -new -key mongod0.key -out mongod0.csr
Submit the Node's Certificate Signing Request (CSR) to a Certificate Authority (CA):
The following signs the mongod0 certificate request with a CA certificate and key, creating a certificate valid for 365 days. It then combines the certificate and private key into a single PEM file. You’ll have to repeat this process for each node in the cluster.
openssl x509 -req -in mongod0.csr -CA /tmp/ca.crt -CAkey /tmp/ca.key -CAcreateserial -out mongod0.crt -days 365 -sha256
cat mongod0.crt mongod0.key > mongod0.pem
Distribute Each Certificate to its Designated Node:
The following copies the mongod0 PEM file and the CA certificate from your local machine to the /tmp directory on a remote server. Replace user@remote.example.com with your server details.
scp /tmp/mongod0.pem user@remote.example.com:/tmp
scp /tmp/ca.crt user@remote.example.com:/tmp
Store the Certificates:
The following creates a directory for MongoDB SSL files, copies the PEM and CA certificate into it, and sets the correct ownership and permissions. This ensures only the mongodb user can access the files.
sudo mkdir -p /etc/ssl/mongodb
sudo cp /tmp/mongod0.pem /etc/ssl/mongodb/
sudo cp /tmp/ca.crt /etc/ssl/mongodb/
sudo chown mongodb:mongodb /etc/ssl/mongodb/*
sudo chmod 600 /etc/ssl/mongodb/*
Update the mongod Configuration File:
The following configures MongoDB to require TLS connections, using the specified certificate and CA files. It sets the server to listen on port 27017 and bind to both localhost and mongod0.replset.com.
net:
tls:
mode: requireTLS
certificateKeyFile: /etc/ssl/mongodb/mongod0.pem
CAFile: /etc/ssl/mongodb/ca.crt
port: 27017
bindIp: 127.0.0.1,mongod0.replset.com