Skip to main content

Bảo Mật MongoDB Từ Cơ Bản Đến Pro – Cái Bẫy Thường Gặp & Cách Phòng Tránh

Posted on:  at 
Tutorials
Picture

Giới thiệu

MongoDB là một trong những cơ sở dữ liệu NoSQL phổ biến nhất hiện nay, được sử dụng rộng rãi trong các ứng dụng web hiện đại. Tuy nhiên, để đảm bảo an toàn cho dữ liệu, việc hiểu rõ về bảo mật và phân quyền user trong MongoDB là vô cùng quan trọng. Bài viết này sẽ hướng dẫn chi tiết về các khía cạnh bảo mật cần thiết khi làm việc với MongoDB.

1. Tổng quan về bảo mật trong MongoDB

Các tính năng bảo mật chính

MongoDB cung cấp nhiều lớp bảo mật để bảo vệ dữ liệu:

  • Authentication (Xác thực): Xác định danh tính user
  • Authorization (Phân quyền): Kiểm soát quyền truy cập tài nguyên
  • Encryption (Mã hóa): Bảo vệ dữ liệu khi truyền tải và lưu trữ
  • Auditing (Kiểm toán): Theo dõi và ghi lại các hoạt động
  • Network Security (Bảo mật mạng): Kiểm soát kết nối mạng

Nguyên tắc bảo mật "Defense in Depth"

MongoDB áp dụng nguyên tắc nhiều lớp bảo mật, đảm bảo rằng ngay cả khi một lớp bị xâm phạm, các lớp khác vẫn có thể bảo vệ hệ thống.

2. Authentication - Xác thực User

2.1 Kích hoạt Authentication

Mặc định, MongoDB không yêu cầu authentication. Để kích hoạt:

# Trong file mongod.conf
security:
  authorization: enabled

Hoặc khởi động với tham số:

mongod --auth

2.2 Các phương thức Authentication

SCRAM (Salted Challenge Response Authentication Mechanism)

Đây là phương thức mặc định và được khuyến nghị:

// Tạo user với SCRAM
db.createUser({
  user: "admin",
  pwd: "securePassword123",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

x.509 Certificate Authentication

Sử dụng chứng chỉ SSL/TLS cho authentication:

// Kết nối với x.509
mongo --ssl --sslPEMKeyFile client.pem --sslCAFile ca.pem --authenticationDatabase '$external' --authenticationMechanism MONGODB-X509

LDAP Authentication

Tích hợp với hệ thống LDAP hiện có:

# Cấu hình LDAP trong mongod.conf
security:
  ldap:
    servers: "ldap.company.com"
    bind:
      method: "simple"
      saslAuthzTo: "cn={USER},ou=users,dc=company,dc=com"

3. Authorization - Phân quyền và Quản lý Role

3.1 Hệ thống Role-Based Access Control (RBAC)

MongoDB sử dụng hệ thống phân quyền dựa trên role, cho phép kiểm soát chi tiết quyền truy cập.

Built-in Roles

Database User Roles:

  • read: Chỉ đọc dữ liệu
  • readWrite: Đọc và ghi dữ liệu

Database Administration Roles:

  • dbAdmin: Quản lý database
  • userAdmin: Quản lý user và role

Cluster Administration Roles:

  • clusterAdmin: Quản lý toàn bộ cluster
  • clusterManager: Quản lý và giám sát cluster

All-Database Roles:

  • readAnyDatabase: Đọc tất cả database
  • userAdminAnyDatabase: Quản lý user trên tất cả database

3.2 Tạo và Quản lý User

Tạo user cơ bản

// Tạo user chỉ đọc cho database 'products'
use products
db.createUser({
  user: "readOnlyUser",
  pwd: "password123",
  roles: [{ role: "read", db: "products" }]
})

// Tạo user có quyền đọc/ghi cho database 'inventory'
use inventory
db.createUser({
  user: "inventoryManager",
  pwd: "securePass456",
  roles: [{ role: "readWrite", db: "inventory" }]
})

Tạo user với nhiều role

// User có quyền trên nhiều database
db.createUser({
  user: "multiDbUser",
  pwd: "complexPassword789",
  roles: [
    { role: "readWrite", db: "sales" },
    { role: "read", db: "analytics" },
    { role: "dbAdmin", db: "logs" }
  ]
})

3.3 Custom Roles

Tạo role tùy chỉnh cho nhu cầu cụ thể:

// Tạo role cho phép đọc và tạo index
db.createRole({
  role: "readAndCreateIndex",
  privileges: [
    {
      resource: { db: "products", collection: "" },
      actions: ["find", "createIndex", "dropIndex"]
    }
  ],
  roles: []
})

// Gán role tùy chỉnh cho user
db.createUser({
  user: "indexManager",
  pwd: "indexPass123",
  roles: ["readAndCreateIndex"]
})

3.4 Quản lý User và Role

// Xem thông tin user
db.getUser("username")

// Cập nhật password
db.changeUserPassword("username", "newPassword")

// Thêm role cho user
db.grantRolesToUser("username", [{ role: "readWrite", db: "newDatabase" }])

// Xóa role khỏi user
db.revokeRolesFromUser("username", [{ role: "read", db: "oldDatabase" }])

// Xóa user
db.dropUser("username")

4. Encryption - Mã hóa Dữ liệu

4.1 Encryption in Transit (TLS/SSL)

# Cấu hình SSL trong mongod.conf
net:
  ssl:
    mode: requireSSL
    PEMKeyFile: /path/to/server.pem
    CAFile: /path/to/ca.pem

4.2 Encryption at Rest

# Kích hoạt mã hóa dữ liệu
security:
  enableEncryption: true
  encryptionKeyFile: /path/to/keyfile

4.3 Field Level Encryption

// Tạo client với field level encryption
const clientEncryption = new ClientEncryption(keyVault, {
  keyVaultNamespace: 'encryption.__keyVault',
  kmsProviders: {
    local: {
      key: localMasterKey
    }
  }
});

// Mã hóa field trước khi insert
const encryptedSSN = await clientEncryption.encrypt(
  "123-45-6789",
  {
    algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
    keyId: dataKeyId
  }
);

5. Network Security - Bảo mật Mạng

5.1 IP Binding

# Chỉ cho phép kết nối từ specific IP
net:
  bindIp: 127.0.0.1,192.168.1.100

5.2 Firewall Configuration

# Chỉ mở port 27017 cho trusted networks
iptables -A INPUT -p tcp --dport 27017 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 27017 -j DROP

6. Auditing - Kiểm toán Hệ thống

6.1 Kích hoạt Auditing

# Cấu hình audit trong mongod.conf
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{ "users.user": { $ne: "system" } }'

6.2 Các sự kiện Audit quan trọng

// Filter audit cho authentication events
{
  "atype": { $in: ["authenticate", "authCheck"] }
}

// Filter cho schema changes
{
  "atype": { $in: ["createCollection", "dropCollection", "createIndex"] }
}

7. Best Practices - Thực hành Tốt nhất

7.1 Password Policy

// Đặt policy password mạnh
db.adminCommand({
  setParameter: 1,
  passwordMinLength: 12,
  passwordComplexity: {
    requireLowercase: true,
    requireUppercase: true,
    requireNumbers: true,
    requireSpecialCharacters: true
  }
})

7.2 Principle of Least Privilege

  • Chỉ cấp quyền tối thiểu cần thiết
  • Thường xuyên review và cleanup quyền không sử dụng
  • Sử dụng role-based thay vì gán quyền trực tiếp

7.3 Regular Security Maintenance

// Script kiểm tra user không hoạt động
db.runCommand({
  usersInfo: 1,
  showCredentials: false,
  showCustomData: false
}).users.forEach(function(user) {
  // Logic kiểm tra last login time
  if (user.customData && user.customData.lastLogin) {
    const daysSinceLogin = (new Date() - new Date(user.customData.lastLogin)) / (1000 * 60 * 60 * 24);
    if (daysSinceLogin > 90) {
      print("User " + user.user + " inactive for " + daysSinceLogin + " days");
    }
  }
});

7.4 Connection String Security

// Sử dụng connection string an toàn
const uri = "mongodb://username:password@host:port/database?ssl=true&authSource=admin";

// Tránh hard-code credentials
const uri = `mongodb://${process.env.DB_USER}:${process.env.DB_PASS}@${process.env.DB_HOST}/${process.env.DB_NAME}`;

8. Monitoring và Alerting

8.1 Giám sát Authentication Failures

// Query audit log cho failed authentications
db.audit.find({
  "atype": "authenticate",
  "result": { $ne: 0 }
}).limit(10).sort({ "ts": -1 })

8.2 Thiết lập Alerts

# Script bash để monitor failed logins
#!/bin/bash
FAILED_LOGINS=$(grep "authenticate" /var/log/mongodb/audit.json | grep '"result":[^0]' | wc -l)
if [ $FAILED_LOGINS -gt 10 ]; then
  echo "High number of failed authentication attempts: $FAILED_LOGINS" | mail -s "MongoDB Security Alert" admin@company.com
fi

9. Backup và Recovery Security

9.1 Secure Backup

# Backup với mã hóa
mongodump --host localhost --port 27017 --username backupUser --password --authenticationDatabase admin --gzip --archive=/encrypted/backup/$(date +%Y%m%d).gz

9.2 Access Control cho Backup

// Tạo user chỉ cho backup
db.createUser({
  user: "backupUser",
  pwd: "backupPassword123",
  roles: ["backup", "clusterMonitor"]
})

10. Kết luận

Bảo mật MongoDB đòi hỏi một cách tiếp cận toàn diện, bao gồm nhiều lớp bảo vệ từ authentication, authorization đến encryption và monitoring. Việc triển khai đúng các biện pháp bảo mật không chỉ bảo vệ dữ liệu mà còn đảm bảo tuân thủ các quy định về bảo mật dữ liệu.

Quan trọng nhất là phải thường xuyên cập nhật kiến thức về bảo mật, thực hiện audit định kỳ và luôn áp dụng nguyên tắc "principle of least privilege" trong mọi quyết định phân quyền.

Tài liệu tham khảo


Bài viết này cung cấp hướng dẫn cơ bản về bảo mật MongoDB. Trong môi trường production, hãy luôn tham khảo thêm documentation chính thức và cân nhắc tư vấn từ chuyên gia bảo mật.