Skip to content

Instantly share code, notes, and snippets.

@ihor-lev
Forked from achesco/generate-mongo-ssl.md
Last active November 2, 2022 12:27
Show Gist options
  • Save ihor-lev/ee21693a31d599ce1430d860a25d3635 to your computer and use it in GitHub Desktop.
Save ihor-lev/ee21693a31d599ce1430d860a25d3635 to your computer and use it in GitHub Desktop.
Generate self-signed SSL certificates for MongoDb server and client

Notes

  • CNs are important
  • -days 3650
  • SSL is deprecated in MongoDB in favour of TLS

Make PEM containig a public key certificate and its associated private key

openssl req -newkey rsa:2048 -new -x509 -days 3650 -nodes -subj '/C=US/ST=Massachusetts/L=Bedford/O=Personal/OU=Personal/emailAddress=example@example.com/CN=localhost' -out mongodb-cert.crt -keyout mongodb-cert.key
cat mongodb-cert.key mongodb-cert.crt > mongodb.pem
cp mongodb-cert.crt mongodb-ca.crt

Edit /etc/mongod.conf, network interfaces section

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,10.0.0.1
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb.pem
    CAFile: /etc/ssl/mongodb-cert.crt
    allowInvalidHostnames: true

Check for startup config errors

sudo mongod --config /etc/mongod.conf

Restart mongo

sudo systemctl restart mongod

Test connection with mongosh

mongosh --tls --tlsAllowInvalidHostnames --tlsCAFile "/etc/ssl/mongodb-ca.crt" --tlsCertificateKeyFile "/etc/ssl/mongodb.pem"

NodeJS: Mongo connection options

{ 
    ssl: true,
    sslValidate: true,
    sslKey: fs.readFileSync('/etc/ssl/mongodb.pem'),
    sslCert: fs.readFileSync('/etc/ssl/mongodb-cert.crt'),
    sslCA: fs.readFileSync('/etc/ssl/mongodb-ca.crt')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment