Implementing Encryption Mechanisms

Data encryption is a vital component of database security, ensuring that sensitive information remains protected even if the database is accessed by unauthorized parties. MongoDB provides various encryption mechanisms for both data at rest (stored data) and data in transit (data being transmitted). In this chapter, we’ll explore MongoDB's encryption options, including setting up field-level encryption, enabling TLS/SSL for encryption in transit, and configuring encrypted backups.

Understanding Encryption in MongoDB

Encryption is the process of transforming readable data (plaintext) into an unreadable format (ciphertext) to prevent unauthorized access. MongoDB offers robust encryption features to protect data, including:

  • Encryption at Rest: Protects stored data from being accessed if storage devices are stolen.
  • Encryption in Transit: Protects data traveling over networks.
  • Field-Level Encryption: Provides granular encryption at the individual field level within documents.

Each encryption type has its own application and configuration methods, which we’ll discuss in the following sections.

Encryption at Rest

Encryption at Rest ensures that data stored on MongoDB servers is encrypted, preventing unauthorized access to data stored on disk. MongoDB Enterprise Edition and MongoDB Atlas provide built-in encryption at rest, enabling data to be automatically encrypted without the need for application-level changes.

Setting Up Encryption at Rest in MongoDB Atlas

MongoDB Atlas, the managed cloud service for MongoDB, offers automatic encryption at rest by default. When you create a MongoDB cluster on Atlas, it automatically encrypts all data at rest using AWS Key Management Service (KMS), Azure Key Vault, or Google Cloud KMS.

  1. Log in to MongoDB Atlas.

  2. Create or Configure a Cluster:

  • Go to your desired project and click “Build a Cluster” or select an existing cluster.

Encryption Settings:

  • Under the cluster configuration options, ensure that “Encryption at Rest” is enabled. Atlas handles encryption using the underlying cloud provider’s encryption keys (e.g., AWS KMS).

No further setup is required on MongoDB Atlas, as it handles all encryption-related configurations on your behalf.

Configuring Encryption at Rest in MongoDB Enterprise Edition

For MongoDB instances running on-premises or on custom infrastructure, MongoDB Enterprise Edition provides encryption at rest.

  1. Install MongoDB Enterprise Edition:

    • MongoDB Enterprise includes the mongod process with encryption-at-rest capabilities. Verify that you have MongoDB Enterprise Edition installed.
  2. Specify the Encryption Key File:

    • MongoDB uses a key file to encrypt the database. You can generate a key file using OpenSSL.
				
					openssl rand -base64 32 > mongodb-keyfile
chmod 600 mongodb-keyfile

				
			

Enable Encryption in the Configuration File:

  • In MongoDB’s configuration file (/etc/mongod.conf), add encryption options.
				
					security:
  enableEncryption: true
  encryptionKeyFile: /path/to/mongodb-keyfil
				
			

Start the MongoDB Server:

  • Restart the MongoDB instance for changes to take effect.
				
					sudo systemctl restart mongod

				
			

Testing Encryption at Rest

Once encryption at rest is enabled, MongoDB automatically encrypts data on disk. However, when accessing data through MongoDB, the application sees it as plaintext because decryption happens automatically within MongoDB.

Output:

After enabling encryption at rest, you won’t notice changes in data behavior at the application level. Data retrieval, updates, and deletions proceed as usual, but the data on disk is now encrypted.

Encryption in Transit (TLS/SSL)

Encryption in transit secures data while it’s being transferred across the network between MongoDB clients and servers. MongoDB provides support for Transport Layer Security (TLS) and Secure Sockets Layer (SSL) for this purpose.

Generating TLS/SSL Certificates

To enable TLS/SSL, you need a server certificate. For development, you can create a self-signed certificate, but for production, it’s recommended to obtain a certificate from a trusted Certificate Authority (CA).

Creating a Self-Signed Certificate (for Testing Purposes)

				
					openssl req -newkey rsa:4096 -nodes -keyout mongodb.key -x509 -days 365 -out mongodb.crt
cat mongodb.key mongodb.crt > mongodb.pem

				
			

Configuring MongoDB to Use TLS/SSL

Edit the MongoDB Configuration File:

  • In /etc/mongod.conf, configure the SSL/TLS settings.
				
					net:
  ssl:
    mode: requireSSL
    PEMKeyFile: /path/to/mongodb.pem
				
			

Start the MongoDB Server:

  • Restart the MongoDB server for the SSL settings to take effect.
				
					net:
  ssl:
    mode: requireSSL
    PEMKeyFile: /path/to/mongodb.pem
				
			

Connecting to MongoDB with TLS/SSL

When connecting to a MongoDB instance that requires SSL, you need to specify the --ssl option and the path to the CA file if the certificate is self-signed.

				
					mongo --host <hostname> --ssl --sslCAFile /path/to/mongodb.crt

				
			

Output:

Using the mongo client with --ssl ensures that data transmitted between your MongoDB server and clients is encrypted, protecting it from eavesdropping.

Field-Level Encryption (FLE)

Field-Level Encryption (FLE) is a powerful feature available in MongoDB Enterprise Edition and MongoDB Atlas. FLE enables you to encrypt specific fields within documents, providing highly granular control over sensitive data.

Setting Up Field-Level Encryption in MongoDB Atlas

1. Define the Encryption Schema:

  • MongoDB uses JSON schema to define which fields should be encrypted.
				
					{
  "bsonType": "object",
  "properties": {
    "name": { "encrypt": { "bsonType": "string", "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" } },
    "ssn": { "encrypt": { "bsonType": "string", "algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random" } }
  }
}
				
			

2. Configure MongoDB Client for Field-Level Encryption:

  • MongoDB clients like Node.js and Python support FLE configuration. You must specify the encryption keys and encryption schema in the client code.

3. Access Encrypted Data:

  • When using FLE, the client handles encryption and decryption. Fields configured for encryption are automatically encrypted before storing them in MongoDB and decrypted when retrieved.

Example with Node.js

To use FLE with MongoDB’s Node.js driver:

				
					const { MongoClient, ClientEncryption } = require('mongodb');

// Client settings with encryption options
const client = new MongoClient("mongodb+srv://<username>:<password>@cluster.mongodb.net", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  autoEncryption: {
    keyVaultNamespace: "encryption.__keyVault",
    kmsProviders: {
      local: {
        key: Buffer.from(process.env.LOCAL_MASTER_KEY, "base64")
      }
    },
    schemaMap: {
      "myDB.myCollection": {
        bsonType: "object",
        properties: {
          ssn: {
            encrypt: {
              bsonType: "string",
              algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
            }
          }
        }
      }
    }
  }
});

async function run() {
  try {
    await client.connect();
    const collection = client.db("myDB").collection("myCollection");
    await collection.insertOne({ name: "John Doe", ssn: "123-45-6789" });
    const result = await collection.findOne({ name: "John Doe" });
    console.log(result);
  } finally {
    await client.close();
  }
}
run();

				
			

Explanation:

  • Key Vault: Stores encryption keys securely.
  • Encryption Schema: Specifies which fields to encrypt and the encryption algorithm.
  • Inserting Data: The ssn field is automatically encrypted when inserted.
  • Retrieving Data: The ssn field is automatically decrypted when queried.

We explored MongoDB’s various encryption mechanisms, from encryption at rest to field-level encryption. Each of these methods ensures that data remains secure at different stages, whether in storage or transit, and at various levels of granularity. Implementing these encryption techniques helps protect sensitive data, comply with regulatory standards, and strengthen the overall security of your MongoDB application. Happy Coding!❤️

Table of Contents