Jump toUpdate content

Installing and Securing MongoDB on Ubuntu 16.04

Reviewed on 10 May 2021 • Published on 25 June 2018
  • database
  • compute
  • mysql
  • mongoDB

MongoDB is a document-oriented database that is free and open-source. It considered one of the most popular NoSQL database engines because it is scalable, powerful, reliable and easy to use. In contrast to relational database, MongoDB does not require a deep predefined schema before you can add data since it can be altered at any time. As it uses the NoSQL concept, data rows are stored in JSON-like documents which allows arbitrary data to be inserted.

Requirements:

Setting up MongoDB

Adding MongoDB Repository

Important:

You should always use the official MongoDB mongodb-org packages, which are kept up-to-date with the most recent major and minor MongoDB releases.

  1. Connect to your instance via SSH.

    ssh root@your.instance.ip.address

    If you do not know your server IP, you can list your existing servers using scw ps (Scaleway CLI). Type yes or y when prompted to confirm that we wish to proceed. If the Scaleway CLI is not installed, you have several options:

    • (Preferred) On Mac OS using Homebrew and launching brew install scw
    • On Mac OS using a manual install
    Install the latest stable release on Mac OS X manually:
    # prepare for first install and upgrade
    mkdir -p /usr/local/bin
    mv /usr/local/bin/scw /tmp/scw.old
    # get latest release
    wget "https://github.com/scaleway/scaleway-cli/releases/download/v1.19/scw-darwin-amd64" -O /usr/local/bin/scw
    # test
    scw version
    Install the latest release on Linux:
    # get latest release
    export ARCH=amd64 # can be 'i386', 'amd64' or 'armhf'
    wget "https://github.com/scaleway/scaleway-cli/releases/download/v1.19/scw_1.19_${ARCH}.deb" -O /tmp/scw.deb
    dpkg -i /tmp/scw.deb && rm -f /tmp/scw.deb
    # test
    scw version
    • On Windows by downloading the .exe
    Important:

    If you use the root user, you can remove the sudo before each command.

  2. Update Ubuntu packet manager

    sudo apt-get update
  3. Upgrade the Ubuntu packages already installed

    sudo apt-get upgrade
  4. Import the key for the official MongoDB repository (Ubuntu ensures the authenticity of software packages by verifying that they are signed with GPG keys.)

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
    Executing: /tmp/tmp.68PpBponrV/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)
  5. Add the MongoDB repository details so that Ubuntu’s apt command-line tool will know where to download the packages. Execute the following command to create a list file for MongoDB.

    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
  6. Update the packages list

    sudo apt-get update && sudo apt-get upgrade -y

Installing MongoDB

  1. Install the mongodb-org meta-package, which includes the daemon, configuration and init scripts, shell, and management tools on the server.

    sudo apt-get install mongodb-org
  2. Press enter or type Y to proceed when prompted. Once the installation is completed, we start the MongoDB daemon

    sudo systemctl start mongod
  3. Since systemctl does not provide output, verify that the service has started properly.

    sudo systemctl status mongod
    mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset:
    Active: active (running) since Wed 2018-xx-yy 13:04:39 UTC; 1min 52s ago
    Docs: https://docs.mongodb.org/manual
    Main PID: 25081 (mongod)
    CGroup: /system.slice/mongod.service
    └─25081 /usr/bin/mongod --config /etc/mongod.conf

    Press q to exit.

  4. Ensure that it restarts automatically at each boot

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

Securing MongoDB

The default installation of MongoDB is vulnerable because no authentication is required to interact with the database. Any user could create and destroy databases, as well as read from and write to their contents by default. To secure MongoDB, we need to create an administrative user and enable authentication.

  1. Connect to the Mongo shell to add a new user

    mongo
    MongoDB shell version v3.4.15
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 3.4.15
    Server has startup warnings:
    2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten]
    2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
    2018-06-27T13:04:39.592+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never'
    2018-06-27T13:04:39.706+0000 I CONTROL [initandlisten]

    You can choose any preferred name for the administrative user since the privilege level is assigned from the role of userAdminAnyDatabase.

    The admin database designates where the credentials are stored. You can learn more about authentication in the MongoDB Security Authentication section.

  2. Set the username of your choice and be sure to pick your own secure password and substitute them in the command below:

    use admin
    db.createUser(
    {
    user: "AdminOce",
    pwd: "PWD2018AdminOce",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
    }
    )
    use admin
    switched to db admin
    > db.createUser(
    ... {
    ... user: "AdminOce",
    ... pwd: "PWD2018AdminOce",
    ... roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
    ... }
    ... )
    Successfully added user: {
    "user" : "AdminOce",
    "roles" : [
    {
    "role" : "userAdminAnyDatabase",
    "db" : "admin"
    }
    ]
    }
  3. Type exit and press ENTER or use CTRL+C to leave the client.

    > exit
    bye

Enabling Authentication

In order to enforce authentication, we need to enable authentication and restart the MongoDB daemon.

  1. Open the configuration file

    sudo nano /etc/mongod.conf
  2. In the #security section, remove the hash in front of security to enable the section. Then, we add the authorization lines (indented with two spaces) as per the following excerpt below:

    security:
    authorization: "enabled"
  3. Restart the daemon

    sudo systemctl restart mongod
  4. Check the status to verify that the service has rebooted

    sudo systemctl status mongod
    mongod.service - High-performance, schema-free document-oriented database
    Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: e
    Active: active (running) since Wed 2018-xx-yy 15:36:34 UTC; 2min 16s ago
    Docs: https://docs.mongodb.org/manual
    Main PID: 25593 (mongod)
    CGroup: /system.slice/mongod.service
    └─25593 /usr/bin/mongod --config /etc/mongod.conf

    Press q to exit.

  5. Ensure that the daemon restarts automatically at boot

    sudo systemctl enable mongod

    If we see Active: active (running) in the output and it ends with something similar to the text below, the restart command was successful:

    Jun 27 15:36:34 mongoDB systemd[1]: Started High-performance, schema-free document-oriented database.

Testing Authentication

  1. Connect without credentials to verify that our actions are restricted

    mongo
    MongoDB shell version v3.4.15
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 3.4.15

    We are connected to the test database.

  2. Test that the access is restricted with the show dbs command:

    show dbs
    2018-06-27T15:55:36.481+0000 E QUERY [thread1] Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
    "code" : 13,
    "codeName" : "Unauthorized"
    } :
  3. Exit the shell to proceed

    > exit
    bye

Verifying the Administrative User’s Access

  1. Connect as our administrator with the -u option to supply a username and -p to be prompted for a password. Supply the database where we stored the user’s authentication credentials with the --authenticationDatabase option.

    mongo -u AdminOce -p --authenticationDatabase admin
  2. Once the correct password is entered, we are dropped into the shell, where we can issue the show dbs command:

    MongoDB shell version v3.4.15
    Enter password:
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 3.4.15
    > show dbs
    admin 0.000GB
    local 0.000GB

Type exit or press CTRL+C to exit.

Configuring Remote Access (Optional)

Enabling UFW

Uncomplicated Firewall (UFW), is a front-end to iptables. Its main goal is to make managing your firewall drop-dead simple and to provide an easy-to-use interface.

Note: If UFW is already installed on your computer, go directly to step 5.
  1. Install UFW.

    sudo apt-get install ufw
  2. Check UFW status.

    sudo ufw status
  3. Enable UFW, as it is probably inactive.

    sudo ufw enable
  4. Ensure to allow SSH.

    sudo ufw allow OpenSSH
  5. Rerun the UFW status command.

    sudo ufw status
    Status: active

    To Action From
    -- ------ ----
    OpenSSH ALLOW Anywhere
    OpenSSH (v6) ALLOW Anywhere (v6)
  6. Allow access to the default MongoDB port 27017 but restrict that access to a specific host.

    sudo ufw allow from client_ip_address to any port 27017
  7. Re-run this command using the IP address for each additional client that needs access. To double-check the rule, run ufw status again:

    sudo ufw status
    To                         Action      From
    -- ------ ----
    OpenSSH ALLOW Anywhere
    27017 ALLOW client_ip_address
    OpenSSH (v6) ALLOW Anywhere (v6)

Configuring a Public bindIP

  1. To allow remote connections, add our host’s publically-routable IP address to the mongod.conf file.

    sudo nano /etc/mongod.conf
  2. In the net section, add the MongoHost’s IP to the bindIp line

    Note:

    Verify your private IP with the ifconfig command.

    net:
    port: 27017
    bindIp: 127.0.0.1,IP_of_MongoHost
  3. Restart the daemon

    systemctl restart mongod
  4. Check the daemon status

    systemctl status mongod
    Active: active (running) since Thu 2018-xx-yy 13:15:35 UTC; 5s ago

Testing the Remote Connections

Ensure that Mongo is listening on its public interface by adding the --host flag with the IP address from the mongodb.conf file.

mongo -u AdminOce -p --authenticationDatabase admin --host IP_address_of_MongoHost
MongoDB shell version v3.4.15
Enter password:
connecting to: mongodb://10.15.124.17:27017/
MongoDB server version: 3.4.15

Uninstalling MongoDB

Important:

This process will completely remove MongoDB, its configuration, and all databases. This process is not reversible, so ensure that all of your configuration and data is backed up before proceeding.

  1. Stop MongoDB.

    sudo service mongod stop
  2. Remove any MongoDB packages that you had previously installed.

    sudo apt-get purge mongodb-org*
  3. Remove MongoDB databases and log files.

    sudo rm -r /var/log/mongodb
    sudo rm -r /var/lib/mongodb