Mongo: Demo 2 TLS/SSL

by Mark Nielsen
Copyright October 2021


This is not intended to be a complete document on how to do TLS/SSL in mongo. Rather, links and a script is provided. We assume Mongo 5.0 on Ubuntu. An explanation of the steps of the script might be given. This is just a demo.
  1. Links
  2. Notes
  3. TLS/SSL on the server.
  4. TLS/SSL on the client

Links



Notes



Server


mongo_ssl=" --sslMode requireSSL --sslPEMKeyFile mongo/mongodb-server.pem \
  --sslAllowInvalidHostnames  "
margs=" --oplogSize 100 --wiredTigerCacheSizeGB 0.25 \
    --bind_ip 127.0.0.1 $mongo_ssl "
hn=`hostname``
ssl=" -subj '/C=GB/ST=London/L=London/O=Global Security/OU=IT Department/CN=$hn'"  
client=" --tls  --tlslAllowInvalidCertificates --host 127.0.0.1 --quiet "


  # If restarting, kill the mogo processes and then do 
rm -rf  mongo/d1 mongo/d2 mongo/d3 mongo/logs
  # Setup 3 directories:
mkdir -p mongo/d1 mongo/d2 mongo/d3 mongo/logs

# Make the certificate -- self signed
cmd="openssl req -newkey rsa:2048 -new -x509 -days 365  -nodes -out mongo/mongodb-cert.crt -keyout mongo/mongodb-cert.key $ssl "
echo "$cmd" | bash

# Make the pem file
cat mongo/mongodb-cert.key mongo/mongodb-cert.crt > mongo/mongodb-server.pem

#openssl req -newkey rsa:2048 -new -x509 -days 365  -nodes -out mongo/mongo-cert.crt -keyout mongo/mongo-cert.key
#cat mongo/mongo-cert.key mongo/mongo-cert.crt > mongo/mongo-client.pem


# If not AWS,	  ignore.  
# sudo  -s -- bash -c   '  echo "127.0.0.1 localhost ">> /etc/hosts '
  # Start once mongo instance
mongod --dbpath mongo/d1 --port 3001 --replSet r $margs  > mongo/logs/1.log 2>&1  & 
sleep 5
  # In  the mongo shell
mongo $client --port 3001 --eval "rs.initiate( { _id: 'r', version: 1, members: [ {_id :0, host: 'localhost:3001' } ] } )"

sleep 5
  # Start and add two other replica sets
mongod --dbpath mongo/d2 --port 3002 --replSet r $margs > mongo/logs/2.log 2>&1  &
mongod --dbpath mongo/d3 --port 3003 --replSet r $margs > mongo/logs/3.log 2>&1  &
sleep 10
mongo $client --port 3001 --eval "rs.add('localhost:3002')"
sleep 3
mongo $client --port 3001 --eval "rs.add('localhost:3003')"
sleep 3
  # Look at the status
mongo $client --port 3001 --eval "rs.status()"

  # Let's check ssl










echo ""
echo "This should work with msg of self signed."
mongo $client --port 3001 --eval "Date()"

echo ""
echo "This should fail."
mongo  --port 3001 --eval "Date()"



Client

On the client side, I just added the options
  client=" --tls  --tlsAllowInvalidCertificates --host 127.0.0.1 --quiet "
  mongo $client --port 3001 --eval "Date()" 
But, you can have certificates for clients and the server can required certifciates for clients. Eeven though communiction is ecrypted with self-signed cetificates, it doesn't stop man in the middle attacks and verify who is connecting is who they say they are.