Hey guys 👋🏻,
In this article, let us understand about Security and Authentication in MongoDB. We will understand the security aspect from the perspective of developers and NOT for the database admins.
This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.
What are the most important parts for securing the mongodb database ?
Security Checklist
For hardening the Mongo Environment and making sure that it is safe and cannot be tampered from outside, we need a security checklist.
Authentication and Authorization
The database that we will be using to store data and users will know the users and your code will have to authenticate as a database in order to get data, update data and do all kinds of stuffs with the data that you get back. It is the most important building block for securing your MongoDB environment.
Another important building block is the Transport Encryption
Transport Encryption
This means the data that you sent from your app to the server should be encrypted so that no MAN IN THE MIDDLE attack can compromise your credentials.
Encryption at Rest
This means that the data in the database also should be encrypted otherwise if someone somehow gets access to your database servers well they can then read plain text information easily.
So it is a must to store the data in the database in the encrypted format as well.
Auditing
This is the pure server admin task and not the concern for the developer but Mongodb provides auditing to servers to see who did what and what actions occurred so that you can control and are aware of what is happening inside the database
Server & Network Config and Setup
Additionally the server on which you run database server (like physical machine that is running somewhere or the cloud provider like AWS) the instances that we book there the network that you are using for hosting your Mongo Server should also be secure.
Backups and Software Updates
As an owner of the database environment you should regularly take backup of your data. The softwares that you are running should be up to date.
Let us talk about the below three in great detail :
- Authentication and Authorization
- Transport Encryption
- Encryption at Rest
Understanding the Role Based Access Control
Authentication and Authorization
Authentication is all about identification of the users in the databaseComing to Authorization,
Authorization is all about what these users may actually do in the database
MongoDB employs the Role Based Access Control System
Let us say we have the MongoDB server with three databases
- Admin database which is the special database that exists out of the box
- Blog database
- Shop database
Authentication can be enabled in a very easy way and suddenly MongoDBs server only allows access to the authenticated users.
Let us considered a user like some data analyst/software developer who directly connects with our shell or say we have the app code that uses the driver to connect to the database. The analyst or developer is NOT a user of your application, not the user
of the web application that you are building and we now need to login to the MongoDB Server. With our username and password, we can do that since authentication was enabled that means user needs to exist on the MongoDB server otherwise the login of the user will not be possible.
Now say we get loggedin but we have no rights to do anything…
The users in MongoDB are not just entities that are made up of username and passwords but they are also assigned some roles and these roles are basically the group of the privileges
A privilege is a combination of the resource and the action.
A resource would be something like the products collection in the Shop database and an action would be an insert() command for example to insert a product for example in our products collection
Actions are basically the task commands that we can do in our MongoDB database and resources define what resources we can access based on the access privileges that we are granted.
Typically multiple privileges are grouped into something called as the ROLES
That means a user has a role and that role includes all the privileges holding actions and resources that makes sense for this user.
This is the model that MongoDB uses since it is the most flexible model that Mongo has defined for its userbase. This allows us to create multiple owners where we can give every user exactly the rights that every user needs. We do not want to give every user all the rights because if we give all rights to any unauthorized person then they may do something malicious with our database which they were not designated to do.
Different types of database users
Admin – A real person who needs to be able to manage the database configuration and create users etc, create new databases, create new collections. The admin would need to be required to be work with data in the database. He does not need to be able to insert or fetch data.
Developer – A developer needs to be able to insert, delete, update or fetch data (all the CRUD operations that we discussed). The developer is not responsible for creating the users and manage the database configurations. This is not your job and the app code should not be able to do that.
Data Scientist – A data scientist needs to be able to fetch the data. He/she does not need to be able to create users, manage the database configuration or insert, edit, delete, update the data. His sole responsibility is to work with large amounts of data and derive valuable insights that are important for an organization. Working with large dataset along with strong analytic skills are a must for a data scientist.
CREATING A USER
Let us learn about creating and editing a user in MongoDB.
Users are created by a user with special permissions with the
createUser
command. You then create the user with a username
and the password
. This user will have a couple of roles or atleast one role and each role will then contain a bunch of privileges. A user is created on the database. This does not limit the access of the user to that authentication database. But this is the database against which the user will have to authenticate. The exact rights the user has depends on the role that you have assigned to the user.
If we have the need we can also updateUser
command, this means the admin can update the user that means for example we can use this to change the password
mongod --auth
We can also make use of the command
db.auth(“username goes here”,”password goes here”)
for signing up the user.
We can also connect by writing
mongo -u usernamesgoeshere -p passwordgoeshere
But what if we don’t have a user to begin with. MongoDB has a special solution which is called the localhost exception. More on this can be read here :
https://docs.mongodb.com/manual/core/localhost-exception
You are allowed to create one user who then can be allowed to create more users.
For this you need to switch to the admin
database
and run the command
use admin
Then create a user
db.createUser({ user: "alex", pwd:"alex1234", roles: [ "userAdminAnyDatabase" ]})
Built in Roles
MongoDB ships with a bunch of built in roles to cover most of theuse cases that you may require. You can also create your own roles
but that is pure admin task.
We got a typical role for the users of the database
Database user
read readWrite
You also got typical admin roles like the
dbAdmin
userAdmin
dbOwner
All database roles
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase
Besides these roles we also have the cluster administration
Clusters are the concept where you have multiple MongoDB servers working together. So that you can have multiple machines running MongoDB servers and store your data which can then work and scale together. And managing this cluster of servers is ofcourse a meaningful task
clusterManager
clusterMonitor
hostManager
clusterAdmin
Backup/Restore roles
backup
restore
SuperUser Roles
dbOwner(admin)
userAdmin(admin)
userAdminAnyDatabase
root (the most powerful role)
root superuser can do everything
ASSIGNING ROLES TO USERS AND DATABASES
Run this command using the credentials of the created user
mongo --authenticationDatabase admin -u usernamegoeshere -p passwordgoeshere
db.createUser({ user : 'appdev', pwd : 'dev', roles : ['readWrite'] });
Successfully added user: { "user" : "appdev", "roles" : [ "readWrite" ] }
We can now authenticate in that user with the following command
db.auth('appdev','dev')
This gives 1. This 1 signal indicates that this works.
Adding SSL Transport Encryption
Transport Encryption
We have our application and this could be Node, Django, PHPapplication that uses the MongoDB driver to communicate withMongoDB Server to store the data and ofcourse it is importantthat the data is encrypted whilst it is in transport so thatsomeone who is spoofing our connection can not read our data.
and MongoDB has everything for that built into it.
How we can secure our data whilst it is own its way from client to the server ?
To encrypt the data whilst it is in transport, MongoDB uses
SSL or actually TLS for encryption and uses public private key pair to decrypt this information on the server and to proveto the server to prove that who we are. It is secure way of
encrypting our data and decrypting our data on the server.
While its own its way it is consistently updated.
ENCRYPTION AT REST
The data which is stored on our MongoDB Server in a file thisofcourse might also be encrypted so that we can decrypt there
two different things
- The overall storage (feature built in for enterprise versions)
- The thing as a developer you can do is to encrypt certain values in your code. For example, if you are storing the user password you should hash that password and not store the plain text you can go so far for all data you always have a way for encrypting that.
So you can encrypt both your data as well as the overall file storage to achieve max security that is possible
Here are some of the important links that you must reference to know more about Security and Authentication in MongoDB:
Official “Encryption at Rest” Docs: https://docs.mongodb.com/manual/core/security-encryption-at-rest/
Official Security Checklist: https://docs.mongodb.com/manual/administration/security-checklist/
What is SSL/ TLS? => https://www.acunetix.com/blog/articles/tls-security-what-is-tls-ssl-part-1/
Official MongoDB SSL Setup Docs: https://docs.mongodb.com/manual/tutorial/configure-ssl/
Official MongoDB Users & Auth Docs: https://docs.mongodb.com/manual/core/authentication/
Official Built-in Roles Docs: https://docs.mongodb.com/manual/core/security-built-in-roles/
Official Custom Roles Docs: https://docs.mongodb.com/manual/core/security-user-defined-roles/
So this is it for this article. Thanks for reading.
If you enjoy my articles, consider following me on Twitter for more interesting stuff :
⚡Twitter : https://twitter.com/The_Nerdy_Dev