Unable to use authentication mechanisms in db.createUser() - mongodb

I am using MongoDB 4.2. I tried to test out how to use all the Authentication Mechanisms in mongodb. I did something like this
db.createUser({user:"admin2", pwd: "admin2", roles : [{role:"readWrite", db: "test"}], mechanisms : ["SCRAM-SHA-256"]})
This worked fine for SCRAM-SHA-1 and SCRAM-SHA-256. But I tried to work with PLAIN, GSSAPI, MONGODB-X509, MONGODB-CR. Like this,
db.createUser({user:"admin2", pwd: "admin2", roles : [{role:"readWrite", db: "test"}], mechanisms : ["PLAIN"]})
and respectively others. But this does not work throwing an error
uncaught exception: Error: couldn't add user: Unknown auth mechanism 'PLAIN'
What is the reason for this issue ? How to solve this ?

Only scram mechanisms are valid in createUser, as stated in the documentation.
For other mechanisms, you need to create a user in the special $external database. Here is an example invocation that does that for X.509.
db.getSiblingDB("$external").runCommand(
{
createUser: "C=US,ST=New York,L=New York City,O=MongoDB,OU=x509,CN=localhost",
roles: [
{ role: "root", db: "admin" },
],
writeConcern: { w: "majority" , wtimeout: 5000 },
}
)

Related

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.

Cannot access authenticated MongoDB collection from ReactiveMongo Play app

I have a MongoDB server where I have enabled authentication and created users with DB-specific permissions. The user for this app is defined as shown below i.e. geoAdmin has read, readWrite and dbOwner permissions for the relevant database:
MongoDB shell version: 3.0.0
connecting to: 192.168.2.89/test
> use geo_db
switched to db geo_db
> db.getUser("geoAdmin")
{
"_id" : "geo_db.geoAdmin",
"user" : "geoAdmin",
"db" : "geo_db",
"roles" : [
{
"role" : "read",
"db" : "geo_db"
},
{
"role" : "dbOwner",
"db" : "geo_db"
},
{
"role" : "readWrite",
"db" : "geo_db"
}
]
}
The following query works OK i.e. connecting to the remote server from my local mongo client:
mint:~ $ mongo 192.168.2.89:27017 -u geoAdmin -p secret --authenticationDatabase geo_db
MongoDB shell version: 3.0.0
connecting to: 192.168.2.89/test
> use geo_db
switched to db geo_db
> db.LAD_DEC_2013_GB_BFE.findOne({},{'properties.LAD13NM':1})
{
"_id" : ObjectId("54ffe2824f0787ec1293017f"),
"properties" : {
"LAD13NM" : "Hartlepool"
}
}
I then connect to the same remote host from a ReactiveMongo Play app on the same local client, with this URL in the app config file:
# ReactiveMongo
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db"
But when my app tries to read from the same collection, I get a MongoDB "code = 13" error:
[DetailedDatabaseException: DatabaseException['not authorized for query on geo_db.LAD_DEC_2013_GB_BFE' (code = 13)]]
The app works fine if I connect to a local MongoDB which does not have authentication enabled.
Any ideas what might be going wrong here?
ReactiveMongo 0.11.7.play23 is supporting mongo 3.0 auth-protocols, but is still using the old as default.
With ReactiveMongo 0.11.7.play23 -plugin, you can make it authenticate with mongo 3.0, by adding "?authMode=scram-sha1" to the end of your mongodb.uri.
E.g.:
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db?authMode=scram-sha1"
mongo 2.6 uses MONGODB-CR auth protocol and 3.0 uses MONGODB-SHA-1 by default
reactivemongo use MONGODB-CR auth protocol(not sure)
downgrade mongodb 3.0 auth mechanisms to MONGODB-CR
login mongo noauth
remove all user
update the version document for the authSchema.
ex.
db.getSiblingDB("admin").system.users.remove( {} )
db.getSiblingDB("admin").system.version.update(
{ _id: "authSchema" },
{ $set: { currentVersion: 3 } }
);
add authSource parameter to mongodb url
ex.
mongodb.uri = "mongodb://geoAdmin:secret#192.168.2.89:27017/geo_db?authSource=geo_db"

MongoDB user authentication performing actions

I have installed MongoDB for my research and I created to DBs: mydb, jobs
I created a user:
db.createUser( { user: "devdbuser", pwd: "123456", roles: [ "readWrite" ] } )
Then in my jave code I am trying:
MongoClient client = new MongoClient(Arrays.asList(new ServerAddress[] { new ServerAddress("localhost", 27017)}),
Arrays.asList(new MongoCredential[] { MongoCredential.createMongoCRCredential("devdbuser", "mydb", "123456".toCharArray()) } ));
DB myDB = client.getDB("jobs"); // Here I get the jobs DB with user I created for 'mydb'
DBCollection collection = myDB.getCollection("myfirstcollection");
collection.insert((DBObject)JSON.parse("{\"name\": \"First user\", \"email\": \"first_user#mail.com\"}"));
client.close();
Please notice then when I create the MongoClient I am requesting to connect to 'mydb' and I provide the credentials for the created user.
But when I take the jobs DB and try to insert data to a collection everything works well.
I would expect an error that user has no privileges, am I missing something?
Thank you for your help.
You have created a user devdbuser with readWrite role. Due to which devdbuser acquires all the privileges of the read and has the ability to modify data of all non-system collections.
If you try to create credentials with "jobs" database instead of "mydb" then authentication would fail.
MongoClient client = new MongoClient(Arrays.asList(new ServerAddress[] { new ServerAddress("localhost", 27017)}),
Arrays.asList(
new MongoCredential[] { MongoCredential.createMongoCRCredential("devdbuser",
"jobs", "123456".toCharArray()) } ));
Error Stacktrace
com.mongodb.CommandFailureException: { "serverUsed" : "localhost/127.0.0.1:27017" , "ok" : 0.0 , "errmsg" : "auth failed" , "code" : 18}
Essentially user once authenticated on "mydb" but has readWrite permission for collections across database

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 2.4 Replica set with authorization

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.