Exception text reinterpreted as HTMLΒΆ
ID: js/xss-through-exception
Kind: path-problem
Security severity: 6.1
Severity: warning
Precision: high
Tags:
- security
- external/cwe/cwe-079
- external/cwe/cwe-116
Query suites:
- javascript-code-scanning.qls
- javascript-security-extended.qls
- javascript-security-and-quality.qls
Click to see the query in the CodeQL repository
Directly writing error messages to a webpage without sanitization allows for a cross-site scripting vulnerability if parts of the error message can be influenced by a user.
RecommendationΒΆ
To guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the page, or one of the other solutions that are mentioned in the references.
ExampleΒΆ
The following example shows an exception being written directly to the document, and this exception can potentially be influenced by the page URL, leaving the website vulnerable to cross-site scripting.
function setLanguageOptions() {
var href = document.location.href,
deflt = href.substring(href.indexOf("default=")+8);
try {
var parsed = unknownParseFunction(deflt);
} catch(e) {
document.write("Had an error: " + e + ".");
}
}
ExampleΒΆ
This second example shows an input being validated using the JSON schema validator ajv
, and in case of an error, the error message is sent directly back in the response.
import express from 'express';
import Ajv from 'ajv';
let app = express();
let ajv = new Ajv();
ajv.addSchema({type: 'object', additionalProperties: {type: 'number'}}, 'pollData');
app.post('/polldata', (req, res) => {
if (!ajv.validate('pollData', req.body)) {
res.send(ajv.errorsText());
}
});
This is unsafe, because the error message can contain parts of the input. For example, the input {'<img src=x onerror=alert(1)>': 'foo'}
will generate the error data/<img src=x onerror=alert(1)> should be number
, causing reflected XSS.
ReferencesΒΆ
OWASP DOM Based XSS.
Wikipedia: Cross-site scripting.
Common Weakness Enumeration: CWE-79.
Common Weakness Enumeration: CWE-116.