6 keys to MongoDB database security

Don’t be the next MongoDB data breach. Close these holes in your MongoDB deployment before it’s too late

6 keys to MongoDB database security

Security is a trending topic again, thanks to recent data leaks involving big corporations. For example, as reported by ZDNet, Chinese companies have leaked an astonishing 590 million resumes. Most of the resume leaks occurred because of poorly secured databases, which were left exposed online without a password or ended up online following unexpected firewall errors. Of the eight hacks mentioned in the article, only one was related to MongoDB, but that breach accounted for around one-third of the documents exposed.

In another reported case, an Indian government agency left details of millions of pregnant women exposed online. The exposed data contained detailed information about the patients, doctors, and medical centers. At the time this article was written, the MongoDB database was still exposed online without a password. The good news is that the medical records have been removed from the database.

Because of its NoSQL origin and document architecture design, MongoDB is much more flexible and scalable than SQL databases. As a result, typically much more data is stored in MongoDB than in traditional SQL databases, with MongoDB databases commonly exceeding a terabyte of data. The large amount of data that can be exposed in a single database makes breaches involving MongoDB much more devastating.

The good news is that much has been done to improve MongoDB security in the years since the product was launched in 2009. All of the breaches mentioned above could have been avoided with some simple actions.

What does MongoDB offer to mitigate security threats? Let’s explore a few areas and proposed solutions, as well as what the future holds for MongoDB.

Data encryption in MongoDB

One of the most serious problems with MongoDB was that data files didn’t have encryption at rest. Percona Server for MongoDB, since version 3.6.8, offers at-rest encryption for the MongoDB Community Edition. In upstream MongoDB software, data encryption at rest is available in MongoDB Enterprise only.

The example below shows how to activate WiredTiger encryption for data at rest in Percona Server for MongoDB. First, it is necessary to edit the encryption options in mongod.conf:

# Encryption variables in mongod.conf shell
[root@app ~]# grep security -A2 /etc/mongod.conf
  enableEncryption: true
  encryptionKeyFile: /data/key/mongodb.key

By default, Percona Server for MongoDB uses the AES256-CBC cipher mode. It is necessary to create the key with OpenSSL as below:

# Create Encryption KeyShell
[root@app ~]# mkdir /data/key
[root@app ~]# openssl rand -base64 32 > /data/key/mongodb.key
[root@app ~]# chmod 600 /data/key/mongodb.key

Now start Percona Server for MongoDB:

[root@app ~]# systemctl start mongod

To check whether encryption is successfully enabled in the database, use the command below:

# Security outputShell
mongo > db.serverCmdLineOpts().parsed.security
{ "enableEncryption" : true, "encryptionKeyFile" : "/data/key/mongodb.key" }

Transport encryption in MongoDB

MongoDB has support for using transport encryption between the client and the nodes, as well as between the nodes in the cluster. Encrypting traffic ensures that no one can “sniff” sensitive data on the network. For example, tools like Wireshark or Tcpdump can easily capture unencrypted sensitive data such as user names and passwords.

MongoDB supports X.509 certificate authentication for use with a secure TLS/SSL connection. The members can use X.509 certificates to verify their membership of the replica set.

In order to use encryption, it is necessary to create certificates on all of the nodes and have a certificate authority (CA) that signs them. Because using a certificate authority can be quite costly, it is also possible to use self-signed certificates. Using a public CA is not necessary inside a private infrastructure.

To set up the SSL, it is necessary to modify the configuration file:

# /etc/mongod.conf
 port: 27017
 mode: <disabled|allowSSL|preferSSL|requireSSL>
 PEMKeyFile: /etc/ssl/mongo

Authorization in MongoDB

Enabling access control on a MongoDB deployment enforces authentication, requiring users to identify themselves. When accessing a MongoDB deployment that has access control enabled, users can perform only those actions determined by their roles. Also, replica sets and sharded clusters require internal authentication between members when access control is enabled. It is important to follow the principle of least privilege. No one should be given more permissions than they need to do their job, and even a DBA should log in with a non-elevated account.

MongoDB grants access to data and commands through role-based authorization and includes built-in roles that provide the different levels of access commonly needed in a database system. Additionally, it is possible to create user-defined roles.

To create a role in MongoDB and add it to a user:

role : 'write_foo2_Collection',
privileges : [ {resource : {db : "percona", collection : "foo2"}, actions : ["insert","remove"]}
roles : ["read"]

db.updateUser('client_read', roles : ['write_foo2_Collection'])

Authentication in MongoDB

Most breaches involving MongoDB occur because authentication is disabled by default. MongoDB provides support for authentication on a per-database level. Users exist in the context of a single logical database. However, MongoDB does not support items like password complexity, age-based rotation, and centralization and identification of user roles versus service functions.

Thankfully, LDAP can be used to fill many of these gaps. Many connectors allow the use of Windows Active Directory (AD) systems to talk with LDAP.

LDAP support is available in MongoDB Enterprise but not MongoDB Community Edition. However, it is available in other open source versions of MongoDB, such as Percona Server for MongoDB.

In order to set up LDAP authentication in Percona Server for MongoDB, take the following steps:

1. Configure the mongod.conf file into the /etc/sasl2 folder (as root):

# mkdir -p /etc/sasl2
# echo 'pwcheck_method: saslauthd
saslauthd_path: /var/run/saslauthd/mux
log_level: 5
mech_list: plain' > /etc/sasl2/mongod.conf

2. Edit mongod.conf, or add startup parameters, in order to use the sasauthd library to validate the users and passwords. If using a configuration file:

   authenticationMechanisms: PLAIN,SCRAM-SHA-1

If using startup parameters:

--setParameter authenticationMechanisms=PLAIN,SCRAM-SHA-1

Create the first user as root. Considering the process is up and running, it is necessary to create an administrator user. For this example, a user called admin with a root role will be created (meaning this user can perform any operation in the database):

mongo > use admin
mongo > db.createUser({user : 'admin', pwd: '1234', roles :['root']})

Create the standard user using LDAP authentication. There is no password saved on the admin database when the next operation is performed. The following command creates a user based on LDAP, and the password verification is performed outside of the database. The Cyrus library either answers OK or NOK for the validation, and the authorization document (roles) is still managed by the database:

use admin
> db.auth('admin','1234')
> db.getSiblingDB("$external").createUser({
user : 'support1',
roles: [ {role : "read", db: 'percona'} ]
Successfully added user: {
"user" : "support1",
"roles" : [
    "role" : "read",
    "db" : "percona"

Auditing in MongoDB

Auditing is not designed to mitigate a security threat, but helps when investigating unauthorized access or tracking data access and modification. The general database auditing concept is about tracking the use of database records and authority. When a database is audited, each operation on the data can be monitored and logged to an audit trail, including information about which database object or data record was touched, which account performed the action, and when the activity occurred.

MongoDB Atlas offers audit logging natively, and Percona Server for MongoDB extends this feature to the MongoDB Community Edition. To enable the audit log in Percona Server for MongoDB in the command line or the config file, add these entries in the command line:

mongod --dbpath /var/lib/mongodb --auditDestination file --auditFormat BSON --auditPath /var/lib/mongodb/auditLog.bson

Or in the MongoDB configuration file:

   destination: file
   format: BSON
   path: /var/lib/mongodb/auditLog.bson

MongoDB loves a firewall

It is imperative to put any database server behind a firewall, especially if it contains personally identifiable information (PII) or protected health information (PHI). Using default ports, allowing anonymous log-ins, and exposing the database to the Internet create a perfect storm of vulnerability. Firewalls are the first line of defense, especially when running MongoDB in a public cloud.

Finally, it's worth mentioning that MongoDB recently hired its first-ever chief information security officer, Lena Smart, which bodes well for the future of MongoDB security. A 20-year cybersecurity veteran with an impressive résumé, Smart most recently served as global chief information security officer for international fintech company Tradeweb. We can expect MongoDB security will continue to improve.

Vinicius Grippa serves as support engineer for MongoDB and MySQL at Percona, a provider of enterprise-class MySQL, MongoDB, and PostgreSQL solutions and services.

New Tech Forum provides a venue to explore and discuss emerging enterprise technology in unprecedented depth and breadth. The selection is subjective, based on our pick of the technologies we believe to be important and of greatest interest to InfoWorld readers. InfoWorld does not accept marketing collateral for publication and reserves the right to edit all contributed content. Send all inquiries to newtechforum@infoworld.com.

Copyright © 2019 IDG Communications, Inc.