Supported JavaScript cleansing functions
Function | Documentation | Flaw class |
---|---|---|
DOMPurify.sanitize | DOMPurify on github.com, DOMPurify on owasp.org | CWE-80 |
encodeURI | encodeURI on developer.mozilla.org | CWE-80, 93, 113, and 117 |
encodeURIComponent | encodeURI on developer.mozilla.org | CWE-80, 93, 113, and 117 |
JSON.stringify | JSON.stringify on developer.mozilla.org | CWE-117 |
vcEncodeHtml | See below | CWE-80 |
Preventing cross-site scripting with text nodes
Veracode Static Analysis automatically detects the proper use of text nodes, as described in MDN Web Docs:
- https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
- https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext
Using text nodes automatically resolves cross-site scripting flaws (CWE-80). In addition to strict data validation, it is the best approach for cross-site scripting prevention in a browser context.
The following code example uses built-in browser web APIs to demonstrate proper usage of text nodes to protect your code from cross-site scripting attacks:
const response = await fetch("//reversegeocoding/lat/lon");
const json = await response.json();
const address = json.address;
// validation logic for address omitted, will be different depending on a region
if (isValidAddress(address) === true) {
const addressElement = document.getElementById("address-display");
// this snippet will be safe even in the the case that validation fails to protect from malicious data potentially embedded in the address
addressElement.textContent = address;
} else {
// log an error and setup alerting on the backend - a service may have been compromised!
}
A similar approach is available in libraries or frameworks like jQuery.
The vcEncodeHtml
helper function
You can use a function similar to the following to pass data through a text node to force the browser to HTML encode.
const dangerousUserData = decodeURIComponent(window.location.hash.substring(1));
const safelyEncodedData = vcEncodeHtml(dangerousUserData);
const myHtml = `<p>${safelyEncodedData}</p>`;
document.write(myHtml);
/**
* Encode String to HTML encoded String.
*
* Use TextNode to let browser do encoding.
* Copied from: https://docs.veracode.com
* @param {string} value String to encode
* @returns {string} Encoded string
*/
function vcEncodeHtml(value) {
var text = document.createTextNode(value);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}
This function does not already exist, so you must copy it or implement a similar function. Veracode Static Analysis detects the technique regardless of what the function is named.