Learn How to Secure MongoDB Community Version using Authentication Part 1

Introduction

Part one of this tutorial will discuss the fundamental security features built into MongoDB for use when performing MongoDB authentication. This tutorial will also cover the basic differences between authorization and authentication and how the localhost exception allows administrators to enable access control.

Prerequisite

  • A properly working MongoDB installation.
    NOTE: Neither LDAP and KERBEROS will be covered in this tutorial as both were only available in the Enterprise version of MongoDB.

    What are Authorization and Authentication

    “Authentication” and “authorization” are two common points of confusion as these two terms are commonly, but incorrectly, used interchangeably. However, the two terms actually have very different meanings:
    Authentication is defined as the process by which the identity of the user is verified.
    Authorization is defined as the process by which the privileges of a user are verified.
    A user can be authenticated and granted access to the system while authorization determines what particular resources the user can access in that system. In other words, authentication means, “Who are you?” whereas authorization means, “What access permissions do you have?”

Authentication

Now that the definition of authentication is clear, this tutorial will discuss the various MongoDB supported authentication mechanisms.

Authentication mechanism categories.

MongoDB authentication mechanisms can be grouped into the following two categories:

  1. Client authentication and user authentication
    • This authentication deals with how clients of the database are authenticated to MongoDB.
  2. Internal authentication
    • This is how different replica sets or sharded-cluster authentication interact with one another.
      Table1.
      Client/User AuthInternal AuthMongoDB Version
      SCRAM-SHA-1Keyfile(SRAM-SHA-1)Community
      MONGODB-CRX.509Community
      LDAPEnterprise
      KERBEROSEnterprise
      NOTE: In version 4.X, MongoDB removed support for the deprecated MongoDB Challenge-Response (MONGODB-CR) authentication mechanism.
      The above table displays the different kinds of MongoDB supported authentication mechanisms. Notice that that the LDAP and KERBEROS are both available only in the Enterprise version. Additionally, the SCRAM-SHA-1 and MONGODB-CR (deprecated in 4.x) are considered challenge and response mechanisms, while the X.509 is a certificate-based authentication mechanism and LDAP and Kerberos falls under external mechanisms.

Learning Authentication Mechanisms

Understanding SCRAM-SHA-1

SCRAM-SHA-1 (Salted Challenge Response Authentication Mechanism – Secure Hash Algorithm 1) is one of the mechanisms responsible for authenticating a client or user in MongoDB. SCRAM-SHA-1 is an IETFSInternet Engineering Task Force Standard that defines the best practices and methods for the enforcement of the challenge and response mechanism for authenticating users with passwords.
SCRAM-SHA-1 offers protection from the following types of attacks:

  1. Eavesdropping – A hacker taps into a network and just silently listens, capturing all of the traffic exchanges between the client and the server. In order to protect against this threat clients are not permitted to send a plain-text password over the network.

  2. Replay/Playback – This type of attack is a delayed and repeated data transmission. It is designed to fool those involved with the data transmission into believing the transmission of their data has been successful. This attack is mitigated by making each authentication session unique, using random notifications to make messages valid for only a single session.

  3. Database Compromise – This type of attack grants a hacker database access to read the server’s persistent memory. This attack is mitigated by SCRAM-SHA-1 through salting and iteratively hashing the passwords before storing them.

It is worth mentioning the MONGODB-CR authentication mechanism used a username and password authentication mechanism. However, this mechanism is effectively replaced by SCRAM-SHA-1 in MongoDB version 3.0 and fully removed in version 4.0. Upgrading to a SCRAM-SHA-1-supported version is highly recommended should MONGODB-CR be encountered during production.

What is X.509 Authentication Mechanism?

The X.509 certificate is a digital certificate that utilizes the widely accepted international X.509 public key infrastructure, also known as PKI standard, to validate that a certain public key belongs to the user, computer or some kind of service identity enclosed within the certificate. In the case of MongoDB, X.509 client authentication permits clients to authenticate to servers via certificates instead of using a username and password.

NOTE: X.509 requires a TLS, (Transport Layer Security) connection or MongoDB version 3.2.x or greater. In these cases the MongoDB version is already compiled with TLS support.

Keyfile Authentication

The Keyfile authentication utilizes both SCRAM-SHA-1 and X.509 authentication. The contents of the Keyfile acts as shared password among the member of the replica set or sharded cluster. In keyfile authentication, every instances of mongod in the replica set will use the contents of the keyfile as the shared password for authenticating the other members within the deployment. Note that only instances of mongod having the correct keyfile can join the replica set.

Keyfile’s content must be between six and 1024 characters in length and may only contain a B64 character set. Additionally, it is important to remember that whenever the internal authentication is enabled via X.509 or keyfile it will automatically enable the client authentication.

NOTE: While the same certificate can be used for all members, it is recommended that each member be provided with a different certificate. This allows for deploying just one certificate, rather than having to update the entire cluster should one of the certificates become compromised.

The Localhost exception

Perform a test to see how the various types of MongoDB supported authentication mechanisms work via Mongo shell and the Mongo server by starting MongoDB with the following command:

mongod --auth --port 27017 --dbpath /data/db

The server will display something like the following:
NOTE: Some of the texts was removed from the below results. Notice the result says 2019-06-26T19:29:05.674+0800 I NETWORK [initandlisten] waiting for connections on port 27017

2019-06-26T19:29:05.492+0800 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost.  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server.  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten] ** Start the server with --bind_ip to specify which IP  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning.  
2019-06-26T19:29:05.493+0800 I CONTROL [initandlisten]  
2019-06-26T19:29:05.644+0800 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'  
2019-06-26T19:29:05.674+0800 I NETWORK [initandlisten] waiting for connections on port 27017

Starting the MongoDB in this manner enables the authorization protocols, thus requiring clients to authenticate to the server before they can perform any actions on the database. Below is an example of a basic command in the Mongo Shell performed by an unauthenticated user:

> show users  
2019-06-26T19:45:47.586+0800 E QUERY [js] Error: command usersInfo requires authentication:  
_getErrorWithCode@src/mongo/shell/utils.js:25:13  
DB.prototype.getUsers@src/mongo/shell/db.js:1763:1  
shellHelper.show@src/mongo/shell/utils.js:859:9  
shellHelper@src/mongo/shell/utils.js:766:15  
@(shellhelp2):1:1

In the above result, notice the error 2019-06-26T19:45:47.586+0800 E QUERY [js] Error: command usersInfo requires authentication:
The localhost exception allows administrators to enable access control and then create the first user in the system. With the localhost exception, after enabling access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. The Localhost Exception enables the user to initiate access control and creates the first user in the system with the privilege to create other users as well. Execute the following command to preform this function.

NOTE: Select the admin database by using the command — use admin as follows:

>use admin  
db.createUser(  
{  
user: "UserAdminName",  
pwd: "replaceWithStrongPassword",  
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]  
}  
)

The local host exception applies when the user is connected to the database via the local host interface or on the same physical computer. Now authenticate the new user with the following command:

mongo --port 27017 -u "UserAdminName" --authenticationDatabase "admin" -p

This will require the password, in this case replaceWithStrongPassword.
Once authenticated, execute the following commands in sequence:

use admin
db.system.users.find()

The results should resemble the following:

{ "_id" : "admin.rommel", "userId" : UUID("d45d4fb6-b7f3-4749-888e-a9251a89c592"), "user" : "UserAdminName", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "mw+OhsQyade4FI5LMlweWg==", "storedKey" : "cwsxp8LZEpcmRS9mHV33pNkkX2I=", "serverKey" : "RZZAzftEBlUONMgJ3Ymjk85IIPc=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "PFwwWms5+FWUoDmRFGXasISg7vRWSMZJiBO57w==", "storedKey" : "vevwsomL+cSakyXfE7YSeNF67DczaOYmk1xfM9P6T6g=", "serverKey" : "f+q6uFbnwRNR+oeKQir0D+p8XM7a1Q3LO/FBIFMGy3U=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" }, { "role" : "readWriteAnyDatabase", "db" : "admin" } ] }

The above results shows the user details.

Authentication Methods

This section will discuss the different authentication methods supported by MongoDB, with “methods” referring to the different ways authentication can be performed directly with the MongoDB database. MongoDB supports two variations of authentication methods. The first is using the Command Line.

Command Line Authentication MethodAs the user was created against the admin database, proper authenticate is perfomed with the following command:

mongo admin -u UseUserAdminName -p replaceWithStrongPassword

This tells MongoDB to connect directly to the admin database using the username and password credentials instead of the default database, which is test.

Mongo Shell Authentication Method

Authentication can also be performed via Mongo Shell with the other MongoDB supported authentication method using the db.auth in the Mongo Shell. Perform this function with the following command:

mongo -u UseUserAdminName -p replaceWithStrongPassword

NOTE: -u flag is for username and -p flag is for the password
Notice that as no parameters were specified the system uses the default test database. As connection to the admin database is needed, switch to the admin database by entering useadmin and then run the following command:

db.auth('UseUserAdminName','replaceWithStrongPassword')

The above command will result in “1” being returned, confirming authentication with the admin database was successful.

Conclusion

Part one of this tutorial explained the supported MongoDB Authentication mechanism and methods. Part two in this series will discuss how to enable and configure these authentication mechanisms. Be sure to have a sold grasp on the examples in part one of “Learn How to Secure MongoDB Community Version using Authentication” before moving on to part two.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.