跳到主要内容

安全配置

本章介绍 MongoDB 的安全机制,包括用户认证、角色授权和网络配置。

安全概述

MongoDB 提供多层安全保护:

用户认证

启用认证

// 配置文件启用认证 (mongod.conf)
security:
authorization: enabled

// 命令行启用
mongod --auth --replSet rs0

创建用户

// 创建管理员用户(需要在认证前创建)
use admin
db.createUser({
user: "admin",
pwd: "admin123",
roles: [
{ role: "root", db: "admin" }
]
})

// 创建应用用户
use myapp
db.createUser({
user: "appuser",
pwd: "apppass123",
roles: [
{ role: "readWrite", db: "myapp" },
{ role: "read", db: "myapp_logs" }
]
})

用户认证

// 方法1:连接时指定用户名密码
// mongodb://username:password@host:port/database

// 方法2:连接后认证
use admin
db.auth("admin", "admin123")
// 返回 1 表示成功

// 方法3:mongosh 中使用 --username 参数
mongosh -u admin -p --authenticationDatabase admin

角色授权

内置角色

MongoDB 提供了丰富的内置角色:

角色说明
read读取指定数据库所有非系统集合
readWriteread 权限 + 写入/修改/删除
dbAdmin管理数据库(非用户)
dbOwnerdbAdmin + readWrite + 用户管理
userAdmin管理数据库用户和角色
clusterAdmin管理集群(副本集、分片)
clusterMonitor监控工具readonly访问
backup备份权限
restore恢复权限
root超级管理员

查看角色

// 查看当前数据库的所有角色
db.getRoles()

// 查看某个角色的详细信息
db.getRole("readWrite", { showPrivileges: true })

// 查看用户的角色
db.getUser("username")

自定义角色

// 创建自定义角色
db.createRole({
role: "customRole",
privileges: [
{
resource: { db: "myapp", collection: "orders" },
actions: ["find", "update", "insert"]
},
{
resource: { db: "myapp", collection: "reports" },
actions: ["find"]
}
],
roles: [] // 继承的其他角色
})

// 为用户分配自定义角色
db.grantRolesToUser("appuser", [{ role: "customRole", db: "admin" }])

// 移除用户角色
db.revokeRolesFromUser("appuser", [{ role: "customRole", db: "admin" }])

资源文档

资源可以是数据库或集合:

// 数据库级别
{ db: "myapp", collection: "" }

// 集合级别
{ db: "myapp", collection: "orders" }

// 所有数据库
{ db: "", collection: "" }

// 集群资源
{ cluster: true }

操作列表

// 常用操作
// 集合操作:find, insert, update, remove, createIndex, dropCollection
// 数据库操作: dbStats, collStats
// 管理操作: shutdown, replSetGetStatus
// 用户操作: createUser, grantRole

用户管理

用户操作

// 更新用户密码
db.updateUser("appuser", { pwd: "newpassword" })

// 删除用户
db.dropUser("appuser")

// 删除所有用户(需先切换到该数据库)
db.dropAllUsers()

// 查看所有用户
db.getAllUsers()

// 验证用户权限
db.runCommand({ usersInfo: "appuser", showPrivileges: true })

LDAP 认证(企业版)

// 配置 LDAP 认证
security:
authorization: enabled
authenticationMechanisms: PLAIN,SCRAM-SHA-1,SCRAM-SHA-256

网络安全

TLS/SSL 配置

// mongod 配置 TLS
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem
allowConnectionsWithoutCertificates: true

防火墙配置

# iptables 限制访问
iptables -A INPUT -p tcp --dport 27017 -s 192.168.1.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 27017 -j DROP

绑定 IP

// 只允许本地和特定 IP
net:
bindIp: 127.0.0.1,192.168.1.100

// 命令行
mongod --bind_ip "127.0.0.1,192.168.1.100"

审计

启用审计

// mongod 配置
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.log

审计过滤器

// 只记录特定操作
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.log
filter: '{ "atype": { "$in": ["createUser", "dropUser"] } }'

最佳实践

1. 强密码策略

// 使用复杂密码
db.createUser({
user: "secureuser",
pwd: "K8#mNp$2xL!wQ9", // 包含大小写、数字、特殊字符
roles: [{ role: "readWrite", db: "myapp" }]
})

2. 最小权限原则

// 不使用 root 用户进行应用操作
// 创建特定角色

// 为报表用户创建只读角色
db.createRole({
role: "reportsReader",
privileges: [
{ resource: { db: "analytics", collection: "" }, actions: ["find"] }
],
roles: []
})

3. 网络隔离

// 生产环境配置
net:
bindIp: 10.0.0.0/16 # 只允许内网
ssl:
mode: requireSSL

4. 定期审计

// 定期检查用户
db.getAllUsers().forEach(user => {
print(`User: ${user.user}, Roles: ${JSON.stringify(user.roles)}`)
})

// 检查异常登录
db.system.profile.find({ "clientMetadata.application.name": "unknown" })

配置文件示例

# mongod.conf - 生产环境配置
storage:
dbPath: /data/db
journal:
enabled: true

systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true

net:
port: 27017
bindIp: 127.0.0.1,10.0.0.100
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem

security:
authorization: enabled
javascriptEnabled: false

processManagement:
timeZoneInfo: /usr/share/zoneinfo

小结

本章我们学习了:

  1. 认证:用户创建和身份验证(SCRAM-SHA)
  2. 授权:内置角色和自定义角色
  3. 用户管理:用户操作和权限管理
  4. 网络安全:TLS/SSL、防火墙、IP绑定
  5. 审计:审计日志和过滤
  6. 最佳实践:强密码、最小权限、网络隔离