Skip to content

安全管理

用户管理

创建用户

javascript
db.createUser({
  user: "admin",
  pwd: "Admin@123",
  roles: [
    { role: "userAdminAnyDatabase", db: "admin" },
    { role: "readWriteAnyDatabase", db: "admin" },
  ],
});

db.createUser({
  user: "appuser",
  pwd: "App@123",
  roles: [{ role: "readWrite", db: "mydb" }],
});

查看用户

javascript
use admin
db.system.users.find()
db.getUsers()
db.getUser('appuser')

修改密码

javascript
db.changeUserPassword("appuser", "NewPass@123");

更新用户

javascript
db.updateUser("appuser", {
  roles: [
    { role: "readWrite", db: "mydb" },
    { role: "read", db: "reports" },
  ],
});

删除用户

javascript
db.dropUser("appuser");
db.dropAllUsers();

角色管理

内置角色

数据库用户角色

角色说明
read读取权限
readWrite读写权限

数据库管理角色

角色说明
dbAdmin数据库管理
dbOwner数据库所有者
userAdmin用户管理

集群管理角色

角色说明
clusterAdmin集群管理
clusterManager集群监控和管理
clusterMonitor集群监控
hostManager服务器管理

备份恢复角色

角色说明
backup备份权限
restore恢复权限

全局角色

角色说明
readAnyDatabase读取任意数据库
readWriteAnyDatabase读写任意数据库
userAdminAnyDatabase管理任意数据库用户
dbAdminAnyDatabase管理任意数据库
root超级管理员

创建自定义角色

javascript
db.createRole({
  role: "readOnlyRole",
  privileges: [{ resource: { db: "mydb", collection: "" }, actions: ["find"] }],
  roles: [],
});

db.createRole({
  role: "appRole",
  privileges: [
    {
      resource: { db: "mydb", collection: "users" },
      actions: ["find", "insert", "update"],
    },
    {
      resource: { db: "mydb", collection: "orders" },
      actions: ["find", "insert"],
    },
  ],
  roles: [{ role: "read", db: "mydb" }],
});

查看角色

javascript
db.getRoles();
db.getRole("readOnlyRole", { showPrivileges: true });

删除角色

javascript
db.dropRole("readOnlyRole");
db.dropAllRoles();

授予角色

javascript
db.grantRolesToUser("appuser", [{ role: "readWrite", db: "mydb" }]);

撤销角色

javascript
db.revokeRolesFromUser("appuser", [{ role: "read", db: "reports" }]);

权限操作

操作类型

操作说明
find查询
insert插入
update更新
remove删除
createCollection创建集合
dropCollection删除集合
createIndex创建索引
dropIndex删除索引

授予权限

javascript
db.grantPrivilegesToRole("appRole", [
  {
    resource: { db: "mydb", collection: "products" },
    actions: ["find", "insert", "update"],
  },
]);

撤销权限

javascript
db.revokePrivilegesFromRole("appRole", [
  {
    resource: { db: "mydb", collection: "products" },
    actions: ["remove"],
  },
]);

认证机制

启用认证

yaml
security:
  authorization: enabled

认证方式

SCRAM (默认)

javascript
db.createUser({
  user: "user",
  pwd: "password",
  roles: ["readWrite"],
});

x.509 证书

yaml
security:
  clusterAuthMode: x509
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /path/to/mongodb.pem
    CAFile: /path/to/ca.pem
javascript
db.getSiblingDB("$external").createUser({
  user: "CN=user,OU=users,O=company,C=CN",
  roles: [{ role: "readWrite", db: "mydb" }],
});

连接认证

bash
mongosh "mongodb://user:password@localhost:27017/mydb?authSource=admin"

mongosh "mongodb://localhost:27017" --username user --password --authenticationDatabase admin

TLS/SSL 加密

配置 TLS

yaml
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /path/to/mongodb.pem
    CAFile: /path/to/ca.pem
    allowConnectionsWithoutCertificates: false

TLS 模式

模式说明
disabled禁用 TLS
allowTLS允许 TLS
preferTLS优先 TLS
requireTLS强制 TLS

生成证书

bash
openssl req -new -x509 -days 365 -nodes -out mongodb-cert.crt -keyout mongodb-cert.key
cat mongodb-cert.key mongodb-cert.crt > mongodb.pem

连接 TLS

bash
mongosh "mongodb://localhost:27017" --tls --tlsCAFile /path/to/ca.pem
mongosh "mongodb://localhost:27017" --tls --tlsCAFile /path/to/ca.pem --tlsCertificateKeyFile /path/to/client.pem

网络安全

绑定地址

yaml
net:
  bindIp: 127.0.0.1,192.168.1.100
  port: 27017

限制访问

yaml
security:
  javascriptEnabled: false

禁用 HTTP 接口

yaml
net:
  http:
    enabled: false

防火墙配置

bash
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 27017 -j ACCEPT
iptables -A INPUT -p tcp --dport 27017 -j DROP

审计日志

启用审计

yaml
security:
  auditLog:
    destination: file
    format: JSON
    path: /var/log/mongodb/audit.log

审计目标

目标说明
file文件
console控制台
syslog系统日志

审计格式

格式说明
JSONJSON 格式
BSONBSON 格式

审计过滤器

yaml
security:
  auditLog:
    destination: file
    format: JSON
    path: /var/log/mongodb/audit.log
    filter: '{ "atype": { "$in": [ "authenticate", "createUser", "dropUser" ] } }'

审计事件类型

事件说明
authenticate认证
createUser创建用户
dropUser删除用户
createCollection创建集合
dropCollection删除集合
insert插入
update更新
delete删除

数据加密

静态加密

yaml
security:
  enableEncryption: true
  encryptionKeyFile: /path/to/keyfile

WiredTiger 加密

yaml
storage:
  wiredTiger:
    engineConfig:
      encryptionCipherMode: AES256-CBC

字段级加密

javascript
const clientEncryption = db.getMongo().getClientEncryption();

let keyId = clientEncryption.createDataKey("local");

let encrypted = clientEncryption.encrypt(
  keyId,
  "sensitive data",
  "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
);

let decrypted = clientEncryption.decrypt(encrypted);

加密函数

javascript
db.users.insertOne({
  name: "张三",
  ssn: encrypt("123456789"),
});

function encrypt(value) {
  return db.runCommand({
    encrypt: 1,
    value: value,
    keyId: UUID("..."),
    algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
  });
}

安全配置

配置文件

yaml
security:
  authorization: enabled
  javascriptEnabled: false

net:
  bindIp: 127.0.0.1
  port: 27017
  tls:
    mode: requireTLS
    certificateKeyFile: /path/to/mongodb.pem
    CAFile: /path/to/ca.pem

storage:
  wiredTiger:
    engineConfig:
      encryptionCipherMode: AES256-CBC

禁用危险功能

yaml
security:
  javascriptEnabled: false

storage:
  journal:
    enabled: true

限制操作

javascript
db.adminCommand({
  setParameter: 1,
  notablescan: true,
});

安全检查清单

1. 认证授权

  • [ ] 启用身份认证
  • [ ] 使用强密码
  • [ ] 遵循最小权限原则
  • [ ] 定期审计用户权限

2. 网络安全

  • [ ] 限制绑定地址
  • [ ] 启用 TLS/SSL
  • [ ] 配置防火墙
  • [ ] 禁用 HTTP 接口

3. 数据安全

  • [ ] 启用静态加密
  • [ ] 敏感数据字段加密
  • [ ] 定期备份
  • [ ] 加密备份文件

4. 审计监控

  • [ ] 启用审计日志
  • [ ] 监控异常登录
  • [ ] 记录敏感操作
  • [ ] 定期检查日志

5. 系统安全

  • [ ] 更新 MongoDB 版本
  • [ ] 限制文件访问权限
  • [ ] 使用专用用户运行
  • [ ] 定期安全扫描

安全脚本

初始化安全配置

javascript
use admin

db.createUser({
    user: 'admin',
    pwd: 'StrongPassword@123',
    roles: ['root']
})

db.createUser({
    user: 'appuser',
    pwd: 'AppPassword@123',
    roles: [
        { role: 'readWrite', db: 'mydb' }
    ]
})

db.dropUser('')

db.adminCommand({
    setParameter: 1,
    javascriptEnabled: false
})

权限审计

javascript
db.system.users
  .find(
    {},
    {
      user: 1,
      roles: 1,
      _id: 0,
    },
  )
  .forEach(function (user) {
    print("User: " + user.user);
    user.roles.forEach(function (role) {
      print("  Role: " + role.role + " on " + role.db);
    });
  });

下一步学习