MongoDB is a popular NoSQL database that has been widely adopted by many organizations for its scalability and flexibility. However, with the increase in cyber attacks, it is important to ensure that MongoDB databases are secure to prevent data breaches. As a security engineer, I had to face challenges while creating security checks and security plans on MongoDB. I am trying to collate the sweeter grapes of that journey in this write-up. Some resources might seem a bit high-level, but these can be utilized to come down to a granular level as per your org setup or requirements.
Let’s begin :)
Authentication
MongoDB provides authentication features that allow users to access the database only after providing valid credentials. MongoDB supports several authentication mechanisms, including LDAP, Kerberos, and x.509 certificates. However, SSO integrations for authentication have been the best approach so far. There are various SSO providers, as an example you may use OKTA as SSO integration, which reduces the risk of credential leakage. High-level steps to integrate OKTA with MongoDB:
- Set up an Okta account: If you haven’t already, sign up for an Okta account at https://www.okta.com/. This will serve as your identity provider for SSO.
- Configure Okta as an identity provider for MongoDB: In the Okta Admin Dashboard, navigate to the “Applications” section and click on “Add Application”. Search for or select “SAML 2.0” as the application type.
- Set up the MongoDB SAML integration: In the Okta application settings, provide the necessary details for MongoDB SAML integration. This typically includes the following:
a. Single sign-on URL: This should be the URL where MongoDB is configured to handle SAML-based authentication requests.
b. Audience URI (SP Entity ID): This is a unique identifier for MongoDB within the SAML context.
c. Name ID format: Select the appropriate format for the user identifier (e.g., email).
d. Attribute statements: Define the attributes that Okta should send to MongoDB, such as username or email. - Configure MongoDB to trust Okta as the SSO provider: On the MongoDB side, you need to configure it to trust Okta as the SSO provider. This involves adding the Okta metadata URL or manually importing the metadata XML file provided by Okta.
- Enable SSO on MongoDB: Adjust the MongoDB configuration file (
mongod.conf
) to enable SSO. Add the necessary parameters, including the SSO URL and other SSO-related settings. Refer to MongoDB's official documentation for the specific configuration options and details. - Test the SSO integration: Once the configurations are in place, test the SSO integration. Access MongoDB and attempt to log in using an account associated with Okta. You should be redirected to Okta’s login page, authenticate there, and then be redirected back to MongoDB with a valid session.

Reference:
Okta Documentation — Integrating SAML-based Applications: https://help.okta.com/en/prod/Content/Topics/Apps/Apps_SAML_Based_Apps.htm
MongoDB Documentation — Configure MongoDB for SAML Authentication: https://docs.mongodb.com/manual/core/security-configure-for-saml/ Okta Developer Documentation — SAML Integration Guides: https://developer.okta.com/docs/guides/saml-guides/
MongoDB Blog — How to Set Up Okta SSO for MongoDB Atlas: https://www.mongodb.com/blog/post/how-to-set-up-okta-sso-for-mongodb-atlas
Encryption
MongoDB provides field-level encryption (FLE) to protect sensitive data within a database. FLE encrypts individual fields within a document, rather than encrypting the entire document or the entire database. FLE can be used to protect sensitive data such as personally identifiable information (PII), financial information, and health records.
To enable FLE for a MongoDB deployment, you must perform the following high-level steps:
- Configure a key management system (KMS): FLE requires a KMS to securely manage the encryption keys used to encrypt and decrypt the data. MongoDB supports several KMS providers, including AWS Key Management Service (KMS), HashiCorp Vault, and Azure Key Vault. You can also use a custom KMS implementation that meets MongoDB’s requirements.
- Define the encryption schema: The encryption schema defines which fields in the database should be encrypted and how they should be encrypted. The schema includes a JSON schema that specifies the fields to be encrypted and the encryption options to use. The schema is stored in the MongoDB database as a system collection.
- Create and configure a client-side encryption configuration: To use FLE, you must create and configure a client-side encryption configuration file. The configuration file specifies the KMS provider, the encryption schema, and other options.
- Enable FLE on the MongoDB client: After the encryption configuration is created, you can enable FLE on the MongoDB client by specifying the encryption configuration as a parameter when connecting to the MongoDB server.

Reference:
MongoDB Documentation — Field Level Encryption: https://docs.mongodb.com/manual/core/security-client-side-encryption/
Encryption in transit
To protect data in transit and data at rest, encryption should be enabled for MongoDB databases. SSL/TLS encryption should be used for data in transit, and encryption at the file system level should be used for data at rest.
To configure TLS (Transport Layer Security) in MongoDB, you can follow these steps:
- Obtain or generate SSL/TLS certificates:
- Obtain a valid SSL/TLS certificate from a trusted certificate authority (CA) or generate a self-signed certificate for testing purposes.
- Ensure that the certificate includes the necessary hostname(s) or IP address(es) that clients will use to connect to MongoDB.
2. Prepare the SSL/TLS certificate files:
- Convert the SSL/TLS certificate and private key into the required PEM format.
- Save the certificate file and private key file on the server where MongoDB is installed.
3. Update the MongoDB configuration file (mongod.conf
):
- Open the MongoDB configuration file for editing (
mongod.conf
). - Add or modify the
net
section to include the SSL/TLS configuration parameters. - Specify the
sslMode
asrequireSSL
to enforce TLS encryption for all incoming connections. - Provide the path to the SSL/TLS certificate file using the
sslPEMKeyFile
parameter. - Optionally, specify the
sslCAFile
parameter to specify the CA certificate file for client authentication.
Sample mongod.conf
configuration:
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/ssl_certificate.pem
CAFile: /path/to/ca_certificate.pem
4. Restart the MongoDB service:
- Save the changes made to the MongoDB configuration file.
- Restart the MongoDB service to apply the new TLS configuration.
5. Verify TLS connectivity:
- Connect to the MongoDB server using the MongoDB client or application.
- Ensure that the connection is established over TLS by checking for the presence of the TLS handshake and verifying the certificate details.
Reference:
MongoDB 5.0: https://docs.mongodb.com/manual/tutorial/configure-ssl/ MongoDB 4.4: https://docs.mongodb.com/v4.4/tutorial/configure-ssl/
MongoDB 4.2: https://docs.mongodb.com/v4.2/tutorial/configure-ssl/
Auditing
MongoDB provides auditing features that can be used to track and record database activities. Administrators can use auditing features to monitor user activities and detect potential security threats.
To enable logging in MongoDB, you can modify the MongoDB configuration file (usually mongod.conf
) to specify the log output options. The following is a sample logging configuration for MongoDB:
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
logRotate: reopen
verbosity: 1
journal:
enabled: true
In this example, MongoDB logs are written to a file at the specified path (/var/log/mongodb/mongod.log
). Log messages are appended to the file (logAppend: true
) and the log file is reopened after rotation (logRotate: reopen
). The verbosity level is set to 1 (verbosity: 1
), which logs basic information. The journal
section specifies that journaling is enabled.
Export MongoDB Logs to S3 Buckets
A central log repository is a common and industry best practice these days. S3 buckets are always popular for storing logs. Let’s see how we can export the mongo logs to S3:
- Set up an Amazon S3 Bucket:
- Log in to the AWS Management Console and navigate to the S3 service.
- Create a new S3 bucket or select an existing bucket to store the MongoDB logs.
- Take note of the bucket name and the AWS access credentials required to access the bucket.
2. Configure MongoDB Logging:
- Open the MongoDB configuration file (
mongod.conf
) on the MongoDB server. - Locate the
systemLog
section in the configuration file. - Set the
destination
parameter tofile
orsyslog
to enable file-based logging. - Set the
path
parameter to specify the path and filename for the log file.
Example configuration for mongod.conf:
systemLog:
destination: file
path: /var/log/mongodb/mongodb.log
3. Install and Configure AWS CLI:
- Install the AWS Command Line Interface (CLI) on the MongoDB server.
- Configure the AWS CLI with the access credentials required to access the S3 bucket. Use the
aws configure
command to set up the credentials.
4. Create a Script or Cron Job:
- Write a script (e.g., a Bash script) that performs the following actions:
- Copies the MongoDB log file to a temporary location.
- Uses the AWS CLI command
aws s3 cp
to upload the log file to the specified S3 bucket. - Deletes the temporary log file.
Example script:
#!/bin/bash
# Copy log file to temporary location
cp /var/log/mongodb/mongodb.log /tmp/mongodb.log
# Upload log file to S3 bucket
aws s3 cp /tmp/mongodb.log s3://your-s3-bucket/
# Delete temporary log file
rm /tmp/mongodb.log
5. Schedule the Script or Cron Job:
- Set up a scheduled task or cron job on the MongoDB server to run the script at desired intervals.
- This ensures that the MongoDB logs are regularly exported to the S3 bucket.
Regularly Update MongoDB
MongoDB should be regularly updated to ensure that the latest security patches and updates are applied. Keep an eye on the release channel https://www.mongodb.com/docs/manual/release-notes/
Restrict Network Acces
To prevent unauthorized access to MongoDB databases, network access should be restricted. Access should be restricted to only authorized users and IP addresses.
- Configure MongoDB to listen on specific IP addresses: By default, MongoDB listens on all available network interfaces. To restrict access, you can modify the MongoDB configuration file (usually
mongod.conf
) to specify the IP addresses or network interfaces on which MongoDB should listen. Set thebindIp
configuration option to the desired IP addresses or network interfaces.
Example configuration formongod.conf
:
net: bindIp: 127.0.0.1,192.168.0.100
In this example, MongoDB will only listen on the loopback address (127.0.0.1) and the IP address 192.168.0.100. Adjust the IP addresses according to your specific requirements.
2. Utilize firewall rules: In addition to configuring MongoDB, you can further restrict network access by implementing firewall rules. Use a firewall tool (such as iptables on Linux or Windows Firewall on Windows) to allow incoming connections to MongoDB only from trusted IP addresses or specific network ranges. Block all other incoming connections to MongoDB’s default port (27017) or the custom port you have configured. Example iptables rule to allow connections from a specific IP address:
iptables -A INPUT -s 192.168.0.100 -p tcp --dport 27017 -j ACCEPT
iptables -A INPUT -p tcp --dport 27017 -j DROP
In this example, connections from the IP address 192.168.0.100 are allowed, while all other connections to port 27017 are dropped.
3. Consider using a virtual private network (VPN): If you require more advanced network access restrictions, you can establish a VPN connection and configure MongoDB to only accept connections from within the VPN network. This adds an extra layer of security by limiting access to the database to authorized VPN users.
4. Regularly review and update access restrictions: As your network configuration changes or when new trusted sources are added, ensure that you update the MongoDB configuration and firewall rules accordingly. Regularly reviewing and updating access restrictions helps maintain the security of your MongoDB deployment.
Remember to carefully plan and test these network access restrictions to avoid inadvertently blocking legitimate connections. It’s essential to strike a balance between restricting access and ensuring that authorized users can still connect to the MongoDB server when needed.
Common threat: Injection attack
Injection attacks occur when a malicious user inserts malicious code into a MongoDB database. To prevent injection attacks you should consider:
- Parameterized Queries:
Use parameterized queries or prepared statements provided by your MongoDB driver. These features allow you to separate user input from the query logic, preventing malicious data from being interpreted as commands. - Input Sanitization:
Validate and sanitize user input to remove or escape characters that have special meaning in MongoDB queries, such as$
,.
or}
. Use input validation techniques to ensure that user-supplied data meets expected patterns and formats. - Whitelist Validation:
Implement whitelist validation to explicitly define the allowed values for user input. Reject any input that does not match the expected patterns or criteria. - Role-Based Access Control (RBAC):
Implement RBAC in MongoDB to restrict user privileges and prevent unauthorized access to sensitive data and commands. Assign specific roles to users based on their functional requirements and enforce the principle of least privilege. - Least Privileged User:
Ensure that the user account accessing the MongoDB database has the minimum required privileges. Avoid using a superuser account for regular application operations.
Common Threat: DoS attack
DoS attacks occur when a malicious user floods a MongoDB database with requests, causing it to become unresponsive.
Here are some strategies to help mitigate DoS attacks:
- Limit Resource Consumption:
Configure resource limits to prevent excessive consumption of system resources by individual operations. MongoDB provides various settings, such asmaxIncomingConnections
,maxConns
, andmaxConnsPerHost
, which can be adjusted to limit the number of concurrent connections and operations. - Implement Connection Pooling:
Utilize connection pooling to efficiently manage connections between your application and MongoDB. Connection pooling helps optimize resource utilization and prevents resource exhaustion. - Enforce Authentication and Authorization:
Enforce authentication and authorization mechanisms to ensure that only authorized users can access MongoDB. This prevents unauthorized clients from overwhelming the system with requests. - Employ Rate Limiting:
Implement rate limiting to control the number of requests per unit of time from individual clients. This helps prevent excessive requests and limits the impact of a potential DoS attack. - Implement Firewall and Network Security:
Utilize firewalls, network security groups, and other network security measures to restrict access to MongoDB servers. Allow access only from trusted hosts or networks to minimize the risk of DoS attacks originating from unknown sources. - Use Replica Sets or Sharded Clusters:
Deploy MongoDB in a replica set or sharded cluster configuration to distribute the load across multiple servers. This helps improve resilience and can mitigate the impact of a DoS attack by distributing the workload. - Monitoring and Alerting:
Implement robust monitoring and alerting systems to detect and respond to abnormal or suspicious activity. Monitor system metrics, such as CPU and memory usage, incoming connection rates, and query response times to identify potential DoS attack patterns. - Conduct Load Testing and Capacity Planning:
Perform load testing and capacity planning exercises to ensure your MongoDB deployment can handle anticipated workloads. Identify performance bottlenecks and potential limitations in advance to prevent potential DoS situations. - Implement Request Validation:
Validate incoming requests to MongoDB and enforce appropriate checks on the input parameters. Filter out or reject requests that contain suspicious or malicious data to minimize the impact of potential attacks.
Thank you for spending your precious time going through my article :)
Comments
Post a Comment