Whether we like it or not, non-relational open source databases constitute a significant part of the existing ecosystem of data storage tools that are widely used in both small and large Web projects. It is likely that some of you have had to deal with MongoDB in production. The ability to protect the database from external encroachment is a necessary skill for successful operation. We will discuss this and many other issues on PG Day'17 in the open database section . In the meantime, we are pleased to provide you with a translation of an interesting MongoDB security overview publication.
MongoDB has everything you need to keep your data safe. We will talk about what you may need and how to customize it.
')
Security MongoDB again in the news. More recently, the media flooded stories telling how
hackers captured MongoDB databases and demanded a ransom in bitcoins . Tens of thousands of MongoDB installations have been compromised,
according to Rapid7 .
We all worry about security. If you support applications, networks or databases, ensuring security is always of paramount importance. As many companies switch to open source software, such as MongoDB, to store important corporate data, the issue of security becomes even more pressing. Depending on your business, you may also have different government (such as the Health Insurance Portability and Accountability Act, Health Insurance Portability and Accountability Act, HIPAA) or business (Payment Card Industry Data Security Standard, or PCI DSS) network standards. security that you must obey.
Is MongoDB database software safe? Does it meet these standards? The short answer is: yes, safe, and yes, appropriate! You just need to know how to configure, configure, and work with your particular installation.
In this article I will talk about the security of MongoDB. MongoDB is safe to use if you know what to look for and how to configure it.
First, let's look at what mistakes people make when working with MongoDB in terms of security. There are a few key points that users stumble on when it comes to MongoDB security:
- use the ports specified by default;
- do not include authentication right away (the most serious problem!);
- when using authentication, give everyone and everyone broad access;
- Do not use LDAP to force passwords;
- Do not insist on using SSL in the database;
- Do not restrict database access for known network devices (application hosts, load balancers, etc.);
- they do not restrict which interfaces are listening on connections (although this clause no longer affects any of the supported versions).
MongoDB has five main security zones:- Authentication. LDAP authentication centralizes items in your company directory.
- Authorization Authorization determines what access rights the database provides depending on the role of the user.
- Encryption. Encryption can be divided into At-Rest and In-Transit. It is critical to the security of MongoDB.
- Audit Auditing involves the ability to see who did what in the database.
- Control. Management involves checking documents and sensitive data (such as an account number, password, social security number, or date of birth). This concerns both the knowledge of where confidential data is stored and the prevention of their entry into the system.
LDAP AuthenticationMongoDB has built-in user roles that are disabled by default. However, it lacks such elements as password complexity, rotation by age, as well as centralization and identification of user roles with a different set of available functionality. This is important for passing regulatory checks, such as
PCI DSS compliance . For example, PCI DSS prohibits the use of old and easily cracked passwords and requires a change in user access with each change of status (for example, when a user leaves a department or company).
Fortunately, you can use LDAP to fill most of these spaces. Many connectors allow you to use Windows Active Directory (AD) to interact with LDAP.
Note : LDAP support is available only in MongoDB Enterprise. It is not in the Community version. But it is available in other open source versions of MongoDB, such as Percona Server for MongoDB.
MongoDB 3.2 stores users in LDAP, but not their roles (they are now stored on individual machines). MongoDB 3.4 Enterprise
should provide the ability to store roles in LDAP for centralized access. (We will discuss the roles later).

Fig. 1. Steps in SASL (Simple Authentication and Security Layer) authentication.
Using
LDAP and
AD , you can associate users with your corporate directory. When they change roles or leave the company, HR staff can remove them from the group in your database. Thus, you have an automated system that ensures that only those who you want to give access to work with data manually will receive it, and nothing will be accidentally lost.
Working with LDAP in Mongo is quite simple. MongoDB has a special command that tells it to check the external LDAP database:
$ external .
Here are a couple of cautions on using LDAP:
- Create a user using .createUser , as usual, but be sure to add db / collection resource tags.
- In addition, two more fields are required for LDAP authentication:
- mechanism: “PLAIN”
- digestPassword: false
User rolesRole-based access control (RBAC) is at the core of MongoDB. Embedded roles have been available since version 2.6. You can create your own roles by writing down exactly what actions a specific user is allowed to perform. This functionality is embedded in the MongoDB kernel, and it is available in almost any commercial version of open source software.
The five main built-in roles in MongoDB that you should know:
- read :
- read access, usually given to most users;
- readWrite :
- readWrite access allows you to edit data;
- readWrite includes read rights;
- dbOwner :
- Enable readWrite, dbAdmin, userAdmin (for database). userAdmin means adding and deleting users, issuing user rights and creating roles. These rights are assigned to only one specific database server;
- dbAdminAnyDatabase :
- creates dbAdmin on all databases, but does not allow administering users (for example, create and delete them). You can create indexes, call data compression procedures, and more. Separate access is not available here;
- root :
- This is a superuser, but with restrictions.
- he can perform most actions, but not all:
- cannot change the system collection;
- Some commands for this role are not available depending on the version. For example, the root role in MongoDB 3.2 does not allow changing the oplog or profiler size, and in MongoDB 3.4 it doesn’t read current views.
Wildcard databases and collectionsWildcard means providing access to large groups of databases or collections (or both) on the server. By setting the value to null, you can specify all databases or collections at once, and avoid the
dbAdminAnyDatabase role. This allows elected users to have all rights, including administrator functions.
Is it dangerous.
Using a wildcard, you give out a lot of special rights and you should know that you open the following possible ways to attack:
- readWriteAnyDatabase rights are very extensive and open user names and their roles for potential attacks through the application user;
- using a template means that you do not limit specific applications to specific databases;
- wildcard prevent you from using multi-tenancy with multiple databases;
- Access to new databases is not automatically granted.
Creating a custom roleThe power of roles in MongoDB is the ability to create your own roles. In a custom role, you can specify that any action on any resource can be specified for a specific user. With this level of detail, you can deeply control who can do what in your MongoDB environment.
When it comes to setting a custom role, there are four different types of resources:
- db . Indicates a database. You can use a string for a name or “” for “any” (no patterns).
- collection . Specifies a set of documents. You can use a string for a name or “” for “any” (no patterns).
- cluster . Specifies a shaded cluster or other metadata sources. It is a boolean true / false value.
- anyResource . Means access to everything, everywhere. It is a boolean true / false value.
Any role can inherit the properties of another role. There is an array called “roles”, and you can add a new role to it. She inherits the properties of the specified role.
Use
createRole to add a role to an array.
You can add new or existing databases to a user or role. For example, you can add read / write access to the database by attaching this database to a role.
Use the
grantPrivilegesToRole command to add new resources to an existing role.
Below is an example of creating a new super user role. Again, this role is necessary in order to have one user in MongoDB without any restrictions (in case of an unforeseen situation).
db = db.geSiblingDB(“admin”); db.createRole({ role: “superRoot”, privileges:[{ resource: {anyResource:true}, actions: ['anyAction'] }] roles:[] }); db.createUser({ user: “comanyDBA”, pwd: “EWqeeFpUt9*8zq”, roles: [“superRoot”] })
These commands create a new role in the
geSiblingDB database called
superRoot and assign any resource and action to this role. Then we create a new
companyDBA user (with password) in the same database and assign him a new role
superRoot .
Using SSL for everythingSSL helps keep your data safe on unsecured networks. If you work with a database that interacts with the Internet, you need to use SSL.
There are two very good reasons to use SSL to protect MongoDB: privacy and authentication. Without SSL, your data can be accessed, copied and used for illegal or malicious purposes. With authentication, you have an extra level of security. The SSL Private Key Infrastructure (PKI) ensures that only users with the correct CA certificate can access MongoDB.
SSL support has been around for quite some time in MongoDB, but has been significantly improved in recent versions. Previously, if you wanted to use SSL, you had to download it and manually compile it with the MongoDB Community version. Starting with MongoDB 3.0, SSL is compiled with default software.
In legacy versions of MongoDB, there was also no host validation check; it was just a flag that you could check in the configuration file that satisfies the SSL request from the connection.
The latest versions of SSL in MongoDB include the following key features:
- verification of the correctness of the host (optional);
- the ability to specify a specific setup .key to use;
- Custom Certificate Authority (CA) for self-signed certificates and alternate subscribers;
- allowSSL , preferSSL , requireSSL modes that allow you to select the details for your SSL usage (from less secure to more secure).
SSL: Using Custom CANewer versions of SSL in MongoDB allow you to use your own CAs. Although it gives you the flexibility to determine how you want to work with SSL, there are some reservations. If you are just trying to protect the connection, you may be tempted to choose
sslAllowInvalidCertficates . However, as a rule, this is a bad idea for several reasons:
- allows connection even if certificates are revoked or expired;
- You do not provide restrictions on a specific hostname;
- you are not at all as protected as you think.
To solve this problem, configure
net.ssl.CAFile , and MongoDB will use both the key and the CA file (this must be done on the client).
However, the use of SSL has a well-known disadvantage: performance. When using SSL, it will definitely decrease.
Disk encryptionThe data is either in the “in transit” state or “at rest.” You can encrypt one of them or both in MongoDB. We talked about data encryption in transit (SSL). Now look at the data at rest.
At-rest data is data stored on disk. Encrypting such data usually means storing it in an encrypted vault. This is done to prevent physical theft, as well as to create backups stored in such a way that it is not easy for a third party to read them. There are practical limitations to this. The biggest of them is the trust of your system administrators and the confidence that the hacker has not gained administrative access to the system.
This problem is not unique to MongoDB. Preventive measures used in other systems work here. These may include encryption tools such as LUKS and cryptfs, or even more secure methods, such as signing encryption keys with LDAP, smart cards, and RSA type tokens.
When performing this level of encryption, you need to consider factors such as automatic partitioning and decryption of disks. But this is not new to your system administrators. They can manage this requirement just like in other parts of your network. An additional advantage is a single storage encryption procedure, rather than one for each technology used by a particular function.
At-rest data encryption can be implemented in one of the following ways or all at once:
- encrypt the entire disk;
- Encrypt only database files
- encrypt in the application.
The first option can be implemented using disk encryption in the file system. It is easy to configure using LUKS and dm-crypt. To comply with PCI DSS standards and other certification requirements, only the first and second options are required.
AuditAt the heart of any good security architecture is the ability to keep track of which user performed what actions in the database (just like how you should manage your actual servers). Auditing allows you to filter the output of a particular user, database, collection, or source location. It creates a log to check for any security incidents. More importantly, it shows to any security auditor that you have taken the right steps to protect your database from intrusion and to understand the depth of any intrusion if this happens.
Audit allows you to fully monitor the actions of the attacker in your environment.
Note : Auditing is available only in MongoDB Enterprise. It is not in the Community version. But it is available in other open source versions of MongoDB, such as Percona Server for MongoDB.
In addition, you can make changes to the schema occur only with proper validation by DBA staff, as the developer’s code may not work if someone changes the format of what you are storing in the database. This adds an extra layer of control to the MongoDB dynamic production scheme (allowing you to store anything, even if it is not necessary).
ControlManagement is associated with inserting and updating data. This is also useful for checking whether a field name is defined, such as “bday”, “birthday”, “ssn” or “social”. Simply put, management is the ability to implement complex standards into MongoDB using Document Validation.
Document validation allows you to determine which areas of the document are valid for a particular collection. You can set parameters to search for keys and values ​​and ensure that they meet predefined standards. For example, you can check if a key exists and if it is the correct key type.
The main commands for checking documents are:- collMod . Identifies the key to check.
- validator . Defines the parameters to be checked.
- validationLevel . Sets the validator's severity (how often it turns on and how serious it performs depending on validationAction).
- validationAction . Sets the procedure for when something fails.
We are not limited to specific keys and key values. You can also use regular expression strings. Using a regular expression, you can run a check for strings like a credit card number:
^ d {4} -d {4} -d {4} -d {4} $ . With regular expressions, you can also check the user ID, date of birth, social security number, etc.
These are examples of how your database administrators and security architects can help developers avoid exposing the company to additional risk.
Reducing the attack area of ​​your networkReducing the attack surface of your network means trying to control all possible vulnerabilities in the equipment and software of your network that are available to unauthenticated users.
MongoDB documentation offers you to place a copy of mongo on each application host. This proposal is certainly true for reducing the latency in your database environment (by limiting network hops). But, although this is good for performance, for safety it is very bad.
Each copy of Mongo should be able to refer to:- each primary node;
- each secondary node;
- each configuration server.
You can imagine what a nightmare is for safety. With each mongo instance, you have x more connections covering your network. This is x more connections that an attacker can use.
Instead, it’s better to have a MongoDB server group next to applications that you allow to access other systems. Set up a load balancer (or something similar) for the application and allow applications to access only MongoDB servers. This will provide a reasonable DMZ type setting that will prevent too many connections from opening on the network.

Fig. 2. MongoDB, deployed with load balancers.
Default settings heat databasesOpen source databases in general, and MongoDB in particular, have all the security parameters necessary to ensure the protection of your data (without the need to buy a corporate version).
Know how security works in your open source database. Saving the default settings is the right path to disaster. By understanding and solving the above questions, you can meet all your security needs (including regulatory compliance) and protect your company using sensible and well-known methods.

Everyone for whom the issues of MongoDB operation and security of your project are relevant are pleased to submit several reports from the upcoming PG Day'17:
replication to MongoDB from Henrik Ingo,
MongRocks repository based on Dennis Antimensky’s LSM-Tree ,
security for every day in Sergey’s
Web projects Novikov and
all that the developers wanted to know about database security, but were afraid to ask Ilya Verbitsky. Join now!