Skip to content

Commit 7de6e32

Browse files
authored
Merge pull request #598 from xxyy/feature/csp
Implement basic CSP support
2 parents fbfe327 + 3a752fd commit 7de6e32

12 files changed

Lines changed: 132 additions & 15 deletions

File tree

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ There are some configs you need to change in the files below
197197
| HMD_HSTS_INCLUDE_SUBDOMAINS | `true` | set to include subdomains in HSTS (default is `true`) |
198198
| HMD_HSTS_MAX_AGE | `31536000` | max duration in seconds to tell clients to keep HSTS status (default is a year) |
199199
| HMD_HSTS_PRELOAD | `true` | whether to allow preloading of the site's HSTS status (e.g. into browsers) |
200+
| HMD_CSP_ENABLE | `true` | whether to enable Content Security Policy (directives cannot be configured with environment variables) |
200201

201202
## Application settings `config.json`
202203

@@ -208,7 +209,8 @@ There are some configs you need to change in the files below
208209
| port | `80` | web app port |
209210
| alloworigin | `['localhost']` | domain name whitelist |
210211
| usessl | `true` or `false` | set to use ssl server (if true will auto turn on `protocolusessl`) |
211-
| 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) |
212+
| 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) |
213+
| 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`. |
212214
| protocolusessl | `true` or `false` | set to use ssl protocol for resources path (only applied when domain is set) |
213215
| urladdport | `true` or `false` | set to add port on callback url (port 80 or 443 won't applied) (only applied when domain is set) |
214216
| usecdn | `true` or `false` | set to use CDN resources or not (default is `true`) |

app.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ var config = require('./lib/config')
2424
var logger = require('./lib/logger')
2525
var response = require('./lib/response')
2626
var models = require('./lib/models')
27+
var csp = require('./lib/csp')
2728

2829
// generate front-end constants by template
2930
var constpath = path.join(__dirname, './public/js/lib/common/constant.ejs')
@@ -108,6 +109,19 @@ if (config.hsts.enable) {
108109
logger.info('https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security')
109110
}
110111

112+
// Generate a random nonce per request, for CSP with inline scripts
113+
app.use(csp.addNonceToLocals)
114+
115+
// use Content-Security-Policy to limit XSS, dangerous plugins, etc.
116+
// https://helmetjs.github.io/docs/csp/
117+
if (config.csp.enable) {
118+
app.use(helmet.contentSecurityPolicy({
119+
directives: csp.computeDirectives()
120+
}))
121+
} else {
122+
logger.info('Content-Security-Policy is disabled. This may be a security risk.')
123+
}
124+
111125
i18n.configure({
112126
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'],
113127
cookie: 'locale',

config.json.example

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,17 @@
1717
"production": {
1818
"domain": "localhost",
1919
"hsts": {
20-
"enable": "true",
20+
"enable": true,
2121
"maxAgeSeconds": "31536000",
22-
"includeSubdomains": "true",
23-
"preload": "true"
22+
"includeSubdomains": true,
23+
"preload": true
24+
},
25+
csp: {
26+
"enable": true,
27+
"directives": {
28+
},
29+
"upgradeInsecureRequests": "auto"
30+
"addDefaults": true
2431
},
2532
"db": {
2633
"username": "",

lib/config/default.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ module.exports = {
1313
includeSubdomains: true,
1414
preload: true
1515
},
16+
csp: {
17+
enable: true,
18+
directives: {
19+
},
20+
addDefaults: true,
21+
upgradeInsecureRequests: 'auto'
22+
},
1623
protocolusessl: false,
1724
usecdn: true,
1825
allowanonymous: true,

lib/config/environment.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ module.exports = {
1414
includeSubdomains: toBooleanConfig(process.env.HMD_HSTS_INCLUDE_SUBDOMAINS),
1515
preload: toBooleanConfig(process.env.HMD_HSTS_PRELOAD)
1616
},
17+
csp: {
18+
enable: toBooleanConfig(process.env.HMD_CSP_ENABLE)
19+
},
1720
protocolusessl: toBooleanConfig(process.env.HMD_PROTOCOL_USESSL),
1821
alloworigin: toArrayConfig(process.env.HMD_ALLOW_ORIGIN),
1922
usecdn: toBooleanConfig(process.env.HMD_USECDN),

lib/csp.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
var config = require('./config')
2+
var uuid = require('uuid')
3+
4+
var CspStrategy = {}
5+
6+
var defaultDirectives = {
7+
defaultSrc: ['\'self\''],
8+
scriptSrc: ['\'self\'', 'vimeo.com', 'https://gist.github.com', 'www.slideshare.net', 'https://query.yahooapis.com', 'https://*.disqus.com', '\'unsafe-eval\''],
9+
// ^ TODO: Remove unsafe-eval - webpack script-loader issues https://github.com/hackmdio/hackmd/issues/594
10+
imgSrc: ['*'],
11+
styleSrc: ['\'self\'', '\'unsafe-inline\'', 'https://assets-cdn.github.com'], // unsafe-inline is required for some libs, plus used in views
12+
fontSrc: ['\'self\'', 'https://public.slidesharecdn.com'],
13+
objectSrc: ['*'], // Chrome PDF viewer treats PDFs as objects :/
14+
childSrc: ['*'],
15+
connectSrc: ['*']
16+
}
17+
18+
var cdnDirectives = {
19+
scriptSrc: ['https://cdnjs.cloudflare.com', 'https://cdn.mathjax.org'],
20+
styleSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.googleapis.com'],
21+
fontSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.gstatic.com']
22+
}
23+
24+
CspStrategy.computeDirectives = function () {
25+
var directives = {}
26+
mergeDirectives(directives, config.csp.directives)
27+
mergeDirectivesIf(config.csp.addDefaults, directives, defaultDirectives)
28+
mergeDirectivesIf(config.usecdn, directives, cdnDirectives)
29+
if (!areAllInlineScriptsAllowed(directives)) {
30+
addInlineScriptExceptions(directives)
31+
}
32+
addUpgradeUnsafeRequestsOptionTo(directives)
33+
return directives
34+
}
35+
36+
function mergeDirectives (existingDirectives, newDirectives) {
37+
for (var propertyName in newDirectives) {
38+
var newDirective = newDirectives[propertyName]
39+
if (newDirective) {
40+
var existingDirective = existingDirectives[propertyName] || []
41+
existingDirectives[propertyName] = existingDirective.concat(newDirective)
42+
}
43+
}
44+
}
45+
46+
function mergeDirectivesIf (condition, existingDirectives, newDirectives) {
47+
if (condition) {
48+
mergeDirectives(existingDirectives, newDirectives)
49+
}
50+
}
51+
52+
function areAllInlineScriptsAllowed (directives) {
53+
return directives.scriptSrc.indexOf('\'unsafe-inline\'') !== -1
54+
}
55+
56+
function addInlineScriptExceptions (directives) {
57+
directives.scriptSrc.push(getCspNonce)
58+
// TODO: This is the SHA-256 hash of the inline script in build/reveal.js/plugins/notes/notes.html
59+
// Any more clean solution appreciated.
60+
directives.scriptSrc.push('\'sha256-EtvSSxRwce5cLeFBZbvZvDrTiRoyoXbWWwvEVciM5Ag=\'')
61+
}
62+
63+
function getCspNonce (req, res) {
64+
return "'nonce-" + res.locals.nonce + "'"
65+
}
66+
67+
function addUpgradeUnsafeRequestsOptionTo (directives) {
68+
if (config.csp.upgradeInsecureRequests === 'auto' && config.usessl) {
69+
directives.upgradeInsecureRequests = true
70+
} else if (config.csp.upgradeInsecureRequests === true) {
71+
directives.upgradeInsecureRequests = true
72+
}
73+
}
74+
75+
CspStrategy.addNonceToLocals = function (req, res, next) {
76+
res.locals.nonce = uuid.v4()
77+
next()
78+
}
79+
80+
module.exports = CspStrategy

lib/response.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,8 @@ function showPublishSlide (req, res, next) {
598598
lastchangeuserprofile: note.lastchangeuser ? models.User.getProfile(note.lastchangeuser) : null,
599599
robots: meta.robots || false, // default allow robots
600600
GA: meta.GA,
601-
disqus: meta.disqus
601+
disqus: meta.disqus,
602+
cspNonce: res.locals.nonce
602603
}
603604
return renderPublishSlide(data, res)
604605
}).catch(function (err) {

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@
118118
"tedious": "^1.14.0",
119119
"to-markdown": "^3.0.3",
120120
"toobusy-js": "^0.5.1",
121+
"uuid": "^3.1.0",
121122
"uws": "~0.14.1",
122123
"validator": "^6.2.0",
123124
"velocity-animate": "^1.4.0",

public/js/mathjax-config-extra.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
window.MathJax = {
2+
messageStyle: 'none',
3+
skipStartupTypeset: true,
4+
tex2jax: {
5+
inlineMath: [['$', '$'], ['\\(', '\\)']],
6+
processEscapes: true
7+
}
8+
}

public/views/hackmd/foot.ejs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
<script type="text/x-mathjax-config">
2-
MathJax.Hub.Config({ messageStyle: "none", skipStartupTypeset: true ,tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']], processEscapes: true }});
3-
</script>
1+
<script src="<%= url %>/js/mathjax-config-extra.js"></script>
42
<% if(useCDN) { %>
53
<script src="https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js" integrity="sha256-PieqE0QdEDMppwXrTzSZQr6tWFX3W5KkyRVyF1zN3eg=" crossorigin="anonymous" defer></script>
64
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>

0 commit comments

Comments
 (0)