C# says invalid certificate error on Linux Centos - mongodb

We are using C# driver "Mongo Db driver 2.9.2" in C# API(.NET core version 2.2) deployed in Linux CentOS to connect to Mongo server 4.2 deployed on Linux CentOS. TLS is enabled on Mongo and self signed certificates are used. Same code and certificates are working from Windows machine but on Linux we are getting following error. Please suggest:
A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : \"1\", ConnectionMode : \"Automatic\", Type : \"Unknown\", State : \"Disconnected\", Servers : [{ ServerId: \"{ ClusterId : 1, EndPoint : \"Unspecified/ServerName\" }\", EndPoint: \"Unspecified/ip-ServerName\", State: \"Disconnected\", Type: \"Unknown\", HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.\n at System.Net.Security.SslState.StartSendAuthResetSignal

We could resolve this by using server certificate instead of wild card certificate.

Related

Cannot connect to Atlas MongoDB from Azure Functions

I just created an Azure Function that should connect to my instance of MongoDB on Atlas, basically following this tutorial:
https://www.mongodb.com/blog/post/how-to-integrate-azure-functions-with-mongodb
From my local development with Visual Studio, everything works fine and I can connect to the Atlas environment, but when I deploy the code on Azure, the following exception raises:
A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017" }", EndPoint: "Unspecified/ltdevcluster-shard-00-00.qkeby.mongodb.net:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server.
---> MongoDB.Driver.MongoConnectionException: An exception occurred while receiving a message from the server.
---> System.IO.EndOfStreamException: Attempted to read past the end of the stream.
If I instead set the Network Access to "everywhere", again everything works fine.
Now, in the Network Access panel of Atlas, I added the IPs retrieved from the Azure Portal under my function app => Networking => Inbound traffic and Outbound traffic (a total of 1 IP for inbound and 3 IPs for outbound).
But adding those 4 IPs has not solved the issue.
What else should I do?
If you are using static IP, for a workaround, you can check this: How do I set a static IP in Functions?
You can also set up a Private Endpoint and for the security of the database credentials check secrets engine integration using vault.
You can refer to How to connect Azure Function with MongoDB Atlas ,Azure functions unable to connect with Mongo Db Atlas M10 and How to connect Azure Function with MongoDB Atlas

Mongodb connectionString can't connect

I can connect via Mongodb COMPASS using my username and password but apparently i can't connect it to my website.
mongodb://localhost:27017/mydb works fine in connection string but not atlas/online cluster
{"connectionString":"mongodb+srv://myuser:mypass#thiscluster.azure.mongodb.net/mydb?retryWrites=true&w=majority"
,"secret":""}
Error :
Server listening on port 3000
Unhandled rejection MongoError: not authorized on admin to execute command { lis
tIndexes: "sessions", cursor: { } }
at Function.MongoError.create (C:\Users\user\Documents\GitHub\meanie\serv
er\node_modules\mongodb-core\lib\error.js:31:11)
at queryCallback (C:\Users\user\Documents\GitHub\meanie\server\node_modul
es\mongodb-core\lib\cursor.js:212:36)
at C:\Users\user\Documents\GitHub\meanie\server\node_modules\mongodb-core
\lib\connection\pool.js:469:18
at processTicksAndRejections (internal/process/task_queues.js:79:11)
I am using MEANIE STACK BLOG
Reference : Cloud mongodb guide
mongodb+srv://:#thiscluster.azure.mongodb.net/?retryWrites=true&w=majority
Other reference : https://docs.mongodb.com/manual/reference/connection-string/
SOLVED
config.json / node's "connectionString" can't be parsed using mongo+srv://user:pw#thiscluster.mongodb.com/mydb?thisoptions
node version i'm using is 2.2 12
fixed via :
"connectionString":"mongodb://user:pass#test-shard-00-00-sample.azure.mongodb.net:27017,test-shard-00-01-sample.azure.mongodb.net:27017,test-shard-00-02-sample.azure.mongodb.net:27017/THISDB?ssl=true&replicaSet=Test-shard-0&authSource=admin&retryWrites=true&w=majority",

Cosmos DB failover with MongoDB.Driver library

I have an application which is using the MongoDB.Driver library (2.7.3) to connect to CosmosDB on Azure. The Cosmos account is set to replicate to a secondary in another region for disaster recovery. An issue I'm running into is that when we failover the Cosmos account, we lose connectivity and get the following error when we write data:
A timeout occured after 30000ms selecting a server using
CompositeServerSelector{ Selectors =
MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector,
LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000
} }. Client view of cluster state is { ClusterId : "1", ConnectionMode
: "Automatic", Type : "ReplicaSet", State : "Connected", Servers : [{
ServerId: "{ ClusterId : 1, EndPoint :
"Unspecified/myCosmosAccount.documents.azure.com:10255" }",
EndPoint: "Unspecified/myCosmosAccount.documents.azure.com:10255",
State: "Connected", Type: "ReplicaSetOther", Tags: "{ region : North
Europe }", WireVersionRange: "[0, 2]" }] }
I know it's possible to specify multiple servers in the MongoDB Connection String, however I'm not clear on how this can be achieved with Cosmos DB which only has a single endpoint for the account. My current connection string is this:
mongodb://myCosmosAccount:Key#myCosmosAccount.documents.azure.com:10255/myCosmosDatabase?ssl=true
Is this possible to do using this library, or do I need to switch to using the Cosmos DB SDK to improve Disaster Recovery?
I found a solution to this here: https://social.msdn.microsoft.com/Forums/azure/en-US/8cdf09af-ff75-4c9b-8eb4-179464e04018/azure-cosmos-db-breaks-during-manual-failover?forum=azurecosmosdb
I needed to add: replicaSet=globaldb to the end of my connection string, so it now looks like this:
mongodb://myCosmosAccount:Key#myCosmosAccount.documents.azure.com:10255/myCosmosDatabase?ssl=true&replicaSet=globaldb

Unable to connect to MongoDb using MongoClientSettings as parameter to MongoClient

I am developing a C# MVC Web API which uses MongoDb as backend.I tried connecting to my mongodb database using
MongoClient mongoClient = new MongoClient(connectionString)
where connectionstring is in format : mongodb://Username:Password#hostname.eastus.cloudapp.azure.com
Mongo db is hosted in a virtual machine in Azure.I am able to connect to the database and all works good.But I am getting frequent exceptions:
"MongoDb.driver.MongoConnectionException".An exception occurred while
receivinf a message from server--->System.IO.IOException:Unable to
read data from the transport connection : A connection attempt failed
because the connected party did not properly respond after a period of
time,......"
So after a bit of research I have learnt that Azure is killing idle connections and I have to set MaxConnectionIdleTime.
In order to set MaxConnectionIdleTime I decided to connect to Mongodb in the below way
var credential = MongoCredential.CreateCredential("dbname", "UserName", "Password");
var settings = new MongoClientSettings
{
Credentials = new[] { credential },
Server = new MongoServerAddress("HostName", 27017),
MaxConnectionIdleTime = new TimeSpan(0, 3, 0)
};
MongoClient mongoClient = new MongoClient(settings);
In this case I am using the same username,password combination given in the connection string which I used to connect before.
While trying to connect here I am getting inner Exception:
MongoDB.Driver.MongoAuthenticationException: "Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1".
"MongoDb.driver.MongoConnectionException".An exception occurred while receivinf a message from server--->System.IO.IOException:Unable to read data from the transport connection : A connection attempt failed because the connected party did not properly respond after a period of time,....
The reason behind this exception is when hosted in Azure,Azure tries to kill the idle connections but the C# driver is not aware of this.The driver tries to execute queries on the killed connections without knowing the connection is not existing.
The solution that worked out for me is to set maxIdleTimeMS=45000 in connection string.
This way driver will not use a connection which has been idle for long time.
Here is the connection string that worked out for me
connectionString="Username:Password#hostname.eastus.cloudapp.azure.com/?connectTimeoutMS=30000&socketTimeoutMS=30000&waitQueueTimeoutMS=30000&maxIdleTimeMS=45000"
I have had a similar error with my Azure hosted MongoDb (Cosmos Db). It turned out to be network settings such that I had blocked all access. Changing it to Allow access from "All networks" fixed the issue.
The error is very misleading, I would have expected a connection timeout.
A timeout occured after 30000ms selecting a server using
CompositeServerSelector{ Selectors =
MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector,
LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000
} }. Client view of cluster state is { ClusterId : "1", ConnectionMode
: "ReplicaSet", Type : "ReplicaSet", State : "Disconnected", Servers :
[{ ServerId: "{ ClusterId : 1, EndPoint :
"Unspecified/XXXX.documents.azure.com:10255" }", EndPoint:
"Unspecified/XXXX.documents.azure.com:10255", State: "Disconnected",
Type: "Unknown", HeartbeatException:
"MongoDB.Driver.MongoConnectionException: An exception occurred while
opening a connection to the server. --->
MongoDB.Driver.MongoAuthenticationException: Unable to authenticate
using sasl protocol mechanism SCRAM-SHA-1. --->
MongoDB.Driver.MongoCommandException: Command saslContinue failed: Not
Authenticated.
To troubleshot I tried from MongoDb Compass as well and that didn't work either, showing me it wasn't the code.

MongoDB db.serverStatus() gives error when running using tunnel that is targeted to api.cloudfoundry.com

Following is the console session...
C:\Users\xxx>vmc tunnel myMongoDB
Getting tunnel connection info: OK
Service connection info:
username : uuuu
password : pppp
name : db
url : mongodb://uuuu:pppp#172.30.xx.xx:25200/db
Starting tunnel to myMongoDB on port 10000.
1: none
2: mongo
3: mongodump
4: mongorestore
Which client would you like to start?: 2
Launching 'mongo --host localhost --port 10000 -u uuuu -p pppp db'
MongoDB shell version: 2.0.6
connecting to: localhost:10000/db
> db.serverStatus()
{ "errmsg" : "need to login", "ok" : 0 }
>
Which credentials should I use to login (assuming should use db.auth) to get rid of the error "{ "errmsg" : "need to login", "ok" : 0 }".
When I run the same in micro CF on my machine it works ok and gives me the expected output.
P.S. I'm trying this to get to know the current connections on my application, written in node.js. Trying to debug some issues with connections to the DB. If there is any other alternative that I can use please suggest that as well.
this should work! Not sure why your tunnel isn't connecting, my immediate suggestion is to try another instance of MongoDB and see if the same error occurs.
If you are trying to inspect the bound services on you node.js app you should be able to inspect them in the VCAP_SERVICES environment variable. For example;
var http = require('http');
var util = require('util');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(util.inspect(process.env.VCAP_SERVICES));
res.write("\n\n************\n\n");
res.end(util.inspect(req.headers));
}).listen(3000);
This code is currently running at http://node-headers.cloudfoundry.com/ to serve as an example. However, mongodb connections for node.js applications should automatically configure to the bound service. If this does not work for you, then please do let me know.