Securing MongoDB on Ubuntu 20.04 involves implementing various measures to protect your database from unauthorized access and potential security threats. Here are steps you can take to enhance the security of your MongoDB installation:
-
Enable Authentication:
By default, MongoDB doesn't require authentication. To enable authentication, you need to create an administrative user. Connect to the MongoDB shell:
mongo
Switch to the
admin
database and create an administrative user:use admin db.createUser({ user: "adminUser", pwd: "yourAdminPassword", roles: ["root"] })
Exit the shell:
exit
Edit the MongoDB configuration file to enable authentication. Open the configuration file in a text editor:
sudo nano /etc/mongod.conf
Add the following lines:
security: authorization: enabled
Save the file and restart MongoDB:
sudo systemctl restart mongod
Now, you will need to authenticate to access the MongoDB shell.
-
Bind to Localhost:
Configure MongoDB to listen only on the localhost interface by specifying
127.0.0.1
as thebindIp
in the configuration file. Open the configuration file:sudo nano /etc/mongod.conf
Add the following lines:
net: bindIp: 127.0.0.1
Save the file and restart MongoDB:
sudo systemctl restart mongod
-
Firewall Configuration:
If you have a firewall enabled, allow access only to necessary ports. MongoDB typically uses port 27017. Adjust your firewall rules accordingly.
-
Enable Access Control:
In the MongoDB shell, create users for specific databases with limited privileges:
use yourDatabase db.createUser({ user: "yourDatabaseUser", pwd: "yourDatabasePassword", roles: ["readWrite"] })
Replace
yourDatabase
,yourDatabaseUser
, andyourDatabasePassword
with your actual database name, username, and password. -
Transport Encryption (Optional but Recommended):
Enable TLS/SSL to encrypt the communication between MongoDB clients and the server. Obtain an SSL certificate and update the MongoDB configuration file with the certificate paths and settings.
-
Regular Backups:
Regularly back up your MongoDB data to prevent data loss in case of accidental deletions or hardware failures.
-
Monitor and Audit:
Set up monitoring tools and regularly review logs to identify and respond to any suspicious activity.
-
Updates:
Keep MongoDB and your operating system up-to-date with the latest security patches.
-
Disable unnecessary services:
If your MongoDB server is dedicated to MongoDB, consider disabling unnecessary services to reduce the attack surface.
-
Restrict Physical Access:
Ensure that physical access to the server is restricted to authorized personnel.
Remember that security is an ongoing process, and it's essential to stay informed about security best practices and apply them regularly. Additionally, consider consulting the MongoDB documentation and relevant security guides for more detailed information.