The definitive guide to MongoDB security

A step-by-step survival guide to reduce your vulnerability to the next database disaster.
174 readers like this.

Picture this: you are all ready to pack up and head home after a tiring day at work, but just as you are about to shut down, this pops up:

MongoDB ransomware message

A sinking feeling starts to set in as you go into denial. No way this is happening to me! Then reality sets in—your company's database has been deleted and backed up to another server. Welcome to the MongoDB apocalypse!

Stories like this were all too common between December 2016 and the first quarter of 2017, when nearly 30,000 MongoDB databases were hacked, deleted, and put behind a ransom request.

While in most cases, the demands hackers make to release a database seem paltry (around USD$500), it's the irreparable damage such intrusions cause to a company's reputation and market worth that gives their executives sleepless nights.

Clients, suppliers, and partners may walk away, legal consequences may follow, employees might be fired, and the company may never recover from the experience. As many as 60% of small businesses that experience a cybersecurity attack go out of business within six months.

How do these hacks happen and what can you do to mitigate the risk? Here's what you need to know to reduce your MongoDB attack surface.

Is your database the problem? Or you?

While MongoDB 2.6.0 and above can be accessed only by local connections, the previous versions did not come with default authentication features. Consequently, they would accept requests from remote connections unless the user took the time to set up restrictions.

We are still seeing MongoDB database breaches, as demonstrated by the exposure of 445 million records in one 2018 incident. Hackers search for unsecured databases using a search engine such as ZoomEye. A simple query could result in thousands of prospective victims in a matter of minutes.

After discovering their marks, hackers simply copy the entire dataset to an offsite server and delete it from the target database. The user then gets a message telling them to send a certain number of bitcoins to an address to have their database released.

Many have assumed that MongoDB's security configuration and options are the cause of its security vulnerabilities. But the main reason for the success of these hacks is that most organizations are in the habit of using default database presets rather than configuring their installations personally.

In other words, the whole thing could have been avoided had organizations simply added a few lines of code to their database config files. Clearly, users are often at fault. While MongoDB has addressed the issue by creating stronger default settings, there are still steps you can take to ensure you never wake up to another MongoDB apocalypse.

Creating a foolproof MongoDB security policy

By now you're probably reasonably worried. When it comes to security, worried is good! Here's a step-by-step survival guide you can use to reduce your vulnerability to the next database disaster.

Authentication

Authentication is the process of verifying the identity of a client that is trying to connect with a database. MongoDB offers various methods to verify a client's identity. Challenge-based default measures include:

  • SCRAM-SHA-1: Salted Challenge Authentication Mechanism uses simple text-based usernames and passwords transmitted over a channel protected by transport layer security (TLS).

  • MongoDB-CR: Like SCRAM, MongoDB-CR verifies a username and password against an authentication database. MongoDB-CR was removed from Version 3.0, and only older iterations use it today.

Either method sends passwords encrypted, and a different hash is generated for each new session so no one can sniff them out.

MongoDB can employ external authentication protocols as well:

  • LDAP: Lightweight Directory Access Protocol allows users to log in using their centralized passwords. LDAP is designed to help anyone locate and access information they need in either a public or private network.

  • Kerberos: This is a secret key authentication protocol for server-client interactions. Using Kerberos, users can log in only once using an access ticket.

MongoDB authentication best practices

First things first: Always enable auth on a production install. For Version 3.5 onwards, this feature is enabled by default.

  • Enable access control and use one of MongoDB's authentication mechanisms mentioned above. If your deployment is clustered, each instance should be individually configured.

  • Always start by creating an administrator user. Then add additional users as needed.

  • Encrypt all communications between mongod and mongos instances as well as internal and external communications using TLS/SSL.

  • Encrypt data on each MongoDB host using filesystem, device, or physical encryption.

  • Run MongoDB on a trusted network only. Do not allow your database to be routable outbound to the public internet, even when inside a trusted network, and don't let it run on any more interfaces than it has to. This prevents a bad actor from having a means of moving your data from the server to another offsite location (for hardware, that is—software-based routers and static routing tables can still be modified by hackers).

  • Make a habit of tracking changes in both the database and data. If you are using MongoDB Enterprise, then use its auditing facility for analysis.

Authorization/role-based security

Role-based access control (RBAC) is one of MongoDB's best features. While you can find well-defined roles within MongoDB that can cover most users, custom roles can be created as well.

A role essentially determines what permissions a user has and what he/she can access. Once a user has been defined by a role, the user cannot access the system beyond it.

You can enable authorization using the --auth or the security-authorization setting. --auth enables authorization to control a user's access to a database and its resources. This feature also enforces authentication after it's enabled—it requires all clients to verify their identities before being given access.

Access-control best practices

Giving users too much access gives way to potential misuse of privileges, which is why exercising due diligence is important when assigning roles. A report by Gartner reveals that 62% of company insiders indulged in actions that gave them a second income. This is usually done by misusing company data.

Too much access is an issue that constantly figures in the top-10 lists of IT issues companies wrestle with. To ensure privileges are never misused, consider following these guidelines:

  • Understand each role right down to its most minute detail. The better roles are understood, the more accurately privileges can be assigned to them.

  • It's best to follow a principle of least privilege. Assign to users only those roles they need to get the job done. More privileges can be assigned if needed.

  • Create a new MongoDB user for each application/use case of the database. For example, create a user named "webapp" (with least privileges) to run your web application, while creating another user, "analytics," (perhaps read-only) for a business analytics system. This creates isolated privileges and allows granular control of application usage of the database.

  • Create a resource to help users understand basic information security. Run drills to ensure employees understand the security requirements and are clear on what consequences they can face should the requirements not be met.

  • Revoke access of users no longer with your organization as soon as they leave.

  • Implement user provisioning software to manage multiple users more efficiently.

  • MongoDB 3.5 onwards comes with client source filtering that allows you to filter connections based on IP addresses or IP ranges. Use it to have better control over who can access an environment.

  • Implement user-level access control lists to grant permissions to individual users.

TLS/SSL encryption

MongoDB offers network encryption and can pass through disk encryption to help you protect your database and communications. TLS and SSL are both standard technologies that are used for encrypting network traffic.

As of MongoDB 2.6, both SSL and TLS are supported by the x.509 certificates, and clients can use the latter to authenticate their identities rather than a username and password. A minimum of 128-bit key length is required by MongoDB for all connections when using TLS/SSL.

While MongoDB can use any valid certificate, self-signed certificates are best avoided as there will be no validation of server identity, even though the communication channel will remain encrypted. In such scenarios, databases may become vulnerable to man-in-the-middle attacks.

How to configure mongod and mongos for TLS/SSL

To use TLS/SSL in your MongoDB deployment, include the following runtime options with mongod and mongos:

  • net.ssl.mode set to requireSSL. This setting restricts each server to use only TLS/SSL encrypted connections. You can also specify either the value allowSSL or preferSSL to set up the use of mixed TLS/SSL modes on a port. See net.ssl.mode for details.

  • PEMKeyfile with the .pem file that contains the TLS/SSL certificate and key.

Hardening your MongoDB database

While these steps will help your database survive malicious online activity, going the extra mile hardens your defenses even further. "Hardening" essentially refers to a layer-by-layer method of adding security, where each part of a database is given its own security measures.

MongoDB databases come with their own hardening features.

Configuration hardening with IP binding

For Version 3.6 onwards, MongoDB binds to localhost by default, while for versions 2.6 to 3.4, only binaries from the official MongoDB RPM and DEB packages will bind to localhost by default.

Network hardening with firewalls and VPNs

  • Firewalls: These can help you exert much finer control over network communications. Firewalls limit incoming traffic, particularly from untrusted sources. As ransomware and other kinds of attacks target specific ports, having well-configured firewalls is an ideal defense.



    On Linux systems, administrators can use the iptables interface to access the underlying netfilter firewall. On Windows systems, the netsh command-line interface can be used to access the Windows firewall.

  • Virtual private networks (VPN): VPNs are ideal for connecting two endpoints over a less-than-secure communication network. Depending on features and how they are configured, VPNs allow for certificate validation and encryption protocols. As VPNs provide a secure tunnel between client and server, they can also be used along with self-generated certificates without needing to worry about man-in-the-middle attacks.

Understanding the anatomy of a ransomware attack

Now that you know how to reduce threats to your network, let's take a look at how ransomware attacks work. While they may have begun as a small-time nuisance, ransomware attacks have become an extremely sophisticated business that is costing businesses millions of dollars.

A study by Ostermon Research found that 40% of companies in the US, UK, Canada, and Germany have suffered a ransomware attack. Of them, a third lost revenue and 20% had to suspend all business activities until the situation was brought under control.

So, just how does a ransomware attack work? While they may differ in execution, most attacks share some common elements. Here's a quick rundown of how a typical ransomware attack works.

Step 1: Delivery

This is the phase where the malware enters into the targeted network. There are a number of delivery models attackers can use. Some of the most common ones are:

  • Email: By far the biggest target. The vast majority of ransomware attempts originate as a phishing attack that uses authentic-looking email with malicious content.

  • Web-based attacks: Downloading scripts and unregistered software, cross-site scripting attacks, infected ads, and social media intrusions are the choice of entry points here.

  • Networks: Automated search tools are used to scan a network for vulnerabilities. Once found, they may be used to deploy any manner of malware. Network-based attacks were what most MongoDB databases experienced.

  • Web-based applications: Webmail, shopping sites, and online forms are sometimes susceptible to malware infections.

Step 2: Infection

Provided a user unwittingly clicks on a malicious piece of code and executes it, the malware, an advanced persistent threat, will rapidly start to encrypt targeted files. In some cases (like MongoDB), it deletes them altogether.

The user is presented a ransom note that tells them to send some money (typically bitcoins, as they are untraceable) to an address then follow up through email to have their system unlocked.

Step 3: Recovery

The user now has two choices—pay up and hope the attackers will restore their system. Or, if they have been smart, simply restore their system using backup copies. You should know that only 19% of ransomware victims who pay actually get their files back. So the odds are you will be without your data and your money at the end of the day.

In any case, the business now has to clean the infected file and get its system back online. A fully updated network and endpoint security system will prove crucial to helping them save time. The steps differ from company to company, but all involve a thorough analysis of system logs, backup copies, and before/after states to find the best course of action.

Concluding thoughts

The business cost of cybercrime is pegged at around US$600 billion annually, according to a McAfee report, a trend that shows no signs of stopping. Cybercriminals are using newer, more robust techniques, so much so that today we have cybercrime-as-a-service business models. The rise of cryptocurrency and anonymous browsers such as Tor has only emboldened cybercriminals as their activities become nearly impossible to trace.

The unfortunate truth is no technology can ever be completely safe from an attack, as the human component of it will always be open to manipulation. Even a glance at how most cybercrimes work lays bare the fact that they primarily rely on human error, ignorance, or oversight as their modus operandi. If a user willingly gives system access to a malicious piece of code, then there's precious little that any security system can do to stop it.

So, while having an up-to-date security system is a good start, creating strong and well-thought-out security policies is what will ultimately help you fend off attacks and mitigate the risk to your system. Consider the following steps:

  1. Always set your database management system (DBMS) to require a strong password.

  2. Stay away from default users and demo databases. Since this information is public, it can be used against you.

  3. Never use standard usernames like root, user, or app, as they are the easiest to guess.

  4. Restrict public network access to the greatest extent possible. Only IP addresses that need to talk to your database server should be given access to it. Using a good quality VPN is highly recommended.

  5. Set up monitoring systems to look out for high CPU usage and I/O activity. Doing so will alert you to unusual patterns that are typical with cyberattacks.

  6. Again, follow the principle of least privilege when assigning user roles. This cannot be emphasized enough.

  7. Conduct database audits at regular intervals. The longer your audit trail, the more secure you are.

  8. Encrypt your backup data. Ransomware attacks have begun to infect backups as well.

  9. Consider hiring ethical hackers to gain an outsider perspective and probe your database for weaknesses.

  10. Always ascertain the identity of a person before accepting any communications from them. Ask yourself:

    • Do I know this person?

    • Do I absolutely have to click on the link or open that attachment?

    • Is the name and email of the person the same as what's in my contact list?

    • Was I expecting an email from them?

  11. Keep yourself up to date on the latest goings-on in the security world.

Digital security is a shifting target that's never the same from one moment to the next. As every business has its own set of strengths and weaknesses, it is best that every organization's systems and policies be based on them.

User profile image.
Tim is an open-source enthusiast with a long background of optimising large infrastructures in all areas of the stack in various combinations of sys/ops admin, DBA and developer roles. Tim focuses on improving the automation of MongoDB as a Sr. Technical Operation Architect at Percona.

Comments are closed.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.