Home > Net >  Node.js Restrict HTTP server to be accessible only on 127.0.0.1
Node.js Restrict HTTP server to be accessible only on 127.0.0.1

Time:09-02

I have created a ws websocket server in nodejs and a http server that is listening on a specific port and host is 127.0.0.1. WebSocket server connection is established on the upgrade event emitted by the http server. For security purpose I want the server to be accessible only on localhost/127.0.0.1 and not from 0.0.0.0 IP.

Example:

  1. ws://0.0.0.0:5050 - Should not accept connections
  2. ws://127.0.0.1:5050 - Should accept connections

How can I restrict the server to be only reachable from localhost and not from any other IP(including 0.0.0.0)?

const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
server.listen(5050, '127.0.0.1');

server.on('upgrade', function (request, socket, head) {
  wss.handleUpgrade(request, socket, head, function (ws) {
  //conditional checks
  wss.emit('connection', ws, request);
  })
})

Can somebody please direct me to the proper way of doing this.

CodePudding user response:

if(req.socket.remoteAddress !== '127.0.0.1'){
res.send('403 Access Denied');
res.end();
} else { 
// allow access
}

CodePudding user response:

0.0.0.0 isn't an IP address. It is a non-routable meta-address used to designate an invalid, unknown or non-applicable target.

You might have a client that treats requests to 0.0.0.0 as being intended for localhost, but that isn't a security problem since your server still won't be accessible outside of the current machine.

Your existing code, where you only listen on 127.0.0.1 is sufficient.

CodePudding user response:

Access and security that you are talking about are supposed to be done at the firewall of your instance hosting nodejs server.

However, if you still want to implement it on your nodejs layer you can dig the request object there you will find the IP address from where the request is coming, and based on that you can take your action.

Hope it helps, Thank you

  • Related