How to connect via mongoose and a ssh tunnel - node.js

I have setup my mongod.conf as follows so it only allows localhost connection.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
net:
port: 27017
bindIp: 127.0.0.1
I then want my site to ssh into the mongodb so the port has to be converted to localhost.
However how can I integrate this with mongoose's connect function?
mongoose.connect(configDB.url, function(err){
if (err){
console.log('Error connecting to mongodb: ' + err)
}
});
I have found the following command but I am not sure if this is what I need:
ssh -L 4321:localhost:27017 -i ~/.ssh/ssh_key user#ip-adress
This should ssh me via port 4321 to the localhost right? So I think I need something like this in the nodejs mongoose's connect function. I've tried to read up on this on the mongodb security tutorials but I cannot link their instructions to nodejs at all. Anyone who has experience with this?

You're nearly there. Set up the tunnel independent of node:
ssh -Nf -p [db_server_ssh_port] [mongo_user]#[mongo_domain] -L \
[local_db_port]:localhost:[remote_db_port]
And then within node, connect to mongo using [local_db_port]:
mongoose.connect(
"mongodb://localhost:[local_db_port]/[db_name]",
{"pass":"[db_pwd]"}
)
All the traffic sent to [local_db_port] on the web server will be sent through the tunnel to port [remote_db_port] on [mongo_domain]. The following post gives more info. It's connecting to a MySQL database, but the principle is the same.
Connect to MySQL using SSH Tunneling in node-mysql

Set up the tunnel independent of node:
ssh -L [your given port]:localhost:27017 [username of ssh]#[ip address of ssh matchine] -f -N
after that you have include your given port for mongo database.
In the nodejs you have to setup for mongoose connection like this
'mongodb://localhost:[your given port number]/[database name]'
enjoy it

Related

SSH tunnle to mongodb using mongodb connection string

Thought it should be straight forward but I have a very hard time figuring out the following:
I got mongodb connection string: mongodb://user:password#123.123.123.111:27017/?authSource=admin
I want to be able to connect to mongo from localhost at port 1234 by doing: mongo localhost:1234
The solution is to create a tunnel, but nothing I do works for me.
I tried the following command:
ssh -L 1234:localhost:27017 user:password#123.123.123.111 -p 27017
Please help me understand what I am doing wrong.
You need to have a unix user on 123.123.123.111
ssh -L 1234:localhost:27017 UNIXuser#123.123.123.111
Then your local mongodb connection string is : mongodb://user:password#localhost:1234/?authSource=admin
MongoDB and ssh use different protocols, so you can't use ssh to connect directly to a mongod process.
If you want to use an ssh tunnel you will first need to have an account on the destination machine, and use that account's credentials with ssh to connect to port 22 (assuming default port). The mongod username/password will probably not be valid for ssh.
Once the tunnel is established, you would connect to the local port using a driver or mongo shell using the connection string:
mongodb://user:password#127.0.0.1:1234/?authSource=admin

connection refused connecting to remote mongodb server

So we've accumulated enough applications in our network that use MongoDB to justify building a dedicated server specifically for MongoDB. Unfortunately, I'm pretty new to mongodb (coming from SQL/MySQL derivatives). I have followed several guides on installing and configuring mongodb for my environment. None are perfect, but I think I'm close... I've have managed to get to a point that I can connect to the db server from the local server using the following command:
mongo -u user 127.0.0.1/admin
However, I'm NOT able to connect to the server using this from either the local OR a remote computer using it's network address, IE:
mongo -u user 192.168.24.102/admin
I've tried both with authentication enabled and disabled, and I've tried setting the bindIP to 192.168.24.102 and 0.0.0.0 with no love. Thinking it was a Firewall issue, I disabled the firewall entirely... same. no love...
so what's the secret sauce? how do I connect to a MongoDB server remotely?
Some notes to know: This server is on a local network only. There will be some NAT shenanigans at some point directing public traffic to it from remote application servers, but only specific ports (we will NOT be using 27017 when that happens) and it will sit behind a pretty robust firewall appliance, so I'm not worried about securing the server as I about securing MongoDB itself.
This answer assume a setup where a Linux server is completely remote and has MongoDB already installed.
Steps:
1. Connect to your remote server over SSH.
ssh <userName>#<server-IP-address>
2. Start Mongo shell and add users to MongoDB.
Add the admin;
use admin
db.createUser(
{
user: "AdminSammy",
pwd: "AdminSammy'sSecurePassword",
roles: [
{"userAdminAnyDatabase",
"dbAdminAnyDatabase",
"readWriteAnyDatabase"}
]
}
)
Then add general user/users. Users are added to specific databases.
use some_db
db.createUser({
user: 'userName',
pwd: 'secretPassword',
roles: [{ role: 'readWrite', db:'some_db'}]
})
3. Edit your MongoDB config file, mongod.conf, that is found in etc directory.
sudo vim /etc/mongod.conf
Scroll down to the #security: section and add the following line. Make sure to un-comment the security: line.
security:
authorization: 'enabled'
After authorization has been enabled only those authenticated with password will access the database. In this case these are the ones added in step 2 above.
Note: Visual Studio code can also be used over SSH to edit the mongo.conf file.
4. Add remote server's IP address to mongod.conf file.
Look for the net line and add the IP address of the server that is hosting this MongoDB installation, example 178.45.55.88
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1, 178.45.55.88
5. Open port 27017 on your server instance.
This allows access to your MongoDB server from anywhere in the world to anyone who knows your remote server IP address. This is one reason to have authenticated users. More robust ways of handling security are really important! Consult MongoDB manual for that.
Check firewall status using ufw.
sudo ufw status
If its not active, activate it.
sudo ufw enable
Then,
sudo ufw allow 27017
Important: You also need to allow port 22 for your SSH communication with your remote server. Otherwise you will be locked out from your remote server. Assumption here is that SSH uses port 22 for communication, the default.
sudo ufw allow 22
6. Restart Mongo daemon (mongod)
sudo systemctl restart mongod
7. Connect to remote Mongo server using Mongo shell
You can now connect to the remote MongoDB server using the following command.
mongo -u <user-name> -p <user-password> <remote-server-IP-address>:<mongo-server-port>
You can also connect to the remote MongoDB server with authentication:
mongo -u <user-name> -p <user-password> <remote-server-IP-address>:<mongo-server-port> --authenticationDatabase <auth-db-name>
You can also connect to a specific remote MongoDB database with authentication:
mongo -u <user-name> -p <user-password> <remote-server-IP-address>:<mongo-server-port>/<db-name> --authenticationDatabase <auth-db-name>
At this moment you can read and write within the some_db database from your local computer without ssh.
Important: Put into consideration the standard security measures for any database. Local security practices should guide what to do at any of the above steps.

how to connect same mongodb (in compass using hostname: localhost and port : 27017) local in 2 different PC's [duplicate]

I follow this mongoose document enter link description here
mongoose.connect('mongodb://localhost/waterDB');
Using This, I can connect local machine waterDBmongoDB DataBase
My Personal Machine Local IP : 192.168.1.5
My Server Machine Local IP : 192.168.1.100
Both machine have waterDB DataBase . There is no username and password for both DB
I wanted to connect Server Machine waterDB Inside My Personal Machine.
According To This : mongoose.connect('mongodb://username:password#host:port/database?options...');
I try : mongoose.connect('mongodb://192.168.1.100:27017/waterDB');
But,
MongoError: failed to connect to server [192.168.1.100:27017] on first connect
at null.<anonymous> (/home/water/node_modules/mongodb-core/lib/topologies/server.js:313:35)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
..........
Any solution for err ?
Thank (#_#)
It might be a problem with your MongoDB instance listening on localhost only.
You can change the bind address in MongoDB's configuration file. The config file may be located in /etc/mongodb.conf or /etc/mongod.conf. There are also 2 config file formats:
Old format (still supported):
bind_ip = 0.0.0.0
YAML (version 2.6+):
net:
bindIp: 0.0.0.0
After changing the config file you have to restart the MongoDB server.
Try without the Port no.
mongoose.connect('mongodb://192.168.1.100/waterDB');
this should work for you.
But make sure both are connected on the same network, if you are connected on other network than your server is, then it wont work
You will have to use SSH tunnel in this case. Refer to the following link which shows how you can create SSH tunnel.
Node.js SSH Tunneling to MongoDB using Mongoose
For me (using windows and mongo version 6, and remotely connecting from Mac), after changing config file to
net:
port: 27017
bindIp: "*" # OR 0.0.0.0
Then starting server with: mongod, it was still binding to 127.0.0.1 (localhost). I had to start the server with: mongod --bind_ip_all

Can't connect Node.js to Mongodb

I'm newbie about node.js and MongoDB.
I have installed MongoDB on a server A. MongoDB is running and port 27017 is opened. I am able to connect to robo3T
I have a Node.js app on another server B. Node.js is running.
When I access the website, everything is displayed correctly but when I want to login (so it needs MongoDB access), the website turns and get this error: Cannot GET /502.shtml
Here are all details
Mongodb server
mongod.conf :
port: 27017
bindIp: 0.0.0.0
Nodejs app.js:
var promise = mongoose.connect('mongodb://XXXX:27017/preprod', {useMongoClient: true}, function(err) {
if (err) return console.error(err);});
mongoose.Promise = require('bluebird');
XXXX = address IP of server A (mongodb server)
when I run app.js I got this error
name: 'MongoError',
message: 'failed to connect to server [XXX:27017] on first connect [MongoError: connect ETIMEDOUT XXXX:27017]' }
I am able to connect from my linux machine, other VPS server but not to my nodejs server!
Maybe I missed something?
Do this on a Linux machine,
iptables -A INPUT -s 0.0.0.0 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 0.0.0.0 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
and try connecting from the remote server (Server B) with the IP address of Server A.
Resolved:
Actually the port 27017 was closed on my nodejs server.
now it can connected!
if it can help someone else
mongoose.connect(mongodb://localhost:27017/<project_name>, {
useMongoClient: true
});
Where is the name of the project.
Make sure you've installed and imported mongoose. And also, that you've got mongod running.
Also, I'd remove 'var promise = ' before mongoose.connect(..)

Sequelize connection over ssh

I am not able to connect to a remote mysql server using sequelize but I am able to ssh into the machine and connect to mysql.
How do I make Sequelize connect to mysql server over ssh rather than directly in node?
You set up an SSH tunnel to your server, which listens on (for example) port 33060:
ssh -NL 33060:localhost:3306 yourserver
In another window/terminal, you can use the MySQL client (assuming that it's installed locally) to connect to the remote MySQL server over the SSH tunnel:
mysql --port 33060 --host 127.0.0.1
If that works, it's just a matter of changing the port number in Sequelize:
var sequelize = new Sequelize('database', 'username', 'password', {
host: "127.0.0.1",
port: 33060
});
If it doesn't work, it might be that the remote MySQL server isn't configured to accept connections over TCP. If that's the case, you should configure your MySQL server to get it to accept TCP connections.

Resources