Not authorized for query on admin.system.namespaces on mongodb - linux

I start a new mongo instance, create a user, authorize it, but when I run "show collections", the system says that the id is not authorized. I do not know why?
# mongo admin
MongoDB shell version: 2.4.3
connecting to: admin
Server has startup warnings:
Thu May 23 18:23:56.735 [initandlisten]
Thu May 23 18:23:56.735 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
Thu May 23 18:23:56.735 [initandlisten] ** 32 bit builds are limited to less than 2GB of data (or less with --journal).
Thu May 23 18:23:56.735 [initandlisten] ** See http://dochub.mongodb.org/core/32bit
Thu May 23 18:23:56.735 [initandlisten]
> db = db.getSiblingDB("admin")
admin
> db.addUser({user:"sa",pwd:"sa",roles:["userAdminAnyDatabase"]})
{
"user" : "sa",
"pwd" : "75692b1d11c072c6c79332e248c4f699",
"roles" : [
"userAdminAnyDatabase"
],
"_id" : ObjectId("519deedff788eb914bc429b5")
}
> show collections\
Thu May 23 18:26:50.103 JavaScript execution failed: SyntaxError: Unexpected token ILLEGAL
> show collections
Thu May 23 18:26:52.418 JavaScript execution failed: error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:L128
> db.auth("sa","sa")
1
> show collections
Thu May 23 18:27:22.307 JavaScript execution failed: error: {
"$err" : "not authorized for query on admin.system.namespaces",
"code" : 16550
} at src/mongo/shell/query.js:L128

I had the same problem, but I found this tutorial and it helped me.
http://www.hacksparrow.com/mongodb-add-users-and-authenticate.html
use:
db.addUser('sa', 'sa')
instead of
db.addUser({user:"sa",pwd:"sa",roles:["userAdminAnyDatabase"]})
{
"user" : "sa",
"pwd" : "75692b1d11c072c6c79332e248c4f699",
"roles" : [
"userAdminAnyDatabase"
],
"_id" : ObjectId("519deedff788eb914bc429b5")
}

As Robert says, admin users has only rights to admin, not to write in databases.
So you have to create a custom user for your database. There's different ways. I have choose the dbOwner way.
(I use Ubuntu Server, mongo 2.6.3 and Robomongo)
So to do this, fisrt create your admin user like mongo says :
type mongo in your linux shell
and these command in the mongo shell :
use admin
db.createUser({user:"mongoadmin",pwd:"chooseyouradminpassword",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
db.auth("mongoadmin","chooseyouradminpassword")
exit
edit the mongo conf file with :
nano /etc/mongod.conf
You can use vi if nano is not installed.
activate authentication by uncommented/adding these line auth=true
if you want to use Robomongo from other machine change the line bind_ip=127.0.0.1 by bind_ip=0.0.0.0 (maybe you should add more protection in production).
type in linux shell :
service mongod restart
mongo
And in mongo shell :
use admin
db.auth("mongoadmin","pwd:"chooseyouradminpassword")
use doomnewdatabase
db.createUser({user:"doom",pwd:"chooseyourdoompassword",customData:{desc:"Just me as I am"},roles : [{role:"dbOwner",db:"doomnewdatabase"}]})
db.auth("doom","chooseyourdoompassword")
show collections
(customData is not required).
If you want to try if it works, type this in the mongo shell :
db.products.insert( { item: "card", qty: 15 } )
show collections
db.products.find()
Good luck ! Hope it will help you and others !
I have search this informations for hours.

I had the same problem and this is how I solved it:
db = db.getSiblingDB('admin')
db.addUser(
{ user: "mongoadmin",
pwd: "adminpass",
roles: ['clusterAdmin', 'userAdminAnyDatabase', 'readAnyDatabase'] } )

For MongoDB version 2.6 use:
db.createUser(
{
user: "testUser"
pwd: "password",
roles: [{role: "readWrite", db:"yourdatabase"}]
})
See the docs

I solved it like so
for mongoDB 2.6 + currently 3
db.createUser(
{
user: "username",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
)
note that for the role filed instead of userAdminAnyDatabase we use root

I would try granting the read role to the user. userAdminAnyDatabase grants the ability to administer users.

Related

Linux User NameSpaces

I am experimenting with user namespaces using Go on Linux. The thing that I cannot figure out is that although am setting the uid and gid mappings when creating the namespace it still identifies as the nobody user when I launch the binary using sudo but when I launch it using the normal user everything works fine. For reference please see my code below
...
cmd := exec.Command("/bin/sh")
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUSER,
UidMappings: []syscall.SysProcIDMap{
{
ContainerID: 0,
HostID: 1000,
Size: 1,
},
},
GidMappings: []syscall.SysProcIDMap{
{
ContainerID: 0,
HostID: 1000,
Size: 1,
},
},
}
cmd.Run()
....
...
From the host I can confirm that indeed the user and group mappings were successful. The current pid is 87751
sudo cat /proc/87751/uid_map
0 1000 1
sudo cat /proc/87751/gid_map
0 1000 1
But when I run the binary after building
go build -o user_n
sudo ./user_n
sh-5.0$ whoami
nobody
sh-5.0$ id
uid=65534(nobody) gid=65534(nobody) groups=65534(nobody) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
But when I run the binary using the normal user it works as expected
./user_n
sh-5.0# whoami
root
sh-5.0# id
uid=0(root) gid=0(root) groups=0(root),65534(nobody) context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
While running the binary using the normal user is an option I would like to know why running using sudo does not give the expected results. Any pointers will be greatly appreciated.
More info
Fedora 31
Kernel 5.3.11-100.fc29.x86_64
go version go1.14.3 linux/amd64
In the first case, you are running as root user (through sudo) for which there is no mapping specified in the child user namespace. Hence, the resulting "nobody" id.
In the second case, you run the program as user id 1000 for which the mapping says : 1000 becomes root in the child user namespace. Hence, the resulting "root" id.

Login problems connecting with SQL Server in nodejs

I'm working in osx with SQL Server using a docker image to be able to use it, running:
docker run -d --name sqlserver -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=myStrongPass' -e 'MSSQL_PID=Developer' -p 1433:1433 microsoft/mssql-server-linux:2017-latest
I can connect successfully in Azure Data Studio GUI with the following configuration
But the connection does not works in my nodejs code using mssql module.
const poolConnection = new sql.ConnectionPool({
database: 'myDbTest',
server: 'localhost',
port: 1433,
password: '*******',
user: 'sa',
connectionTimeout: 5000,
options: {
encrypt: false,
},
});
const [error, connection] = await to(poolConnection.connect());
The error always is the same:
ConnectionError: Login failed for user 'sa'
Is my first time working with SQL Server and is confusing for me the fact that I can connect correctly in the Azure Studio GUI but I can't do it in code.
I'm trying create new login users with CREATE LOGIN and give them privileges based on other post here in stackoverflow but nothing seems to work.
UPDATE:
I realize that i can connect correctly if i put master in database key.
Example:
const poolConnection = new sql.ConnectionPool({
database: 'master', <- Update here
server: 'localhost',
port: 1433,
password: '*******',
user: 'sa',
connectionTimeout: 5000,
options: {
encrypt: false,
},
});
1) Db that i can connect
2) Db that i want to connect but i can't.
Container error
2020-03-18 03:59:14.11 Logon Login failed for user 'sa'. Reason: Failed to open the explicitly specified database 'DoctorHoyCRM'. [CLIENT: 172.17.0.1]
I suspect a lot of people miss the sa password complexity requirement:
The password should follow the SQL Server default password policy, otherwise the container can not setup SQL server and will stop working. By default, the password must be at least 8 characters long and contain characters from three of the following four sets: Uppercase letters, Lowercase letters, Base 10 digits, and Symbols. You can examine the error log by executing the docker logs command.
An example based on: Quickstart: Run SQL Server container images with Docker
docker pull mcr.microsoft.com/mssql/server:2017-latest
docker run -e "ACCEPT_EULA=Y" -e "SA_PASSWORD=myStr0ngP4ssw0rd" -e "MSSQL_PID=Developer" -p 1433:1433 --name sqlserver -d mcr.microsoft.com/mssql/server:2017-latest
docker start sqlserver
Checking that the docker image is running (it should not say "Exited" under STATUS)...
docker ps -a
# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
# af9f01eacab2 mcr.microsoft.com/mssql/server:2017-latest "/opt/mssql/bin/nonr…" 45 seconds ago Up 34 seconds 0.0.0.0:1433->1433/tcp sqlserver
Testing from within the docker container that SQL Server is installed and running...
docker exec -it sqlserver /opt/mssql-tools/bin/sqlcmd \
-S localhost -U "sa" -P "myStr0ngP4ssw0rd" \
-Q "select ##VERSION"
# --------------------------------------------------------------------
# Microsoft SQL Server 2017 (RTM-CU19) (KB4535007) - 14.0.3281.6 (X64)
# Jan 23 2020 21:00:04
# Copyright (C) 2017 Microsoft Corporation
# Developer Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)
Finally, testing from NodeJS...
const sql = require('mssql');
const config = {
user: 'sa',
password: 'myStr0ngP4ssw0rd',
server: 'localhost',
database: 'msdb',
};
sql.on('error', err => {
console.error('err: ', err);
});
sql.connect(config).then(pool => {
return pool.request()
.query('select ##VERSION')
}).then(result => {
console.dir(result)
}).catch(err => {
console.error('err: ', err);
});
$ node test.js
tedious deprecated The default value for `config.options.enableArithAbort` will change from `false` to `true` in the next major version of `tedious`. Set the value to `true` or `false` explicitly to silence this message. node_modules/mssql/lib/tedious/connection-pool.js:61:23
{
recordsets: [ [ [Object] ] ],
recordset: [
{
'': 'Microsoft SQL Server 2017 (RTM-CU19) (KB4535007) - 14.0.3281.6 (X64) \n' +
'\tJan 23 2020 21:00:04 \n' +
'\tCopyright (C) 2017 Microsoft Corporation\n' +
'\tDeveloper Edition (64-bit) on Linux (Ubuntu 16.04.6 LTS)'
}
],
output: {},
rowsAffected: [ 1 ]
}
Hope this helps.

mongod ERROR: child process failed, exited with error number 14

I got the following error when I tried to restart the db after the server (a linux VM) rebooted without shutting down the db first. I saw someone posted the same error over one and half years ago, but the solution proposed there didn't apply to my situation because it's not a yaml config issue (the db had been running for quite a while). I also included the log at the end. Thanks for any help.
sudo mongod --fork --logpath /nas/is1/bin/mongodb/data/db/mongodb.log --dbpath /nas/is1/bin/mongodb/data/db
about to fork child process, waiting until server is ready for connections.
forked process: 20085
ERROR: child process failed, exited with error number 14
output in the log file.
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] MongoDB starting : pid=20085 port=27017 dbpath=/data/mongodb/data/db 64-bit host=raboso
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] db version v3.2.1
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] git version: a14d55980c2cdc565d4704a7e3ad37e4e535c1b2
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] allocator: tcmalloc
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] modules: none
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] build environment:
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] distarch: x86_64
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] target_arch: x86_64
2017-01-19T15:33:45.286-0500 I CONTROL [initandlisten] options: { processManagement: { fork: true }, storage: { dbPath: "/data/mongodb/data/db" }, systemLog: { destination: "file", path: "/data/mongodb/data/db/mongodb.log" } }
2017-01-19T15:33:45.329-0500 I - [initandlisten] Detected data files in /data/mongodb/data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2017-01-19T15:33:45.346-0500 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=112G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-01-19T15:33:54.009-0500 E STORAGE [initandlisten] WiredTiger (-31802) [1484858034:9041][20085:0x7f0fcf72bcc0], file:sizeStorer.wt, WT_SESSION.open_cursor: sizeStorer.wt read error: failed to read 4096 bytes at offset 49152: WT_ERROR: non-specific WiredTiger error
2017-01-19T15:33:54.011-0500 I - [initandlisten] Invariant failure: ret resulted in status UnknownError -31802: WT_ERROR: non-specific WiredTiger error at src/mongo/db/storage/wiredtiger/wiredtiger_size_storer.cpp 67
2017-01-19T15:33:54.022-0500 I CONTROL [initandlisten]
0x12cf722 0x127ac14 0x1266dad 0x1058db2 0x10425ea 0x103f540 0xf679a8 0x93bc91 0x9403b9 0x7f0fce33bb35 0x939829
----- BEGIN BACKTRACE -----
{"backtrace":[{"b":"400000","o":"ECF722"},{"b":"400000","o":"E7AC14"},{"b":"400000",
"o":"E66DAD"},{"b":"400000","o":"C58DB2"},{"b":"400000","o":"C425EA"},{"b":"400000",
"o":"C3F540"},{"b":"400000","o":"B679A8"},{"b":"400000","o":"53BC91"},{"b":"400000",
"o":"5403B9"},{"b":"7F0FCE31A000","o":"21B35"},{"b":"400000","o":"539829"}],
"processInfo":{ "mongodbVersion" : "3.2.1", "gitVersion" : "a14d55980c2cdc565d4704a7e3ad37e4e535c1b2",
"compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "3.10.0-514.2.2.el7.x86_64",
"version" : "#1 SMP Wed Nov 16 13:15:13 EST 2016", "machine" : "x86_64" },
"somap" : [ { "elfType" : 2, "b" : "400000" }, { "b" : "7FFEF9CD5000", "elfType" : 3 },
{ "b" : "7F0FCF31B000", "path" : "/lib64/librt.so.1", "elfType" : 3 }, { "b" : "7F0FCF117000",
"path" : "/lib64/libdl.so.2", "elfType" : 3 }, { "b" : "7F0FCEE0F000", "path" : "/lib64/libstdc++.so.6",
"elfType" : 3 }, { "b" : "7F0FCEB0D000", "path" : "/lib64/libm.so.6", "elfType" : 3 },
{ "b" : "7F0FCE8F7000", "path" : "/lib64/libgcc_s.so.1", "elfType" : 3 }, { "b" : "7F0FCE6DB000",
"path" : "/lib64/libpthread.so.0", "elfType" : 3 }, { "b" : "7F0FCE31A000", "path" : "/lib64/libc.so.6",
"elfType" : 3 }, { "b" : "7F0FCF523000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3 } ] }}
mongod(_ZN5mongo15printStackTraceERSo+0x32) [0x12cf722]
mongod(_ZN5mongo10logContextEPKc+0x134) [0x127ac14]
mongod(_ZN5mongo17invariantOKFailedEPKcRKNS_6StatusES1_j+0xAD) [0x1266dad]
mongod(_ZN5mongo20WiredTigerSizeStorerC1EP15__wt_connectionRKSs+0x222) [0x1058db2]
mongod(_ZN5mongo18WiredTigerKVEngineC2ERKSsS2_S2_mbbb+0x6DA) [0x10425ea]
mongod(+0xC3F540) [0x103f540]
mongod(_ZN5mongo20ServiceContextMongoD29initializeGlobalStorageEngineEv+0x588) [0xf679a8]
mongod(_ZN5mongo13initAndListenEi+0x321) [0x93bc91]
mongod(main+0x149) [0x9403b9]
libc.so.6(__libc_start_main+0xF5) [0x7f0fce33bb35]
mongod(+0x539829) [0x939829]
----- END BACKTRACE -----
2017-01-19T15:33:54.022-0500 I - [initandlisten]
***aborting after invariant() failure
If a system running MongoDB with the WiredTiger storage engine crashes or experiences an unclean shutdown, MongoDB may not be able to recover data files on restart if the crash/shutdown interrupted a WiredTiger checkpoint.
MongoDB cannot automatically recover data files on restart.
Sadly there is no workaround. Either you can restore data from backups or resync from another replica set member.
WiredTiger (-31802) [1484858034:9041][20085:0x7f0fcf72bcc0], file:sizeStorer.wt, WT_SESSION.open_cursor: sizeStorer.wt read error: failed to read 4096 bytes at offset 49152: WT_ERROR: non-specific WiredTiger error
Above error suggets that your database has been corrupted. Repair it by:
mongod --repair --dbpath /path/to/data/db

Could not connect to mongod from mongo shell when auth enabled (on ubuntu)

System: ubuntu 14.04
mongodb 3.0.3 tar ball is downloaded from mongodb download center
connected to mongodb without auth, then from mongo shell, created a user for 'test' db. following is the command.
db.createUser({user: "user1",
pwd: "test123",
roles: [ { role: "readWrite", db: "test" }
]})
Verified that user details in admin db. Following is the command & result:
> db.system.users.findOne({user:'user1'})
{
"_id" : "testdb.user1",
"user" : "user1",
"db" : "testdb",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "kNfOd1vs+QT+ueH7SI6Vzw==",
"storedKey" : "JCesIKSW1pb74ddo2Y19rEO1GVY=",
"serverKey" : "d87Sb1htoD5K8zecAy73JPZyHdc="
}
},
"roles" : [
{
"role" : "readWrite",
"db" : "test"
}
]
}
Now exit from the mongo shell, killed the mongod.
Started the mongodb with auth, following is the command.
$ ./mongod --auth
Connected to mongo shell as usual, see the below:
$ ./mongo
MongoDB shell version: 3.0.3
connecting to: test
> show collections
2016-05-11T22:33:46.302+0530 E QUERY Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on test to execute command { listCollections: 1.0 }",
"code" : 13
}
at Error (<anonymous>)
at DB._getCollectionInfosCommand (src/mongo/shell/db.js:646:15)
at DB.getCollectionInfos (src/mongo/shell/db.js:658:20)
at DB.getCollectionNames (src/mongo/shell/db.js:669:17)
at shellHelper.show (src/mongo/shell/utils.js:625:12)
at shellHelper (src/mongo/shell/utils.js:524:36)
at (shellhelp2):1:1 at src/mongo/shell/db.js:646
> db.auth({user:'user1', pwd:'test123'})
1
> use test
switched to db test
> db.collone.insert({name:'firstcollection'})
WriteResult({ "nInserted" : 1 })
> show collections
collone
system.indexes
> db.collone.find()
{ "_id" : ObjectId("5733669fb7d44cd444ebf028"), "name" : "firstcollection" }
> exit
bye
When i tried to do the authentication while starting the mongo shell, getting authentication failed error. See below:
$ ./mongo test -u 'user1' -p 'test123' --authenticationDatabase 'admin'
MongoDB shell version: 3.0.3
connecting to: test
2016-05-11T22:37:21.559+0530 E QUERY Error: 18 Authentication failed.
at DB._authOrThrow (src/mongo/shell/db.js:1266:32)
at (auth):6:8
at (auth):7:2 at src/mongo/shell/db.js:1266
exception: login failed
All this is just a POC that i'm trying to do.
Once it's success, my target is to connect from mongoose client(from Node.js app) to mongod.
The following command from a stackoverflow post can help me to set up connection from mongoose to mongod with auth.

How to use wait-for-sync properly

For experiments with single node configuration I run ArangoDB with the command:
arangod --server.endpoint=tcp://0.0.0.0:8529 --server.disable-authentication=true --database.wait-for-sync=true
Then I do a few commands:
db._createDatabase("foo")
db._useDatabase("foo")
db._create("a")
db.a.properties()
Get the result:
{
"doCompact" : true,
"journalSize" : 33554432,
"isSystem" : false,
"isVolatile" : false,
"waitForSync" : false,
"keyOptions" : {
"type" : "traditional",
"allowUserKeys" : true
},
"indexBuckets" : 8
}
And where is my "waitForSync": true by default? Where do I do a mistake?
I can confirm your problem using ArangoDB 2.8.7 and the arangosh. This is a bug. If the same is done on the console (with --console), then it works.
From arangosh the request goes via the HTTP API and there the default of "false" for "waitForSync" is added, the command line option is ignored, which is the bug. I will make sure that this will be fixed in the next release of ArangoDB.
In the meantime, please add "waitForSync": true in all db._create calls in arangosh and all POST /_api/collection API calls via HTTP.

Resources