Secure Your MongoDB Databases

This tutorial will show you how to install and secure MongoDB on an Ubuntu or Debian. This guide will also explain on some basic features and functions of the MongoDB database.


Prerequisites

To follow this guide, you will need one (physical or virtual) machine installed with Ubuntu or Debian having sudo non-root user privileges.

Set Timezone

You can set correct timezone on your Ubuntu or Debian using the below command:
sudo timedatectl set-timezon America/NW_York

Set Hostname

You can set hostname on your Ubuntu or Debian using the below command:
sudo hostnamectl set-hostname your_server_name

Adding MongoDB Source

You should check the available MongoDB version on https://repo.mongodb.org/apt/ubuntu. For this guide, we will install and use MongoDB version 4.2.
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4b7c549a058f8b6b
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu/dists/bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

Install MongoDB

Type below command to install MongoDB on your Ubuntu or Debian:
sudo apt update
sudo apt -y install mongodb-org

Secure MongoDB

Edit mongod.conf file with any of your prefered editor:
sudo nano /etc/mongod.conf
Locate the security section, comment out by removing #, then add the authorization: enabled string like below:
security:
  authorization: enabled
Make sure you add double blank space in the beginning of authorization string.

Save and close the editor.

The authorization option enables role-based access control for your databases. If no value is specified, any user will have the ability to modify any database. We'll explain it to you how to create database users and set their permissions later in this guide.

Start or restart MongoDB to apply changes:
sudo systemctl start mongod
sudo systemctl enable mongod
Confirm that the MongoDB is up and running:
sudo systemctl status mongod
You will see output like below:
mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Mon 2020-05-18 10:24:47 PKT; 8s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 18880 (mongod)
     Memory: 76.0M
     CGroup: /system.slice/mongod.service
             └─18880 /usr/bin/mongod --config /etc/mongod.conf

May 18 10:24:47 localhost systemd[1]: Started MongoDB Database Server.

Create an Administrative user

We will create a administrative privileges user to be used on the database as we have already enabled role-based access control in the (Secure MongoDB) section.

Type below command to open the mongo shell:
mongo
You will see MongoDB prompt like below:
MongoDB shell version v4.2.6
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("e767a67e-9c03-444f-a20d-ee29dafc9300") }
MongoDB server version: 4.2.6
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
>
Type below to switch to admin database:
use admin
Type below command to create an administrative privileged user with the ability to create other users on any database.

For this guide, we will create a user called administrator:
db.createUser({user: "administrator", pwd: "Type_Strong_Password_Here", roles:[{role: "userAdminAnyDatabase", db: "admin"}]})
You will see output similar to the following:
Successfully added user: {
        "user" : "administrator",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}
Now exit from the mongo shell with below command:
quit()
Next, connect to your MongoDB with the newly created user like below:
mongo -u administrator -p --authenticationDatabase admin
The -u, -p, and --authenticationDatabase options in the above command are required in order to authenticate connections to the shell. Without authentication, the MongoDB shell can be accessed but will not allow connections to databases.

You will login to MongoDB shell like below:
MongoDB shell version v4.2.6
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f0bfa573-d1b4-4068-ae89-12ab7bbaec5f") }
MongoDB server version: 4.2.6
>
As the administrator user, create a new database to store regular user data for authentication. For this guide, we will create a database called testDB:
use testDB
db.createUser({user: "testuser1", pwd: "Type_Strong_Password_Here", roles:[{role: "read", db: "testDB"}, {role:"readWrite", db: "testDB"}]})
You will see output similar to the following:
Successfully added user: {
        "user" : "testuser1",
        "roles" : [
                {
                        "role" : "read",
                        "db" : "testDB"
                },
                {
                        "role" : "readWrite",
                        "db" : "testDB"
                }
        ]
}
Now exit from the mongo shell with below command:
quit()

Managing the Data and Collections

This section will explain a few basic features, but we encourage you to do further research based on your specific use case.

Access the MongoDB shell using the testuser1 we created in earlier step:
mongo -u testuser1 -p --authenticationDatabase testDB
You will login to MongoDB shell:
MongoDB shell version v4.2.6
Enter password:
connecting to: mongodb://127.0.0.1:27017/?authSource=testDB&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("7d1aa588-f666-45ca-8e65-d3e8ec090428") }
MongoDB server version: 4.2.6
>
Type below to switch to testDB:
use testDB
Type below to create a new collection, for example testDBCollection:
db.createCollection("testDBCollection", {capped: false})
Next, create sample data entry into the testDB database. MongoDB accepts input as documents in the form of JSON objects such as the below. The a and b variables are used to simplify entry; objects can be inserted directly via functions as well.
var a = { name : "Muhammad Anwar",  attributes: { age : 34, address : "21 Fish St", phone : +923218675309 }}
var b = { name : "Larry Ellison",  attributes: { age : 70, address : "31 Main Rd", favorites : { food : "Burgers", animal : "Cat" } }}
Note that documents inserted into a collection need not have the same schema, which is one of many benefits of using a NoSQL database. Insert the data into testDBCollection, using the insert method:
db.testDBCollection.insert(a)
The output will show the number of objects successfully written to the current working database:
WriteResult({ "nInserted" : 1 })
db.testDBCollection.insert(b)
Confirm that the testDBCollection was properly created:
show collections
The output will list collections within the current working database like below:
testDBCollection
View unfiltered data in the testDBCollection using the find method like below:
db.testDBCollection.find()
If the query passed, you will see the output similar to the following:
{ "_id" : ObjectId("5ec2208e4419e2c582d7a707"), "name" : "Muhammad Anwar", "attributes" : { "age" : 34, "address" : "21 Fish St", "phone" : 923218675309 } }
{ "_id" : ObjectId("5ec2209e4419e2c582d7a708"), "name" : "Larry Ellison", "attributes" : { "age" : 70, "address" : "31 Main Rd", "favorites" : { "food" : "Burgers", "animal" : "Cat" } } }
You may notice the objects we entered are preceded by _id keys and ObjectId values. These are unique indexes generated by MongoDB when an _id value is not explicitly defined. ObjectId values can be used as primary keys when entering queries, although for ease of use, you may wish to create your own index as you would with any other database system.

The find method can also be used to search for a specific document or field by entering a search term parameter (in the form of an object) rather than leaving it empty. For example:
db.testDBCollection.find({"name" : "Muhammad Anwar"})
This returns a list of documents containing the {"name" : "Muhammad Anwar"} object.
{ "_id" : ObjectId("5ec2208e4419e2c582d7a707"), "name" : "Muhammad Anwar", "attributes" : { "age" : 34, "address" : "21 Fish St", "phone" : 923218675309 } }

Wrapping up

We hope this guide was helpful to install and secure MongoDB on your Ubuntu or Debian server. If you wish to learn how to set up a highly available fault-tolerant MongoDB Sharded Cluster for your production use, follow this guide.

3 comments:

  1. AnonymousMay 15, 2020

    this is not working

    ReplyDelete
  2. Hi,
    Good tutorial. After "Add the MongoDB repository to your sources.list.d directory" step you shroud run "sudo apt-get update".

    ReplyDelete

Powered by Blogger.