Skip to content

Commit 04f5e3a

Browse files
committed
Move CSP logic to new file, Fix boolean config examples
Not sure why I was quoting these in the first place
1 parent e5f03fe commit 04f5e3a

5 files changed

Lines changed: 91 additions & 81 deletions

File tree

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,8 @@ Application settings `config.json`
171171
| port | `80` | web app port |
172172
| alloworigin | `['localhost']` | domain name whitelist |
173173
| usessl | `true` or `false` | set to use ssl server (if true will auto turn on `protocolusessl`) |
174-
| 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) |
175-
| csp | `{"enable": "true", "directives": {"scriptSrc": "trustwodthy-scripts.example.com"}, "upgradeInsecureRequests": "auto", "addDefaults": "true"}` | Configures [Content Security Policy](https://helmetjs.github.io/docs/csp/). Directives are directly passed to Helmet, so [their format](https://helmetjs.github.io/docs/csp/) applies. Further, some defaults are added so that the application doesn't break. To disable adding these defaults, set `addDefaults` to `false`. If `usecdn` is on, default 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`. |
174+
| 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) |
175+
| 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`. |
176176
| protocolusessl | `true` or `false` | set to use ssl protocol for resources path (only applied when domain is set) |
177177
| urladdport | `true` or `false` | set to add port on callback url (port 80 or 443 won't applied) (only applied when domain is set) |
178178
| usecdn | `true` or `false` | set to use CDN resources or not (default is `true`) |

app.js

Lines changed: 4 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ var session = require('express-session')
1212
var SequelizeStore = require('connect-session-sequelize')(session.Store)
1313
var fs = require('fs')
1414
var path = require('path')
15-
var uuid = require('uuid')
1615

1716
var morgan = require('morgan')
1817
var passportSocketIo = require('passport.socketio')
@@ -25,6 +24,7 @@ var config = require('./lib/config')
2524
var logger = require('./lib/logger')
2625
var response = require('./lib/response')
2726
var models = require('./lib/models')
27+
var csp = require('./lib/csp')
2828

2929
// generate front-end constants by template
3030
var constpath = path.join(__dirname, './public/js/lib/common/constant.ejs')
@@ -109,83 +109,14 @@ if (config.hsts.enable) {
109109
logger.info('https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security')
110110
}
111111

112-
app.use((req, res, next) => {
113-
res.locals.nonce = uuid.v4()
114-
next()
115-
})
112+
// Generate a random nonce per request, for CSP with inline scripts
113+
app.use(csp.addNonceToLocals)
116114

117115
// use Content-Security-Policy to limit XSS, dangerous plugins, etc.
118116
// https://helmetjs.github.io/docs/csp/
119-
function getCspNonce (req, res) {
120-
return "'nonce-" + res.locals.nonce + "'"
121-
}
122-
123-
function getCspWebSocketUrl (req, res) {
124-
// wss: is included in 'self', but 'ws:' is not
125-
return (req.protocol === 'http' ? 'ws:' : 'wss:') + config.serverurl.replace(/https?:/, "")
126-
}
127-
128-
function mergeWithDefaults(configured, defaultDirective, cdnDirective) {
129-
var directive = [].concat(configured)
130-
if (config.csp.addDefaults && defaultDirective) {
131-
directive = directive.concat(defaultDirective)
132-
}
133-
if (config.usecdn && cdnDirective) {
134-
directive = directive.concat(cdnDirective)
135-
}
136-
return directive
137-
}
138-
139117
if (config.csp.enable) {
140-
var defaultDirectives = {
141-
defaultSrc: ['\'self\''],
142-
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
143-
imgSrc: ['*'],
144-
styleSrc: ['\'self\'', '\'unsafe-inline\'', 'https://assets-cdn.github.com'], // unsafe-inline is required for some libs, plus used in views
145-
fontSrc: ['\'self\'', 'https://public.slidesharecdn.com'],
146-
objectSrc: ['*'], // Chrome PDF viewer treats PDFs as objects :/
147-
childSrc: ['*'],
148-
connectSrc: ['*']
149-
};
150-
var cdnDirectives = {
151-
scriptSrc: ['https://cdnjs.cloudflare.com', 'https://cdn.mathjax.org'],
152-
styleSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.googleapis.com'],
153-
fontSrc: ['https://cdnjs.cloudflare.com', 'https://fonts.gstatic.com']
154-
}
155-
var directives = {}
156-
for (var propertyName in config.csp.directives) {
157-
if (config.csp.directives.hasOwnProperty(propertyName)) {
158-
directives[propertyName] = mergeWithDefaults(
159-
config.csp.directives[propertyName],
160-
defaultDirectives[propertyName],
161-
cdnDirectives[propertyName]
162-
)
163-
}
164-
}
165-
for (var propertyName in defaultDirectives) {
166-
if (!directives[propertyName]) {
167-
directives[propertyName] = mergeWithDefaults(
168-
[],
169-
defaultDirectives[propertyName],
170-
cdnDirectives[propertyName]
171-
)
172-
}
173-
}
174-
if (directives.scriptSrc.indexOf('\'unsafe-inline\'') === -1) {
175-
directives.scriptSrc.push(getCspNonce)
176-
// TODO: This is the SHA-256 hash of the inline script in
177-
// build/reveal.js/plugins/notes/notes.html . Any cleaner
178-
// solution appreciated.
179-
directives.scriptSrc.push('\'sha256-EtvSSxRwce5cLeFBZbvZvDrTiRoyoXbWWwvEVciM5Ag=\'')
180-
}
181-
directives.connectSrc.push(getCspWebSocketUrl)
182-
if (config.csp.upgradeInsecureRequests === 'auto') {
183-
directives.upgradeInsecureRequests = config.usessl === 'true'
184-
} else {
185-
directives.upgradeInsecureRequests = config.csp.upgradeInsecureRequests === 'true'
186-
}
187118
app.use(helmet.contentSecurityPolicy({
188-
directives: directives
119+
directives: csp.computeDirectives()
189120
}))
190121
} else {
191122
logger.info('Content-Security-Policy is disabled. This may be a security risk.')

config.json.example

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +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
2424
},
2525
csp: {
26-
"enable": "true",
26+
"enable": true,
2727
"directives": {
2828
},
2929
"upgradeInsecureRequests": "auto"
30-
"addDefaults": "true"
30+
"addDefaults": true
3131
},
3232
"db": {
3333
"username": "",

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

public/js/index.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
modeType, Idle, serverurl, key, gapi, Dropbox, FilePicker
44
ot, MediaUploader, hex2rgb, num_loaded, Visibility */
55

6-
76
require('../vendor/showup/showup')
87

98
require('../css/index.css')

0 commit comments

Comments
 (0)