Mongo Server and DB Security

Login as ADMIN

use admin

Create SITE ADMIN users

First create Root Admin user

db.createUser( {

    user: “siteRootAdmin”,

    pwd: “***”,

    roles: [ { role: “root”, db: “admin” } ]

  });

  Then create Any DB Admin

db.createUser( {

    user: “siteUserAdmin”,

    pwd: “***”,

    roles: [ { role: “userAdminAnyDatabase”, db: “admin” } ]

  });

Create a specific DB ADMIN users

db.createUser( {

    user: “sports”,

    pwd: “***”,

    roles: [ { role: “dbOwner”, db: “sports” } ]

  });

Check if Users created properly

db.system.users.find({})

db.runCommand(   {     usersInfo:”siteRootAdmin”,  showPrivileges:true   } )

Setup Security for ReplicaSet Members

http://docs.mongodb.org/v2.6/tutorial/deploy-replica-set-with-auth/#create-the-key-file-to-be-used-by-each-member-of-the-replica-set

Create the Key file

Share the same Key file in all ReplicaSet members

Stop the ReplicaSet members

Add Security in the Config

security:

   authorization: “enabled”

./mongodb/bin/mongod –config mongo.conf

Restart each ReplicaSet member

Check if Auth working properly

Say, grant an User a Role to a new DB

db.auth(“siteRootAdmin”, “****”)

db.grantRolesToUser(

    “sports”,

    [

      { role: “readWrite”, db: “medicine” }

    ]

)

Check Authn from Client

mongo –port 27017 -u siteUserAdmin -p ***** –host node1 –authenticationDatabase admin  OR mongo node1

[mongo_shell] db.auth(“siteRootAdmin”, “****”)

 Password Protection

 Demonstration of  password encryption and decryption using Nodejs library

var bcrypt = require(‘bcrypt’);

var Enc = require(‘enc’);

Step 1 :  Generate a secure key for the password string ‘demo’
Option A : use bcrypt

var salt = bcrypt.genSaltSync(10);

var key = bcrypt.hashSync(‘demo’, salt);

For example ,   key ==>  $xYz101aBc#$123333SDFfffffffff…………

Option B : use md5

var key = Enc.md5(‘demo’);

For example , key ==> $xYz101aBc#$123333SDFfffffffff…………

Step 2 :  Generate encrypted string

Assumption :  Option B of Step 1 is used to generate the Key

var key = $s344555sddggA$$nn@!qw12333…………;

var encrypted_str = Enc.aes192.encode(‘demo’, key);

For example , encrypted_str ==>  $xYz101aBc#$123333SDFfffffffff…………

Step 3 :  Decrypt the password while connecting to DB from Server Apps

Pass the above values as masked env variables to the App Runtime :

 key = process.env.DB_KEY;

 encrypted_str = process.env.DB_PWD

 decrypted_str = Enc.aes192.decode(encrypted_str, key);

 tempered = !Enc.md5(decrypted_str)==key

 // if we have use Option A (bcrypt) to generate hash , then use following code snippet

 // tempered = bcrypt.compareSync(decrypted_str, hash, key); // 

if(tempered) console.log(“encrypted pwd doesn’t match with key.”)

Please note that , similar strategy can be adopted for apps developed in other languages (python , ruby , java ) using corresponding hashing / encrypt / decrypt library

Advertisements