mongodb remote authentication failure Mongod v4 - mongodb

I have recently installed mongodb on one of our windows 2016 server with below configuration and running mongod as
mongod --config C:\mongo_db\config\mongo_db_configuration.conf --auth
--config file
net:
# MongoDB server listening port
#bindIp: 0.0.0.0,192.168.43.250
port: 27017
bindIpAll: true
storage:
# Data store directory
dbPath: "C:\\mongo_db\\db"
mmapv1:
# Reduce data files size and journal files size
smallFiles: true
systemLog:
# Write logs to log file
destination: file
path: "C:\\mongo_db\\logs\\mongodb.log"
security:
authorization: enabled
We have created a root user in admin database
MongoDB Enterprise > db.runCommand({connectionStatus:1})
{
"authInfo" : {
"authenticatedUsers" : [
{
"user" : "root",
"db" : "admin"
}
],
"authenticatedUserRoles" : [
{
"role" : "dbAdminAnyDatabase",
"db" : "admin"
},
{
"role" : "root",
"db" : "admin"
}
]
},
"ok" : 1
}
I am able to connect to the mongod instance locally (mongo --port 27017 -u "root" -p "12345" --authenticationDatabase admin) but getting error while connecting remotely.the server firewall is disabled.
"C:\Mongodb>mongo.exe 192.168.0.171:27017/admin -u root -p 12345
MongoDB shell version v4.0.4
connecting to: mongodb://192.168.0.171:27017/admin
Implicit session: session { "id" : UUID("c68e9dd5-6f7b-4356-bc3e-688a7e2b3e1d") }
MongoDB server version: 4.0.4
2018-11-26T23:50:47.534+0800 E QUERY [js] Error: Authentication failed. :
DB.prototype._authOrThrow#src/mongo/shell/db.js:1685:20
#(auth):6:1
#(auth):1:2
exception: login failed"

I stumbled upon this when I was having the same problem. I was connecting to a MongoDB server version 4.2.6 from a MongoDB shell version v3.6.9. In case anyone else finds this question like I did, here's the syntax that worked:
mongo --host mongodb://username:password#IP:PORT/ --authenticationDatabase admin

I'm also having similar issue with my virtual machines. I have 2 linux and 1 windows machine (which are remotely connected to my windows machine). Let's say Linux A has mongo with credentials. When I try to login from my windows machine, I got the same error that you mention.
However, when I connect mongo from linux B to linux A, I can successfully connect from shell using:
mongo --host 192.168.1.6 --port 27017 -u username -p 'pwd'
I use exact same command from windows as well but somehow it fails to login. Maybe this command could work on your environment but waiting for proper solution as well.

Related

MongoDB unable to connect to the newly created admin user in admin db

We have created a new admin user in mongodb version 3.6.21
[root#MONGODB01 mongodb]# mongo --port 37017
MongoDB shell version v3.6.21
connecting to: mongodb://127.0.0.1:37017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("54681232-fa6b-4dbd-bfe5-c1bde274d430") }
MongoDB server version: 3.6.21
s1:PRIMARY> use admin
switched to db admin
s1:PRIMARY> db.createUser(
... {user: "admin",
... pwd: "reco#123",
... roles:[{role: "root" , db:"admin"}]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
s1:PRIMARY> exit
bye
After that we are trying to login but facing below error. Please help
[root#MONGODB01 mongodb]# mongo --port 37017 –u admin –p reco#123 -authenticationDatabase admin
MongoDB shell version v3.6.21
connecting to: mongodb://127.0.0.1:37017/%E2%80%93u?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("729e70cf-d594-4bd1-b6dc-73d75fd20f89") }
MongoDB server version: 3.6.21
loading file: admin
2021-10-18T15:35:07.305+0530 E - [main] file [admin] doesn't exist
failed to load: admin
Below is the config file for primary mongod instance.
[root#MONGODB01 mongodb]# cat /etc/mongod.conf
# mongod.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/primary1/mongod.log
storage:
dbPath: /data/mongodb/primary1/db
journal:
enabled: true
# mmapv1:
# # Reduce data files size and journal files size
# smallFiles: true
wiredTiger:
engineConfig:
cacheSizeGB: 4
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
net:
port: 37017
bindIp: 0.0.0.0
security:
# authorization: enabled
keyFile: /data/mongodb/key/mongodb.key
replication:
replSetName: s1
sharding:
clusterRole: shardsvr
FYI - We are running Primary shard1, Replica Shard 2 and Replica Shard 3 on single node.
You need two hyphen --, should be this:
mongo --port 37017 --authenticationDatabase admin -u admin -p reco#123
You may enclose the password by quotes, i.e.
mongo --port 37017 --authenticationDatabase admin -u admin -p "reco#123"
For username and password you use either short or long form, i.e.
-u admin -p "reco#123"
or
--username admin --password "reco#123"
I was able to solve this issue by using below command instead
mongo --port 37017 -authenticationDatabase admin -u admin -p reco#123

How to run a command from the mongo shell in docker after having connected to an instance with x509 certificates?

I'm running a bash script called by Dockerfile.
I give my user the necessary permissions:
chown -R mongodb:mongodb /home/mongod
I have one replica with 3 instances.
Before initiating this replica, I start the mongod process respective to each instance:
nohup gosu mongodb mongod --config /home/mongodb/instanceR0.conf
nohup gosu mongodb mongod --config /home/mongodb/instanceR1.conf
nohup gosu mongodb mongod --config /home/mongodb/instanceR2.conf
All the processes started successfully.
After, I want to connect to one of the instances in order to authenticate and initiate the replica set:
# connect to one db instance
nohup gosu mongodb mongo --port 57040 --ssl --host example.com --sslPEMKeyFile /home/mongodb/certificateExample.pem --sslCAFile /home/mongodb/caExample.pem
# authenticate with user
nohup gosu mongodb mongo "db.getSiblingDB('\$external').auth({ mechanism: 'MONGODB-X509', user: 'CN=example.com,OU=StackOverflow,O=Example,L=City,ST=City,C=PT' })"
# initiate replica sets
nohup gosu mongodb mongo "rs.initiate({ _id: 'replicaExample', members: [{ _id : 0, host : '127.0.0.1:57040' }, { _id : 1, host : '127.0.0.1:57041' }, { _id : 2, host : '127.0.0.1:57042' }] })"
The problem happens when connecting to one db instance. It connects successfully to the mongo shell but when executing authenticate with user it leaves the mongo shell.
connecting to: mongodb://example.com:57040/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("27eb0298-2766-4efb-8054-211e18c88ea8") }
MongoDB server version: 4.2.6
bye
How can I construct a bash script command which after connecting to a db instance, will continue inside the mongo shell and execute the 2 remaining commands (authenticate with user and initiate replica sets?
Solution:
Use --eval after the statement to run the javascript functions.
For example:
nohup gosu mongodb mongo --port 57040 --ssl --host example.com --sslPEMKeyFile /home/mongodb/certificateExample.pem --sslCAFile /home/mongodb/caExample.pem --eval "db.getSiblingDB('\$external').auth({ mechanism: 'MONGODB-X509', user: 'CN=example.com,OU=StackOverflow,O=Example,L=City,ST=City,C=PT' });rs.initiate({ _id: 'replicaExample', members: [{ _id : 0, host : '127.0.0.1:57040' }, { _id : 1, host : '127.0.0.1:57041' }, { _id : 2, host : '127.0.0.1:57042' }] })"

On MongoDB , command mongostat not work , error username

i have a problem with mongostat .
test1 :
mongostat
2019-11-15T16:06:55.722+0100 Failed: error connecting to db server: no reachable servers
test2:
mongostat -u "dominio\\username" -p password--host hostname --authenticationMechanism PLAIN --authenticationDatabase '$external' --ssl --sslCAFile /pathcert
2019-11-15T16:07:44.682+0100 Failed: not authorized on admin to execute command { serverStatus: 1, recordStats: 0, $readPreference: { mode: "secondaryPreferred" }, $db: "admin" }.
I have 2 questions:
- with mongostat can i specify a specific DB?
- the username that privileges need to have?
How can I resolve these?

mongoDB : Authentication of user is working fine, but getting "Unauthorized not authorized on admin to execute command" in the logs

I've followed the steps as mentioned in How do I add an admin user to Mongo in 2.6?
At first, "auth=true" in the /etc/mongod.conf file is commented out so that authentication is not done and I could create the following users in respective dbs.
Admin:
use admin;
db.createUser({user: "mongoRoot", pwd: "password", roles: [{role: "root", db: "admin"}]});
db.createUser({user: "mongoAdmin", pwd: "password", roles: ["readWrite"]});
db.createUser({user: "siteUserAdmin", pwd: "password", roles: [{role: "userAdminAnyDatabase", db: "admin"}]});
db.createUser({user: "mongoDBAdmin", pwd: "password", roles: [{role: "dbAdmin", db: "admin"}]});
db.createUser({user: "mongoDBOwner", pwd: "password", roles: [{role: "dbOwner", db: "admin"}]});
db.createUser({user: "mongoWrite", pwd: "password", roles: [{role: "readWrite",db: "mongo_database"}]}); (Added in admin so that by giving the command from the command-line 'mongo mongo_database --port 27018 -u mongoWrite -p password --authenticationDatabase admin', the user mongoWrite is able to login as done in https://gist.github.com/tamoyal/10441108)
db.createUser({user: "mongoRead", pwd: "password", roles: [{role: "read", db: "mongo_database"}]}); (Added in admin so that by giving the command from the command-line 'mongo mongo_database --port 27018 -u mongoRead -p password --authenticationDatabase admin', the user mongoRead is able to login as done in https://gist.github.com/tamoyal/10441108)
Config:
use config;
db.createUser({user: "mongoConfig", pwd: "password", roles: [{role: "readWrite", db: "config"}]});
Test:
use test;
db.createUser({user: "mongoTest", pwd: "password", roles: [{role: "readWrite", db: "test"}]});
mongo_database:
use mongo_database;
db.createUser({user: "mongoWrite", pwd: "password", roles: [{role: "readWrite",db: "mongo_database"}]});
db.createUser({user: "mongoRead", pwd: "password", roles: [{role: "read", db: "mongo_database"}]});
db.createUser({user: "mongoAdmin", pwd: "password", roles: [{role: "readWrite", db: "mongo_database"}]});
After making sure that all the required users are added, turning on the authentication by uncommenting "auth=true" in the /etc/mongod.conf file and restarting the mongodb.
[ec2-user#ip-xxx-xx-xx-xx ~]$ mongo mongo_database --port 27018 -u mongoWrite -p password --authenticationDatabase admin
MongoDB shell version: 2.6.10
connecting to: 127.0.0.1:27018/mongo_database
rs0:PRIMARY> db.test.insert({"Hello":"World"});
WriteResult({ "nInserted" : 1 })
rs0:PRIMARY> exit
bye
[ec2-user#ip-xxx-xx-xx-xx ~]$ mongo mongo_database --port 27018 -u mongoRead -p password --authenticationDatabase admin
MongoDB shell version: 2.6.10
connecting to: 127.0.0.1:27018/mongo_database
rs0:PRIMARY> db.test.insert({"Hello":"World"});
WriteResult({
"writeError" : {
"code" : 13,
"errmsg" : "not authorized on mongo_database to execute command { insert: \"test\", documents: [ { _id: ObjectId('559bba6ead81843e121c5ac7'), Hello: \"World\" } ], ordered: true }"
}
})
rs0:PRIMARY>
Everything works fine till this point. The only issue that am encountering is that my log file is getting bombarded with the following 2 lines at almost tens of thousand lines per minute and within no time, my disk is running out of space.
2015-07-07T11:40:28.340+0000 [conn3] Unauthorized not authorized on admin to execute command { writebacklisten: ObjectId('55913d82b47aa336e4f971c2') }
2015-07-07T11:40:28.340+0000 [conn2] Unauthorized not authorized on admin to execute command { writebacklisten: ObjectId('55923232e292bbe6ca406e4e') }
Just to give an idea, in a span of 10 seconds, 10 MB worth of log file is generated consisting of just the above mentioned 2 lines.
[ec2-user#ip-xxx-xx-xx-xx ~]$ date
Tue Jul 7 11:44:01 UTC 2015
[ec2-user#ip-xxx-xx-xx-xx ~]$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/xvdh 4.8G 388M 4.2G 9% /log
[ec2-user#ip-xxx-xx-xx-xx ~]$ date
Tue Jul 7 11:44:14 UTC 2015
[ec2-user#ip-xxx-xx-xx-xx ~]$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/xvdh 4.8G 398M 4.2G 9% /log
To my knowledge, the authentication seems to be working fine. Just that the logs are getting filled at super sonic speed. What am I doing wrong? Please help. Thanks In Advance.
The excessive logging was from the config servers and even after adding the authentication to the config servers with authentication turned on, it wouldn't stop. Upgraded to mongo 3.0.4 for replica sets, turned on the authentication on replica sets and upgraded mongo to 3.0.4 on config servers and it started working fine without any issues (Same steps on mongo 2.6.x would result in the issue I mentioned above). So, we planned to upgrade to 3.0.4 in order to bypass this issue. Hope, it will be helpful to someone.

Testing mongo replication on OSX

In two different terminals, I start up mongod with:
mongod --dbpath 1 --port 27001 --smallfiles --oplogSize 50 --logpath log.1 --replSet test
mongod --dbpath 2 --port 27002 --smallfiles --oplogSize 50 --logpath log.2 --replSet test
(data subdirectories 1 and 2 already created).
I go into a third window and run the mongo shell against one of the mongod instances
mongo --port 27001
In the shell, I setup a configuration as
cfg = { _id: "test", members: [ {_id:0, host: "localhost:27001"}, {_id:1, host:"localhost:27002"} ] }
then run:
use admin
rs.initiate(cfg)
The response from the shell is:
{
"startupStatus" : 4,
"info" : "hotest",
"errmsg" : "all members and seeds must be reachable to initiate set",
"ok" : 0
}
The logfile for instance on port 27001 reports:
Sun Nov 18 18:32:56 [rsStart] trying to contact macbookpro.local:27001
Sun Nov 18 18:32:56 [rsStart] couldn't connect to macbookpro.local:27001: couldn't connect to server macbookpro.local:27001
Sun Nov 18 18:32:56 [rsStart] replSet can't get local.system.replset config from self or any seed (yet)
It appears that the rs.initiate(cfg) cannot connect to the mongod instance on port 27001. But when I run mongod without --replSet the mongo shell connects just fine.
It isn't clear where I am screwing up but I will bet it is obvious.
Found it!
It turns out that when one installs MongoDB on OSX with brew a configuration file is created at /usr/local/etc/mongo.conf. In this file there was the line:
# Only accept local connections
bind_ip = 127.0.0.1
Well, if you look at the log the rsStart error was:
Sun Nov 18 18:32:56 [rsStart] trying to contact macbookpro.local:27001
Sun Nov 18 18:32:56 [rsStart] couldn't connect to macbookpro.local:27001: couldn't connect to server macbookpro.local:27001
Sun Nov 18 18:32:56 [rsStart] replSet can't get local.system.replset config from self or any seed (yet)
and if I ping macbookpro.local the IP address returned was 192.168.41.1. 192.168.41.1 <> 127.0.0.1 so mongod was refusing to respond. Removing this line from the configuration allowed be to setup replication successfully.
sheesh. I am such an idiot. Looked for hours at this and kept thinking that the machine name when connected to the network was 127.0.0.1. Let this be a lesson to you---don't get old!
Figuring out the hostnames can be painful, so instead of passing the config object and trying to work out what your hostname should be, just do rs.initiate() with no arguments on the first host. That will create the required config, discovering the correct value for you. It will print out the "valid" version of the config that it created. Here's a sample:
> rs.initiate()
{
"info2" : "no configuration explicitly specified -- making one",
"me" : "adamc-mbp.local:27001",
"info" : "Config now saved locally. Should come online in about a minute.",
"ok" : 1
}
Copy and paste the "me" field and use the new port number, pass to rs.add():
sotest:PRIMARY> rs.add("adamc-mbp.local:27002")
{ "ok" : 1 }
Now take a look at your config:
sotest:PRIMARY> rs.conf()
{
"_id" : "sotest",
"version" : 2,
"members" : [
{
"_id" : 0,
"host" : "adamc-mbp.local:27001"
},
{
"_id" : 1,
"host" : "adamc-mbp.local:27002"
}
]
}
You should be good to go :)
I had the same issue. Somehow mongo resolves localhost as your machine's name macbookpro.local.
Just add this line to your /etc/hosts file :
127.0.0.1 macbookpro.local