Search code examples
node.jssocketsssltcphandshaking

Using SSL over TCP to establish safe connection between two servers with NodeJS


I am trying to send a package from one server to another but i need to be sure that the sender is the "real" one and the package cannot be intercepted, How can i do this using SSL with NodeJS or some other way.

This is what I've done:

Server code:

server = tls.createServer(function(c) {
console.log('server connected',

c.authorized ? 'authorized' : 'unauthorized');
});

Client code:

var tls = require('tls');
var fs = require('fs');

var options = {
key  : fs.readFileSync('server.key'),
cert : fs.readFileSync('server.crt')
};

var client = tls.connect(9838, options, function () {

console.log(client.authorized ? 'Authorized' : 'Not authorized');

});

and this errors out:

Error: 101057795:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv handshake failure:openssl\ssl\s23_clnt.c:769:

Solution

  • To ensure that the sender (the client) is the "real" one, you might try using TLS client auth (or mutual authentication). This means you'll need a client certificate (and key), a server certificate (and key), the CA certificate which issued/signed the server certificate, and the CA certificate which issued/signed the client certificate.

    First, your TLS server will need to provide its certificate to any connecting TLS clients; this means you'll need to configure its certificate and key. You'll also want the TLS server to request that the client send its certificate to the server, as part of the handshake:

    var tlsOptions = {
      cert: fs.readFileSync('server-cert.pem'),
      key: fs.readFileSync('server-key.pem'),
      ca: [ fs.readFileSync('client-ca-cert.pem'),
      requestCert: true,
      rejectUnauthorized: true
    };
    
    var server = tls.createServer(tlsOptions, function () {
    

    Then, for the client, you configure it with its certificate and key, and the CA certificate which issued/signed the server certificate (so that the client can verify that the receiver is the "real" one):

    var tlsOptions = {
      host: 'server.example.com',
      port: 9838,
      cert: fs.readFileSync('client-cert.pem'),
      key: fs.readFileSync('client-key.pem'),
      ca: [ fs.readFileSync('server-ca-cert.pem')
    };
    
    var client = tls.connect(tlsOptions, function () {
    

    Hope this helps!