MongoDB (named from “huMONGOus“) is a full flexible index support and rich queries database. Its is a NoSQL database. MongoDB provides large media storage with GridFS.
MongoDB has released a new stable version 4.2 with lots of major enhancements. This tutorial latest tested on CentOS 7 and help you to install MongoDB 4.2 on CentOS 8/7/6 and RHEL 8/7/6 systems.
Step 1 – Add MongoDB Yum Repository
Add the following content in yum repository configuration file mongodb.repo as per your required MongoDB version and system architecture. For this article, we are using MongoDB 4.0 repository.
CentOS and RedHat systems Only
vi /etc/yum.repos.d/mongodb.repo
[MongoDB] name=MongoDB Repository baseurl=http://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc
Step 2 – Install MongoDB Server
Let’s use the yum package manager to install mongodb-org package, it will automatically install all its dependencies. To install any specific revision of MongoDB specify package name with version like mongodb-org-4.0.0. The following command will install the latest stable version available.
sudo yum install mongodb-org
Step 3 – Start MongoDB Service
Package mongodb-org-server provided MongoDB init script, Use that script to start service.
systemctl start mongod.service # For CentOS 8/7 service mongod restart # For CentOS 6
Configure MongoDB to autostart on system boot.
systemctl enable mongod.service # For CentOS 8/7 chkconfig mongod on # For CentOS 6
Step 4 – Check MongoDB Version
Use the following command to check installed MongoDB version
[root@tecadmin ~]# mongod --version db version v4.2.1 git version: edf6d45851c0b9ee15548f0f847df141764a317e OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013 allocator: tcmalloc modules: none build environment: distmod: rhel70 distarch: x86_64 target_arch: x86_64
Connect MongoDB using the command line and execute some test commands for checking proper working.
[root@tecadmin ~]# mongo > use mydb; > db.test.save( { a: 1 } ) > db.test.find() { "_id" : ObjectId("54fc2a4c71b56443ced99ba2"), "a" : 1 }
Congratulation’s You have successfully installed mongodb server on your system.
MongoDB Infrastructure Security for Linux
MongoDB config
- The default file is located at /etc/mongodb.conf
- The default port is TCP 27017
- MongoDB server version: 3.4.1
Limit network exposure
Edit the /etc/mongodb.conf or /usr/local/etc/mongodb.conf file, enter:$ sudo vi /etc/mongodb.conf
If your web-app and MongoDB (mongod server) installed on the same machine, set the IP address of MongoDB to 127.0.0.1. This cuts communication directly from the internets:
# network interfaces net: port: 27017 bindIp: 127.0.0.1
However, it is possible that you have two or more servers, and you need to bind mongod to something like192.168.1.7 so that it can be only accessed over network:
bindIp: 192.168.1.7
The bind_ip directive ensure that MongoDB runs in a trusted network environment and limit the interfaces on which MongoDB instances listen for incoming connections.
Change the default port
You can also change the default port if you want. In this example set it to 2727:
port: 2727
Save and close the file. You need to restart MongoDB, enter:$ sudo systemctl restart mongod
OR if you are using FreeBSD Unix:# service mongod restart
Verify open ports with netstat command:$ netstat -tulpn
$ ss -tulpn
$ sockstat #freebsd unix command
$ ss -tulpn | grep 2727
$ netstat -tulpn | grep 2727
Sample outputs:
tcp 0 0 127.0.0.1:2727 0.0.0.0:* LISTEN 6818/mongod
Setup access control
You need to add a user administrator to a MongoDB instance running without access control and then enables access control. By default anyone can connect to the MongoDB and this is not a good idea.
Connect to the DB instance
$ mongo
## or ##
$ mongo --port 2727 --host 192.168.1.7
MongoDB shell version: 2.6.10
connecting to: test
Create the user administrator
Warning: Create user with strong password. For demo purpose I am using ‘mySuperSecretePasswordHere’ but you should use strong password.
You need to use admin database. Type the following command at > prompt to create your superuser:> use admin
switched to db admin
Next creates the user vivek in the admin database with the userAdminAnyDatabase role:> db.createUser({user:"vivek",pwd:"mySuperSecretePasswordHere", roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Sample outputs:
Successfully added user: { "user" : "vivek", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
Disconnect the mongo shell by typing the following command:> exit
bye
$
Re-start the MongoDB instance
Edit the /etc/mongod.conf or /usr/local/etc/mongodb.conf file, enter:$ sudo vi /etc/mongod.conf
Turn on security:
security: authorization: enabled
Save and close the file. Re-start the MongoDB instance:$ sudo systemctl restart mongod
OR if you are using FreeBSD Unix:# service mongod restart
To authenticate during connection using user vivek and password for the admin database:$ mongo -u vivek -p mySuperSecretePasswordHere --authenticationDatabase admin
Add additional user to your DB. First create a new database called “nixcraft”:> use nixcraft
switched to db nixcraft
Create a user named ‘nixdbuser’ with a password named ‘myKoolPassowrd’ for nixcraft db:
db.createUser( { user: "nixdbuser", pwd: "myKoolPassowrd", roles: [ { role: "readWrite", db: "nixcraft" }, { role: "read", db: "reporting" } ] } ) |
Sample outputs:
Successfully added user: { "user" : "nixdbuser", "roles" : [ { "role" : "readWrite", "db" : "nixcraft" }, { "role" : "read", "db" : "reporting" } ] }
You can now connect to nixcraft db as follows:$ mongo --port 2727 --host 192.168.1.7 -u "nixdbuser" -p "myKoolPassowrd" --authenticationDatabase "nixcraft"
This make sure only authorized admin user named ‘vivek’ can execute commands or nixdbuser can do read/write operation on nixcraft db. You can verify it as follows by inserting records:> use nixcraft
> db
> db.names.insert({"title":"Mr", "last":"Gite", "First":"Vivek"})
> db.names.find()
> show dbs
Use firewall
Use firewalls to restrict which other entities are allowed to connect to your mongodb server. In this example only allow your application servers access to the database using ufw on Ubuntu or Debian Linux:$ sudo ufw allow proto tcp from 192.168.1.5 to 192.168.1.7 port 2727
$ sudo ufw allow proto tcp from 192.168.1.6 to 192.168.1.7 port 2727
Enable SSL
Use SSL between your MongoDB client and server when connecting to your Mongodb server over the internet. Otherwise your session is open for the “man in the middle” attack. My setup is as follows:
mongodb-server: 127.0.0.1 mongodb-client: 127.0.0.1 Common Name (e.g. server FQDN or YOUR name) []: 127.0.0.1 The PEM pass phrase for server: mongodb_server_test_ssl The password/passphrase for client: mongodb_client_test_ssl
Type the following command the server certificate
$ sudo mkdir /etc/ssl/mongodb/
$ cd /etc/ssl/mongodb/
$ sudo openssl req -new -x509 -days 365 -out mongodb-server-cert.crt -keyout mongodb-server-cert.key
Sample outputs:
$ cd /etc/ssl/mongodb/
$ sudo bash -c 'cat mongodb-server-cert.key mongodb-server-cert.crt > mongodb-server.pem'
Type the following command for the client certificate
$ cd /etc/ssl/mongodb/
$ sudo openssl req -new -x509 -days 365 -out mongodb-client-cert.crt -keyout mongodb-client-cert.key
Sample outputs:
Create the client .pem file with both key and certificate:
$ cd /etc/ssl/mongodb/
$ sudo bash -c 'cat mongodb-client-cert.key mongodb-client-cert.crt > mongodb-client.pem'
Configure mongod and mongos for TLS/SSL server
Edit the /etc/mongod.conf or /usr/local/etc/mongod.conf file, enter:$ sudo vi /etc/mongod.conf
Update the config file as follows:
# network interfaces net: port: 27017 bindIp: 127.0.0.1 ssl: mode: requireSSL PEMKeyFile: /etc/ssl/mongodb/mongodb-server.pem CAFile: /etc/ssl/mongodb/mongodb-client.pem PEMKeyPassword: mongodb_server_test_ssl |
Save and close the file. Re-start the MongoDB instance:$ sudo systemctl restart mongod
OR if you are using FreeBSD Unix:# service mongod restart
TLS/SSL Configuration for MongoDB clients
The syntax is as follows for mongo shell interface:$ mongo --ssl --sslCAFile /etc/ssl/mongodb/mongodb-server.pem \
--sslPEMKeyFile /etc/ssl/mongodb/mongodb-client.pem \
--sslPEMKeyPassword mongodb_client_test_ssl \
--host 127.0.0.1 --port 27017 \
--u "nixdbuser" -p "myKoolPassowrd" --authenticationDatabase "nixcraft"
Sample outputs:
And here is a Python client for connection to SSL enabled MongoDB:
client = pymongo.MongoClient('127.0.0.1', ssl=True) |
OR
client = pymongo.MongoClient('127.0.0.1', ssl=True, ssl_certfile='/etc/ssl/mongodb/mongodb-client.pem', ssl_keyfile='/etc/ssl/mongodb/mongodb-server.pem', ssl_pem_passphrase=mongodb_client_test_ssl) |