From 4b183c8976787ad591a40508a8e6cfbe25c9ee24 Mon Sep 17 00:00:00 2001 From: Tankred Hase Date: Fri, 10 Jun 2016 17:48:41 +0200 Subject: [PATCH] Add HTTPS public key pinning --- README.md | 2 ++ config/default.js | 2 ++ config/production.js | 4 ++-- src/app.js | 25 +++++++++++++++---------- 4 files changed, 21 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index ea80007..e95eab9 100644 --- a/README.md +++ b/README.md @@ -219,6 +219,8 @@ npm start The `config/development.js` file can be used to configure a local development installation. For production use, the following environment variables need to be set: * NODE_ENV=production +* UPGRADE_HTTPS=true (upgrade HTTP to HTTPS and use [HSTS](https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security)) +* PUBLIC_KEY_PIN= (use [HPKP](https://developer.mozilla.org/de/docs/Web/Security/Public_Key_Pinning)) * MONGO_URI=127.0.0.1:27017/test_db * MONGO_USER=db_user * MONGO_PASS=db_password diff --git a/config/default.js b/config/default.js index ee38db3..2f4ecd8 100644 --- a/config/default.js +++ b/config/default.js @@ -6,6 +6,8 @@ module.exports = { server: { port: process.env.PORT || 8888, + upgradeHTTPS: process.env.UPGRADE_HTTPS, + publicKeyPin: process.env.PUBLIC_KEY_PIN }, mongo: { diff --git a/config/production.js b/config/production.js index 70be3ca..e38fa9a 100644 --- a/config/production.js +++ b/config/production.js @@ -5,7 +5,7 @@ module.exports = { }, server: { - upgradeHTTP: true - }, + upgradeHTTPS: process.env.UPGRADE_HTTPS || true // use HTTPS by default + } }; \ No newline at end of file diff --git a/src/app.js b/src/app.js index db94091..55f3788 100644 --- a/src/app.js +++ b/src/app.js @@ -73,9 +73,23 @@ router.get('/user/:search', function *() { // display homepage router.get('/', home); +// Redirect all http traffic to https +app.use(function *(next) { + if (util.isTrue(config.server.upgradeHTTPS) && util.checkHTTP(this)) { + this.redirect('https://' + this.hostname + this.url); + } else { + yield next; + } +}); + // Set HTTP response headers app.use(function *(next) { - this.set('Strict-Transport-Security', 'max-age=16070400'); + if (util.isTrue(config.server.upgradeHTTPS)) { + this.set('Strict-Transport-Security', 'max-age=31536000'); + } + if (config.server.publicKeyPin) { + this.set('Public-Key-Pins', 'pin-sha256="' + config.server.publicKeyPin + '"'); + } this.set('Access-Control-Allow-Origin', '*'); this.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); this.set('Access-Control-Allow-Headers', 'Content-Type'); @@ -84,15 +98,6 @@ app.use(function *(next) { yield next; }); -// Redirect all http traffic to https -app.use(function *(next) { - if (config.server.upgradeHTTP && util.checkHTTP(this)) { - this.redirect('https://' + this.hostname + this.url); - } else { - yield next; - } -}); - app.use(router.routes()); app.use(router.allowedMethods());