Thursday, August 8, 2019

Encrypt Communication between Mongodb Server and Clients


Step 1. Generate Root Certificate

#!/bin/bash

mkdir -p server client
caFile=ca.pem
caKeyDB=privateKey.pem
serverConfig=server-self-signed-cert.req
clientConfig=client-self-signed-cert.req
serverCSR=server/server.req
clientCSR=client/client.req
encryptedServerKeyFile=server/encrypted-server.key
encryptedClientKeyFile=client/encrypted-client.key
serverCert=server/server.crt
clientCert=client/client.crt
serverNonEncryptedKey=server/server.key
clientNonEncryptedKey=client/client.key
mongoServerKeys=server/mongodbServer.pem
mongoClientKeys=client/mongodbClient.pem

# Generate CA Key Database and CA File, i.e. privkey.pem & ca.pem

openssl req -out $caFile -keyout $caKeyDB -new -x509 -days 3650  -subj  "/C=CA/ST=ON/L=TORONTO/O=GOWEEKEND/CN=root/emailAddress=sysadmin@goweekend.ca"


#Generate Server Key DB
openssl genrsa -out $serverNonEncryptedKey 2048

#Generate Client Key DB
openssl genrsa -out $clientNonEncryptedKey 2048

# Generate Server CSR
openssl req -key $serverNonEncryptedKey -new -out $serverCSR  -subj  "/C=CA/ST=ON/L=TORONTO/O=GOWEEKEND/CN=127.0.0.1/emailAddress=sysadmin@goweekend.ca"

# Generate Client CSR
openssl req -key $clientNonEncryptedKey -new -out $clientCSR  -subj  "/C=CA/ST=ON/L=TORONTO/O=GOWEEKEND/CN=127.0.0.1/emailAddress=sysadmin@goweekend.ca"

# Generate Server Certificate
openssl x509 -req -in $serverCSR -CA $caFile -CAkey $caKeyDB -CAserial file.srl -out $serverCert -days 3650

# Generate Client Certificate
openssl x509 -req -in $clientCSR -CA $caFile -CAkey $caKeyDB -CAserial file.srl -out $clientCert -days 3650

# Merge Private/Public Keys
cat $serverNonEncryptedKey $serverCert > $mongoServerKeys
cat $clientNonEncryptedKey $clientCert > $mongoClientKeys

# Verify the generated certificates
openssl verify -CAfile $caFile $mongoServerKeys
openssl verify -CAfile $caFile $mongoClientKeys

Step 2: Configure Mongodb
# cat  /etc/mongod.conf
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
storage:
  dbPath: /data/mongodb
  journal:
    enabled: true
processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo
net:
  port: 27017
  bindIp: 127.0.0.1  # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
  ssl:
      ###certificateSelector: <string>
      mode: requireSSL
      PEMKeyFile: /etc/mongodb/ssl/mongodbServer.pem
      ###PEMKeyPassword: csis2006
      CAFile: /etc/mongodb/ssl/ca.pem

Step 3: Start up MongoDB
$ cat x509MongoStart.sh
#!/bin/bash

cd /data/mongodb
mongod -f /etc/mongod.conf &

Step 4: Connect to MongoDB
$ cat mongoClient.sh
unset HTTP_PROXY
unset HTTPS_PROXY
mongo --ssl --sslCAFile /etc/mongodb/ssl/ca.pem --sslPEMKeyFile /etc/mongodb/ssl/mongodbClient.pem

No comments:

Post a Comment