hedgedoc/lib/web/imageRouter/index.js
Sheogorath dc29a286e6
Fix arbitary file upload for uploadimage API endpoint
This patch fixes a security issue with all existing CodiMD and HedgeDoc
installation which allows arbitary file uploads to instances that expose
the `/uploadimage` API endpoint. With the patch it implies the same
restrictions on the MIME-types as the frontend does. Means only images
are allowed unless configured differently.

This issue was reported by Thomas Lambertz.

To verify if you are vulnerable or not, create two files `test.html` and
`test.png` and try to upload them to your hedgedoc installation.

```
curl -X POST -F "image=@$(pwd)/test.html" http://localhost:3000/uploadimage
curl -X POST -F "image=@$(pwd)/test.png" http://localhost:3000/uploadimage
```

Note: Not all backends are affected. Imgur and lutim should prevent this
by their own upload API. But S3, minio, filesystem and azure, will be at
risk.

Addition Note: When using filesystem instead of an external uploads
providers, there is a higher risk of code injections as the default CSP
do not block JS from the main domain.

References:
https://github.com/hedgedoc/hedgedoc/security/advisories/GHSA-wcr3-xhv7-8gxc

Signed-off-by: Christoph Kern <sheogorath@shivering-isles.com>
2020-12-27 19:51:01 +01:00

49 lines
1.6 KiB
JavaScript

'use strict'
const Router = require('express').Router
const formidable = require('formidable')
const config = require('../../config')
const logger = require('../../logger')
const errors = require('../../errors')
const imageRouter = module.exports = Router()
// upload image
imageRouter.post('/uploadimage', function (req, res) {
var form = new formidable.IncomingForm()
form.keepExtensions = true
if (config.imageUploadType === 'filesystem') {
form.uploadDir = config.uploadsPath
}
form.parse(req, function (err, fields, files) {
if (err) {
logger.error(`formidable error: ${err}`)
return errors.errorForbidden(res)
} else if (!files.image || !files.image.path) {
logger.error(`formidable error: Upload didn't contain file)`)
return errors.errorBadRequest(res)
} else if (!config.allowedUploadMimeTypes.includes(files.image.type)) {
logger.error(`formidable error: MIME-type "${files.image.type}" of uploaded file not allowed, only "${config.allowedUploadMimeTypes.join(', ')}" are allowed)`)
return errors.errorBadRequest(res)
} else {
logger.debug(`SERVER received uploadimage: ${JSON.stringify(files.image)}`)
const uploadProvider = require('./' + config.imageUploadType)
logger.debug(`imageRouter: Uploading ${files.image.path} using ${config.imageUploadType}`)
uploadProvider.uploadImage(files.image.path, function (err, url) {
if (err !== null) {
logger.error(err)
return res.status(500).end('upload image error')
}
logger.debug(`SERVER sending ${url} to client`)
res.send({
link: url
})
})
}
})
})