How to secure tcp connection - nodejs?

2.9k Views Asked by At

I have following sample code used in the tcp server

var server = net.createServer();

server.on('connection', function (socket) {

   if(restrictedIP == sock.remoteAddress){
      //How to close the particular connection safely without 
      //affecting other connections
   }

  socket.on('data', function(data) {
    console.log(data);        
  });

  socket.on('close', function(data) {
    console.log('client disconnected');
  });
});

server.listen(3000, '127.0.0.1');

Note : I have a check to authenticate the client/server ip (3rd line).

Problem :

  1. Whether this logic sounds good to authenticate the client/server.

  2. Main thing, How to close the particular connection from the restricted ip address.(4th line - comment)

Scenario :

I have two servers one is client server which is express/http server lets name it as server1-express, and other one is tcp server named as server2-tcp.

  1. server1-express server will talk to server2-tcp using tcp.

  2. server2-tcp should only allow this particular server1-express server, It shouldn't allow connection to any other ip,

  3. Using socket.destroy() will crash the server2-tcp.

  4. Using socket.end() will force us to write to servers.

How to allow only particular ip and deny all other ip access?

Any help or suggestion will be grateful

1

There are 1 best solutions below

2
On BEST ANSWER

It depends on what you mean by "authenticate", but obviously an IP address could be used by multiple people (e.g. behind a router). So if that is a concern, you will have to come up with your own protocol or re-use an existing one (probably a better idea to use one that has been "battle tested"). A more "complex" example would be to use TLS, which is built into node and would give you both encryption and authentication via certificates/keys, while still giving you a raw socket.

As far as terminating a connection goes, you can do that gracefully by calling .end() on the socket, or .destroy() to forcefully terminate the socket.