I am trying to fix the Checkmarx scanning tool reported issue, I tried to sanitized the err as well as req in the below route module. However, it still complains about the same error.
index.js
const express = require('express')
const router = express.Router()
const fs = require('fs')
const config = require('config')
var _require = require('jsdom'),
JSDOM = _require.JSDOM;
var window = new JSDOM('').window;
var DOMPurify = createDOMPurify(window);
function sanitizeError(value){
return DOMPurify.sanitize(value);
}
function sanitizeObject(obj) {
var sanitizedObject = {};
Object.keys(obj).forEach(function (key) {
sanitizedObject[key] = sanitizeValue(obj[key]);
});
return sanitizedObject;
};
//error handler route
router.use('/error',(err, req, res, next) => {
//sanitizeObject(req)
req.logger.error('uncaught error page', sanitizeError(err))
res.redirect('/toanotehrerror page')
})
module.exports = router
Checkmarx Error:
Reflected_XSS error. It is referring to the line req.logger.error
in the above module
The application's router.use embeds untrusted data in the generated output with error, at line x of \routes\index.js. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.
The attacker would be able to alter the returned web page by simply providing modified data in the user input error, which is read by the router.use method at line x of \routes\index.js. This input then flows through the code straight to the output web page, without sanitization.
This can enable a Reflected Cross-Site Scripting (XSS) attack.
Checkmarx does not have DOMPurify in the list of its recognized sanitizers. What it does recognize are the ESAPI library, xss-filters and htmlescape packages
https://www.npmjs.com/package/xss-filters
https://www.npmjs.com/package/node-esapi
https://www.npmjs.com/package/htmlescape
While technically your code can prevent XSS, I would rewrite it using using any of the packages above. For instance if we are to use xss-filters:
var xssFilters = require('xss-filters');
function sanitizeError(value){
return xssFilters.inHTMLData(value);
}