MongoDB 2.4 Replica set with authorization - mongodb

How to set up proper authorization for mongodb 2.4.1.
My setup seem to be not working.
Replica members config:
dbpath = /vol/data/mongodb/
# logfile
logpath = /var/log/mongodb/mongodb.log
logappend = true
# socket
bind_ip = 0.0.0.0
port = 27018
# replication
replSet = <%= hostname[14,4] %>
# authentication
keyFile = /etc/mongodb.pass
# turn off legacy privilege mode
setParameter = supportCompatibilityFormPrivilegeDocuments=false
setParameter = textSearchEnabled=false
# turn off authorization
auth = true
After adding user authorization:
> use admin
> db.addUser( { user: "admin", pwd: "xxx", roles: [ "userAdminAnyDatabase", "readWriteAnyDatabase", "dbAdminAnyDatabase" ] } )
I can't access to rs.* commands.
> use admin
> db.auth('admin','xxx')
1
> rs.status()
{ "ok" : 0, "errmsg" : "unauthorized" }

I too was dealing with the same sort of problem.I have a solution for it.
Turn off auth
1.Create a user with root privilege
Root privilege yields readWrite access to database while userAdminAnyDatabase role doesn't.
use admin
db.createUser( {
user: "root",
pwd: "pass",
roles: [ { role: "root", db: "admin" } ]
});
Turn on auth
2.Login with the root user
mongo -u root --authenticationDatabase admin -p
Then you can execute your commands.
Hope this helps :)

I think you need to use a keyFile if you have a replicaset.
Taken from http://docs.mongodb.org/manual/tutorial/enable-authentication/ :
Enable authentication using the auth or keyFile settings. Use auth for standalone instances, and keyFile with replica sets and sharded clusters. keyFile implies auth and allows members of a MongoDB deployment to authenticate internally.

Related

> show dbs 2017-04-25T12:02:12.277-0400 E QUERY Error: listDatabases failed:{

I created a one node Mongo database, everything went fine and I'm able to enter mongo shell and execute commands like "db","use test" , but that's about it , I'm not able to execute any other commands like "show dbs" or insert anything. I googled as there are lot of threads on this error with some suggesting to run rs.slaveOk() and some others asking to create user, I tried creating user as below:
db.createUser(
{
user: "okkadu",
pwd: "abc123",
roles: [ { role: "root", db: "test" } ]
}
)
However this also failed with below error:
Error: couldn't add user: not authorized on test to execute command
Could someone help me out what else can I try ?, please find the copy if my config file as well:
##
**### Basic Defaults
##
port = 27017
dbpath = /opt/mongodb/data
logappend = true
logpath = /var/log/mongodb/mongodb.log
rest = true
fork = true
#bind_ip = 127.0.0.1
pidfilepath = /var/log/mongodb/mongodb.pid
journal = true
httpinterface = true
storageEngine = wiredTiger
auth=true**

mongodb authorization exception in JMeter : code13

In MongoDB 3.2 I've setup a user with rights:
db.createUser(
{
user: "username",
pwd: "pass",
roles: [ { role: "readWrite", db: "dbname" }]
}
)
db.auth("username", "pass" )
When I use the JMeter(2.13) to connect to the database (using Jmeter's elements MongoDB Source Config , MongoDB Script) and run a query like this:
db.mycollectionname.find()
I get this error:
error: { "$err" : "not authorized on dbname to execute command { $eval: \"db.mycollectionname.find()\", args: [] }" , "code" : 13}
While I have provided all the necessary details Server Address List , Database , User , Password to Jmeter's MongoDB Source Config , MongoDB Script respectively.
Any ideas what can be happening?
I had the same issue. I had to set up a user with eval permissions even though this is not recommended (even the admin user does not have these permissions).
Try that and change you script to look at the new user and it should work.

create admin with "dbAdminAnyDatabse" role with mongodb v2.4.8

I have create an admin user for my mongo installation as follow:
> use admin
> db.addUser( { user: "test",
pwd: "password",
roles: [ "dbAdminAnyDatabse",
otherDBRoles:
{
"otherTestDB": [ "readWrite" ]
}]
} )
When I try to connect to "otherTestDB" using user: "test" and pwd: "password" with robomongo or java driver i get a wrong authentication error.
where mistake?
You have created a userid for the admin db, so to use that userid you have to connect to the admin db, not the otherTestDB. The otherDBRoles document controls access to other dbs while connected to the admin db as that user. So with the addUser as you have specified it the following command fails because the user is for the admin db, not for the otherTestDB:
$ mongo otherTestDB --username test --password password --eval 'printjson(db.c.findOne())'
connecting to: otherTestDB
Thu Feb 27 10:45:20.722 Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" } at src/mongo/shell/db.js:228
whereas the following command, which connects to the admin db and then uses otherTestDB via getSiblingDB, succeeds:
$ mongo admin --username test --password password --eval 'printjson(db.getSiblingDB("otherTestDB").c.findOne())'
connecting to: admin
{ "_id" : ObjectId("530f5d904dbd43cfb46aab5b"), "hello" : "world" }
If you want a user that can authenticate when connecting to the otherTestDB with that userid and password, you will need to separately add such a user to the otherTestDB.
Does this help?

Create Read only user in Mongo DB Instance for a particular database

I have created a user "mongo01testro" in the mongo01test database.
use mongo01test
db.addUser( "mongo01testro", "pwd01", true );
db.system.users.find();
{ "_id" : ObjectId("53xyz"), "user" : "mongo01testro", "readOnly" : true, "pwd" : "b9eel61" }
When I logged in from another session as this newly created user,
I am able to insert documents into the collection which is strange.
I am looking to do the following:
Create 2 separate users one for read only and one for read write for
each database.
Create an admin user which have sysadmin/dba access to all the
databases in MongoDB instance used for Backup/Recovery or admin
purpose.
Please kindly help.
Regards,
Parag
You forgot --auth to enable
Create Users
// ensure that we have new db, no roles, no users
use products
db.dropDatabase()
// create admin user
use products
db.createUser({
"user": "prod-admin",
"pwd": "prod-admin",
"roles": [
{"role": "clusterAdmin", "db": "admin" },
{"role": "readAnyDatabase", "db": "admin" },
"readWrite"
]},
{ "w": "majority" , "wtimeout": 5000 }
)
// login via admin acont in order to create readonly user
// mongo --username=prod-admin --password=prod-admin products
db.createUser({
"user": "prod-r",
"pwd": "prod-r",
"roles": ["read"]
})
Enable auth:
sudo vim /etc/mongod.conf # edit file
# Turn on/off security. Off is currently the default
#noauth = true
auth = true
sudo service mongod restart # reload configuiration
Check write restriction:
# check if write operation for readonly user
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on products to execute command { insert: \"laptop\", documents: [ { _id: ObjectId('53ecb7115f0bfc61d8b1113e'), name: \"HP\" } ], ordered: true }"
}
})
# check write operation for admin user
$ mongo --username=prod-admin --password=prod-admin products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({ "nInserted" : 1 })
# check read operation for readonly user
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.findOne()
{ "_id" : ObjectId("53ecb54798da304f99625d05"), "name" : "HP" }
MongoDB changed the way it handles users in versions >= 2.2 and 2.6 and if you are updating mongodb you will have to Upgrade User Authorization Data to 2.6 Format.
In versions < 2.2 (legacy) you use the db.addUser(username, password, readOnly) function as #Hüseyin BABAL suggested. If you are using version > 2.2 or 2.6 you have a lot more control over what you can do with roles and privileges.
So assuming you use mongo v > 2.6 you can create something like:
use admin
db.createUser({
user: "myUsername",
pwd: "mypwd",
roles: [{
role: "userAdminAnyDatabase",
db: "admin"
}]
})
db.addUser({
user: "username",
pwd: "password",
roles: [{
role: "readWrite",
db: "myDBName"
}]
})
You can use the Build in Roles or you can even create custom roles.
So as you can see you clearly have a lot more options when using v > 2.6 when it comes to authentication and role management.
if the Access control is enabled on the MongoDB deployment, Then you should login by authenticating to the relevant database with admin user (or user with userAdmin role) which you want to control the access. to do that
mongo <db_name> -u <user_name> -p <user_password>
ex: mongo mongo01test -u admin -p admin_paaswrod
then execute the following query to create a read only user for current connected database,
db.createUser({user:"user_name",pwd:"password",roles:[{role:"read", db:"db_name"}]});
ex:db.createUser({user:"user_rd",pwd:"password",roles:[{role:"read", db:"mongo01test"}]});
create a user with both readWrite access,
db.createUser({user:"user_name",pwd:"password",roles:[{role:"readWrite", db:"db_name"}]});
ex:db.createUser({user:"user_rw",pwd:"pass_rw",roles:[{role:"readWrite", db:"mongo01test"}]});
to create a user with admin privileges,
use admin;
db.createUser({user:"admin_user_name",pwd:"password", roles:[{role:"dbAdmin", db:"admin"},{role:"readWriteAnyDatabase", db:"admin"},{role:"backup", db:"admin"},{role:"restore", db:"admin"}]});
Here is my scneario;
// Create admin user
use admin
db.addUser('root', 'strong_password');
// Read only user
use dbforuser1
db.addUser('user1', 'user1_pass', true);
// Read / Write access
use dbforuser2
db.addUser('user2', 'user2_pass');
If you want to login to dbforuser1
use dbforuser1
db.auth('user1', 'user1_pass')

MongoDB with Authentication

I am trying to get MongoDB running on my localhost (Windows) with authentication.
To do so, I first have to add a user, right?
I did so by starting the daemon using this command:
C:\[…]\mongod.exe -f C:\[…]\mongo.config
mongo.config contains the following:
# Basic database configuration
dbpath = C:\[…]\db\
bind_ip = 127.0.0.1
port = 20571
# Security
noauth = true
# Administration & Monitoring
nohttpinterface = true
After that I connected via this command:
C:\[…]\mongo.exe --port 20571 127.0.0.1
There I added a user:
> use admin
switched to db admin
> db.addUser('test', 'test')
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }
{
"user" : "test",
"readOnly" : false,
"pwd" : "a6de521abefc2fed4f5876855a3484f5",
"_id" : ObjectId("50db155e157524b3d2195278")
}
To check if everything worked I did the following:
> db.system.users.find()
{ "_id" : ObjectId("50db155e157524b3d2195278"), "user" : "test", "readOnly" : false, "pwd" : "a6de521abefc2fed4f5876855a3484f5" }
Which seemed OK to me.
After that I changed "noauth = true" to "auth = true" in the mongo.config file and restarted the daemon.
Now I expected to be able to connect with user and password:
C:\[…]\mongo.exe --port 20571 -u test -p test 127.0.0.1
Which denied access to me with this message:
MongoDB shell version: 2.0.4
connecting to: 127.0.0.1:20571/127.0.0.1
Wed Dec 26 16:24:36 uncaught exception: error { "$err" : "bad or malformed command request?", "code" : 13530 }
exception: login failed
So here's my question: Why does the login fail?
I can still connect without providing user and password, but can't access any data because "unauthorized db:admin lock type:-1 client:127.0.0.1". Which is actually what I expected.
As Andrei Sfat told me in the comments on the question I made 2 major errors.
First, I thought I could pass the IP to the Client as a simple argument. But you have to use --host for that.
Instead, the parameter I thought was the IP address actually should be the db name.
So the correct command to connect to a Server is as follows:
C:\[…]\mongo.exe --port 20571 -u test -p test --host 127.0.0.1 admin
Second, users are per database. As I only added the user "test" to the db "admin", it only works there.
Obviously the auth = true configuration wasn't load successfully. Did you forget the -f paramter when you restart the mongod.exe?
C:\[…]\mongod.exe -f C:\[…]\mongo.config