Official Power Up Hosting Blog

Everything about Linux, Windows, and hosting ;)

Selvakumar
Author

I am an Online Marketer and technology lover. I like to learn new things and share that with people.

Share


Our Newsletter


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Tags


Twitter


Official Power Up Hosting Blog

How to install MongoDB and Secure it on Ubuntu 16.04 with Commands

SelvakumarSelvakumar

Before knowing the how to install MongoDB on Ubuntu 16.04, First, you should know

What is Mongo DB?

install mongodb ubuntu

Mongo DB is the document based open source Database, and it uses the Dynamic schema to store and manipulate data. It is Unlike traditional RDBMS which uses table form to store data.

It is classified as NoSQL because it is not following the traditional database structure which uses the table.
For, e.g., if you have JSON documents, you can use the dynamic schema to store the document.

The specialty here is the Mongo DB does not require you to create a new schema to store data. You can also change the schema at any time if you need that too without creating the new database with updated schema.

It sounds easy. Is not it?

Here we are going to see the three steps to install Mongo DB and secure it more on Ubuntu.

Here is the short view of what we are going to do

  1. Install Mongo DB using Repository
  2. Secure Mongo DB with Passwords
  3. Adding the more security to the Mongo DB.

Prerequisites

Here is let us look at what we need to have Mongo DB installed and further implement the steps we are going to discuss in the article.

You need one Ubuntu 16.04 servers.

Note: It should be configured with non-root sudo user.

Here, we are going to see how to start mongodb in ubuntu step by step. You will know the mongodb ubuntu command line used for the following steps.

Step 1: Installing Mongo DB using Official Repository

Note: In the Ubuntu 16.0 Mongodb comes as default package, but here we are going to use the official Mongo DB repository.

The reason is it has the package up-to-date. It is recommended.

Now, you have to add the official Mongo DB Repository to the server.

Since we are adding the new resource, The Ubuntu verify the authenticity by checking whether they signed using GPS Keys.

Listen, now you have to import the Official Repository GPG keys to gain access.

Here is the command for that.

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

Now we have imported the GPG keys, and the following output from executed command will be like this.

Now:

It is confirmed that the key is imported

Executing: /tmp/tmp.RYmA05K7mL/gpg.1.sh --keyserver
hkp://keyserver.ubuntu.com:80
--recv
0C49F3730359A14518585931BC711F9BA15703C6
gpg: requesting key A15703C6 from hkp server     keyserver.ubuntu.com
gpg: key A15703C6: public key "MongoDB 3.4 Release     Signing Key <packaging@mongodb.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
)

Now, let us add the Mongo DB repository so that the apt will know the exact location to download the Mongo DB.

To create the Mongo DB, execute the following command.

$ echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

The Next step is you have to execute the following command to update the Mongo DB using install mongodb ubuntu apt-get line

sudo apt-get update

Now, we can install the Mongo DB.

Step 2: installing the Mongo DB

We are going to install the mongodb-org meta-package and it contains the following.

1.the daemon,
2.The configuration,
3.Shell
4.init scripts,
5.Management tools.

Here is the command

$ sudo apt-get install mongodb-org

Now press Y and Enter. You can check the installation status.

Once the installation is finished, now it is the time to

initiate the Mongo Daemon using sudo service mongod start

Execute the following command

$ sudo systemctl start mongod

Here you won't get any output. Instead, you can check the status using the following command

$ sudo systemctl start mongod

The result will be like

$ mongod.service - High-performance, schema-free    document-oriented database
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: active (running) since Fri 2017-02-17 18:57:26 UTC; 17min ago
Docs: https://docs.mongodb.org/manual
Main PID: 2811 (mongod)
Tasks: 17
Memory: 56.8M
CPU: 7.294s
CGroup: /system.slice/mongod.service
       └─2811 /usr/bin/mongod --quiet --config /etc/mongod.conf

Now, Press Q to exit. We have manually started the Mongo Daemon and verified that it is running.

Here is the one more step to do, Just ensure that it automatically restarts in the boot.

$ sudo systemctl enable mongod

Here the output of the command will be like the following

Output
Created symlink from /etc/systemd/system/multi-      user.target.wants/mongod.service
to /lib/systemd/system/mongod.service.

You have installed the Mongo DB and the next step would be securing the database.

Securing MongoDB

Have you heard about the automated exploits? That is the biggest threat for Mongo DB earlier versions. Here the reason is there is no authentication required to access the database.

Any user, even you can create and remove the databases and could read from, write to content which you and they created.

The previous version of Mongo DB configures the Mongo Deamon to listen to all ports. So, the automated scripts could detect the Mongo DB instances which are not secured by Firewall.

The problem is if the authentication enabled, anyone, can have complete access to Mongo DB.

To overcome the situation, it is reduced in the Mongo DB 3.X and earlier versions by some package managers.

Now the Deamon made to listen to 127.0.0.1 IP. It will only accept connections from UNIX socket to protect from the automated exploiters as it cannot be opened automatically for the internet.

But by default, the authentication is not enabled and all local users can access the database. To avoid that and secure Mongo DB we are going to create authentication and test it by ourselves.

Creating the Administrator.

Execute the following command

$ mongo

You will get a warning from the output that it says the authentication is not enabled and read and write operations are also not restricted.

Output
 MongoDB shell version v3.4.2
 connecting to: mongodb://127.0.0.1:27017
 MongoDB server version: 3.4.2
 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
 Server has startup warnings:
 2017-02-21T19:10:42.446+0000 I STORAGE       [initandlisten]
 2017-02-21T19:10:42.446+0000 I STORAGE       [initandlisten] ** WARNING: Using the XFS filesystem is      strongly recommended with the WiredTiger storage engine
 2017-02-21T19:10:42.446+0000 I STORAGE  [initandlisten] **          See      http://dochub.mongodb.org/core/prodnotes-filesystem
 2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]
 2017-02-21T19:10:42.534+0000 I CONTROL       [initandlisten] ** WARNING: Access control is not enabled      for the database.
 2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten] **          Read and write access to data      and configuration is unrestricted.
 2017-02-21T19:10:42.534+0000 I CONTROL  [initandlisten]

We can choose own username for the administrative user as the privilege level set by the userAdminAnyDatabase

Only the Database Administrator decides where to store the credentials.

Here the below command add your choice user and the password you feel that is most secure.

use admin
db.createUser(
  {
user: "AdminSammy",
pwd: "AdminSammy'sSecurePassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }   ]
}
)

After executing the db.createUser The mongodb shell commands adds three dots before the command to represents the execution. The output will be like this

 Output
> use admin
switched to db admin
> db.createUser(
...   {
...     user: "AdminSammy",
...     pwd: "AdminSammy'sSecurePassword",
...     roles: [ { role: "userAdminAnyDatabase", db:    "admin" } ]
 ...   }
... )
 Successfully added user: {
    "user" : "AdminSammy",
    "roles" : [
            {
                    "role" : "userAdminAnyDatabase",
                    "db" : "admin"
            }
    ]
}

To leave the client type exit and enter or Press CTRL+C.

Now, the user can enter their credentials, but it is not required until we enable the authentication and mongodb restart ubuntu.

Enabling the Authentication

To enable the authentication, you have to add the "enabled" option in the file. To do that first open the configuration file using the command.

$ sudo nano /etc/mongod.conf

The security session will open, and you have to remove the #infront of security.

Now you have to add the authorization setting which says authorization: "enabled." The code will be like this

mongodb.conf
. . .
security:
authorization: "enabled"
. . . 

Note: Here there should be no space before the security line

==Note: You have to add two space after "authorization." ==

Now save and exit the file. After that restart, the Mongo Daemon using the below code

$ sudo systemctl restart mongod

If you have made any error in the configuration, the daemon won't restart. However, we cannot see any output for that.

But, we can check that the command restarted successfully by using the following command

$ sudo systemctl status mongodb

When the output shows Active and contains the following line, then it means the restart worked.

**Output**
Jan 23 19:15:42 MongoHost systemd[1]: Started High-performance, schema-free document-oriented database.

Check whether the authentication works.

Next, you have to check the authentication works or not.

Check The Unauthenticated users are Restricted

Now, let us access db without credentials and see whether the DB allows us. Start with the below command.

$ mongo

Here the authentication is enabled, and the warnings are resolved.

The output will look similar to the following

Output
MongoDB shell version v3.4.2
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2

It ensures that we are connected to the database. But wait, we have to make sure that our access is restricted.

Test that with the following command "show dbs"

> show dbs
The output follow as below

Output
2017-02-21T19:20:42.919+0000 E QUERY    [thread1]    Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
    "code" : 13,
    "codeName" : "Unauthorized"
. . . 

See, the command returns the error as your restricted for the access.

Here, you cannot create users and access further without authentication. Now let us exit the shell

> exit

The next step is verifying that our administrative accounts have the access.

Verify the Administrative User Access

Now, let us access the Database without authentication using the following command where -u refers to the user name and the -p refers to your password.

Make sure you represents the database where you have stored your password. Add --authenticationDatabase in the last section of the command.

The entire command for verifying authentication is

mongo -u AdminSammy -p --authenticationDatabase admin

Now the prompt will ask for your the password. Enter the correct password and enter.

Now you will be transferred to the shell where you can use the command "show dbs"

Output
MongoDB shell version v3.4.2
Enter password:
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.2

>

Use "show dbs" command as mentioned; then you will be allowed to access the Database instead of denied.

show dbs
Output
admin  0.000GB
local  0.000GB

To exit the shell type exit and enter or press CTRL+C

Connect to Remote MongoDB

Before creating installations to gain remote access, let us look at the Mongo DB which is secured behind the firewall and protected by Virtual Private Network or strong host.

Here, we are going to enable the firewall on the database server and restricting the access to the specified host which requires the DB access.

Step 1:Enable the UWF

Initially, we have enabled the UWF, and that only allows the SSH connections. Now let us check the UWF status again using the below command

$ sudo ufw status

If the output shows that the firewall is inactive, you have to activate it using the command

host$ sudo ufw enable

Once enabled, use the status command again

$ sudo ufw statu

It will show you the rules and if you need SSH, be sure to enable it using the command.

$host sudo ufw allow OpenSSH

If you do not make the above changes, the output will show that only SSH connection is allowed.

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

We are going to access the default Mongo DB port 27027. Be sure that you restricted the access to the host.

One more thing to listen here, if you changed the default port, update it with the following command.

host$ sudo ufw allow from client_ip_address to any port 27017

Now, you have to run the command again and again with the client IP address which you will access from.

Once finished let us check the status using the command

host$ sudo ufw status

It should return the output like below

Output
To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
27017                       ALLOW         client_ip_address
OpenSSH (v6)               ALLOW       Anywhere (v6)

Here in out, the permitted client address will appear.

Now we are going to configure the Mongo DB to listen to its public interface while the firewall rules are in place.

Step 2: Setting Up the Public bindIP

To enable remote access, we have to create public IP address for Mongo DB by inserting the Publically accessible IP in mongod.conf

Use the below command for that

$ sudo nano /etc/mongod.conf

A file will open and you have to add the Mongo Host IP in the "bindIP"

Here is how the file looks like when adding bindIP

Excerpt of /etc/mongod.conf
. . .
net:
port: 27017
bindIp: 127.0.0.1,IP_of_MongoHost
. . .

After that save and exit from the file, then restart the Mongo Daemon using the below command

$ sudo systemctl restart mongod

Once again you have to check whether the restart is successful using the "status."

$ sudo systemctl status mongodb

The output should show the Active: active(running). After that let us test the remote access.

Test Remote Connection

Let us test that the Mongo DB is listening to its public interface by using the --host flag and IP address mentioned in mongodb.conf file.

$ mongo -u AdminSammy -p --authenticationDatabase admin --host IP_address_of_MongoHost

MongoDB shell version v3.4.2
Enter password:
connecting to: mongodb://107.170.233.82:27017/
MongoDB server version: 3.4.2

If you can reach the prompt, then it means the Mongo DB is listening to its public interface.

Here, the connection between the Mongo DB and remote access is unencrypted.

Conclusion

Here in this article, we have added the Official Mongo DB repository to the package list to install the latest version of Mongo DB.

Also added administrator user and authentication.

Here, you have also seen, how to enable the remote connection and setup firewall for restricting the connections to the specific host.

uninstall mongodb ubuntu to get the latest version if available. Because the ubuntu 16.04 mongodb can get updated anytime.

Interested in How to install robomongo ubuntu, we will cover it soon.

Selvakumar
Author

Selvakumar

I am an Online Marketer and technology lover. I like to learn new things and share that with people.

Comments