mongodb authentication disable and enable issue - mongodb

Now I have a mongoDB in my computer,locates at c:\mongodb\bin. At first, it is auth disable. so when I press:
C:\Windows\system32>mongo
There is some warnings:
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** WARNING:
Access contr ol is not enabled for the database.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] **
Read and wri te access to data and configuration is unrestricted.
So I tried to add access control to mongoDB. What I did are:
C:\mongodb\bin>use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
But after I did above, still I can log in MongoDb without username and pwd. Even after I restart the mongoDB service, or restart the computer. eg:
C:\Windows\system32>mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2018-03-28T16:53:43.515+0800 I CONTROL [initandlisten]
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** WARNING: Access contr
ol is not enabled for the database.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] ** Read and wri
te access to data and configuration is unrestricted.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten]
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten] Hotfix KB2731284 or late
r update is not installed, will zero-out data files.
2018-03-28T16:53:43.516+0800 I CONTROL [initandlisten]
> show dbs
admin 0.000GB
local 0.000GB
> use admin
switched to db admin
>
The only way that I can make the mongodb change to authentication is delete the mongodb service and install this service again by using follwoing script:
C:\mongodb\bin>sc delete MongoDB
C:\mongodb\bin>mongod --dbpath C:\mongodb\data --logpath C:\mongodb\log\MongoDB.log --auth --install
But If I use this way to create the auth mongoDB, when I try to login without username and pwd, it will faied as below:
C:\Windows\system32>mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
> show dns
2018-03-28T17:59:06.344+0800 E QUERY [thread1] Error: don't know how to show
[dns] :
shellHelper.show#src/mongo/shell/utils.js:906:11
shellHelper#src/mongo/shell/utils.js:659:15
#(shellhelp2):1:1
> show dbs
2018-03-28T17:59:10.073+0800 E QUERY [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases:
1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs#src/mongo/shell/mongo.js:62:1
shellHelper.show#src/mongo/shell/utils.js:769:19
shellHelper#src/mongo/shell/utils.js:659:15
#(shellhelp2):1:1
>
So I can NOT create a user and pwd for this mongoDB. How could I login?
Anybody can tell me how to do the setting step by step to make my mongoDB to authentication? or delete a old mongoDB and create a new one with authutication and also with username and pwd?
I will get an exception below if I tried to set a without auth mongoDB and auth one.
C:\Windows\system32>mongod --auth --port 27017 --dbpath C:\mongodb\data
2018-03-28T16:49:43.874+0800 I CONTROL [initandlisten] MongoDB starting : pid=7
988 port=27017 dbpath=C:\mongodb\data 64-bit host=wolf-PC
.....
2018-03-28T16:49:43.877+0800 I STORAGE [initandlisten] exception in initAndList
en: 98 Unable to create/open lock file: C:\mongodb\data\mongod.lock Another program is using this file.... Is a mongod instance already running?, terminating
I checked the questions:
MongoDB: Server has startup warnings ''Access control is not enabled for the database''
which I failed to follow with step4 on above excpetion.
MongoDB: Server has startup warnings
I got the same exception.
So anyone can give me a detail soultion?

The reason why authentication is not working in your first example is because you have not yet enabled it. Auth is enabled by configuration only and not by the presence of db users. As you already demonstrated, the way to enable auth is to either start the db with the --auth flag or ensure that authorization is enabled within the security section of your mongod.conf file (like below).
security:
authorization: enabled
Once authorization is enabled, you must authenticate first before performing any operations by using the below options when you start the shell.
mongo <db> -u <username> -p <password>
For example, since you already created your myUserAdmin user on the admin database, then you can authenticate like this:
mongo admin -u myUserAdmin -p abc123
Or, if you have already started the shell with just mongo, then you can authenticate like this:
1) First switch to the admin db.
use admin
2) Then authenticate your user:
db.auth('myUserAdmin ', 'abc123')
Also, keep in mind that the userAdminAnyDatabase is a very powerful admin role, but it only allows read/write access to the admin database (not databases that you create to store data for your app). It also enables admin operations (e.g. createUser, createRole, etc) across ALL databases which could be dangerous if compromised.
So, if you are trying to create a user to read/write from a non-system database, then you should create a different, specific user for that. For Example...
1) authenticate your admin user (like what was shown above).
2) create a new user to read/write from your app database:
db.createUser(
{
user: <app db user>,
pwd: <password>,
roles: [ { role: "readWrite", db: <app db> } ]
}
);
Here is more detail about each of the mongodb roles and how they behave.

Related

mongo : not authorizeed on admin to execute on admin to execute command

I am new to Mongod, and have to get up a cluster. The db is started with --replSet=Data and I have created the cluster with rs.Initiate beforehand. But this question is about user administration.
This replica set was set up with this command:
rs.initiate({ _id : "Data",members: [
{ _id: 0, host: "srv1:27017" },
{ _id: 1, host: "srv2:27017" },
{ _id: 2, host: "srv3:27017" , arbiterOnly: true }
})
And the server was started with $ /usr/bin/mongod -f /etc/mongod.conf --replSet=rs0
Note that I have not yet configured the other nodes/added these into the cluster as far as I am aware, but I did distribute the keyFile: /etc/mongod/keyfile to each server.
An rs.status says it's not running.
> rs.Status();
{
"ok : 0"
"errmsg" : no replset config has been received",
"code" : 94,
"codename" : "NotYetInitialized"
}
I have run into some nib problems.
I created a user before called mgdb with the command :
# mongo admin -port 27017
> db.createUser ( {
user : 'mgdb', pwd: 'password', roles: [ { roles: root, db: admin } ]
})
This returned ok.
Next I tried with,
$ mongo --authenticationDatabase admin --username "mgdb" --password "password"
but got an error
E QUERY [js] Error authentication failed.
Next I tried to see the user list,
> show users;
not authorizeed on admin to execute on admin to execute command { UserInfo: 1.0}, lsid: { id: UID"xxxxxxxx") }. $db: "admin" } DB.prototy[e.getUsers#.....
So, I am bit lost. I used mysql a few years ago, but have not used it since. My dB experience is very little.
Although I can connect as the admin user, the admin user does not seem to have rights to do basic "show users;"
Where can I look in the dB to find out what went wrong?
Environment: RHEL 7.6 SELinux Enforcing, MOngdodB 4.2.9
In MongoDB you can create users per database. Usually users are create in database admin (I wouldn't know any reason to create them somewhere else):
use admin
db.createUser(...
or
db.getSiblingDB("admin").createUser(...
When you connect to Mongo then you need to specify the authentication database, i.e. the database where user was created:
mongo --usermame=mgdb --password 'password' --authenticationDatabase admin
See Authentication failure while trying to save to mongodb
In order to deploy a sharded cluster have a look at Deploy a Sharded Cluster or Deploy a Replica Set tutorial.

Mongo DB 3.2 Authentication

I've just followed this guide on setting up Auth with Mongo DB, as well as this guide to get a user set up as an administrator.
Running mongo > use admin > show users prints the following:
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
After this, I run the server again with --auth and use the following command:
mongo -u "root" -p "xxx" --authenticationDatabase "admin"
This prints the following:
MongoDB shell version: 3.2.19
connecting to: test
2018-03-29T15:52:32.329+0200 E QUERY [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow#src/mongo/shell/db.js:1441:20
#(auth):6:1
#(auth):1:2
exception: login failed
Trying to run this without the --auth parameter lets me log in just fine.
The --auth parameter also gives me the following output in the server console:
I ACCESS [conn1] note: no users configured in admin.system.users, allowing localhost access
But I'm actually unsure about why it isn't picking up any root/admin user I create. When trying to connect with Robo 3T, the terminal prints the following:
I NETWORK [initandlisten] connection accepted from xxx:44924 #2 (2 connections now open)
I ACCESS [conn2] SCRAM-SHA-1 authentication failed for root on admin from client xxx ; UserNotFound: Could not find user root#admin
I NETWORK [conn2] end connection xxx:44924 (1 connection now open
Solution by OP.
Issue fixed by following this article.
It seems that, despite using --auth when connecting to the server, by not commenting out the line bindIp: 127.0.0.1 and adding authorization: 'enabled' to the security section in /etc/mongod.conf, I was only allowing access to the local machine - the server itself. The error messages could have been worded a bit better, but that's security. I guess.
Whilst this was a very silly oversight, no documentation I had previously looked at had covered this issue.

Meteor and MongoDB: Authentication failures

If I run Meteor locally it works perfectly. If I call Meteor with a MONGO_URL that has no username:password it works perfectly too. However, if I turn on the MongoDB authentication and restart and then run Meteor with the username:password set, as in MONGO_URL="mongodb://username:password#127.0.0.1:27017/meteor", then I get an authentication failure as Meteor loads. I have checked that the username and password are correct. I have read that there maybe problems with Meteor and MongoDB authentication so does anyone have any information on this? I am using the following versions:
Meteor - 1.0.3.2
MongoDB - 2.6.7 (installed via brew)
I20150304-21:48:00.597(1)? Exception in callback of async function: MongoError: auth failed
I20150304-21:48:00.598(1)? at Object.toError (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/utils.js:110:11)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1128:31
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1843:9
I20150304-21:48:00.598(1)? at Server.Base._callHandler (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
I20150304-21:48:00.598(1)? at [object Object].MongoReply.parseBody (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:95:17)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:98:17)
=================================================
I thought I had an answer to the above but alas not, I made suggested changes and I still could not authenticate. So, to provide more details:
I have upgraded to MonogoDB 3.0.0
I delete the database so that a brand new one was created.
My config file is as follows:
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
security:
authorization: enabled
On the "admin" database a "super user" has been created as follows:
use admin
db.createUser({user: "superuser", pwd: "password", roles:["root"]})use admin
I then created a user on the "meteor" database
db.auth("superuser", "password")
use meteor
db.createUser({user: "meteor", pwd: "password", roles: [{ role: "readWrite", db: "meteor"}]})
The above step generates:
Successfully added user: {
"user" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
If I perform a db.getUsers() I get the message:
[
{
"_id" : "meteor.meteor",
"user" : "meteor",
"db" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
]
If I comment out the two security lines in the config then I can access MongoDB from Meteor or RoboMongo without a problem - using mongodb:127.0.0.1:27017/meteor. If I uncomment the two security lines in the config then I can no longer access MongoDB from either Meteor or MongoDB - using mongodb://meteor:password#127.0.0.1:27017/meteor. In the last instance I continue to get the message that authentication failed. In the MongoDB logs I have:
authenticate db: meteor { authenticate: 1, nonce: "xxx", user: "meteor", key: "xxx" }
2015-03-08T14:34:44.909+0100 I ACCESS [conn7] Failed to authenticate meteor#meteor with mechanism MONGODB-CR: AuthenticationFailed UserNotFound Could not find user meteor#meteor
Update
The answer below and the configuration above work on v2.6.7
I haven't seen the issues you describe and without seeing code or knowing how you "turned on" MongoDB authentication I need to guess - so let's focus on what made things work for me.
You should check where the user was created. In MongoDB there are multiple databases, each having their own users. When using your connection string
mongodb://username:password#127.0.0.1:27017/meteor
you are authenticating against the meteor database. Using a tool such as RoboMongo I'd check if the user is actually inside that database or whether you created it inside the admin (or any other) database.
As a quick rundown:
When securing MongoDB you need to set an admin account, change the mongodb.conf file that it contains the line auth = true and restart. Then using the admin account you create a new (low-privilege) db user that has only access to the meteor database. You can do this using the command line like this (code for 2.6 as this was in your questions and will be default for next Meteor version):
db.createUser(
{ user: "username",
pwd: "password",
roles: [
{ role: "readwrite", db: "meteor" }
]
})
If you run mongod on the same box as Meteor I think we can safely rule out any issues with net.port or net.bindIpconfig settings where the DB would simply not listen to requests.
If you did all this and restarted MongoDB, perhaps a meteor reset inside your projects can help fix anything.
it turns out for me was just about having special chars on the password and a dash on the username, once i made it simpler it all worked like magic :(
I had the same issue when I deployed on my new VPS.
On this new VPS, mongo version is 3.0.1
To solve the problem, a meteor update before building the package and it works
(meteor version: 1.0.4.1)

Can't authenticate with mongoenine to mongodb replicas

1) Before even setting replica sets in mongo i created admin user, with "readWriteAnyDatabase", "userAdminAnyDatabase", "dbAdminAnyDatabase", "clusterAdmin" roles.
2) Then i set my /etc/mongodb.conf configurations on all 3 servers.
dbpath=/var/lib/mongodb
logpath=/var/log/mongodb/mongodb.log
logappend=true
port = 27017
auth = true
replSet = test4
3) Initiated replicas, but got error
(Do not remember exactly what the error was, but something related to that one of the server was not up. So i figured that it just can't authenticate)
config = {"_id" : "test4", "version" : 1, "members" : [{"_id" : 0,"host" : "xxx.xxx.xxx.xxx:27017"}, {"_id" : 1,"host" : "xxx.xxx.xxx.xxx:27017"}, {"_id":2,"host" : "xxx.xxx.xxx.xxx:27017"}]}
rs.initiate(config)
4) To solve the error, i generated keyFile and added keyFile authentication to my mongodb.conf file.
dbpath=/var/lib/mongodb
keyFile = /etc/keyFile
logpath=/var/log/mongodb/mongodb.log
logappend=true
port = 27017
auth = true
replSet = test4
And everything worked like a charm. Database copied itself over replicas. Admin user worked as expected too.
5) Then i created user with all needed permissions for other database i have, lets call it 'testdb' and user: notadmin, pass: notadmin.
But there is one strange thing i noticed. When i enter mongo in console i do not see replicas, until i log in admin database as an admin like this:
use admin
db.auth('admin', 'admin')
Then my console changes to test4:PRIMARY> or test4:SECONDARY> and i can perform actions with replicas. Guess it should be like this.
And everything works fine, if i insert data through pymongo library. Permissions work, admin user can insert into any database, given permissions, and notadmin user can insert into testdb.
But if i try to make the same thing with mongoengine models,
mongodsn = 'mongodb://notadmin:notadmin#xxx.xxx.xxx.xxx:27017,xx.x.xx.xxx:27017,xxx.xxx.xxx.xx:27017/'
db_instance = mongoengine.connect('testdb', host=mongodsn, replicaSet='test4', readPreference='secondaryPreferred')
rt = ReconnectTest()
rt.content = 'item#{0:d}'.format(x)
rt.save()
i get authentication error:
mongoengine.errors.OperationError: Could not save document (command
SON([('authenticate', 1), ('user', u'notadmin'), ('nonce',
u'9ae2f85cd41f6c74'), ('key', u'8f814aa2434s4t2e0ff9bae03762e')])
failed: auth fails)
The only thing it permits me is from admin user to write to admin database. So something like this works:
mongodsn = 'mongodb://admin:admin#xxx.xxx.xxx.xxx:27017,xx.x.xx.xxx:27017,xxx.xxx.xxx.xx:27017/'
db_instance = mongoengine.connect('admin', host=mongodsn, replicaSet='test4', readPreference='secondaryPreferred')
rt = ReconnectTest()
rt.content = 'item#{0:d}'.format(x)
rt.save()
I am so confused, because mongoengine is just wrapper around pymongo. So how come i can do actions with pymongo, and can't do the same with mongoenige. How do i authenticate with mongoengine to testdb ?
You need to create a user under the "testdb" database, as follows:
$ mongo admin -u <username> -p <password>
> use testdb
> db.addUser({user: <username>, pwd: <password>, roles: [<permissions>]})
Then trying to connect through mongoengine using the newly created user.
Also, add the database in the connection string, as such:
'mongodb://notadmin:notadmin#xxx.xxx.xxx.xxx:27017/testdb'

MongoDB: set user/password to access to db

I'm trying to set password for mongodb to prevent access to db with empty login and pass (set by default).
I'm statring mongo server:
sudo ./mongod
Starting client:
./mongo
Setting password:
use admin
db.addUser("root", "root")
exit
The output is:
MongoDB shell version: 2.2.0
connecting to: test
> use admin
switched to db admin
> db.addUser("root", "root")
{
"user" : "root",
"readOnly" : false,
"pwd" : "2a8025f0885adad5a8ce0044070032b3",
"_id" : ObjectId("50c90b94e28c41a388104f64")
}
> exit
Hoever, wheh I try to auth with empty credentials (I use mViever admin UI), it still works. Otherwise, access with root/root is not avialable. What I'm doing wrong?
Also tried to start mongo server with -auth parameter, the same result:
./mongod -auth
UPD: After starting with -auth parameter can't login with any pass. Getting:
Thu Dec 13 03:27:38 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
Update: I dont know what's goin on...
> db.auth("root","root");
1
> ^C
bye
It can login. Let's restart ./mongod --auth and ./mongo:
MacBook-Pro-Ilya:bin ilyarusanen$ ./mongo
MongoDB shell version: 2.2.2
connecting to: test
> db.auth("root","root")
Error: { errmsg: "auth fails", ok: 0.0 }
0
> db.test.insert({"yeah":"2342"})
Fri Dec 14 08:52:05 uncaught exception: getlasterror failed: { "errmsg" : "need to login", "ok" : 0 }
> use admin
switched to db admin
> db.addUser("root","root")
Fri Dec 14 08:52:14 uncaught exception: error {
"$err" : "unauthorized db:admin ns:admin.system.users lock type:1 client:127.0.0.1",
"code" : 10057
}
> db.auth("root","root")
1
Why at first it can login? Why after restarting mongo is not able to login? And why after FAILED attempt to addUser, it becomes able to login? Thanks.
UPDATE2: MongoHub seems to auth ok. However, from NodeJS I still can't login: I use such code:
mongo_db.open(function(err,data){
if(data){
data.authenticate("root", "root",function(err2,data2){
if(data2){
console.log("Database opened");
}
else{
console.log(err2);
}
});
} else {
console.log(err);
}
});
And I get:
{ [MongoError: auth fails] name: 'MongoError', errmsg: 'auth fails', ok: 0 }
But mention, MongoHub with same credentials works fine.
From your comment you mention that you are using mViewer. Version 0.9.1 of mViewer does not support authentication. According to this issue on the mViewer GitHub, this is resolved in version 0.9.2, which was targeted for release in Oct.
Before starting the node with authentication, log on to the node and add a user. Then start the node with --auth and connect to the shell without mViewer.
At this point you can connect to the admin database and authenticate your admin user:
use admin
db.auth('root', 'root')
Since you set up an admin user, which will have access to all the databases, you need to authenticate against the admin database. Once you have done this you will have access to all the databases. You will also be able to create new users on any database, or create new read only users for all the databases.
If you create a new user that has access to only one database, that user would need to use that database and db.auth(name, pass) against it.
If you create a new user that has read only access to all databases, they would use admin and then db.auth(name, pass) to gain their read only access to all databases
You can find more information on setting up authentication here and more information about setting up users here
Note: When you start a node without --auth then no authentication is enabled. This means you can connect with the shell and db.auth('root','root') but it won't do anything as far as access is concerned. MongoDB will not deny access to the databases without --auth command line option (--keyFile in sharded setups or replica sets)