How to Take Control of Your MongoDB Security

Published:27 January 2022 - 5 min. read

Nicholas Xuan Nguyen Image

Nicholas Xuan Nguyen

Read more tutorials by Nicholas Xuan Nguyen!

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Hackers are becoming more sophisticated, and they know how to exploit vulnerabilities. If you have sensitive data in your MongoDB database, it’s crucial to take security seriously. But how? Worry not! This tutorial has got you covered!

In this tutorial, you’ll learn to protect your MongoDB databases and ward off hackers by setting up security measures.

Read on and start taking control of your MongoDB security!

Prerequisites

  • This tutorial will be a hands-on demonstration. To follow along, be sure you have the following:
  • A non-root user with sudo privileges.

Creating a Dedicated Administrative User

MongoDB does not have any built-in authentication system. By default, anyone with access to the database has full administrative privileges — too dangerous! How to secure your database? You’ll create a user with administrative privileges and lock down the databases to that administrative user.

This setup allows you to provide a single point of user access with administrative privileges while restricting what each user can do within the database. For example, developers should have read-only access to databases, while administrators can create and edit data.

1. Open your terminal and run the mongo command below without any arguments. This command lets you connect to your MongoDB shell as the default admin user.

This admin user is powerful as it has full read/write access to all databases on the server, and it’s best to avoid using this user for day-to-day work.

mongo

You will get a warning that says Access control is not enabled…., as shown below.

This warning indicates that anyone who can access the MongoDB server can perform the actions they want with the databases. These actions include but are not limited to deleting, dropping, updating databases.

This warning shows up is because you haven’t enabled access control yet. Don’t worry about it, for now. You’ll learn how to enable access control in the following section.

Connecting to your MongoDB shell
Connecting to your MongoDB shell

2. Next, run the show dbs command to show all databases on the server, including the admin databases that a normal user isn’t supposed to see.

show dbs
Showing all databases on the server
Showing all databases on the server

3. Run the use admin command below to switch to the admin database since your focus is on creating a dedicated administrative user. This command changes your current database context to use the admin database, as shown below.

MongoDB uses the admin database to store access control rules and provide built-in authentication, usernames, and password for users and their roles. You can’t delete or rename the admin database because it’s essential to the database’s functionality.

use admin
Switching to the admin database
Switching to the admin database

4. Now, copy and paste the code below to the mongo shell and hit Enter. This code creates a user called AdminATA, with a password of LDWbPf6Fy9Ezs3Mv, but you can use different credentials as you prefer.

This new user has read/write (readWriteAnyDatabase) access to all databases and admin access to all collections. But this user has no drop/delete database privileges and can’t drop or change privileges of other users.

After running the command and you get an error, recheck your code and try again.

# The db.createUser() method creates a new user on the current database, with the privileges specified by roles.
db.createUser(
{
# Specifying the username AdminATA, but you can enter whatever username you like
user: "AdminATA",
# The passwordPrompt() method is a universal helper function 
# that tells the MongoDB shell to prompt you for a password for the AdminATA user.
pwd: passwordPrompt(),
# Specifying  the roles you want your AdminATA user to have.
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)

5. Provide a secure password when prompted, as shown below, and press Enter.

Providing a secure password
Providing a secure password

Below, you can see a Successfully added user message. This output confirms that you successfully created a user with administrative privileges and restricted them to the least privileges required.

At this point, you already have an administrative user called AdminATA that can do everything you need on the database without giving access to everyone.

Verifying Successful Admin User Creation in MongoDB
Verifying Successful Admin User Creation in MongoDB

6. Finally, run the exit command to leave the mongo shell.

exit
Leaving the mongo shell
Leaving the mongo shell

Adding Security by Enabling Authentication

Now that you have an administrative user, you’ll add another layer of security by enabling authentication. Doing so gives database access to users with the correct credentials only.

Authentication refers to the process of validating a connection, typically by providing a username and password or using an authentication token. Authentication ensures that you are who you say you are and not an imposter trying to access resources.

1. Enable authentication by editing the MongoDB configuration file with the following, and save the changes:

  • Open the /etc/mongod.conf file in your favorite text editor. The /etc/mongod.conf file contains configuration of your MongoDB cluster.
  • Look for and uncomment the #security directive by removing the # symbol in front of the directive, as shown below. This directive tells MongoDB to look for the security setting in the configuration file.
  • Add a new line below the security directive that says authorization: enabled. Note that the authorization: enabled line is indented (has two spaces at the beginning), as shown below.
Adding the authorization parameter
Adding the authorization parameter

2. Next, run the following systemctl command to restart the MongoDB server for the changes to take effect.

sudo systemctl restart mongod

3. Finally, run the below command to view the status of your MongoDB service.

sudo systemctl status mongod

Below, you can see a line that says Active: active (running) in green text, which indicates your MongoDB server is running and ready to accept connections.

Viewing MongoDB Service Status
Viewing MongoDB Service Status

Testing if Authentication Works

You’ve just enabled authentication, but how do you know it works? You’ll log in to the administrative user to test and ensure your authentication works by viewing databases.

1. Run the following commands to access the mongo shell as you did in the “Creating a Dedicated Administrative User” section (step one).

mongo

As you can see below, you no longer receive the Access control is not enabled… warning about enabling authentication. Instead, you’ll get a message that tells you the version of your MongoDB server and MongoDB shell.

Connecting to the MongoDB Shell
Connecting to the MongoDB Shell

2. Next, rerun the show dbs command to check if you can still access the database.

show dbs

The command should show you all databases, even the admin database. But as you see below, nothing shows up. Why? Viewing the list of databases is a privilege reserved for administrative users only.

You haven’t authenticated your mongo shell to use the Admin role, so you’re not authorized to view the list of databases.

Listing All Databases (empty)
Listing All Databases (empty)

With authentication enabled, the connection will fail if someone tries to access the database using a connection string that doesn’t contain the correct credentials.

Authenticating connection strings is a core part of MongoDB security, and you should implement authentication at all layers of the application. All connections to MongoDB must use an authentication string consisting of credentials. These credentials include the correct username and password.

3. Run the exit command to exit from the MongoDB shell.

exit

4. Now, run the command below to log in to the MongoDB shell with your newly-created administrative user’s username (-u) and password (-p). Replace AdminATA with the username you created in the “Creating a Dedicated Administrative User” section (step four).

The --authenticationDatabase parameter tells the MongoDB shell to authenticate against the admin database.

mongo -u AdminATA -p --authenticationDatabase admin

5. Provide your password for your administrative user when prompted.

Providing administrative password
logging into the MongoDB shell as an administrator
logging into the MongoDB shell as an administrator

6. Finally, rerun the show dbs command to try and see if you can view all databases.

show dbs

This time, as you see below, the list of databases shows up since you’re an admin user.

Listing all databases as admin user
Listing all databases as admin user

Conclusion

In this tutorial, you learned how to connect to create an administrative user and enable authentication. You’ve learned to take control of your MongoDB security and put restrictions on who can access databases on your server.

At this point, you get to decide whether who can access what. So what’s next for you? Perhaps learn how to use a MongoDB container securely?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!