diff --git a/README.md b/README.md
index 1e7d79a..fb1f8e3 100644
--- a/README.md
+++ b/README.md
@@ -197,6 +197,7 @@ There are some configs you need to change in the files below
| HMD_HSTS_INCLUDE_SUBDOMAINS | `true` | set to include subdomains in HSTS (default is `true`) |
| HMD_HSTS_MAX_AGE | `31536000` | max duration in seconds to tell clients to keep HSTS status (default is a year) |
| HMD_HSTS_PRELOAD | `true` | whether to allow preloading of the site's HSTS status (e.g. into browsers) |
+| HMD_CSP_ENABLE | `true` | whether to enable Content Security Policy (directives cannot be configured with environment variables) |
## Application settings `config.json`
@@ -208,7 +209,8 @@ There are some configs you need to change in the files below
| port | `80` | web app port |
| alloworigin | `['localhost']` | domain name whitelist |
| usessl | `true` or `false` | set to use ssl server (if true will auto turn on `protocolusessl`) |
-| hsts | `{"enable": "true", "maxAgeSeconds": "31536000", "includeSubdomains": "true", "preload": "true"}` | [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) options to use with HTTPS (default is the example value, max age is a year) |
+| hsts | `{"enable": true, "maxAgeSeconds": 31536000, "includeSubdomains": true, "preload": true}` | [HSTS](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) options to use with HTTPS (default is the example value, max age is a year) |
+| csp | `{"enable": true, "directives": {"scriptSrc": "trustworthy-scripts.example.com"}, "upgradeInsecureRequests": "auto", "addDefaults": true}` | Configures [Content Security Policy](https://helmetjs.github.io/docs/csp/). Directives are passed to Helmet - see [their documentation](https://helmetjs.github.io/docs/csp/) for more information on the format. Some defaults are added to the configured values so that the application doesn't break. To disable this behaviour, set `addDefaults` to `false`. Further, if `usecdn` is on, some CDN locations are allowed too. By default (`auto`), insecure (HTTP) requests are upgraded to HTTPS via CSP if `usessl` is on. To change this behaviour, set `upgradeInsecureRequests` to either `true` or `false`. |
| protocolusessl | `true` or `false` | set to use ssl protocol for resources path (only applied when domain is set) |
| urladdport | `true` or `false` | set to add port on callback url (port 80 or 443 won't applied) (only applied when domain is set) |
| usecdn | `true` or `false` | set to use CDN resources or not (default is `true`) |
diff --git a/app.js b/app.js
index 37e772b..2183b14 100644
--- a/app.js
+++ b/app.js
@@ -24,6 +24,7 @@ var config = require('./lib/config')
var logger = require('./lib/logger')
var response = require('./lib/response')
var models = require('./lib/models')
+var csp = require('./lib/csp')
// generate front-end constants by template
var constpath = path.join(__dirname, './public/js/lib/common/constant.ejs')
@@ -108,6 +109,19 @@ if (config.hsts.enable) {
logger.info('https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security')
}
+// Generate a random nonce per request, for CSP with inline scripts
+app.use(csp.addNonceToLocals)
+
+// use Content-Security-Policy to limit XSS, dangerous plugins, etc.
+// https://helmetjs.github.io/docs/csp/
+if (config.csp.enable) {
+ app.use(helmet.contentSecurityPolicy({
+ directives: csp.computeDirectives()
+ }))
+} else {
+ logger.info('Content-Security-Policy is disabled. This may be a security risk.')
+}
+
i18n.configure({
locales: ['en', 'zh', 'zh-CN', 'zh-TW', 'fr', 'de', 'ja', 'es', 'ca', 'el', 'pt', 'it', 'tr', 'ru', 'nl', 'hr', 'pl', 'uk', 'hi', 'sv', 'eo', 'da'],
cookie: 'locale',
diff --git a/config.json.example b/config.json.example
index c2c270c..f5ddf18 100644
--- a/config.json.example
+++ b/config.json.example
@@ -17,10 +17,17 @@
"production": {
"domain": "localhost",
"hsts": {
- "enable": "true",
+ "enable": true,
"maxAgeSeconds": "31536000",
- "includeSubdomains": "true",
- "preload": "true"
+ "includeSubdomains": true,
+ "preload": true
+ },
+ csp: {
+ "enable": true,
+ "directives": {
+ },
+ "upgradeInsecureRequests": "auto"
+ "addDefaults": true
},
"db": {
"username": "",
diff --git a/lib/config/default.js b/lib/config/default.js
index 000c154..ec7c745 100644
--- a/lib/config/default.js
+++ b/lib/config/default.js
@@ -13,6 +13,13 @@ module.exports = {
includeSubdomains: true,
preload: true
},
+ csp: {
+ enable: true,
+ directives: {
+ },
+ addDefaults: true,
+ upgradeInsecureRequests: 'auto'
+ },
protocolusessl: false,
usecdn: true,
allowanonymous: true,
diff --git a/lib/config/environment.js b/lib/config/environment.js
index eedd491..24a85d6 100644
--- a/lib/config/environment.js
+++ b/lib/config/environment.js
@@ -14,6 +14,9 @@ module.exports = {
includeSubdomains: toBooleanConfig(process.env.HMD_HSTS_INCLUDE_SUBDOMAINS),
preload: toBooleanConfig(process.env.HMD_HSTS_PRELOAD)
},
+ csp: {
+ enable: toBooleanConfig(process.env.HMD_CSP_ENABLE)
+ },
protocolusessl: toBooleanConfig(process.env.HMD_PROTOCOL_USESSL),
alloworigin: toArrayConfig(process.env.HMD_ALLOW_ORIGIN),
usecdn: toBooleanConfig(process.env.HMD_USECDN),
diff --git a/lib/csp.js b/lib/csp.js
new file mode 100644
index 0000000..509bc53
--- /dev/null
+++ b/lib/csp.js
@@ -0,0 +1,80 @@
+var config = require('./config')
+var uuid = require('uuid')
+
+var CspStrategy = {}
+
+var defaultDirectives = {
+ defaultSrc: ['\'self\''],
+ scriptSrc: ['\'self\'', 'vimeo.com', 'https://gist.github.com', 'www.slideshare.net', 'https://query.yahooapis.com', 'https://*.disqus.com', '\'unsafe-eval\''],
+ // ^ TODO: Remove unsafe-eval - webpack script-loader issues https://github.com/hackmdio/hackmd/issues/594
+ imgSrc: ['*'],
+ styleSrc: ['\'self\'', '\'unsafe-inline\'', 'https://assets-cdn.github.com'], // unsafe-inline is required for some libs, plus used in views
+ fontSrc: ['\'self\'', 'https://public.slidesharecdn.com'],
+ objectSrc: ['*'], // Chrome PDF viewer treats PDFs as objects :/
+ childSrc: ['*'],
+ connectSrc: ['*']
+}
+
+var cdnDirectives = {
+ scriptSrc: ['https://cdnjs.cloudflare.com', 'https://cdn.mathjax.org'],
+ styleSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.googleapis.com'],
+ fontSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.gstatic.com']
+}
+
+CspStrategy.computeDirectives = function () {
+ var directives = {}
+ mergeDirectives(directives, config.csp.directives)
+ mergeDirectivesIf(config.csp.addDefaults, directives, defaultDirectives)
+ mergeDirectivesIf(config.usecdn, directives, cdnDirectives)
+ if (!areAllInlineScriptsAllowed(directives)) {
+ addInlineScriptExceptions(directives)
+ }
+ addUpgradeUnsafeRequestsOptionTo(directives)
+ return directives
+}
+
+function mergeDirectives (existingDirectives, newDirectives) {
+ for (var propertyName in newDirectives) {
+ var newDirective = newDirectives[propertyName]
+ if (newDirective) {
+ var existingDirective = existingDirectives[propertyName] || []
+ existingDirectives[propertyName] = existingDirective.concat(newDirective)
+ }
+ }
+}
+
+function mergeDirectivesIf (condition, existingDirectives, newDirectives) {
+ if (condition) {
+ mergeDirectives(existingDirectives, newDirectives)
+ }
+}
+
+function areAllInlineScriptsAllowed (directives) {
+ return directives.scriptSrc.indexOf('\'unsafe-inline\'') !== -1
+}
+
+function addInlineScriptExceptions (directives) {
+ directives.scriptSrc.push(getCspNonce)
+ // TODO: This is the SHA-256 hash of the inline script in build/reveal.js/plugins/notes/notes.html
+ // Any more clean solution appreciated.
+ directives.scriptSrc.push('\'sha256-EtvSSxRwce5cLeFBZbvZvDrTiRoyoXbWWwvEVciM5Ag=\'')
+}
+
+function getCspNonce (req, res) {
+ return "'nonce-" + res.locals.nonce + "'"
+}
+
+function addUpgradeUnsafeRequestsOptionTo (directives) {
+ if (config.csp.upgradeInsecureRequests === 'auto' && config.usessl) {
+ directives.upgradeInsecureRequests = true
+ } else if (config.csp.upgradeInsecureRequests === true) {
+ directives.upgradeInsecureRequests = true
+ }
+}
+
+CspStrategy.addNonceToLocals = function (req, res, next) {
+ res.locals.nonce = uuid.v4()
+ next()
+}
+
+module.exports = CspStrategy
diff --git a/lib/response.js b/lib/response.js
index 1c04f9f..445aa0d 100644
--- a/lib/response.js
+++ b/lib/response.js
@@ -598,7 +598,8 @@ function showPublishSlide (req, res, next) {
lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
robots: meta.robots || false, // default allow robots
GA: meta.GA,
- disqus: meta.disqus
+ disqus: meta.disqus,
+ cspNonce: res.locals.nonce
}
return renderPublishSlide(data, res)
}).catch(function (err) {
diff --git a/package.json b/package.json
index bdb5963..885eee9 100644
--- a/package.json
+++ b/package.json
@@ -118,6 +118,7 @@
"tedious": "^1.14.0",
"to-markdown": "^3.0.3",
"toobusy-js": "^0.5.1",
+ "uuid": "^3.1.0",
"uws": "~0.14.1",
"validator": "^6.2.0",
"velocity-animate": "^1.4.0",
diff --git a/public/js/mathjax-config-extra.js b/public/js/mathjax-config-extra.js
new file mode 100644
index 0000000..11ba59c
--- /dev/null
+++ b/public/js/mathjax-config-extra.js
@@ -0,0 +1,8 @@
+window.MathJax = {
+ messageStyle: 'none',
+ skipStartupTypeset: true,
+ tex2jax: {
+ inlineMath: [['$', '$'], ['\\(', '\\)']],
+ processEscapes: true
+ }
+}
diff --git a/public/views/hackmd/foot.ejs b/public/views/hackmd/foot.ejs
index 16ef573..fc97113 100644
--- a/public/views/hackmd/foot.ejs
+++ b/public/views/hackmd/foot.ejs
@@ -1,6 +1,4 @@
-
+
<% if(useCDN) { %>
diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs
index db72fdc..91d9c36 100644
--- a/public/views/pretty.ejs
+++ b/public/views/pretty.ejs
@@ -72,9 +72,7 @@