I am writing a program that will serve a particular file. However, I get an exception. I am not sure on the error since I am a bit new to node based programming.
I have got the certificates correct.
var tls = require('tls');
var fs = require('fs');
var options = {
key: fs.readFileSync('/home/test/key.pem'),
cert: fs.readFileSync('/home/test/server.crt')
};
tls.createServer(options, function (s) {
content = fs.readFileSync('/home/test/abc.conf','utf8');
s.write(content);
s.setEncoding('utf8');
s.pipe(s);
}).listen(8000);
node app.js
events.js:160
throw er; // Unhandled 'error' event
^
Error: write ECONNRESET
at exports._errnoException (util.js:1020:11)
at WriteWrap.afterWrite (net.js:800:14)
Realized, it is quite easy using just https.createServer and provide options of ciphers there.
var ciphers = [
'AES128-SHA',
'AES256-SHA'
].join(':');
var options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem'),
ciphers: ciphers
};
https.createServer(options, function(req, res) {
console.log("Running node now");
}).listen(443);
Since, I am using 443 https standard port, I need to start this node app with admin permission i.e. sudo.
Related
Hello and sorry for my bad english, but I have a problem with my tchat created with NodeJS. My server.js running on port 1337 in my VPS, but with port isn't secure and i don't know how secure him.
All my website is secure with a Let's Encrypt certificate, but not the 1337 port...
I tried to secure https://www.temtem-france.com:1337/ with Let's encrypt but it doesn't work... :/
I have this on the beggining of my server.js :
var https = require('https'),
fs = require('fs'),
mysql = require('mysql');
var options = {
key: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/privkey.pem'),
cert: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/cert.pem'),
ca: fs.readFileSync('/etc/letsencrypt/archive/temtem-france.com/chain.pem'),
requestCert: false, rejectUnauthorized: false
};
var httpsServer = https.createServer(options, function (req, res) {
res.writeHead(200);
console.log('Affiché');
res.end("Hello World\n");
}).listen(1337);
With inspector on my client.php code, i have this :
socket.io.js:1 Failed to load resource: net::ERR_CERT_DATE_INVALID
client.js:31 Uncaught ReferenceError: io is not defined
at client.js:31
at HTMLDocument.<anonymous> (client.js:117)
at i (jquery-min.js:2)
at Object.fireWith [as resolveWith] (jquery-min.js:2)
at Function.ready (jquery-min.js:2)
at HTMLDocument.K (jquery-min.js:2)
Unchecked runtime.lastError: The message port closed before a response was received.
I already managed to run my codes, but it was several months ago and since I am not very comfortable with server management, I forgot how I had succeeded.
Thanks a lot if you can help me !
I am trying to make 2 servers communicate via socket.io library and SSL.
This used to work until an upgrade of socket.io package (can't tell you which).
I have managed to fix secure connection with a browser. I have also made it work between unsecure (http) servers. But the secure (https) servers refuse to connect between themselves. You may argue that socket.io is not made for server to server communications, but it would save me lots of work to fix it.
I am now running:
node: 7.5.0
express: 4.16.2
socket.io (and socket.io-client): 2.0.3
I cannot even make simple examples below work (removing all my middleware).
node server
// Use SSL certificate
const cert_path = "..";
const fs = require('fs');
const https_options = {
key: fs.readFileSync(cert_path+'/privkey.pem'),
cert: fs.readFileSync(cert_path+'/cert.pem')
};
const app = require('express')();
const https = require('https');
const server = https.createServer(https_options, app);
const io = require('socket.io')(server);
server.listen(8000);
io.on('connection', function (socket) {
console.log("connected");
});
node client
const io = require('socket.io-client');
const socket = io.connect(
'https://localhost:8000',
{secure: true}
);
socket.on("connect", function () {
console.log("connected");
});
Nothing happens, none of them connect. Any idea why?
EDIT: I'm getting both connect_error and reconnect_error that pop every 5s on client side:
{ Error: xhr poll error
at XHR.Transport.onError (../node_modules/engine.io-client/lib/transport.js:64:13)
at Request.<anonymous> (../node_modules/engine.io-client/lib/transports/polling-xhr.js:128:10)
at Request.Emitter.emit (../node_modules/component-emitter/index.js:133:20)
at Request.onError (../node_modules/engine.io-client/lib/transports/polling-xhr.js:310:8)
at Timeout._onTimeout (../node_modules/engine.io-client/lib/transports/polling-xhr.js:257:18)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5) type: 'TransportError', description: 503 }
Digging further in the errors, I see it may come from the certificate. But while I apply several workarounds of SO, I'm getting consecutively ECONNREFUSED, UNABLE_TO_VERIFY_LEAF_SIGNATURE, and finally DEPTH_ZERO_SELF_SIGNED_CERT...
After trying hard:
re-generate my Let's Encrypt certificate
re-generate my self-signed certificates (openssl) and use them by server+client
tinker with socket.io connect options (secure, rejectUnauthorized, ..)
tinker with nodejs global setup even (process.env['NODE_TLS_REJECT_UNAUTHORIZED'])
I finally stumbled on this page of github. It solved my issue and it's worth sharing it.
node client
const https = require('https');
https.globalAgent.options.rejectUnauthorized = false;
const io = require('socket.io-client');
const sockets = io.connect('https://localhost:8001', {agent: https.globalAgent});
Even if I would have preferred getting my connection authorized in the first place, this will work for me.
Generated a self-signed certificate with OpenSSL and copied the certificate & the private key to the required destination folder.
To create an HTTPS server, we require two things: an SSL certificate, and Node's built-in https module.
With Node.js installed, I tried the following JavaScript to run from the command Line
TLSServer.js
var tls = require('tls');
var fs = require('fs');
var port = 8081; //3000;
var host = '127.0.0.1'; //192.168.1.135
var options = {
key: fs.readFileSync('private-key.pem'), // /path/to/private-key.pem
cert: fs.readFileSync('certificate.pem') // /path/to/certificate.pem
};
TLSClient.js
var client = tls.connect(port, host, options, function() {
console.log('connected');
if (client.authorized) {
console.log('authorized: ' + client.authorized);
client.on('data', function(data) {
client.write(data); // Just send data back to server
});
} else {
console.log('connection not authorized: ' + client.authorizationError);
}
});
Actual Output:
cmd>node TLSServer.js
openssl config failed: error:02001005:system library:fopen:Input/output error
cmd>node TLSClient.js
openssl config failed: error:02001005:system library:fopen:Input/output error
events.js:193
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 127.0.0.1:8081
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14)
What might be the reason for getting this issue:
openssl config failed: error:02001005:system library:fopen:Input/output error
httpserver.js
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('private-key.pem'),
cert: fs.readFileSync('certificate.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.write("You are connected to https server");
res.end("\n hello world \n");
}).listen(8080)
https://localhost:8080
From browser I used to get the following output:
You are connected to https server
hello world
But not with TLS Client/Server. But what might be there to modify in OpenSSL config file?
Solved openssl config failed: error:02001005:system library:fopen:Input/output error by adding the path of openssl.cnf in Environment Variables -> System Variables
OPENSSL_CONF=C:\OpenSSL-Win64\bin\openssl.cnf
To validate it you can type in the shell:
echo %OPENSSL_CONF%
But still I'm getting error with TLSServer.js
cmd>node TLSServer.js
module.js:544
throw err;
^
Error: Cannot find module 'C:\Users\user\Desktop\TLSServer.js'
at Function.Module._resolveFilename (module.js:542:15)
at Function.Module._load (module.js:472:25)
at Function.Module.runMain (module.js:682:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:613:3
I am trying to use HTTP/2. My express version is 5.0.0-alpha.2, http2 version is 3.3.4.
I suppose http2 should work well with express 5.
const http2 = require('http2');
// const http2 = require('spdy'); // using spdy package here, everything works perfect
const options = {
key: fs.readFileSync(path.join(__dirname, 'private', 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'private', 'server.crt'))
};
const server = http2
.createServer(options, app)
.listen(3000, err => {
if (err) throw new Error(err);
// I can see "Listening..." message, which means the server starts running well.
console.log('Listening...');
});
The server starts running well, but when I open client website, it gives me this error in the terminal:
_stream_readable.js:512
dest.end();
^
TypeError: dest.end is not a function
at Stream.onend (_stream_readable.js:512:10)
at Stream.g (events.js:286:16)
at emitNone (events.js:91:20)
at Stream.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:975:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
It seems node-http2 has not been supported by Express yet.
Please track this issue Support for module http on github.
In the meanwhile, you can stay with node-spdy.
const spdy = require('spdy');
const options = {
key: fs.readFileSync(path.join(__dirname, 'private', 'server.key')),
cert: fs.readFileSync(path.join(__dirname, 'private', 'server.crt'))
};
const server = spdy
.createServer(options, app)
.listen(3000, err => {
if (err) throw new Error(err);
console.log('Listening...');
});
With Express 5.0 we have another solution :
express = require( 'express' ), //Web framework
// Solution
express.request.__proto__ = http2.IncomingMessage.prototype;
express.response.__proto__ = http2.ServerResponse.prototype;
// Create app for server http/2
var apph2 = express();
And this is the server code :
var
application_root = __dirname,
express = require( 'express' ), //Web framework
http2 = require('http2')
logger = require('morgan')
fs = require('fs')
constants = require('constants');
// Bunyan logger
var bunyan = require('bunyan');
var app = require('./apps/app_name');
var bunlog = bunyan.createLogger({name: "brqx_app"});
var credentials = {
// log : bunlog ,
key : fs.readFileSync('/etc/letsencrypt/live/domain/privkey.pem' ),
cert : fs.readFileSync('/etc/letsencrypt/live/domain/fullchain.pem' ),
ca : fs.readFileSync("/etc/letsencrypt/live/domain/chain.pem" ),
dhparam : fs.readFileSync("/etc/letsencrypt/archive/domain/dh1.pem" ),
secureOptions: constants.SSL_OP_NO_SSLv3 | constants.SSL_OP_NO_SSLv2
};
// Configure server
server = http2.createServer( credentials , app);
server.listen(PORT , function () {
console.log('Started Brqx http/2!');
} )
I hope these easy lines helps to people.
One thing is important when we search information on Internet is the date of test when code was tested : 2017 - October.
Regards.
Ricardo/Brqx.
I'm trying to connect to an https server with a specific certificate. For some reason, it seems to succeed in Node 6.0.0 but fails in Node 4.4.7.
code
var fs = require('fs');
var host = process.argv[2]; // host of the site
var certFile = process.argv[3]; // certificate from server
var ca = fs.readFileSync(certFile, 'ascii');
var https = require('https');
https.request({ host: host, ca: ca }, function (res) {
if (res.client.authorized) {
console.log("node test: OK")
} else {
throw new Error(res.client.authorizationError)
}
}).end()
Node 6.0.0 output
node test: OK
Node 4.4.7 output
events.js:141
throw er; // Unhandled 'error' event
^
Error: unable to verify the first certificate
at Error (native)
at TLSSocket.<anonymous> (_tls_wrap.js:1017:38)
at emitNone (events.js:67:13)
at TLSSocket.emit (events.js:166:7)
at TLSSocket._init.ssl.onclienthello.ssl.oncertcb.TLSSocket._finishInit (_tls_wrap.js:582:8)
at TLSWrap.ssl.onclienthello.ssl.oncertcb.ssl.onnewsession.ssl.onhandshakedone (_tls_wrap.js:424:38)
system
$ lsb_release -d
Description: Ubuntu 16.04 LTS