MongoDB 2019(3)Security and Auth
程序员文章站
2022-03-30 19:23:16
...
MongoDB 2019(3)Security and Auth
Started the mongo cluster first
Connect to it
> mongo -host rancher-worker2 -port 27017
> rs.slaveOk();
> db.users.find();
Check DB
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
Switch to use admin
> use admin
switched to db admin
check if there is any users in DB
> db.system.users.find();
sillycat:PRIMARY>
No users, so I add one user there
https://docs.mongodb.com/manual/tutorial/create-users/
> use admin
switched to db admin
> db.createUser({user: "carl",pwd: "password",roles:[{role: "userAdminAnyDatabase", db:"admin"}]})
Successfully added user: {
"user" : "carl",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Verify my auth
> db.auth("carl","password")
1
Exit and change the configuration for mongodb
> vi conf/mongodb.conf
auth = true
Kill the mongo process and start them again one by one
> mongod -f conf/mongodb.conf
In theory, it should be good to go now.
Wrong password will fail
> mongo --host rancher-home --port 27017 -ucarl -padfasdf --authenticationDatabase admin
Good password will be good
> mongo --host rancher-home --port 27017 -ucarl -ppassword --authenticationDatabase admin
> rs.slaveOk();
sillycat:OTHER>
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
> use admin
Check Users
> db.system.users.find()
{ "_id" : "admin.carl", "userId" : UUID("73415070-d63d-4377-ac3f-a247521a9d43"), "user" : "carl", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "pYlkO1HuxIyKAM9fmnWZvQ==", "storedKey" : "cDocJ/FMaE3+T/KA02kQ+z2tjas=", "serverKey" : "BZe3saf4s7eqzc+Ks6kmvuJRTLw=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "CfET/OxJEo2eRnJufeaVKSmEy+7U89m7XX7NKA==", "storedKey" : "pns2OxgR+zfvJJL07to6PSvhc83R8YfnbrRQXh9xSKo=", "serverKey" : "2DKiqzYZHGszCHsb75VJbjqOrP/LfaEQMkdORPejIPI=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
Check this
> db.createUser({ user: "mongoadmin" , pwd: "mongoadmin", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})
Successfully added user: {
"user" : "mongoadmin",
"roles" : [
"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"
]
}
Check out these
> db.createUser( { user:"siteUserAdmin",pwd:"password",roles:["userAdminAnyDatabase"]})
Successfully added user: { "user" : "siteUserAdmin", "roles" : [ "userAdminAnyDatabase" ] }
> db.createUser( { user:"siteRootAdmin",pwd:"password", roles:["userAdminAnyDatabase","readWriteAnyDatabase","dbAdminAnyDatabase","clusterAdmin"]});
Successfully added user: {
"user" : "siteRootAdmin",
"roles" : [
"userAdminAnyDatabase",
"readWriteAnyDatabase",
"dbAdminAnyDatabase",
"clusterAdmin"
]
}
It is said the MongoDB Replica set needs both user account and keyfile. Keyfile seems for authentication between servers in the replica set, not for login in.
All the configurations are listed here
https://docs.mongodb.com/manual/reference/configuration-options/
Try the settings as follow:
storage:
dbPath: "/data/db/mongodb"
directoryPerDB: true
journal:
enabled: true
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
timeStampFormat: iso8601-utc
replication:
oplogSizeMB: 10240
replSetName: "sillycat"
processManagement:
fork: true
net:
bindIp: 0.0.0.0
port: 27017
security:
keyFile: "/opt/mongodb/keyfile.key"
authorization: "enabled"
Check version
> mongod -version
db version v4.2.1
git version: edf6d45851c0b9ee15548f0f847df141764a317e
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
distmod: rhel70
distarch: x86_64
target_arch: x86_64
Create the keyfile, we usually generate the keyfile on one server, copy that to other servers.
> openssl rand -base64 90 -out ./keyfile.key
Change the permission
> chmod 600 ./keyfile.key
Copy the file to other machines, make sure all 3 nodes having the same keyfile
> sudo rm -fr /data/db/mongodb/*
Facing some failure, because of the previous database data directory is keeping some old configurations. Clear that directories, and restart, it works fine.
We can always check the logging here
> tail -f /var/log/mongodb/mongod.log
> mongod -f conf/mongodb.conf
The final configurations are as follow:
> cat conf/mongodb.conf
storage:
dbPath: /data/db/mongodb
directoryPerDB: true
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
replication:
oplogSizeMB: 10240
replSetName: sillycat
processManagement:
fork: true
net:
bindIp: 0.0.0.0
port: 27017
security:
keyFile: /opt/mongodb/keyfile.key
authorization: enabled
Disable the security—>authorization and security—>keyFile ,restart the services again
Connect to the master server again
> mongo --host rancher-home --port 27017
> rs.status()
{
"operationTime" : Timestamp(0, 0),
"ok" : 0,
"errmsg" : "no replset config has been received",
"code" : 94,
"codeName" : "NotYetInitialized",
"$clusterTime" : {
"clusterTime" : Timestamp(0, 0),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
> rs.initiate()
sillycat:SECONDARY> rs.conf()
sillycat:PRIMARY> rs.add("rancher-worker1:27017")
sillycat:PRIMARY> rs.add("rancher-worker2:27017")
That will recreate the master and 2 replicas.
Create some important user
User root as root role
> db.createUser({user:"root",pwd:"123456",roles:[{role:"root",db:"admin"}] });
sillycat:PRIMARY> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
sillycat:PRIMARY> use admin
switched to db admin
User admin is admin of any database
> db.createUser({user:"admin", pwd:"admin", roles:[{role: "userAdminAnyDatabase", db:"admin" }]})
It works
> sillycat:PRIMARY> db.auth("admin","admin")
1
Create a new database
> sillycat:PRIMARY> use testdb1
switched to db testdb1
Create db owner
> sillycat:PRIMARY> db.createUser({user:"carl",pwd:"123456",roles:[{role:"dbOwner",db:"testdb1"}] })
It works well
sillycat:PRIMARY> db.auth("carl","123456")
1
Shutdown all the services
> mongo --host rancher-home --port 27017
> mongo --host rancher-worker1 --port 27017
> mongo --host rancher-worker2 --port 27017
> sillycat:PRIMARY> use admin
sillycat:PRIMARY> db.shutdownServer()
Need to use local to connect to shutdown the service
> mongo --host localhost --port 27017
Enable all the configurations
security:
keyFile: /opt/mongodb/keyfile.key
authorization: enabled
Start the service again
> mongod -f conf/mongodb.conf
Check admin first
> mongo --host rancher-home --port 27017 -uadmin -padmin --authenticationDatabase admin
Check other db
> mongo --host rancher-home --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:PRIMARY> use testdb1
sillycat:PRIMARY> db.users.insert({name:"Carl", age:31})
sillycat:PRIMARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }
On slave
> mongo --host rancher-worker1 --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:SECONDARY> rs.slaveOk();
sillycat:SECONDARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }
Some other command
sillycat:SECONDARY> use testdb1
switched to db testdb1
sillycat:SECONDARY> show dbs
testdb1 0.000GB
sillycat:SECONDARY> show collections
users
Check current db
> sillycat:SECONDARY> db
test
References:
https://docs.mongodb.com/manual/core/authentication/
https://*.com/questions/20539376/a-mongodb-useradminanydatabase-user-cannot-admin-users-in-any-database-why
http://www.dba86.com/docs/mongo/2.4/tutorial/deploy-replica-set-with-auth.html
https://*.com/questions/38524150/mongodb-replica-set-with-simple-password-authentication
https://docs.mongodb.com/manual/tutorial/deploy-replica-set-with-keyfile-access-control/
https://github.com/johnnian/Blog/issues/8
https://dba.stackexchange.com/questions/82591/sample-yaml-configuration-files-for-mongodb
https://nutao.github.io/2017/07/27/Mongodb-%E9%9B%86%E7%BE%A4%E8%AE%A4%E8%AF%81%EF%BC%88KeyFile%EF%BC%89/
https://www.cnblogs.com/cswuyg/p/5869256.html
Started the mongo cluster first
Connect to it
> mongo -host rancher-worker2 -port 27017
> rs.slaveOk();
> db.users.find();
Check DB
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
Switch to use admin
> use admin
switched to db admin
check if there is any users in DB
> db.system.users.find();
sillycat:PRIMARY>
No users, so I add one user there
https://docs.mongodb.com/manual/tutorial/create-users/
> use admin
switched to db admin
> db.createUser({user: "carl",pwd: "password",roles:[{role: "userAdminAnyDatabase", db:"admin"}]})
Successfully added user: {
"user" : "carl",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Verify my auth
> db.auth("carl","password")
1
Exit and change the configuration for mongodb
> vi conf/mongodb.conf
auth = true
Kill the mongo process and start them again one by one
> mongod -f conf/mongodb.conf
In theory, it should be good to go now.
Wrong password will fail
> mongo --host rancher-home --port 27017 -ucarl -padfasdf --authenticationDatabase admin
Good password will be good
> mongo --host rancher-home --port 27017 -ucarl -ppassword --authenticationDatabase admin
> rs.slaveOk();
sillycat:OTHER>
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
test 0.000GB
> use admin
Check Users
> db.system.users.find()
{ "_id" : "admin.carl", "userId" : UUID("73415070-d63d-4377-ac3f-a247521a9d43"), "user" : "carl", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "pYlkO1HuxIyKAM9fmnWZvQ==", "storedKey" : "cDocJ/FMaE3+T/KA02kQ+z2tjas=", "serverKey" : "BZe3saf4s7eqzc+Ks6kmvuJRTLw=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "CfET/OxJEo2eRnJufeaVKSmEy+7U89m7XX7NKA==", "storedKey" : "pns2OxgR+zfvJJL07to6PSvhc83R8YfnbrRQXh9xSKo=", "serverKey" : "2DKiqzYZHGszCHsb75VJbjqOrP/LfaEQMkdORPejIPI=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
Check this
> db.createUser({ user: "mongoadmin" , pwd: "mongoadmin", roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]})
Successfully added user: {
"user" : "mongoadmin",
"roles" : [
"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"
]
}
Check out these
> db.createUser( { user:"siteUserAdmin",pwd:"password",roles:["userAdminAnyDatabase"]})
Successfully added user: { "user" : "siteUserAdmin", "roles" : [ "userAdminAnyDatabase" ] }
> db.createUser( { user:"siteRootAdmin",pwd:"password", roles:["userAdminAnyDatabase","readWriteAnyDatabase","dbAdminAnyDatabase","clusterAdmin"]});
Successfully added user: {
"user" : "siteRootAdmin",
"roles" : [
"userAdminAnyDatabase",
"readWriteAnyDatabase",
"dbAdminAnyDatabase",
"clusterAdmin"
]
}
It is said the MongoDB Replica set needs both user account and keyfile. Keyfile seems for authentication between servers in the replica set, not for login in.
All the configurations are listed here
https://docs.mongodb.com/manual/reference/configuration-options/
Try the settings as follow:
storage:
dbPath: "/data/db/mongodb"
directoryPerDB: true
journal:
enabled: true
systemLog:
destination: file
path: "/var/log/mongodb/mongod.log"
logAppend: true
timeStampFormat: iso8601-utc
replication:
oplogSizeMB: 10240
replSetName: "sillycat"
processManagement:
fork: true
net:
bindIp: 0.0.0.0
port: 27017
security:
keyFile: "/opt/mongodb/keyfile.key"
authorization: "enabled"
Check version
> mongod -version
db version v4.2.1
git version: edf6d45851c0b9ee15548f0f847df141764a317e
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
distmod: rhel70
distarch: x86_64
target_arch: x86_64
Create the keyfile, we usually generate the keyfile on one server, copy that to other servers.
> openssl rand -base64 90 -out ./keyfile.key
Change the permission
> chmod 600 ./keyfile.key
Copy the file to other machines, make sure all 3 nodes having the same keyfile
> sudo rm -fr /data/db/mongodb/*
Facing some failure, because of the previous database data directory is keeping some old configurations. Clear that directories, and restart, it works fine.
We can always check the logging here
> tail -f /var/log/mongodb/mongod.log
> mongod -f conf/mongodb.conf
The final configurations are as follow:
> cat conf/mongodb.conf
storage:
dbPath: /data/db/mongodb
directoryPerDB: true
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
replication:
oplogSizeMB: 10240
replSetName: sillycat
processManagement:
fork: true
net:
bindIp: 0.0.0.0
port: 27017
security:
keyFile: /opt/mongodb/keyfile.key
authorization: enabled
Disable the security—>authorization and security—>keyFile ,restart the services again
Connect to the master server again
> mongo --host rancher-home --port 27017
> rs.status()
{
"operationTime" : Timestamp(0, 0),
"ok" : 0,
"errmsg" : "no replset config has been received",
"code" : 94,
"codeName" : "NotYetInitialized",
"$clusterTime" : {
"clusterTime" : Timestamp(0, 0),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
}
> rs.initiate()
sillycat:SECONDARY> rs.conf()
sillycat:PRIMARY> rs.add("rancher-worker1:27017")
sillycat:PRIMARY> rs.add("rancher-worker2:27017")
That will recreate the master and 2 replicas.
Create some important user
User root as root role
> db.createUser({user:"root",pwd:"123456",roles:[{role:"root",db:"admin"}] });
sillycat:PRIMARY> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
sillycat:PRIMARY> use admin
switched to db admin
User admin is admin of any database
> db.createUser({user:"admin", pwd:"admin", roles:[{role: "userAdminAnyDatabase", db:"admin" }]})
It works
> sillycat:PRIMARY> db.auth("admin","admin")
1
Create a new database
> sillycat:PRIMARY> use testdb1
switched to db testdb1
Create db owner
> sillycat:PRIMARY> db.createUser({user:"carl",pwd:"123456",roles:[{role:"dbOwner",db:"testdb1"}] })
It works well
sillycat:PRIMARY> db.auth("carl","123456")
1
Shutdown all the services
> mongo --host rancher-home --port 27017
> mongo --host rancher-worker1 --port 27017
> mongo --host rancher-worker2 --port 27017
> sillycat:PRIMARY> use admin
sillycat:PRIMARY> db.shutdownServer()
Need to use local to connect to shutdown the service
> mongo --host localhost --port 27017
Enable all the configurations
security:
keyFile: /opt/mongodb/keyfile.key
authorization: enabled
Start the service again
> mongod -f conf/mongodb.conf
Check admin first
> mongo --host rancher-home --port 27017 -uadmin -padmin --authenticationDatabase admin
Check other db
> mongo --host rancher-home --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:PRIMARY> use testdb1
sillycat:PRIMARY> db.users.insert({name:"Carl", age:31})
sillycat:PRIMARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }
On slave
> mongo --host rancher-worker1 --port 27017 -ucarl -p123456 --authenticationDatabase testdb1
sillycat:SECONDARY> rs.slaveOk();
sillycat:SECONDARY> db.users.find();
{ "_id" : ObjectId("5dcf23e43a8ac5e8fb8bd004"), "name" : "Carl", "age" : 31 }
Some other command
sillycat:SECONDARY> use testdb1
switched to db testdb1
sillycat:SECONDARY> show dbs
testdb1 0.000GB
sillycat:SECONDARY> show collections
users
Check current db
> sillycat:SECONDARY> db
test
References:
https://docs.mongodb.com/manual/core/authentication/
https://*.com/questions/20539376/a-mongodb-useradminanydatabase-user-cannot-admin-users-in-any-database-why
http://www.dba86.com/docs/mongo/2.4/tutorial/deploy-replica-set-with-auth.html
https://*.com/questions/38524150/mongodb-replica-set-with-simple-password-authentication
https://docs.mongodb.com/manual/tutorial/deploy-replica-set-with-keyfile-access-control/
https://github.com/johnnian/Blog/issues/8
https://dba.stackexchange.com/questions/82591/sample-yaml-configuration-files-for-mongodb
https://nutao.github.io/2017/07/27/Mongodb-%E9%9B%86%E7%BE%A4%E8%AE%A4%E8%AF%81%EF%BC%88KeyFile%EF%BC%89/
https://www.cnblogs.com/cswuyg/p/5869256.html