MongoDB 基礎(六)安全性(許可權操作),mongodb安全性
和其他所有資料庫一樣,許可權的管理都差不多一樣。mongodb儲存所有的使用者資訊在admin 資料庫的集合system.users中,儲存使用者名稱、密碼和資料庫資訊。mongodb預設不啟用授權認證,只要能串連到該伺服器,就可串連到mongod。若要啟用安全認證,需要更改設定檔參數auth。
以下測試理解
查看資料庫:
> show dbs
發現 admin 竟然沒有!~
找了好久,找不到相關說明,於是直接建立使用者admin
use admindb.createUser( { user: "admin", pwd: "admin", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })
成功建立,再查詢admin中的集合,有資料了!
> show collectionssystem.indexessystem.userssystem.version
查看3個集合的資訊:
> db.system.users.find();{ "_id" : "admin.admin", "user" : "admin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "cFISfpbm04pmIFpqiL340g==", "storedKey" : "WG1DSEEEHUZUBjsjsnEA4RFVY2M=", "serverKey" : "9Lm+IX6l9kfaE/4C25/ghsQpDkE=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }> > db.system.indexes.find();{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.version" }{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "admin.system.users" }{ "v" : 1, "unique" : true, "key" : { "user" : 1, "db" : 1 }, "name" : "user_1_db_1", "ns" : "admin.system.users" }> > db.system.version.find();{ "_id" : "authSchema", "currentVersion" : 5 }>
現在啟用 auth:
[root@localhost ~]# vi /etc/mongod.conf
auth=true
重啟 mongod 服務:
[root@localhost ~]# service mongod restart
直接預設登入,查看集合,發現無權操作了:
[root@localhost ~]# mongo
[root@localhost ~]# mongoMongoDB shell version: 3.0.2connecting to: test> show dbs2015-05-09T21:57:03.176-0700 E QUERY Error: listDatabases failed:{"ok" : 0,"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }","code" : 13} at Error (<anonymous>) at Mongo.getDBs (src/mongo/shell/mongo.js:47:15) at shellHelper.show (src/mongo/shell/utils.js:630:33) at shellHelper (src/mongo/shell/utils.js:524:36) at (shellhelp2):1:1 at src/mongo/shell/mongo.js:47>
剛才在資料庫 admin 建立了一個賬戶 admin ,先到資料admin進來串連(其他db則失敗):
[root@localhost ~]# mongoMongoDB shell version: 3.0.2connecting to: test>> db.auth("admin","admin")Error: 18 Authentication failed.0> use mydbswitched to db mydb> db.auth("admin","admin")Error: 18 Authentication failed.0> use adminswitched to db admin> db.auth("admin","admin")1>
db.auth("admin","admin") 返回值為1,說明登入成功!~db.auth("admin","admin") 記錄是不存在的,執行完後這一行在shell中不會記錄曆史。
所以現在建立另一個使用者"myuser"
db.createUser( { user: "myuser", pwd: "myuser", roles: [ { role: "readWrite", db: "mydb" } ] })
也可以增刪角色:
#授予角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])db.grantRolesToUser( "myuser" , [ { role: "dbOwner", db: "mydb" } ])#取消角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ])db.revokeRolesFromUser( "myuser" , [ { role: "readWrite", db: "mydb" } ])
因為在admin資料庫建立的,只能在 admin 資料庫中登入:
> db.auth("myuser","myuser")Error: 18 Authentication failed.0> > dbmydb> use adminswitched to db admin> db.auth("myuser","myuser");1>
此時是可以切換到所在的資料庫進行相關操作:
> use mydbswitched to db mydb> > db.tab.save({"id":999});WriteResult({ "nInserted" : 1 })> > db.tab.find({"id":999});{ "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }> > show collectionssystem.indexestab>
在建立使用者時可以在其資料庫中建立,這樣不用每次都進入admin資料庫登入後再切換。如在資料庫"mydb"建立使用者"userkk"。
use admindb.auth("admin","admin")use mydbdb.createUser( { user: "userkk", pwd: "userkk", roles: [ { role: "dbOwner", db: "mydb" } ] })db.auth("userkk","userkk")
------------------------------------------------------------------------------------------------------------------
華麗分割
------------------------------------------------------------------------------------------------------------------
現在授權測試:
#先訪問到admin資料庫
use admindb.auth("admin","admin")
#切換到 mydb ,在資料庫 mydb 中建立角色
#roles: 建立角色"testRole"在資料庫 "mydb" 中
#privileges: 該角色可查看"find"資料庫"mydb"的所有集合
#db.dropRole("testRole")
use mydbdb.createRole({ role: "testRole", privileges: [{ resource: { db: "mydb", collection: "" }, actions: [ "find" ] }], roles: []})
#在admin資料庫產生集合system.roles。查看角色。
> use adminswitched to db admin> > show collectionssystem.indexessystem.rolessystem.userssystem.version> > db.system.roles.find();{ "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find" ] } ], "roles" : [ ] }>
#回到mydb,在資料庫mydb中建立使用者並授予角色"testRole"
#db.dropUser("userkk")
use mydbdb.createUser( { user: "userkk", pwd: "userkk", roles: [ { role: "testRole", db: "mydb" } ] })
退出mongodb,重新登入進行操作。發現只能使用find
>exit
[root@localhost ~]# mongoMongoDB shell version: 3.0.2connecting to: test> use mydbswitched to db mydb> > db.auth("userkk","userkk")1> > db.tab.find({"id":999}){ "_id" : ObjectId("554ef5ac1b590330c00c7d02"), "id" : 999 }> > db.tab.insert({"id":1000})WriteResult({"writeError" : {"code" : 13,"errmsg" : "not authorized on mydb to execute command { insert: \"tab\", documents: [ { _id: ObjectId('554f145cdf782b42499d80e5'), id: 1000.0 } ], ordered: true }"}})>
給角色 "testRole" 添加3個 “Privileges”許可權: "update", "insert", "remove"。再重新操作。
use admindb.auth("admin","admin")use mydb#添加Privileges給角色db.grantPrivilegesToRole("testRole", [{ resource: { db: "mydb", collection: "" },actions: [ "update", "insert", "remove" ]}])exit #退出mongodb重新登入use mydbdb.auth("userkk","userkk")#增刪資料可以操作了!~db.tab.insert({"id":1000})db.tab.find({"id":1000})db.tab.remove({"id":1000})#此時admin的角色記錄為:> db.system.roles.find();{ "_id" : "mydb.testRole", "role" : "testRole", "db" : "mydb", "privileges" : [ { "resource" : { "db" : "mydb", "collection" : "" }, "actions" : [ "find", "insert", "remove", "update" ] } ], "roles" : [ ] }>
#更改角色 roles,把roles值全部更新。同樣Privileges也可以更新替換!~
use admindb.auth("admin","admin")use mydbdb.updateRole("testRole",{ roles:[{ role: "readWrite",db: "mydb"}]},{ w:"majority" })db.auth("userkk","userkk")show dbs
關於角色,參考官方文檔提取總結如下:
角色分類 |
角色 |
許可權及角色 (本文大小寫可能有些變化,使用時請參考官方文檔) |
Database User Roles |
read |
CollStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections |
readWrite |
CollStats,ConvertToCapped,CreateCollection,DbHash,DbStats, DropCollection,CreateIndex,DropIndex,Emptycapped,Find, Insert,KillCursors,ListIndexes,ListCollections,Remove, RenameCollectionSameDB,update |
Database Administration Roles |
dbAdmin |
collStats,dbHash,dbStats,find,killCursors,listIndexes,listCollections, dropCollection 和 createCollection 在 system.profile |
dbOwner |
角色:readWrite, dbAdmin,userAdmin |
userAdmin |
ChangeCustomData,ChangePassword,CreateRole,CreateUser, DropRole,DropUser,GrantRole,RevokeRole,ViewRole,viewUser |
Cluster Administration Roles |
clusterAdmin |
角色:clusterManager, clusterMonitor, hostManager |
clusterManager |
AddShard,ApplicationMessage,CleanupOrphaned,FlushRouterConfig, ListShards,RemoveShard,ReplSetConfigure,ReplSetGetStatus, ReplSetStateChange,Resync, EnableSharding,MoveChunk,SplitChunk,splitVector |
clusterMonitor |
connPoolStats,cursorInfo,getCmdLineOpts,getLog,getParameter, getShardMap,hostInfo,inprog,listDatabases,listShards,netstat, replSetGetStatus,serverStatus,shardingState,top collStats,dbStats,getShardVersion |
hostManager |
applicationMessage,closeAllDatabases,connPoolSync,cpuProfiler, diagLogging,flushRouterConfig,fsync,invalidateUserCache,killop, logRotate,resync,setParameter,shutdown,touch,unlock |
Backup and Restoration Roles |
backup |
提供在admin資料庫mms.backup文檔中insert,update許可權 列出所有資料庫:listDatabases 列出所有集合索引:listIndexes 對以下提供查詢操作:find *非系統集合 *系統集合:system.indexes, system.namespaces, system.js *集合:admin.system.users 和 admin.system.roles |
restore |
非系統集合、system.js,admin.system.users 和 admin.system.roles 及2.6 版本的system.users提供以下許可權: collMod,createCollection,createIndex,dropCollection,insert 列出所有資料庫:listDatabases system.users :find,remove,update |
All-Database Roles |
readAnyDatabase |
提供所有資料庫中唯讀許可權:read 列出叢集所有資料庫:listDatabases |
readWriteAnyDatabase |
提供所有資料庫讀寫權限:readWrite 列出叢集所有資料庫:listDatabases |
userAdminAnyDatabase |
提供所有使用者資料管理許可權:userAdmin Cluster:authSchemaUpgrade,invalidateUserCache,listDatabases admin.system.users和admin.system.roles: collStats,dbHash,dbStats,find,killCursors,planCacheRead createIndex,dropIndex |
dbAdminAnyDatabase |
提供所有資料庫管理員許可權:dbAdmin 列出叢集所有資料庫:listDatabases |
Superuser Roles |
root |
角色:dbOwner,userAdmin,userAdminAnyDatabase readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase,clusterAdmin |
Internal Role |
__system |
叢集中對任何資料庫採取任何操作 |
參考:mongo Shell Methods , Built-In Roles