Merge pull request #598 from xxyy/feature/csp

Implement basic CSP support
This commit is contained in:
Christoph (Sheogorath) Kern 2018-01-22 20:43:46 +01:00 committed by GitHub
commit 7de6e3211f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 132 additions and 15 deletions

View File

@ -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`) |

14
app.js
View File

@ -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',

View File

@ -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": "",

View File

@ -13,6 +13,13 @@ module.exports = {
includeSubdomains: true,
preload: true
},
csp: {
enable: true,
directives: {
},
addDefaults: true,
upgradeInsecureRequests: 'auto'
},
protocolusessl: false,
usecdn: true,
allowanonymous: true,

View File

@ -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),

80
lib/csp.js Normal file
View File

@ -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

View File

@ -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) {

View File

@ -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",

View File

@ -0,0 +1,8 @@
window.MathJax = {
messageStyle: 'none',
skipStartupTypeset: true,
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
processEscapes: true
}
}

View File

@ -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>

View File

@ -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>

View File

@ -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>