Thursday, March 30, 2017

Authenticate Mongodb Connection with Selfsigned Certificates



Create a selfsigned SSL Certificate
Reference: http://www.akadia.com/services/ssh_test_certificate.html


# cat mongodb.conf

logpath = /opt/sysAdmin/logs/mongodb.log
dbpath = /opt/sysAdmin
port = 27017

sslMode = requireSSL
sslPEMKeyFile = /home/mongodb/ssl/mongodb.pem
sslPEMKeyPassword = test
sslCAFile = /home/mongodb/ssl/client.pem


Step 1:
http://demarcsek92.blogspot.ca/2014/05/mongodb-ssl-setup.html

Create Certificate for Server
$ openssl req -new -x509 -days 365 -out mongodb-cert.crt -keyout mongodb-cert.key
or

$ openssl req -new -x509 -days 3650 -out server.crt -keyout encrypted-server.key -subj '/C=CA/ST=ON/L=TORONTO/O=GOWEEKEND/OU=FINANCE/CN=127.0.0.1'

You can remove passphrase from key, but make sure limit the permission of the key file

$ cp mongodb-cert.key mongodb-cert.key.encrypted
$ openssl rsa -in mongodb-cert.key.encrypted -out mongodb-cert.key

$ cat mongodb-cert.key mongodb-cert.crt > mongodb.pem

Create Certificate for Client
$ openssl req -new -x509 -days 365 -out client-cert.crt -keyout client-cert.key

OR

$ openssl req -new -x509 -days 3650 -out client.crt -keyout encrypted-client.key -subj '/C=CA/ST=ON/L=Toronto/O=GOWEEKEND/OU=IT/CN=127.0.0.1'


You can remove passphrase from key, but make sure limit the permission of the key file

$ cp client-cert.key client-cert.key.encrypted
$ openssl rsa -in client-cert.key.encrypted -out client-cert.key


$ cat client-cert.key client-cert.crt > client.pem

Startup Server
mongod -f /etc/mongodb.conf

Connect to Database with mongodb
mongo --ssl --sslCAFile ./mongodb.pem --sslPEMKeyFile ./client.pem

Step 2:
https://docs.mongodb.com/manual/tutorial/configure-x509-client-authentication/

Problem:
Within PHP, below error popped up:
UserNotFound: Could not find user CN=127.0.0.1,OU=FINANCE,O=GOWEEKEND,L=TORONTO,ST=ON,C=CA@$external

$ openssl x509 -in client.pem -inform PEM -subject -nameopt RFC2253
subject= CN=127.0.0.1,OU=WS,O=GOWEEKEND,L=TORONTO,ST=ON,C=CA

Connect to Database

db.getSiblingDB("$external").runCommand(
  {
    createUser: "CN=127.0.0.1,OU=WS,O=GOWEEKEND,L=TORONTO,ST=ON,C=CA",
    roles: [
             { role: 'readWrite', db: 'mydb' },
             { role: 'userAdminAnyDatabase', db: 'admin' }
           ],
    writeConcern: { w: "majority" , wtimeout: 5000 }
  }
)

No comments:

Post a Comment