How to create virtual hosts with https in nodejs? - node.js

i need to know how to serve multiple projects using virtual hosts but using https.
I can easily do this in http using only express and vhost. But i can't get to work with https. I have key and certificate for all my projects.
I basically need to have https://subdomain.example.com and https://example.com running both in the port 443.
What i tried and didn't work:
var express = require('express');
var path = require('path');
var vhost = require('vhost');
var https = require('https');
var fs = require('fs');
var server = express();
// FOODIFY ============================================================================================================
var credenciaisCliente = {
key: fs.readFileSync(__dirname + "/foodify/certificados/cliente/private.key", "utf8"),
cert: fs.readFileSync(__dirname + "/foodify/certificados/cliente/certificate.crt", "utf8"),
ca: fs.readFileSync(__dirname + "/foodify/certificados/cliente/ca_bundle.crt", "utf8")
};
var credenciaisAdministracao = {
key: fs.readFileSync(__dirname + "/foodify/certificados/administracao/private.key", "utf8"),
cert: fs.readFileSync(__dirname + "/foodify/certificados/administracao/certificate.crt", "utf8"),
ca: fs.readFileSync(__dirname + "/foodify/certificados/administracao/ca_bundle.crt", "utf8")
};
var foodifyAdministracao = express();
foodifyAdministracao.use("/", express.static(__dirname + "/foodify/cliente/administracao"));
foodifyAdministracao.get("*", (request, response) => {
response.sendFile(__dirname + "/foodify/cliente/administracao/index.html");
});
var httpsFoodifyAdministracao = https.createServer(credenciaisAdministracao, foodifyAdministracao);
var foodifyCliente = express();
foodifyCliente.use("/", express.static(__dirname + "/foodify/cliente/cliente"));
foodifyCliente.get("*", (request, response) => {
response.sendFile(__dirname + "/foodify/cliente/cliente/index.html");
});
var httpsFoodifyCliente = https.createServer(credenciaisCliente, foodifyCliente);
var foodifyAdministracaoHost = vhost("administracao.foodify.com.br", foodifyAdministracao);
var foodifyHost = vhost("*.foodify.com.br", foodifyCliente);
server.use(httpsFoodifyAdministracao);
server.use(httpsFoodifyCliente);
server.listen(443, () => {
console.log("Servido os projetos na porta 443 por https.");
});
I also tried some other libraries as dietjs but didn't work also.

You can try Redbird: https://www.npmjs.com/package/redbird
Redbird will listen on ports 80,443 and your other apps will listen on their own unique ports. Redbird will route to those other ports from 80/443 based on domain name.

Although it is a bit late, weeks ago I noticed that in NodeJS, the tls module offers a method called server.addContext(hostname, creds), which takes in a hostname and its corresponding credentials. This means you can basically extend your HTTPS server with your subdomain and corresponding certificate. This has a benefit compared to other reverse proxy solutions (such as Redbird, node-http-proxy and Nginx) as it only requires listening on a single port (443) and requires only a single running node script.
I wrote a minimal package vhttps that wraps this and added virtual host features directly onto it (so you might not need the vhost package). You could probably check it out.

Related

Express Static Directory over HTTPS

I would like to implement Node.js with Express for static content over HTTPS. Scouring the Web reveals tons of examples of Express with HTTPS and tons of examples of Express serving a static directory, but I cannot find an example using all three Express, HTTPS and static.
Moreover, looking at the examples I can find, I cannot piece together how to accomplish this.
Here is what I have found:
Express Static Directory over HTTP
var fs = require('fs')
var app = require("express");
var server = app();
server.use(app.static(staticDir))
server.listen(webPort)
Express over HTTPS (without Static Directory)
const app = require('express')();
const https = require('https');
const server = https.createServer(
{
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
},
app
);
server.listen(APIPort);
When I try combining the two approaches, I get stuck because the static example bypasses createServer, and yet createServer is the crux of getting to HTTPS in the examples.
I'm sure the answer is simple, but I cannot arrive at or locate the solution.
Could you try the below code-snippet and see if it works for you?
const fs = require('fs');
const https = require('https');
const express = require('express');
const app = express();
app.use(express.static(process.env.SERVE_DIRECTORY));
app.get('/', function(req, res) {
return res.end('Serving static files!');
});
const key = fs.readFileSync(__dirname + '/selfsigned.key');
const cert = fs.readFileSync(__dirname + '/selfsigned.crt');
const options = {
key: key,
cert: cert
};
const server = https.createServer(options, app);
server.listen(PORT, () => {
console.log(`Serving on port ${PORT}`);
});
Please make sure to do the suitable changes before running the above code.

Express vhosts + https

Is there any way I can run vhosts on Express with https? My current code (non-SSL) looks like this:
var express = require('express');
var vhost = require('vhost');
var path = require('path');
var appOne = express();
var appTwo = express();
var appVhosts = module.exports = express();
appOne.use(express.static(path.join(__dirname, 'pages')));
appTwo.get('/', function(req, res){
res.send('That service isn\'t up right now!')
});
app.use(vhost('siteone.com', appOne));
app.use(vhost('sitetwo.com', appTwo));
appVhosts.listen(80);
However, as far as I know, the https module only accepts one ssl cert.
Apparently, https.Server inherits from tls.Server, which offers a method called addContext(). You can configure multiple certificates there. I also wrote a very small package that uses this method to achieve the result, https://www.npmjs.com/package/vhttps . You can check my implementation there.
You need to define SSL Options for each app and assign to each app as follows:
// (A) read SSL files
var fs = require('fs');
var appOneSSLOps = {
key: fs.readFileSync('./path_to_file/private.key'),
cert: fs.readFileSync('./path_to_file/certificate.crt')
}
var appTwoSSLOps = {
key: fs.readFileSync('./path_to_file/private2.key'),
cert: fs.readFileSync('./path_to_file/certificate2.crt')
}
// (B) assign SSL files to app
var https = require('https');
var appOneServer = https.createServer(appOneSSLOps , appOne).listen(443);
var appTwoServer = https.createServer(appTwoSSLOps , appTwo).listen(80);
// (C) route 80 to 443 - > on your machine route port 80 to 443 either manually or by child_process: I assume you are using linux Ubuntu System
childProcess = require('child_process');
var optionExec = {timeout: 3000}; //option(s) for childProcess.exec
childProcess.exec(
'sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 443',
optionExec,
function(err, stdout, stderr) {
}
);
// (D) then enforce SSL - I assume appOne is the main app.
appOne.use(function(request, response, next) {
if(!request.secure) {
response.redirect('https://' + request.headers.host + request.url);
}
next();
});
Note: I assume appOne is the main app.

Using https on express 4.0 [duplicate]

Given an SSL key and certificate, how does one create an HTTPS service?
The Express API doc spells this out pretty clearly.
Additionally this answer gives the steps to create a self-signed certificate.
I have added some comments and a snippet from the Node.js HTTPS documentation:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
// This line is from the Node.js HTTPS documentation.
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};
// Create a service (the app object is just a callback).
var app = express();
// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);
For Node 0.3.4 and above all the way up to the current LTS (v16 at the time of this edit), https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener has all the example code you need:
const https = require(`https`);
const fs = require(`fs`);
const options = {
key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`),
cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`)
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end(`hello world\n`);
}).listen(8000);
Note that if want to use Let's Encrypt's certificates using the certbot tool, the private key is called privkey.pem and the certificate is called fullchain.pem:
const certDir = `/etc/letsencrypt/live`;
const domain = `YourDomainName`;
const options = {
key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};
Found this question while googling "node https" but the example in the accepted answer is very old - taken from the docs of the current (v0.10) version of node, it should look like this:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
The above answers are good but with Express and node this will work fine.
Since express create the app for you, I'll skip that here.
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});
The minimal setup for an HTTPS server in Node.js would be something like this :
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
If you also want to support http requests, you need to make just this small modification :
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
Update
Use Let's Encrypt via Greenlock.js
Original Post
I noticed that none of these answers show that adding a Intermediate Root CA to the chain, here are some zero-config examples to play with to see that:
https://github.com/solderjs/nodejs-ssl-example
http://coolaj86.com/articles/how-to-create-a-csr-for-https-tls-ssl-rsa-pems/
https://github.com/solderjs/nodejs-self-signed-certificate-example
Snippet:
var options = {
// this is the private key only
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
This is one of those things that's often easier if you don't try to do it directly through connect or express, but let the native https module handle it and then use that to serve you connect / express app.
Also, if you use server.on('request', app) instead of passing the app when creating the server, it gives you the opportunity to pass the server instance to some initializer function that creates the connect / express app (if you want to do websockets over ssl on the same server, for example).
To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
You can use also archive this with the Fastify framework:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert to create the files if you need to write tests)
If you need it only locally for local development, I've created utility exactly for this task - https://github.com/pie6k/easy-https
import { createHttpsDevServer } from 'easy-https';
async function start() {
const server = await createHttpsDevServer(
async (req, res) => {
res.statusCode = 200;
res.write('ok');
res.end();
},
{
domain: 'my-app.dev',
port: 3000,
subdomains: ['test'], // will add support for test.my-app.dev
openBrowser: true,
},
);
}
start();
It:
Will automatically add proper domain entries to /etc/hosts
Will ask you for admin password only if needed on first run / domain change
Will prepare https certificates for given domains
Will trust those certificates on your local machine
Will open the browser on start pointing to your local server https url
Download rar file for openssl set up from here: https://indy.fulgan.com/SSL/openssl-0.9.8r-i386-win32-rev2.zip
Just copy your folder in c drive.
Create openssl.cnf file and download their content from : http://web.mit.edu/crypto/openssl.cnf
openssl.cnf can be put any where but path shoud be correct when we give in command prompt.
Open command propmt and set openssl.cnf path C:\set OPENSSL_CONF=d:/openssl.cnf
5.Run this in cmd : C:\openssl-0.9.8r-i386-win32-rev2>openssl.exe
Then Run OpenSSL> genrsa -des3 -out server.enc.key 1024
Then it will ask for pass phrases : enter 4 to 11 character as your password for certificate
Then run this Openssl>req -new -key server.enc.key -out server.csr
Then it will ask for some details like country code state name etc. fill it freely.
10 . Then Run Openssl > rsa -in server.enc.key -out server.key
Run this OpenSSL> x509 -req -days 365 -in server.csr -signkey server.key -out server.crt then use previous code that are on stack overflow
Thanks

creating a forward https proxy using http-node-proxy

I am trying to create a forward proxy capable of handling HTTPS websites as well. I am trying to observe and modify traffic for different sites. This is my code which works for http sites but not for https sites.
httpProxy.createServer(function(req, res, next) {
//custom logic
next();
}, function(req, res) {
var proxy = new httpProxy.RoutingProxy();
var buffer = httpProxy.buffer(req);
var urlObj = url.parse(req.url);
req.headers.host = urlObj.host;
req.url = urlObj.path;
console.log(urlObj.protocol);
setTimeout(function() {
proxy.proxyRequest(req, res, {
host: urlObj.host,
port: 80,
buffer: buffer,
}
)}, 5000);
}).listen(9000, function() {
console.log("Waiting for requests...");
});
Thanks for your help guys!
There are https options which must be specified when handling the https traffic. Here is what I am doing in my proxy setup.
var fs = require('fs'),
httpProxy = require('http-proxy');
var proxyTable = {};
proxyTable['domain.com'] = 'localhost:3001';
proxyTable['domain.com/path'] = 'localhost:3002';
proxyTable['sub.domain.com'] = 'localhost:3003';
var httpOptions = {
router: proxyTable
};
var httpsOptions = {
router: proxyTable,
https: {
passphrase: 'xxxxxxx',
key: fs.readFileSync('/path/to/key'),
ca: fs.readFileSync('/path/to/ca'),
cert: fs.readFileSync('/path/to/crt')}
};
httpProxy.createServer(httpOptions).listen(80);
httpProxy.createServer(httpsOptions).listen(443);
The documentation for https is on their github page as well.
https://github.com/nodejitsu/node-http-proxy
If you're just doing a forward proxy there's a few things you'll have to take into account.
A regular request is NOT triggered on a proxy for a HTTPS request - instead you'll see a HTTP CONNECT.
Here's the sequence flow you'll need to handle.
CONNECT event is sent from the browser to the proxy specified in the HTTPS section. You'll catch this here: http://nodejs.org/api/http.html#http_event_connect Note that this comes over the HTTP module, not the HTTPS connection.
You create a new socket connection to the requested domain (or your mapped domain). [srvSocket]
You'll respond back to the CONNECT socket with a 200
You'll write the buffer you received with the CONNECT event to srvSocket, then pipe the two sockets together srvSocket.pipe(socket);
socket.pipe(srvSocket);
Since you're trying to spoof the requested domain locally you'll need a few more things in place
You'll need to generate a root CA.
You will need to import this cert as a trusted authority to your OS
You'll use this cert to create a new key/cert file for the domains you're trying to access
Your mapped hosts will need to respond with the appropriate key/cert file generated in step 3 for EACH domain you are mapping.
https://github.com/substack/bouncy
var bouncy = require('bouncy');
var server = bouncy(function (req, res, bounce) {
if (req.headers.host === 'beep.example.com') {
bounce(8001);
}
else if (req.headers.host === 'boop.example.com') {
bounce(8002);
}
else {
res.statusCode = 404;
res.end('no such host');
}
});
server.listen(8000);
If you specify opts.key and opts.cert, the connection will be set to secure mode using tls. Do this if you want to make an https router.
We can have a middleware as below
request = require("request");
app.use(function (req, res, next) {
request('http://anotherurl.that.serves/the/request').pipe(res);
});
See example https://github.com/manuks/proxy
Basically, underneath the http-proxy npm is some networking libraries Node uses (specifically http://nodejs.org/api/https.html and TLS). Even though my Apache was able to connect me just fine on a self-signed certificate w/o the proxy by accessing it in my browser:
https://localhost:8002
You need to establish a certificate authority to get past the "unable to verify leaf signature" error in Node (I used the SSLCACertificateFile option). Then, you'll get hit with "self_signed_cert_in_chain". This led to some Google results indicating npm abandoned self-signed certificates, but I'm pretty sure this does not regard Node.
What you end up with are some people indicating you use process.env.NODE_TLS_REJECT_UNAUTHORIZED or rejectUnauthorized within your https agent. If you dig through the http-proxy souce, you'll find it accepts an agent option. Use this:
/**
* Module dependencies
*/
// basic includes
express = require('express');
fs = require('fs');
http = require('http');
https = require('https');
httpProxy = require('http-proxy');
require('child_process').spawn(__dirname+'/../../../dependencies/apache/bin/httpd.exe',['-f',__dirname+'/../../../dependencies/apache/conf/httpd-payments.conf']);
var app = module.exports = express();
app.set('port', process.env.PORT || 8001); // we sometimes change the port
// creates an output object for this particular request
//app.use(express.cookieParser(''));
//app.use(express.bodyParser());
//app.use(express.methodOverride());
proxy = httpProxy.createProxyServer();
proxy.on('error', function (err, req, res) {
console.log(err);
res.send(500,err);
res.end();
});
app.all('*',function(req,res,next) {
var options = {
hostname: '127.0.0.1',
port: 8002,
rejectUnauthorized: false,
key: fs.readFileSync(__dirname+"/../../../deployment/server.key.pem"),
cert: fs.readFileSync(__dirname+"/../../../deployment/server.crt.pem")
};
agent = new https.Agent(options);
try {
proxy.web(req,res, {
target: "https://localhost:8002",
proxyTimeout: 30,
agent: agent
});
} catch(e) {
// 500 error
res.send(500,e);
}
})
/**
* Start Server
*/
var options = {
key: fs.readFileSync(__dirname+"/../../../deployment/server.key.pem"),
cert: fs.readFileSync(__dirname+"/../../../deployment/server.crt.pem")
};
server = https.createServer(options,app).listen(app.get('port'), function () {
console.log('Running payments server on port ' + app.get('port'));
});

How do I setup a SSL certificate for an express.js server?

Before, in an older version of express, I could do this:
express.createServer({key:'keyFile', cert:'certFile'});
However, in newer versions of express this no longer works:
var app = express();
Should I call app.use() to set the certs? If so how?
See the Express docs as well as the Node docs for https.createServer (which is what express recommends to use):
var privateKey = fs.readFileSync( 'privatekey.pem' );
var certificate = fs.readFileSync( 'certificate.pem' );
https.createServer({
key: privateKey,
cert: certificate
}, app).listen(port);
Other options for createServer are at: http://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener
I was able to get SSL working with the following boilerplate code:
var fs = require('fs'),
http = require('http'),
https = require('https'),
express = require('express');
var port = 8000;
var options = {
key: fs.readFileSync('./ssl/privatekey.pem'),
cert: fs.readFileSync('./ssl/certificate.pem'),
};
var app = express();
var server = https.createServer(options, app).listen(port, function(){
console.log("Express server listening on port " + port);
});
app.get('/', function (req, res) {
res.writeHead(200);
res.end("hello world\n");
});
This is my working code for express 4.0.
express 4.0 is very different from 3.0 and others.
4.0 you have /bin/www file, which you are going to add https here.
"npm start" is standard way you start express 4.0 server.
readFileSync() function should use __dirname get current directory
while require() use ./ refer to current directory.
First you put private.key and public.cert file under /bin folder,
It is same folder as WWW file.
no such directory found error:
key: fs.readFileSync('../private.key'),
cert: fs.readFileSync('../public.cert')
error, no such directory found
key: fs.readFileSync('./private.key'),
cert: fs.readFileSync('./public.cert')
Working code should be
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
Complete https code is:
const https = require('https');
const fs = require('fs');
// readFileSync function must use __dirname get current directory
// require use ./ refer to current directory.
const options = {
key: fs.readFileSync(__dirname + '/private.key', 'utf8'),
cert: fs.readFileSync(__dirname + '/public.cert', 'utf8')
};
// Create HTTPs server.
var server = https.createServer(options, app);

Resources