Friday, November 11, 2016

MongoDB - Enabling Authentication on a Running Replica Set



# Setup directory for replication set testing
# hostname: database
mkdir -p /home/donghua/LAB/{r0,r1,r2}

# Setup replset with 3 replicas
mongod --dbpath /home/donghua/LAB/r0 --logpath /home/donghua/LAB/r0/mongo.log --port 31120 --replSet TO_BE_SECURED --fork
mongod --dbpath /home/donghua/LAB/r1 --logpath /home/donghua/LAB/r1/mongo.log --port 31121 --replSet TO_BE_SECURED --fork
mongod --dbpath /home/donghua/LAB/r2 --logpath /home/donghua/LAB/r2/mongo.log --port 31122 --replSet TO_BE_SECURED --fork

mongo --port 31120 --eval "rs.initiate({_id: 'TO_BE_SECURED',members: [{ _id: 1, host: 'database:31120' },{ _id: 2, host: 'database:31121' },{ _id: 3, host: 'database:31122' }]})"
mongo --port 31120 --eval "rs.status()"


# Create a keyfile to use for internal authentication between the members of the replica set.
openssl rand -base64 755 > /home/donghua/LAB/mongodb-keyfile
chmod 400 /home/donghua/LAB/mongodb-keyfile

# Safely shutdown each member of the replica set, starting with the secondaries to prevent any rollbacks
# Demonstrating different shutdown mongodb methods here
mongo admin --port 31121 -eval "db.shutdownServer()"
mongod --dbpath /home/donghua/LAB/r2 --shutdown
mongo admin --port 31120 -eval "db.shutdownServer()"

# Starting with the primary, restart each member using the shared keyfile you generated.
mongod --dbpath /home/donghua/LAB/r0 --logpath /home/donghua/LAB/r0/mongo.log --port 31120 --replSet TO_BE_SECURED --fork --keyFile /home/donghua/LAB/mongodb-keyfile
mongod --dbpath /home/donghua/LAB/r1 --logpath /home/donghua/LAB/r1/mongo.log --port 31121 --replSet TO_BE_SECURED --fork --keyFile /home/donghua/LAB/mongodb-keyfile
mongod --dbpath /home/donghua/LAB/r2 --logpath /home/donghua/LAB/r2/mongo.log --port 31122 --replSet TO_BE_SECURED --fork --keyFile /home/donghua/LAB/mongodb-keyfile

# Finally, create a user with the root role with the username admin and the password securepass on the admin database.
MongoDB Enterprise TO_BE_SECURED:PRIMARY> db.createUser( {user: "admin", pwd: "securepass", roles:['root']});
MongoDB Enterprise TO_BE_SECURED:PRIMARY> db.auth("admin","securepass")
MongoDB Enterprise TO_BE_SECURED:PRIMARY> db.runCommand({getParameter: 1, authenticationMechanisms: 1})
{
        "authenticationMechanisms" : [
                "MONGODB-CR",
                "MONGODB-X509",
                "SCRAM-SHA-1"
        ],
        "ok" : 1
}


# Shutdown and clean up
mongo admin --port 31120 -eval "db.shutdownServer()" -u admin -p securepass
mongo admin --port 31121 -eval "db.shutdownServer()" -u admin -p securepass
mongo admin --port 31122 -eval "db.shutdownServer()" -u admin -p securepass
rm -rf /home/donghua/LAB