Home > Blockchain >  How to connect to a server via Node TLS without knowing the certificate?
How to connect to a server via Node TLS without knowing the certificate?

Time:08-29

Me and a friend of mine have a game deployed on a Ubuntu server. It's a game that we play from the command line, and we connect via openssl s_client -connect <address> <port>. In this way everything works.

What I want to do is having a NodeJS Express that connects to the same server and forwards the messages in both directions via a websocket (so we can play also from a React App in a browser). The Express app is deployed on the same machine, so I did

const express = require('express');
const cors = require('cors');
const http = require('http');
const { Server } = require('ws');
const tls = require('tls');

const app = express();

app.use(cors());

app.get('/', (_, response) => response.sendStatus(200));

const server = http.createServer(app);

const webBrowser = new Server({ server });

webBrowser.on('connection', (ws) => {
  const server = tls.connect(2121, 'localhost', {}, () => {
    if (server.authorized) {
      ws.send(JSON.stringify({ message: 'Connection successful' }));
    } else {
      ws.send(JSON.stringify({
        message: 'Connection rejected',
        error: server.authorizationError,
      }));
      server.destroy();
    }
  });

  server.on('data', (data) => {
    ws.send(JSON.stringify({ message: 'Data received', data: data.toString() }));
  });

  server.on('close', () => {
    ws.send(JSON.stringify({ message: 'Connection closed' }));
  });

  server.on('error', (error) => {
    server.destroy();

    ws.send(JSON.stringify({ message: 'Error received', error }));
  });

  ws.on('message', (message) => {
    server.write(message);
  });
});

const PORT = 5004;

server.listen(PORT, () => {
  console.log(`Server started on port ${PORT}`);
});

I get the message from the server but every time I do the server.write(message) the server doesn't receive anything. I always see DEPTH_ZERO_SELF_SIGNED_CERT. Is the error related?
I read a lot of stuff here on StackOverflow but I'm not getting the point.
Why do I need a certificate to connect to something that is running on the same machine?
And by the way, how can I generate those certificates?

Thanks a lot!

CodePudding user response:

By reading the Node TLS documentation, you can see that the dev must include the server certificate in order to work, by doing:

const options = {
  // Necessary only if the server requires client certificate authentication.
  key: fs.readFileSync('client-key.pem'),
  cert: fs.readFileSync('client-cert.pem'),

  // Necessary only if the server uses a self-signed certificate.
  ca: [ fs.readFileSync('server-cert.pem') ],

  // Necessary only if the server's cert isn't for "localhost".
  checkServerIdentity: () => { return null; },
};

Doing that solved the problem!

  • Related