Node.js, simple TLS client/server - javascript

I want create a simple secure client/server using TLS. I've follow instruction on the official doc. But I don't know how to create self-signed certificate with openssl (does not work with me).
Here code :
server.js
const tls = require('tls');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync('client-cert.pem') ]
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
client.js :
const tls = require('tls');
const fs = require('fs');
const options = {
// Necessary only if using the client certificate authentication
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
// Necessary only if the server uses the self-signed certificate
ca: [ fs.readFileSync('server-cert.pem') ]
};
const socket = tls.connect(8000, options, () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
console.log(data);
});
socket.on('end', () => {
server.close();
});
I don't know why use two different key-pair :
client-key.pem
client-cert.pem
and :
server-key.pem
server-cert.pem
Anyone can exmplain me ? For work in self-signed.
Sincerely,
Yoratheon

I solve my problem.
Solution here

Related

Why my socketio is not connecting with my socketio-client?

i am working on a chatapp project that needs a real time chatting so i have used socketio in my server side which is written in nodejs and than used socketio-client in my main chatapp react-native project.
But now a problem is coming my socket is not initializing. I'm not able to connect my server with my main app. I am using socketio and socketio client my both the socket version are same 4.5.1 but it's not even connecting. I have tried to use old version of socket but its also not working and I have also tried to change my localhost port to 4000 but it's also not working.
My server code:
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3000;
require('./src/config/database')
const user_routes = require('./src/user/users.routes');
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.use('/User', user_routes)
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('send_message',(data)=>{
console.log("received message in server side",data)
io.emit('received_message',data)
})
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
server.listen(port, () => {
console.log( `Server running at http://localhost:${port}/`);
});
My app socketservice file code:
import io from 'socket.io-client';
const SOCKET_URL = 'http://localhost:3000'
class WSService {
initializeSocket = async () => {
try {
this.socket = io(SOCKET_URL, {
transports: ['websocket']
})
console.log("initializing socket", this.socket)
this.socket.on('connect', (data) => {
console.log("=== socket connected ====")
})
this.socket.on('disconnect', (data) => {
console.log("=== socket disconnected ====")
})
this.socket.on('error', (data) => {
console.log("socekt error", data)
})
} catch (error) {
console.log("scoket is not inialized", error)
}
}
emit(event, data = {}) {
this.socket.emit(event, data)
}
on(event, cb) {
this.socket.on(event, cb)
}
removeListener(listenerName) {
this.socket.removeListener(listenerName)
}
}
const socketServcies = new WSService()
export default socketServcies
Where I have marked it should be connected = true but it's false in the dev console I have done console log so check that it's connecting or not and I can see that it's not connecting. How to make it connect?
There is no error in my app or server I have checked many times and my server is also running when I am running my app.
Answering my own question
The problem was i was using android emulator and android in an emulator can't connect to localhost you need to use the proxy ip so when i add http://10.0.2.2:3000 in const SOCKET_URL = 'http://10.0.2.2:3000' than its working fine
credit goes to gorbypark who told me this in discord
I'm assuming that your front and back runs in localhost. The documentation says that if the front-end is in the same domain as the back-end, you don't need to use the URL. Since you have the options parameter declared, you can use the default argument window.location in first place:
class WSService {
initializeSocket = async () => {
try {
this.socket = io(window.location, {
transports: ['websocket']
})
console.log("initializing socket", this.socket)
this.socket.on('connect', (data) => {
console.log("=== socket connected ====")
})
this.socket.on('disconnect', (data) => {
console.log("=== socket disconnected ====")
})
this.socket.on('error', (data) => {
console.log("socekt error", data)
})
} catch (error) {
console.log("scoket is not inialized", error)
}
}
emit(event, data = {}) {
this.socket.emit(event, data)
}
on(event, cb) {
this.socket.on(event, cb)
}
removeListener(listenerName) {
this.socket.removeListener(listenerName)
}
}
Don't specify the host/port for socket-io to connect to. It can figure it out on its own.
Per documentation, it tries to connect to window.location if no URL is specified as an argument.
So instead of
this.socket = io(SOCKET_URL, {
transports: ['websocket']
})
Just do
this.socket = io()
I am not sure it works with other arguments. You could try like this
this.socket = io(undefined, {
transports: ['websocket']
})

Nodejs Websocket server (using ws) won't run securely

I'm currently running a websocket server on a secure domain (with ssl) but for some reason I cannot get the server to actually use wss instead of ws.
The code below is how I create the Websocket server.
const httpsServer = https.createServer({
cert: fs.readFileSync(`/etc/letsencrypt/live/example.com/cert.pem`, 'utf8'),
key: fs.readFileSync(`/etc/letsencrypt/live/example.com/privkey.pem`, 'utf8'),
ca: fs.readFileSync(`/etc/letsencrypt/live/example.com/chain.pem`, 'utf8'),
})
const wss = new WebSocket.Server({
port: [port],
perMessageDeflate: false,
server: httpsServer,
})
wss.on('connection', (ws: ExtraWS, req) => {
ws.id = [id]
ws.send(`Connected to: ${req.socket.remoteAddress}:${req.socket.remotePort}`)
ws.on('message', msg => {
ws.send(`Recieved: '${msg}'`)
})
})
For whatever reason this socket is only available at ws://example.com:[port], instead of wss://example.com:[port]. If anyone knows what I'm doing wrong here please let me know.
I found the answer to this. The issue was that I was specifying the port in the Socket server instead of specifying it in the httpsServer.listen().
This is the amended code:
const httpsServer = https.createServer({
cert: fs.readFileSync(`/etc/letsencrypt/live/example.com/cert.pem`, 'utf8'),
key: fs.readFileSync(`/etc/letsencrypt/live/example.com/privkey.pem`, 'utf8'),
ca: fs.readFileSync(`/etc/letsencrypt/live/example.com/chain.pem`, 'utf8'),
})
httpsServer.listen([port])
const wss = new WebSocket.Server({
perMessageDeflate: false,
server: httpsServer,
})

Can't connect to local Node.js secure WebSocketServer

For testing a JavaScript / html5 application, I created a local WebSocketServer with node.js and ws package. I want to use secure websockets (wss) with SSL/TLS.
Key and certificate were create for testing purposes by OpenSSL locally (self signed certificate).
The client just tries to use the native WebSocket object to connect to the (local) https Server:
var ws = new Websocket('wss://localhost:8080');
The Problem is, no browser (Firefox, Chrome, Edge) can connect to the server and they all give me different error messages.
Firefox:
Firefox can not connect to the server at wss: // localhost: 8080 /.
Chrome:
ws_client.js:7 WebSocket connection to 'wss://localhost:8080/' failed:
Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
Edge:
SCRIPT12017: SCRIPT12017: WebSocket Error: SECURITY_ERR, Cross zone
connection not allowed
I created the certificate and key in OpenSSL (light, newest version) like this:
openssl req -new -x509 -nodes -out server.crt -keyout server.key
(source)
I checked almost every question about this (and similar) topics, e.g. this question, but none of them could provide a solution.
Please do not mark this question as a duplicate, because all similar questions contain slightly different problems!
Server Code:
var fs = require('file-system');
var pkey = fs.readFileSync('server.key', 'utf8');
var crt = fs.readFileSync('server.crt', 'utf8');
var credentials = { key: pkey, cert: crt };
var https = require('https');
var httpsServer = https.createServer(credentials);
httpsServer.listen(8080);
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({
server: httpsServer
});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send('reply from server : ' + message)
});
});
I tried another code as server, but same errors occur:
const WebSocketServer = require('ws').Server;
var fs = require('file-system');
var ws_cfg = {
ssl: true,
port: 8080,
ssl_key: 'server.key',
ssl_cert: 'server.crt'
};
var processRequest = function(req, res) {
console.log('Request received');
};
var httpServ = require('https');
var app = httpServ.createServer({
key: fs.readFileSync(ws_cfg.ssl_key, 'utf8', (error) => {
console.log('Error reading file');
}),
cert: fs.readFileSync(ws_cfg.ssl_cert, 'utf8', (error) => {
console.log('Error reading file');
})
}, processRequest).listen(ws_cfg.port, function(){
console.log('Server running');
});
var wss = new WebSocketServer( {server: app, port: 8080, host: 'localhost', domain: 'localhost'} );
wss.on('connection', function (ws) {
console.log('Connected to a client');
ws.on('message', function (message) {
console.log('MSG received: ' + message);
});
});
There's one more thing. Always, if I add a console.log(wss); to the server Code, the output looks something like this:
WebSocketServer {
domain: null,
...some more stuff...
...cert key etc....
host: null,
path: null,
port: null } }
host, domain and port is set to null. I tried everything to set it to localhost:8080, but nothing worked out. I think this could be the source of all Problems, but can't find a way. If anyone knows an answer to this question, I would highly appreciate it.
(Using the insecure 'ws' protocol ('ws://localhost:8080') in order to connect to local node.js http server works, but I want to test the app as realistic as possible and use a secure Connection.)
-- This is not an answer, just my workaround --
For anyone having the same problems, here is what I did:
Server Code should be:
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const server = new https.createServer({
cert: fs.readFileSync('localcert.cert'), //what ever you're files are called
key: fs.readFileSync('localkey.key')
});
const wss = new WebSocket.Server({ server }); // !
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('MSG received: %s', message);
});
ws.send('Hi to client');
});
server.listen(8080);
Only working in Google Chrome for now, can still not connect in Firefox.
enter chrome://flags/#allow-insecure-localhost in Google Chrome and enable.
Try to add the self-signed certificate or the generated CA to be trusted on the system that you are using.

TLS to multiple clients and different messages

I am planning a security system based on tcp. I want to secure it with TLS/SSL. I want to make a Client make a message to the server, the server has to check it and send to all the other clients a message back.
I think it is unclear how to handle that, because the documentation of node.js tls only shows how you connect to the server and get a message back.
This is the code of the documentation:
const tls = require('tls');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
rejectUnauthorized: true,
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
Maybe you could make an example, because its totally unclear to me. Thanks for your help. If my question is unclear to you, please let me know.
'use strict';
var tls = require('tls');
var fs = require('fs');
const PORT = 1337;
const HOST = '127.0.0.1'
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('public-cert.pem')
};
var users= [];
var server = tls.createServer(options, function(socket) {
users.push(socket)
socket.on('data', function(data) {
for(var i = 0; i < users.length; i++){
if(users[i]!=socket){
users[i].write("I am the server sending you a message.");
}
}
console.log('Received: %s [it is %d bytes long]',
data.toString().replace(/(\n)/gm,""),
data.length); });
});
server.listen(PORT, HOST, function() {
console.log("I'm listening at %s, on port %s", HOST, PORT);
});
server.on('error', function(error) {
console.error(error);
server.destroy();
});

requestCert not working (Node.js)

I'm trying to use client authentication, but requestCert is not working. When the site is loaded, there isn't any prompt to select a certificate.
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('/etc/pki/tls/private/ca.key'),
cert: fs.readFileSync('/etc/pki/tls/certs/ca.crt'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync('/etc/pki/tls/private/device.key') ]
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.write("Hello.\n");
if(req.client.authorized) {
res.write('Access granted.\n');
}
else {
res.write('Access denied.\n');
}
res.end();
}).listen(5000);
What's wrong? I've used example codes! Thanks.

Categories