MongoDB replicaset TLS/SSL - mongodb

I have launched a MongoDB 4 replica-set on 3 servers by private IP successfully. Now I wanna bind another IP and it needs enabling TLS/SSL.
I have created PEMKeyFile and CAFile and copied these file s on all 3 servers and added the codes below to mongod.config file of all 3 servers.
# network interfaces
net:
port: 27017
bindIp: 10.10.20.21,5.22.25.45 # example private ip and one example valid IP
ssl:
mode: requireSSL
PEMKeyFile: /opt/mongo/mongo.pem
PEMKeyPassword: MyPassword
CAFile : /opt/mongo/CA.pem
allowInvalidCertificates: true
allowInvalidHostnames: true
security:
keyFile: /opt/mongo/mongo-keyfile
I got error
E STORAGE [initandlisten] Failed to set up listener: SocketException: Cannot assign requested address
I CONTROL [initandlisten] now exiting
I CONTROL [initandlisten] shutting down with code:48
What is wrong with it? How can I fix it?

should I see both of these IPs
yes, of course.
bindIp tells mongodb service which system network interfaces to listen on. These are local system interfaces, not the clients. As soon as mongobd bind to an interface, clients from anywhere can connect to this IP:
binding to 10.10.20.XXX : the private class A network interface allows clients to connect from any 10.XXX.XXX.XXX IP within the same network
binding to 5.22.25.XXX : the public network interface allows clients to connect from anywhere in the internet.
If you want to restrict access to mongodb and allow to connect from specific IPs/networks only, you need to enable authentication and apply the restriction to the user or a group: https://docs.mongodb.com/manual/reference/method/db.createUser/#authentication-restrictions.
E.g.
use admin
db.createUser(
{
user: "remote-client",
pwd: "password",
roles: [ { role: "readWrite", db: "reporting" } ],
authenticationRestrictions: [ {
clientSource: ["5.22.25.45"]
} ]
}
)
Will allow mongo -u remote-client -p password to connect from IP 5.22.25.45 only and permit reads and writes to/from "reporting" database.

Related

Troubleshooting Mongoose Error - MongoNetworkError: failed to connect to server [localhost:27017] [duplicate]

I have just started learning about MongoDB and I am trying to host my node js application locally via MongoDB Server 6.0 (without using mongoose or atlas)
I copied the async javascript code given in the MongoDB docs. I made sure to run mongod before executing the below code
MongoDB server started
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"**mongodb://localhost:27017**";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
It's throwing an error:
image of the error it's throwing
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true

how to correct the mongodb error i get here [duplicate]

I have just started learning about MongoDB and I am trying to host my node js application locally via MongoDB Server 6.0 (without using mongoose or atlas)
I copied the async javascript code given in the MongoDB docs. I made sure to run mongod before executing the below code
MongoDB server started
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"**mongodb://localhost:27017**";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
It's throwing an error:
image of the error it's throwing
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true

Mongodb Compass: Connection timed out

I installed Mongodb on my remote server using this documentation. I have Ubuntu 16.04 on my remote server. Mongodb got installed successfully. I added the user like this:
use admin
db.createUser(
{
user: 'myuser',
pwd: 'password',
roles: [ { role: 'readWrite', db: 'mydb' } ]
}
);
I also made changes in the mongod.conf like this:
net:
port: 27017
bindIp: 127.0.0.1,<server_ip>
security:
authorization: 'enabled'
Now when I try to connect to mongodb using conneciton string like this:
mongodb://myuser:password#server_ip:27017/mydb
It gives me the following error:
connection timed out
What am I doing wrong here? I am using Laravel Forge to manage sever.
As it turned out the port was not open and that was the only issue. Opened the port and now its working fine.

MongoDB SSL Replica setup issues - Unsupported Certificate

Trying to set up a 3 node mongodb server replica on Ubuntu 18.04, mongo version 4.0.18
gl1 192.168.1.30
gl2 192.168.1.31
gl3 192.168.1.33
Using an internal CA on the same network to create certs, I have created 2 certs, one for the server mongo is installed on (GL1, GL2, GL3) for PEMKeyFile and one for the clusterFile (mongo1, mongo2, mongo3). Each CAFile is set listing the respective RSA key, PEMKeyFile and RootCA for each server. I have mongo services running (according to systemctl) fine using the individual certs (PEMKey and clusterFILE).
net:
port: 27017
bindIp: 0.0.0.0
net:
ssl:
mode: requireSSL
PEMKeyFile: /opt/ssl/MongoDB.pem
CAFile: /opt/ssl/ca.pem
clusterFile: /opt/ssl/mongo.pem
allowConnectionsWithoutCertificates: true
#replication
replication:
replSetName: rs0
Getting the following error when I try to rs.add("192.168.1.31:27017") I get the following error
"errmsg" : "Quorum check failed because not enough voting nodes responded; required 2 but only the following 1 voting nodes responded: 192.168.1.30:27017; the following nodes did not respond affirmatively: gl2.domain.com:27017 failed with stream truncated",
"code" : 74,
"codeName" : "NodeNotFound",
In the mongod.log on node 192.168.1.31 the following is logged:
2020-05-22T18:20:48.161+0000 E NETWORK [conn4] SSL peer certificate validation failed: unsupported certificate purpose
2020-05-22T18:20:48.161+0000 I NETWORK [conn4] Error receiving request from client: SSLHandshakeFailed: SSL peer certificate validation failed: unsupported certificate purpose. Ending connection from 192.168.1.30:55002 (connection id: 4)
I have read on an old Google groups post: https://groups.google.com/forum/#!msg/mongodb-user/EmESxx5KK9Q/xH6Ul7fTBQAJ that the clusterFile and PEMKeyFile had to be different. However, I did that and it still is throwing errors. I have done a lot of searching on this and I'm seeing much to support that this how it's done, but it is the only place I've found that has a similar error message and it seems logical that it should work. However, I'm not sure how I can verify that my clusterFile is actually being used. It is indeed a separate certificate with a FQDN for each node. All three nodes have host files updated to find each other (gl1, mongo1, etc). I can ping all nodes between themselves, so networking is up. I've also verified the firewall (ufw and iptables) is not blocking 27017 or anything at this point. Previously I tried the self-signed CA and certs but kept running into errors since those were self signed certs, so that is why I went the internal CA route.
The "purpose" is also known as "extended key usage".
Openssl x509v3 Extended Key Usage gives some example code for setting the purposes.
As pointed out by Joe, the documentation states that the certificates must either have no extended key usage at all, or the one in the PEMKeyFile must have server auth, and the one in the cluster file must have client auth.

consul - connect client to server

I'm new at consul and I try to setup a server-client environment. I have started my server with the following command and configuration:
consul.exe agent -ui -config-dir=P:\Consule\config
The config file looks the following ("P:\Consule\config\server.json")
{
"bootstrap": false,
"server": true,
"datacenter": "MyServices",
"data_dir": "P:\\Consule\\data",
"log_level": "INFO"
}
Output when I start consul from commandline with above command:
==> Starting Consul agent...
==> Consul agent running!
Version: 'v0.8.3'
Node ID: '1a244456-e725-44be-0549-33603ea7087d'
Node name: 'MYCOMPUTERNAMEA'
Datacenter: 'myservices'
Server: true (bootstrap: false)
Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
Gossip encrypt: false, RPC-TLS: false, TLS-Incoming: false
Atlas: <disabled>
Now, at another computer in my domain I try to run an consul client with follwoing commandline and config-file:
consul.exe agent -config-dir C:\Consul -bind=127.0.0.1
Config file ("C:\Consul\client.json")
{
"server": false,
"datacenter": "MyServices",
"data_dir": "C:\\TEMP",
"log_level": "INFO",
"start_join": ["MYCOMPUTERNAMEA"]
}
But I always get follwing output/error message:
==> Starting Consul agent...
==> Joining cluster...
==> 1 error(s) occurred:
* Failed to join <IP_OF_MYCOMPUTERNAMEA>: dial tcp <IP_OF_MYCOMPUTERNAMEA>:8301: connectex: No connection could be made because the target machine actively refused it.
Does anyone know what I'm doing wrong?
Thanks and best regards
I suppose, the reason is that your server is available only for 127.0.0.1 ip-address, which is localhost ip and available only from the same server. This can be seen here:
Client Addr: 127.0.0.1 (HTTP: 8500, HTTPS: -1, DNS: 8600)
Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
You have to configure your server, to make it listening all network interfaces or some specific interface, which have to be available from other server.
Try to run it with the client and advertise options set to 0.0.0.0 (or some specific ip). Read about it here and here.
And you might have to delete -bind=127.0.0.1 from the client configuration, since it might be available from the server too.