summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md4
-rw-r--r--app.js14
-rw-r--r--config.json.example13
-rw-r--r--lib/config/default.js7
-rw-r--r--lib/config/environment.js3
-rw-r--r--lib/csp.js80
-rw-r--r--lib/response.js3
-rw-r--r--package.json1
-rw-r--r--public/js/mathjax-config-extra.js8
-rw-r--r--public/views/hackmd/foot.ejs4
-rw-r--r--public/views/pretty.ejs4
-rw-r--r--public/views/slide.ejs6
12 files changed, 132 insertions, 15 deletions
diff --git a/README.md b/README.md
index 1e7d79ab..fb1f8e3d 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 37e772bc..2183b149 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 c2c270c3..f5ddf182 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 000c154a..ec7c7451 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 eedd4913..24a85d65 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 00000000..509bc530
--- /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 1c04f9f6..445aa0d7 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 bdb59635..885eee92 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 00000000..11ba59c6
--- /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 16ef5737..fc971132 100644
--- a/public/views/hackmd/foot.ejs
+++ b/public/views/hackmd/foot.ejs
@@ -1,6 +1,4 @@
-<script type="text/x-mathjax-config">
- MathJax.Hub.Config({ messageStyle: "none", skipStartupTypeset: true ,tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true }});
-</script>
+<script src="<%= url %>/js/mathjax-config-extra.js"></script>
<% if(useCDN) { %>
<script src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js" integrity="sha256-PieqE0QdEDMppwXrTzSZQr6tWFX3W5KkyRVyF1zN3eg=" crossorigin="anonymous" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
diff --git a/public/views/pretty.ejs b/public/views/pretty.ejs
index db72fdc4..91d9c36c 100644
--- a/public/views/pretty.ejs
+++ b/public/views/pretty.ejs
@@ -72,9 +72,7 @@
</body>
</html>
-<script type="text/x-mathjax-config">
- MathJax.Hub.Config({ messageStyle: "none", skipStartupTypeset: true ,tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true }});
-</script>
+<script src="<%= url %>/js/mathjax-config-extra.js"></script>
<% if(useCDN) { %>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.4.0/velocity.min.js" integrity="sha256-bhm0lgEt6ITaZCDzZpkr/VXVrLa5RP4u9v2AYsbzSUk=" crossorigin="anonymous" defer></script>
diff --git a/public/views/slide.ejs b/public/views/slide.ejs
index 3572476f..942add4f 100644
--- a/public/views/slide.ejs
+++ b/public/views/slide.ejs
@@ -41,7 +41,7 @@
<link rel="stylesheet" href="<%- url %>/css/slide.css">
<!-- Printing and PDF exports -->
- <script>
+ <script nonce="<%= cspNonce %>">
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
@@ -89,9 +89,7 @@
</div>
</div>
- <script type="text/x-mathjax-config">
- MathJax.Hub.Config({ messageStyle: "none", skipStartupTypeset: true ,tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true }});
- </script>
+ <script src="<%= url %>/js/mathjax-config-extra.js"></script>
<% if(useCDN) { %>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.3.0/lib/js/head.min.js" integrity="sha256-+09kLhwACKXFPDvqo4xMMvi4+uXFsRZ2uYGbeN1U8sI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reveal.js/3.3.0/js/reveal.min.js" integrity="sha256-lvaInSKflJWLPqf5N5oHr/UZFwXKD6gckerdwoHqECY=" crossorigin="anonymous"></script>