MongoDB 安全

Summary: Author: 张亚飞 | 阅读时间: 4 minute read | Published: 2016-08-16
Filed under Categories: LinuxTags: Note,

Reference:

Clone Repository: git clone https://github.com/mrvautin/adminMongo.git && cd adminMongo
Install dependencies: npm install
Start application: npm start
Visit http://127.0.0.1:1234 in your browser

Mongo 未授权访问漏洞…

初次使用你 show dbs 会看到只有一个local数据库,那个所谓的admin是不存在的.

MongoDB 没有炒鸡无敌用户 root,只有能管理用户的用户 userAdminAnyDatabase

  • 首先在 /etc/mongod.conf 关闭授权认证
...
security:
    #keyFile: "/data/key/config.key"
    authorization: "disabled"
...
  1. 添加管理用户:
Sat Feb 18 15:20:11 coam@as:~$ mongo
MongoDB shell version: 3.2.11
connecting to: test
> show dbs;
admin   0.000GB
local   0.310GB
syData  0.141GB
test    0.000GB
ypage   0.107GB
> use admin
switched to db admin
> show users;
> db.createUser(
...   {
...     user: "zyfmix",
...     pwd: "yafei312",
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
	"user" : "zyfmix",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
> show users;
{
	"_id" : "admin.zyfmix",
	"user" : "zyfmix",
	"db" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
> db.system.users.find()
{ "_id" : "admin.zyfmix", "user" : "zyfmix", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "KLO12K5WMHcPn03xecDbdA==", "storedKey" : "EXnQKdAXm7uKYdNPBIueyRRem+o=", "serverKey" : "HLJzNPfIa2iI18eOCnoHu4bAJQY=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }

roles 中的 db 参数是必须的,不然会报错:

Error: couldn’t add user: Missing expected field “db”

另外,有很多文章记录的是使用 db.addUser(…) 方法,这个方法是旧版的,3.0中已经不存在,详见:http://docs.mongodb.org/manual/reference/method/js-user-management.

  1. 怎么关闭 mongoDB?千万不要 kill -9 pid,可以 kill -2 pid 或 db.shutdownServer()
Sat Feb 18 15:28:03 coam@as:~$ ps -ef | grep mongo
coam    8787  1856  0 15:28 pts/0    00:00:00 grep mongo
root     28149     1  0 15:18 ?        00:00:02 mongod -f /etc/mongod.conf
Sat Feb 18 15:28:05 coam@as:~$ sudo kill -2 28149
Sat Feb 18 15:28:20 coam@as:~$ ps -ef | grep mongo
coam    8796  1856  0 15:28 pts/0    00:00:00 grep mongo
  1. 下面使用 –auth 参数(也可以在 mongo 配置文件配置 auth 授权认证),重新启动 mongoDB:
  • 可以直接在启动参数配置授权认证:
sudo mongod --auth -f /etc/mongod.conf
  • 直接在命令行启动参数加用户认证
mongo --port 27017 -u zyfmix -p 12345678 --authenticationDatabase admin

  • 也可以在 /etc/mongod.conf 开启授权认证:

/etc/mongod.conf

...
security:
    #keyFile: "/data/key/config.key"
    authorization: "enabled"
...
sudo mongod -f /etc/mongod.conf
  • Shell 测试是否认证成功:
Sat Feb 18 15:29:24 coam@as:~$ mongo
MongoDB shell version: 3.2.11
connecting to: test
> use admin
switched to db admin
> db.auth("zyfmix","yafei312")
1            #认证,返回1表示成功

此时 [show collections] 报错

> show collections
> > db.getCollectionNames()
2017-02-18T15:30:00.883+0800 E QUERY    [thread1] Error: listCollections failed: {
	"ok" : 0,
	"errmsg" : "not authorized on admin to execute command { listCollections: 1.0, filter: {} }",
	"code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
shellHelper.show@src/mongo/shell/utils.js:754:9
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1

> show dbs;
admin   0.000GB
local   0.310GB
syData  0.141GB
test    0.000GB
ypage   0.107GB

因为,用户 zyfmix 只有用户管理的权限

下面创建用户,用户都跟着库走,创建的用户都是

use syData
db.createUser(
 {
   user: "zyfmax",
   pwd: "yafei312",
   roles: [
      { role: "readWrite", db: "syData" },
   ]
 }
)
  • 查看刚刚创建的用户[只能查看在当前库(syData)下创建的用户(zyfmax)]:
> show users;
{
	"_id" : "syData.zyfmax",
	"user" : "zyfmax",
	"db" : "syData",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "syData"
		},
		{
			"role" : "readWrite",
			"db" : "ypage"
		}
	]
}
> show collections          #@ 未登录依然不能访问库资料
2017-02-18T15:44:50.704+0800 E QUERY    [thread1] Error: listCollections failed: {
	"ok" : 0,
	"errmsg" : "not authorized on syData to execute command { listCollections: 1.0, filter: {} }",
	"code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
shellHelper.show@src/mongo/shell/utils.js:754:9
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1

> use syData
switched to db syData
> db.auth("zyfmix","yafei312")
Error: Authentication failed.
0       #@ 不能使用其他库(admin)创建的用户(zyfmix)登录此数据库(syData)
> db.auth("zyfmax","yafei312")
1       #@ 使用当前库[syData下的用户(zyfmax:yafei)]登录
> show collections
CertifyAuthInfo
ComplaintsSuggestionsInfo
TruckRoadsPath
...

查看整个mongoDB全部的用户:

> db.system.users.find()
{ "_id" : "admin.zyfmix", "user" : "zyfmix", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "KLO12K5WMHcPn03xecDbdA==", "storedKey" : "EXnQKdAXm7uKYdNPBIueyRRem+o=", "serverKey" : "HLJzNPfIa2iI18eOCnoHu4bAJQY=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
{ "_id" : "syData.zyfmax", "user" : "zyfmax", "db" : "syData", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "u0FbSEHtn0pP0U0AgtOzkQ==", "storedKey" : "c6pMHbm+AFA0KwdzPi10bXwzaes=", "serverKey" : "Q3oc39XPcAkqxTRSqdDqaa+i0Ro=" } }, "roles" : [ { "role" : "readWrite", "db" : "syData" } ]
  • 笔记:
show dbs                 #@ 查看所有库
use admin                #@ 进入库下(admin)域
show collections        #@ 查看当前库下的collections (适用于所有库)
show users               #@ 查看当前库下的用户 (适用于所有库)
db.system.users.find()      #@ 查看所有用户 (限于admin)
db.system.users.remove({"user":"zyfmix"})      #@ 删除用户 (限于admin)

###重点在这里@@@ 可以创建一个全局用户

use admin
db.createUser(
 {
   user: "zyf",
   pwd: "yafei312",
   roles: ["root"]
 }
)
> db.system.users.find()
{ "_id" : "admin.zyfmix", "user" : "zyfmix", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "KLO12K5WMHcPn03xecDbdA==", "storedKey" : "EXnQKdAXm7uKYdNPBIueyRRem+o=", "serverKey" : "HLJzNPfIa2iI18eOCnoHu4bAJQY=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
{ "_id" : "syData.zyfmax", "user" : "zyfmax", "db" : "syData", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "u0FbSEHtn0pP0U0AgtOzkQ==", "storedKey" : "c6pMHbm+AFA0KwdzPi10bXwzaes=", "serverKey" : "Q3oc39XPcAkqxTRSqdDqaa+i0Ro=" } }, "roles" : [ { "role" : "readWrite", "db" : "syData" }, { "role" : "readWrite", "db" : "ypage" } ] }
{ "_id" : "admin.zyf", "user" : "zyf", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "hJAcku2Vk6aGLRA9Mv7Rig==", "storedKey" : "xyi1EKhwKLIWav+lG4rlqNN1Ua4=", "serverKey" : "3oESBU8pcVA5mSo9eGKKC6nvghU=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }

MongoClient

mongodb 基本命令

进入 mongo: mongo 启动服务:net start MongoDB 1. 查看数据库:

show dbs
  1. 查看所有集合:
> show collections;
> db.getCollectionNames();
  1. 查看数据库服务器的状态:
db.serverStatus();
  1. 查询指定数据库统计信息:
use user;
db.stats();
  1. 查询指定数据库包含的集合名称列表
db.getCollectionNames();
  1. 删除数据库
db.dropDatabse();
  1. 创建集合
db.createCollection(name, {size:..., capped:..., max:...})

MongoDB 支持 Capped Collection,一种固定大小的集合,当集合的大小达到指定大小时,新数据会覆盖老数据.

  1. 删除集合:
db.collections.drop();
  1. 插入更新记录,save方法:
db.user.save({'name':'xiaoming','age':25});
  1. 查询一条记录: 参数为查询条件,可选,系统会随机查询获取到满足条件的一条记录(如果存在查询结果数量大于等于1)
db.user.findOne({'name':'xiaoming'})
  1. 查询多条记录:不指定条件则查询全部记录
db.user.find();
  1. 删除记录:
db.user.remove({'name':'xiaomng'});
  1. 创建索引:
>use user
>db.page.ensureIndex({}'name':1, 'age':-1})
>db.system.index.find()

ensureIndex 方法参数中,数字1表示升序,-1表示降序. db.system.indexes.find() 可以查询全部索引

  1. 查询索引:
db.page.getIndexes();
  1. 删除索引:
db.user.dropIndex(name)
db.user.dropIndexes();//删除全部索引
  1. 索引重建:
db.page.reIndex()
  1. 统计集合记录数
user user;
db.baseSe.count();
  1. 查询并统计结果记录数:
use user
db.baseSe.find({'name':'xiaoming'}).count()

先根据条件查询结果,然后再统计结果中的记录数,查询条件也可为空.

Comments

Cor-Ethan, the beverage → www.iirii.com