安全

依赖环境准备

自签名证书生成

0. openssl 配置文件说明

文件 说明

openssl-ca.cnf

设定默认 CN,OU 等名称

openssl-server.cnf

设定默认 CN,OU 等名称,设定 Server DNS 名称为 localhost, server.example.com

openssl-client.cnf

设定默认 CN,OU 等名称

1. 生成一个 CA 密钥文件
$ openssl genrsa -out ca.key 4096
2. 使用 CA 密钥生成 CA 证书
$ openssl req -new -x509 -days 3650 -key ca.key -out ca.crt -config openssl-ca.cnf
Note
Common Name 需要输入一个名称,例如 localhost,其余部分使用配置文件中的默认名称
3. 生成一个密钥文件,用做中介密钥
$ openssl genrsa -out ia.key 4096
4. 根据中介密钥生成一个证书签名请求文件
$ openssl req -new -key ia.key -out ia.csr -config openssl-ca.cnf
Note
Common Name 需要输入一个名称,例如 localhost,其余部分使用配置文件中的默认名称
5. 生成一个中介自签名证书
$ openssl x509 -sha256 -req -days 3650 -in ia.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out ia.crt -extfile openssl-ca.cnf -extensions v3_ca
6. 创建 CA PEM 文件
$ cat ca.crt ia.crt > ca.pem
7. 生成一个 Server 密钥文件
$ openssl genrsa -out server.key 4096
8. 根据 Server 密钥生成一个证书签名请求文件
$ openssl req -new -key server.key -out server.csr -config openssl-server.cnf
Note
Common Name 需要输入一个名称,例如 server.example.com,其余部分使用配置文件中的默认名称
9. 根据中介密钥,中介证书,及 Server 证书签名请求文件生产 server 自签名证书
$ openssl x509 -sha256 -req -days 3650 -in server.csr -CA ia.crt -CAkey ia.key -CAcreateserial -out server.crt -extfile openssl-server.cnf -extensions v3_req
10. 创建 server PEM 文件
$ cat server.crt server.key > server.pem
11. 生成一个 Client 密钥文件
$ openssl genrsa -out client.key 4096
12. 根据 Client 密钥生成一个证书签名请求文件
$ openssl req -new -key client.key -out client.csr -config openssl-client.cnf
Note
Common Name 需要输入一个名称,例如 client.example.com,其余部分使用配置文件中的默认名称
13. 根据中介密钥,中介证书,及 Client 证书签名请求文件生产 Client 自签名证书
$ openssl x509 -sha256 -req -days 3650 -in client.csr -CA ia.crt -CAkey ia.key -CAcreateserial -out client.crt -extfile openssl-client.cnf -extensions v3_req
14. 创建 server PEM 文件
$ cat client.crt client.key > client.pem
15. 查看 PEM 文件subject
$ for i in $(ls *.pem) ; do openssl x509 -in $i -inform PEM -subject -nameopt RFC2253 -noout ; done
subject= CN=localhost,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN
subject= CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN
subject= CN=server.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN

Authentication

两种认证方法

编号 认证方法

1

$ mongo admin -u root -p mongo

2

$ mongo -u root -p mongo --authenticationDatabase admin

SCRAM-SHA-1/SCRAM-SHA-256 认证

1. 启动 mongod,并创建管理用户
$ mkdir -p data/db
$ mongod --dbpath data/db/ --logpath data/db/mongod.log --auth --fork
$ mongo admin --eval 'db.createUser({user: "superuser", pwd: "password", roles: [{role: "root", db: "admin"}]})'
2. 安全登录,执行如下命令查看认证机制
$ mongo -u superuser -p password --authenticationDatabase admin

db.runCommand({getParameter: 1, authenticationMechanisms: 1})
{
	"authenticationMechanisms" : [
		"MONGODB-X509",
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	],
	"ok" : 1
}
Note
如下命令可正确从 Shell 执行:
$ mongo admin -u superuser -p password --eval "db.runCommand({getParameter: 1, authenticationMechanisms: 1})"

$ mongo admin --eval "db.auth('superuser', 'password');db.runCommand({getParameter: 1, authenticationMechanisms: 1})"

$ mongo -u superuser -p password --eval "db=db.getSisterDB('admin');db.runCommand({getParameter: 1, authenticationMechanisms: 1})"
3. 查看 SHA-1/SHA-256 加密串
$ mongo admin -u "superuser" -p "password" --eval 'db.system.users.find().pretty()'
{
	"_id" : "admin.superuser",
	"userId" : UUID("c0f0d3fe-b047-4279-810d-e5a248fb359e"),
	"user" : "superuser",
	"db" : "admin",
	"credentials" : {
		"SCRAM-SHA-1" : {
			"iterationCount" : 10000,
			"salt" : "uKjXKBWEAEn7SZRepZQnvw==",
			"storedKey" : "FsFVBjmUm9xZOE/yr8e+GNSaWrs=",
			"serverKey" : "Y4LPJhOA1IZV6KmpCiJHIX2UrmU="
		},
		"SCRAM-SHA-256" : {
			"iterationCount" : 15000,
			"salt" : "qmy7h7JaaoHQOLS8Q4OMEcTFYrfgOlflgBzt2w==",
			"storedKey" : "YGFaUMsVrcO7LRrdQJ0V7tgENyPLXtIf0LfPRU/UD/8=",
			"serverKey" : "5ADI2L+r0l5g7u6Pj2+Lg9g3W69J97omv9U7b5S1mio="
		}
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}

X.509 认证

1. 根据依赖环境准备自签名证书生成 部分生成证书

2. 启动 mongod 服务
$ mongod --sslMode requireSSL --sslPEMKeyFile server.pem  --sslCAFile ca.pem --auth
3. mongo shell 连接认证
$ mongo --ssl --sslPEMKeyFile client.pem  --sslCAFile ca.pem --host server.example.com:27017

> db.getSiblingDB("$external").runCommand({createUser: "CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN", roles: [{role: 'root', db: 'admin'}]});
{ "ok" : 1 }

> db.getSiblingDB("$external").auth({user: 'CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN', mechanism: 'MONGODB-X509'})
1
4. 查看用户
> db.system.users.find().pretty()
{
	"_id" : "$external.CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN",
	"user" : "CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN",
	"db" : "$external",
	"credentials" : {
		"external" : true
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}

Keyfile 内部认证

1. 生成 Keyfile,及数据库数据存储目录
$ openssl rand -base64 755 > keyfile
$ chmod 400 keyfile

$ mkdir -p r{0,1,2}
2. 启动复制子集,初始化,创建用户,并添加备节点
$ for i in 0 1 2 ; do mongod --dbpath r$i --logpath r$i/mongo.log --port 2700$i --fork --auth --keyFile keyfile --replSet repl-1 ; done

$ mongo admin --port 27000 --eval "rs.initiate()"

$ mongo admin --port 27000 --eval 'db.createUser({user: "root", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27002")'
3. 查看复制子集成员,并输出成员名称
$ mongo admin --port 27000 -u "root" -p "mongo" --eval '
var status = rs.status();
var statuses = status.members.map((member) => (member.stateStr)).sort();
print(JSON.stringify(statuses));
'

["PRIMARY","SECONDARY","SECONDARY"]

X.509 内部认证

1. 生成数据存储目录
$ mkdir -p r{0,1,2}
2. 启动复制子集,初始化,创建用户,并添加备节点
$ for i in 0 1 2 ; do mongod --dbpath r$i --logpath r$i/mongo.log --port 2700$i --fork --auth --replSet repl-2 --sslMode requireSSL --clusterAuthMode x509 --sslPEMKeyFile server.pem --sslCAFile ca.pem; done

$ mongo --ssl --sslPEMKeyFile client.pem  --sslCAFile ca.pem --host server.example.com:27000 --eval "rs.initiate()"

$ mongo --ssl --sslPEMKeyFile client.pem  --sslCAFile ca.pem --host server.example.com:27000

> use $external
> db.createUser({user:"CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN",roles:[{ role: "root", db: "admin" }]})
> db.auth({user: 'CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN', mechanism: 'MONGODB-X509'})

> rs.add("server.example.com:27001")
> rs.add("server.example.com:27002")

升级 MONGODB-CR 到 SCRAM-SHA-1

1. 查看升级前用户
$ mongo admin --eval 'db.system.users.find().pretty()'

{
        "_id" : "admin.alice",
        "user" : "alice",
        "db" : "admin",
        "credentials" : {
                "MONGODB-CR" : "b2d1852f112d209beb4b60a128da1bd2"
        },
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}
2. 升级
$ mongo admin --eval "db.adminCommand({authSchemaUpgrade: 1})"
3. 查看升级后用户
$ mongo admin --eval 'db.system.users.find().pretty()'

{
	"_id" : "admin.alice",
	"user" : "alice",
	"db" : "admin",
	"credentials" : {
		"SCRAM-SHA-1" : {
			"iterationCount" : 10000,
			"salt" : "gUOesIq6elvRPkOaTLZnlw==",
			"storedKey" : "EVgfcW705Tq9ymvUm/XCDtHuE3Q=",
			"serverKey" : "rXcgDeb5fstljhEWRO4/6hkAfT4="
		}
	},
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	]
}

多种认证机制一起使用

1. 生成 Keyfile,及数据库数据存储目录,启动数据库,并初始化
$ mkdir -p ~/tmp/{r0,r1,r2}

$ openssl rand -base64 755 > ~/tmp/keyfile
$ chmod 400 ~/tmp/keyfile

$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --auth --replSet repl-1 --sslMode allowSSL --keyFile keyfile --sslCAFile ca.pem --sslPEMKeyFile server.pem; done

//初始化
$ mongo admin --port 27000 --eval "rs.initiate()"

//创建安全登录账户
$ mongo admin --port 27000 --eval 'db.createUser({user: "root", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

//添加备节点
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27002")'
2. 创建一个外部账户
$ openssl x509 -in client.pem -inform PEM -subject -nameopt RFC2253 -noout

$ mongo admin --port 27000 -u root -p mongo

use $external
db.runCommand({
  createUser: 'CN=client.example.com,OU=SA,O=MongoDB,L=Beijing,ST=Beijing,C=CN',
  roles: [{ role: 'userAdminAnyDatabase', db: 'admin' }],
  writeConcern: { w: "majority" , wtimeout: 5000
}});
**
**
**

Authorization

创建不同权限的管理用户

本部分基于 3 节点的复制子集创建 4 个用户,且这些用户有不同的权限,具体需要创建的用户和权限说明如下:

User Password Can Cannot

userAdmin

mongo

create user on any database

run dbhash

sysAdmin

mongo

config replica set and add shards

run hostinfo

dbAdmin

mongo

create a collection on any database

run insert

dataLoader

mongo

insert data on any database

run validate

1. 创建 3 节点复制集,创建超级管理员用户,初始化复制集
//创建数据库存储文件及内部通信加密文件
$ mkdir -p ~/tmp/r{0,1,2}
$ openssl rand -base64 755 > ~/tmp/keyfile
$ chmod 400 ~/tmp/keyfile

//启动
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --auth --keyFile ~/tmp/keyfile --replSet repl-1 ; done

//初始化
$ mongo admin --port 27000 --eval "rs.initiate()"

//创建安全登录账户
$ mongo admin --port 27000 --eval 'db.createUser({user: "root", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

//添加备节点
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27002")'
2. 创建用户
$ mongo admin -u root -p mongo --port 27000

db.createUser({user: "userAdmin", pwd: "mongo", roles: [{ role:"userAdminAnyDatabase", db: "admin" }]})
db.createUser({user: "sysAdmin", pwd: "mongo", roles: [{ role:"clusterManager", db: "admin" }]})
db.createUser({user: "dbAdmin", pwd: "mongo", roles: [{ role:"dbAdminAnyDatabase", db: "admin" }]})
db.createUser({user: "dataLoader", pwd: "mongo", roles: [{ role:"readWriteAnyDatabase", db: "admin" }]})
3. 查看创建的用户
$ mongo admin -u root -p mongo  --port 27000 --eval "db.auth('userAdmin', 'mongo');
          var users = db.system.users.find().toArray();
          var sortedUsers = users.map((user) => {
            return {
              user: user.user,
              roles: user.roles
            };
          }).sort((a, b) => (a.user > b.user));
          db.auth('sysAdmin', 'mongo');
          var numMembers = rs.status().members.length;
          var obj = {
            users: sortedUsers,
            numMembers: numMembers
          };
          print(JSON.stringify(obj));"

{"users":[{"user":"dataLoader","roles":[{"role":"readWriteAnyDatabase","db":"admin"}]},{"user":"dbAdmin","roles":[{"role":"dbAdminAnyDatabase","db":"admin"}]},{"user":"root","roles":[{"role":"root","db":"admin"}]},{"user":"sysAdmin","roles":[{"role":"clusterManager","db":"admin"}]},{"user":"userAdmin","roles":[{"role":"userAdminAnyDatabase","db":"admin"}]}],"numMembers":3}

创建不同权限的应用用户

本部分基于 3 节点的复制子集创建 2 个应用用户,且这些用户有不同的权限。具体需要创建的用户和权限说明如下:

1. 创建 3 节点复制集,创建超级管理员用户,初始化复制集
//创建数据库存储文件及内部通信加密文件
$ mkdir -p ~/tmp/r{0,1,2}
$ openssl rand -base64 755 > ~/tmp/keyfile
$ chmod 400 ~/tmp/keyfile

//启动
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --auth --keyFile ~/tmp/keyfile --replSet repl-1 ; done

//初始化
$ mongo admin --port 27000 --eval "rs.initiate()"

//创建安全登录账户
$ mongo admin --port 27000 --eval 'db.createUser({user: "admin", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

//添加备节点
$ mongo admin --port 27000 -u "admin" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "admin" -p "mongo" --eval 'rs.add("localhost:27002")'
2. 创建用户
$ mongo admin -u admin -p mongo --port 27000

db.createUser({user: "reader", pwd: "mongo", roles: [{ role:"read", db: "acme" }]})
db.createUser({user: "writer", pwd: "mongo", roles: [{ role:"readWrite", db: "acme" }]})
3. 查看创建的用户
$ mongo admin --port 27000 -u admin -p mongo  --eval "db.auth('admin', 'webscale');
          var users = db.system.users.find().toArray();
          var sortedUsers = users.map((user) => {
            return {
              user: user.user,
              roles: user.roles
            };
          }).sort((a, b) => (a.user > b.user));
          var numMembers = rs.status().members.length;
          var obj = {
            users: sortedUsers,
            numMembers: numMembers
          };
          print(JSON.stringify(obj));"
{"users":[{"user":"admin","roles":[{"role":"root","db":"admin"}]},{"user":"reader","roles":[{"role":"read","db":"acme"}]},{"user":"writer","roles":[{"role":"readWrite","db":"acme"}]}],"numMembers":3}

创建自定制角色

创建如下自定制角色,满足如下特权:

Role 名称 Privileges

HRDEPARTMENT

  • Can find documents on any collection on the HR database

  • Can insert documents only on HR.employees collection

  • Can remove users from the HR database

MANAGEMENT

  • Inherits the dbOwner role of the HR database

EMPLOYEEPORTAL

  • Can find documents on HR.employees collection

  • Can update HR.employees documents

1. 创建 3 节点复制集,创建超级管理员用户,初始化复制集
//创建数据库存储文件及内部通信加密文件
$ mkdir -p ~/tmp/r{0,1,2}
$ openssl rand -base64 755 > ~/tmp/keyfile
$ chmod 400 ~/tmp/keyfile

//启动
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --auth --keyFile ~/tmp/keyfile --replSet repl-1 ; done

//初始化
$ mongo admin --port 27000 --eval "rs.initiate()"

//创建安全登录账户
$ mongo admin --port 27000 --eval 'db.createUser({user: "root", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

//添加备节点
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27002")'
2. 创建自定制角色
$ mongo admin -u root -p mongo --port 27000

db.createRole({
  role: "HRDEPARTMENT",
  privileges: [
    {
      resource: { db: "HR", collection: "" },
      actions: [ "find", "dropUser" ]
    }, {
      resource: { db: "HR", collection: "employees" },
      actions: [ "insert" ]
    }
  ],
  roles:[]
})

db.createRole({
  role: "MANAGEMENT",
  privileges: [],
  roles:[{
    role: "dbOwner", db: "HR"
  }]
})

db.createRole({
  role: "EMPLOYEEPORTAL",
  privileges: [{
    resource: { db: "HR", collection: "employees" },
    actions: [ "find", "update" ]
  }],
  roles:[]
})
3. 查看创建的角色
$ mongo admin --port 27000 -u root -p mongo  --eval "var roles = db.getRoles({showPrivileges: true});
          var sortedRoles = roles.map((role) => {
            return {
              role: role.role,
              inheritedRoles: role.inheritedRoles,
              privileges: role.privileges.map((privilege) => {
                return {
                  resource: privilege.resource,
                  actions: privilege.actions.sort()
                };
              }).sort((a, b) => (a.actions[0] > b.actions[0]))
            };
          }).sort((a, b) => (a.role > b.role));
          print(JSON.stringify(sortedRoles));"

[{"role":"EMPLOYEEPORTAL","inheritedRoles":[],"privileges":[{"resource":{"db":"HR","collection":"employees"},"actions":["find","update"]}]},{"role":"HRDEPARTMENT","inheritedRoles":[],"privileges":[{"resource":{"db":"HR","collection":""},"actions":["dropUser","find"]},{"resource":{"db":"HR","collection":"employees"},"actions":["insert"]}]},{"role":"MANAGEMENT","inheritedRoles":[{"role":"dbOwner","db":"HR"}],"privileges":[]}]

Encryption

TLS 加密复制子集

1. 创建数据库目录
$ mkdir -p ~/tmp/r{0,1,2}
2. 启动数据库
$ for i in 0 1 2 ; do mongod --port 2700$i --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --fork --sslMode requireSSL --replSet repl-1 --sslCAFile ca.pem --sslPEMKeyFile server.pem ; done
3. 初始化复制子集
$ mongo --port 27000 --host localhost --ssl --sslPEMKeyFile client.pem --sslCAFile ca.pem --eval 'rs.initiate({
        "_id" : "repl-1",
        "members" : [
    {
      "_id" : 0,
      "host" : "localhost:27000"
    },
    {
      "_id" : 1,
      "host" : "localhost:27001"
    },
    {
      "_id" : 2,
      "host" : "localhost:27002"
    }
  ]
}
)'
4. 客户端连接验证
$ mongo --quiet --port 31240 --host localhost --ssl --sslPEMKeyFile client.pem --sslCAFile ca.pem --eval "db = db.getSisterDB('admin');
           var numMembers = rs.status().members.length;
           var obj = {
             numMembers: numMembers
           };
           print(JSON.stringify(obj));"
{"numMembers":3}

存储引擎加密

启动一个三节点的 MongoDB 复制集,对存储引擎进行加密。

1. 生产存储引擎加密文件,启动 MongoDB 指向对应加密文件
$ $ mkdir -p ~/tmp/r{0,1,2}
$ openssl rand -base64 32 > ~/tmp/encryptionKeyFile
$ chmod 400 ~/tmp/encryptionKeyFile

//启动
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --auth --enableEncryption --encryptionKeyFile ~/tmp/encryptionKeyFile --replSet repl-1 ; done

//初始化
$ mongo admin --port 27000 --eval "rs.initiate()"

//创建安全登录账户
$ mongo admin --port 27000 --eval 'db.createUser({user: "root", pwd: "mongo", roles: [{ role:"root", db: "admin" }]})'

//添加备节点
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 -u "root" -p "mongo" --eval 'rs.add("localhost:27002")'
2. 查看存储引擎加密信息
$ mongo admin -u root -p mongo --port 27000

db.runCommand({getCmdLineOpts: 1}).parsed.security
{
	"authorization" : "enabled",
	"enableEncryption" : true,
	"encryptionKeyFile" : "/Users/ksoong/tmp/encryptionKeyFile"
}

KMIP 管理加密密钥

1. 测试 KIMP 服务可达
$ ping kmip.example.com -c3
2. 启动 MongoDB
$ mkdir -p ~/tmp/db
$ mongod --dbpath ~/tmp/db --logpath ~/tmp/db/mongo.log --enableEncryption --kmipServerName kmip.example.com --kmipServerCAFile ca.pem --kmipClientCertificateFile client.pem --fork --port 27017

Auditing

审计信息输出到文件

1. 启动 mongod
$ mongod --dbpath db/ --logpath db/mongod.log --fork --auth --auditDestination file --auditFormat JSON --auditPath auditLog.json
2. 执行如下操作
$ mongo admin

db.createUser({user: "root", pwd: "mongo", roles: [{role: "root", db: "admin"}]})
db.auth('root', 'mongo')

use sample
db.sample.insertOne({name: "sample", desc: "description"})
3. 查看审计日志
{ "atype" : "authenticate", "ts" : { "$date" : "2019-05-16T17:47:20.936+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61454 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "user" : "root", "db" : "admin", "mechanism" : "SCRAM-SHA-256" }, "result" : 0 }
{ "atype" : "createDatabase", "ts" : { "$date" : "2019-05-16T17:49:15.993+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61454 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "ns" : "sample" }, "result" : 0 }
{ "atype" : "createCollection", "ts" : { "$date" : "2019-05-16T17:49:15.994+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61454 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "ns" : "sample.sample" }, "result" : 0 }

审计信息输出到文件,并只过滤集合创建事件

1. 启动 mongod
$ mongod --dbpath db/ --logpath db/mongod.log --fork --auth --auditDestination file --auditFormat JSON --auditPath auditLog.json --auditFilter '{atype: {$in: ["createCollection", "dropCollection"]}}'
2. 执行如下操作
db.auth('no-exist', 'mongo')
db.auth('root', 'mongo')
use test;
db.test.insertOne({"name": "test"})
db.test.drop()
3. 查看审计日志
{ "atype" : "createCollection", "ts" : { "$date" : "2019-05-16T18:05:28.580+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61585 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "ns" : "test.test" }, "result" : 0 }
{ "atype" : "dropCollection", "ts" : { "$date" : "2019-05-16T18:06:05.251+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61585 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "ns" : "test.test" }, "result" : 0 }

审计信息输出到文件,并只过滤给某一个数据库创建索引事件

1. 启动 mongod
$ mongod --dbpath db/ --logpath db/mongod.log --fork --auth --auditDestination file --auditFormat JSON --auditPath auditLog.json --auditFilter '{atype: "createIndex", "param.ns": /^my-application\./}'
2. 执行如下操作
use test
db.mycollection.createIndex({foo: 1})

use my-application
db.mycollection.createIndex({foo: 1})
3. 查看审计日志
{ "atype" : "createIndex", "ts" : { "$date" : "2019-05-16T18:31:59.479+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 61943 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "ns" : "my-application.mycollection", "indexName" : "foo_1", "indexSpec" : { "v" : 2, "key" : { "foo" : 1 }, "name" : "foo_1", "ns" : "my-application.mycollection" } }, "result" : 0 }

审计信息输出到文件,并过滤 DML 操作

1. 启动 mongod
$ mongod --dbpath db/ --logpath db/mongod.log --fork --auth --auditDestination file --auditFormat JSON --auditPath auditLog.json --setParameter auditAuthorizationSuccess=true
2. 执行如下操作
use test
db.sample.insertOne({foo: 1})
db.sample.find({foo: 1})

for(var i = 0; i < 10 ; i++) {db.sample.insert({foo: i})}
3. 查看审计日志
{ "atype" : "authCheck", "ts" : { "$date" : "2019-05-16T21:10:59.073+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 64583 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "command" : "insert", "ns" : "test.sample", "args" : { "insert" : "sample", "ordered" : true, "lsid" : { "id" : { "$binary" : "sI+T/bfsSgiS3jOL/b37hA==", "$type" : "04" } }, "$db" : "test", "documents" : [ { "_id" : { "$oid" : "5cdd616377635dff7f2c6b01" }, "foo" : 9 } ] } }, "result" : 0 }
{ "atype" : "authCheck", "ts" : { "$date" : "2019-05-16T21:10:59.074+0800" }, "local" : { "ip" : "127.0.0.1", "port" : 27017 }, "remote" : { "ip" : "127.0.0.1", "port" : 64583 }, "users" : [ { "user" : "root", "db" : "admin" } ], "roles" : [ { "role" : "root", "db" : "admin" } ], "param" : { "command" : "isMaster", "ns" : "test", "args" : { "isMaster" : 1, "forShell" : 1, "$db" : "test" } }, "result" : 0 }

在一个复制子集中打开 Auditing

1. 创建数据库存储目录
$ mkdir -p ~/tmp/r{0,1,2}
2. 启动数据库
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 3131$i --fork --replSet HW-3.1 --auditDestination file --auditFormat JSON --auditPath ~/tmp/r$i/auditLog.json ; done
3. 初始化集群
$ mongo admin --port 31310 --eval "rs.initiate()"
4. 添加备节点
$ mongo admin --port 31310 --eval 'rs.add("localhost:31311")'
$ mongo admin --port 31310 --eval 'rs.add("localhost:31312")'

过滤某一特定用户的 audit 日志

1. 创建数据库存储目录
$ mkdir -p ~/tmp/r{0,1,2}
2. 启动数据库
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 3132$i --fork --replSet HW-3.2 --auditDestination file --auditFormat JSON --auditPath ~/tmp/r$i/auditLog.json --auditFilter '{ "users.user": "steve" }' ; done
3. 初始化集群
$ mongo admin --port 27000 --eval "rs.initiate()"
4. 添加备节点
$ mongo admin --port 27000 --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 --eval 'rs.add("localhost:27002")'
5. 创建用户
$ mongo admin --port 27000 --eval 'db.createUser({user: "steve", pwd: "secret", roles: ["root"]})'

过滤 DML audit 日志

1. 创建数据库存储目录
$ mkdir -p ~/tmp/r{0,1,2}
2. 启动数据库
$ for i in 0 1 2 ; do mongod --dbpath ~/tmp/r$i --logpath ~/tmp/r$i/mongo.log --port 2700$i --fork --replSet repl-1 --auditDestination file --auditFormat JSON --auditPath ~/tmp/r$i/auditLog.json --setParameter auditAuthorizationSuccess=true ; done
3. 初始化集群
$ mongo admin --port 27000 --eval "rs.initiate()"
4. 添加备节
$ mongo admin --port 27000 --eval 'rs.add("localhost:27001")'
$ mongo admin --port 27000 --eval 'rs.add("localhost:27002")'

results matching ""

    No results matching ""