Skip to content

Instantly share code, notes, and snippets.

@ryanlelek
Last active December 28, 2015 18:19
Show Gist options
  • Save ryanlelek/7541987 to your computer and use it in GitHub Desktop.
Save ryanlelek/7541987 to your computer and use it in GitHub Desktop.
Node.js Express SSL
*nat
-A PREROUTING -i eth0 -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
-A PREROUTING -i eth0 -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8443
COMMIT
*mangle
-A PREROUTING -p tcp --dport 8080 -j MARK --set-mark 1
-A PREROUTING -p tcp --dport 8443 -j MARK --set-mark 1
COMMIT
*filter
# Allow HTTP and HTTPS connections from anywhere
# Filter by Source IP: -A INPUT --src [IP ADDRESS]
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 443 -j ACCEPT
# Drop all other inbound - default deny unless explicitly allowed policy
-A INPUT -m mark --mark 1 -j DROP
-A FORWARD -j DROP
COMMIT
This Gist will help you configure SSL on a pure Node.js server
(without a server like Apache/nginx, but you should probably use it in production!)
// Note: Important!
// I would highly recommend running SSL through nginx or similar
// as using a server to handle SSL instead of Node may be faster and more secure
// but this will work for prototyping purposes and testing.
// You don't want to be running any Node.js script as root, so you can
// instead use something like iptables to transform a non-root port (1025+)
// to respond to a root port like 80 or 443 by redirecting the traffic.
// see the iptables_rules file for specific configuration (in addition to default iptables)
var express = require('express');
var fs = require('fs');
var http = require('http');
var https = require('https');
// Create App
var app = express();
// General Settings
app.set('port', process.env.PORT || 8443);
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
// Load SSL Files
var options = {
key : fs.readFileSync('/etc/ssl/selfsigned.key'),
cert : fs.readFileSync('/etc/ssl/selfsigned.crt')
};
// HTTPS Server
https.createServer(options, app).listen(app.get('port'), function () {
console.log('[HTTPS] Express SECURE server listening on port', app.get('port'));
});
// ##### HTTP #####
// HTTP Server to Stop Insecure Connections
var http_app = express().use(function (req, res) {
console.log('Insecure Access Attempt:', req.url);
res.send(400, {
error : {
message : 'HTTPS/SSL is required.',
suggestion : 'Try using: https://' + req.host + req.url
}
});
});
// HTTP Server
http.createServer(http_app).listen(8080, function () {
console.log('HTTP Request Server Running...');
});
// ##### Additional Notes #####
// I don't recommend this approach, but to each his/her own
// http://stackoverflow.com/questions/7450940/automatic-https-connection-redirect-with-node-js-express
// if (!req.secure) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment