6 keys to MongoDB database security

6 keys to MongoDB database security

Data is a company’s lifeblood so keeping a database secure remains a top enterprise priority. In fact, data breaches show no sign of abating according to researchers on the matter ...The following article will introduce you to 6 keys to secure MongoDB database...

Data is a company’s lifeblood so keeping a database secure remains a top enterprise priority. In fact, data breaches show no sign of abating according to researchers on the matter ...The following article will introduce you to 6 keys to secure MongoDB database...

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
[[email protected] ~]# grep security -A2 /etc/mongod.conf
security:
  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
[[email protected] ~]# mkdir /data/key
[[email protected] ~]# openssl rand -base64 32 > /data/key/mongodb.key
[[email protected] ~]# chmod 600 /data/key/mongodb.key

Now start Percona Server for MongoDB:

[[email protected] ~]# 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
net:
 port: 27017
 ssl:
 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:

db.createRole({
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.

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:

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

MongoDB loves a firewall

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):
Shell
# mkdir -p /etc/sasl2
# echo 'pwcheck_method: saslauthd
saslauthd_path: /var/run/saslauthd/mux
log_level: 5
mech_list: plain' > /etc/sasl2/mongod.conf

  1. 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:
setParameter:
   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')
1
> 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:

auditLog:
   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.

====================================================================

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB - Part 3/3

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB

What you’ll learn

  • Work with MongoDB with Clarity and Confidence
  • Use 4 tools MongoCHEF, NOSQL Manager, RoboMongo, MongoBooster easily
  • Do Regex, GridFS , Replication , Sharding, Full text search
  • Basic and Advanced CRUD operations using MongoDB
  • Import and Export data from MongoDB
  • Work MapReduce, Embedded Documents,Save&Insert , indexing, capped collections, TTL
  • Bonus section * Use java,C#,PHP,Nodejs to access MongoDB features like CRUD, GridFS
  • Bonus Section * A 50 minutes MongoDB key feature exercises
  • 100+ Quizzes 40+ Activities

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

MongoDB - The Complete Developer’s Guide

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

Build a CRUD Operation using PHP & MongoBD

MongoDB with Python Crash Course - Tutorial for Beginners

Learn NoSQL Databases from Scratch - Complete MongoDB Bootcamp 2019

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Creating RESTful APIs with NodeJS and MongoDB Tutorial

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB - Part 1/3

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB

What you’ll learn

  • Work with MongoDB with Clarity and Confidence
  • Use 4 tools MongoCHEF, NOSQL Manager, RoboMongo, MongoBooster easily
  • Do Regex, GridFS , Replication , Sharding, Full text search
  • Basic and Advanced CRUD operations using MongoDB
  • Import and Export data from MongoDB
  • Work MapReduce, Embedded Documents,Save&Insert , indexing, capped collections, TTL
  • Bonus section * Use java,C#,PHP,Nodejs to access MongoDB features like CRUD, GridFS
  • Bonus Section * A 50 minutes MongoDB key feature exercises
  • 100+ Quizzes 40+ Activities


Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

MongoDB - The Complete Developer’s Guide

Building A REST API With MongoDB, Mongoose, And Node.js

Node.js, ExpressJs, MongoDB and Vue.js (MEVN Stack) Application Tutorial

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

MongoDB with Python Crash Course - Tutorial for Beginners

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB - Part 2/3

Learn MongoDB - MongoDB Tutorial for Beginners - Getting Started with MongoDB


What you’ll learn

  • Work with MongoDB with Clarity and Confidence
  • Use 4 tools MongoCHEF, NOSQL Manager, RoboMongo, MongoBooster easily
  • Do Regex, GridFS , Replication , Sharding, Full text search
  • Basic and Advanced CRUD operations using MongoDB
  • Import and Export data from MongoDB
  • Work MapReduce, Embedded Documents,Save&Insert , indexing, capped collections, TTL
  • Bonus section * Use java,C#,PHP,Nodejs to access MongoDB features like CRUD, GridFS
  • Bonus Section * A 50 minutes MongoDB key feature exercises
  • 100+ Quizzes 40+ Activities

Learn More

MongoDB - The Complete Developer’s Guide

The Complete Developers Guide to MongoDB

MongoDB - The Complete Developer’s Guide

Learn MongoDB : Leading NoSQL Database from scratch

Learn NoSQL Databases - Complete MongoDB Bootcamp 2019

Why We Moved From NoSQL MongoDB to PostgreSQL?

How to build GraphQL APIs with Kotlin, Spring Boot, and MongoDB?

Build a CRUD Operation using PHP & MongoBD

MongoDB with Python Crash Course - Tutorial for Beginners

Learn NoSQL Databases from Scratch - Complete MongoDB Bootcamp 2019