Reputation: 37
I have a JavaScript AJAX call that pulls in HTML code into an MVC form.
Coverity flags that because it wants me to sanitize JavaScript tags. Quite rightly because you don't want some hacker to go in and mess things right up.
I put in a Trusted HTML Policy. That satisfies Coverity. But now the HTML code shows up as plain-text on the screen.
So $(target).html(result)
is no longer behaving how I expected it to.
I tried different methods: innerHTML
, $.parseHTML()
and .text().html()
all do not give me the desired results.
I even commented out the TrustedHTML policy and put in a replace function instead. That didn't work.
All I have is a string of HTML showing up as plain text on the screen.
I comment out the TrustedHTML and the replace function and it works as intended. But Coverity hates it.
Upvotes: 0
Views: 832
Reputation: 37
After a few days of doing some workshopping with this problem, I have used the following and it seems to satisfy Coverity.
Treat this as a bare bones solution. Coverity wants a Trusted HTML policy. The programmer will need to beef it up to remediate any and all security issues that arise.
const escapeHTMLPolicy =
trustedTypes.createPolicy("newEscapePolicy", {
createHTML: (string) => {
const policyWhitelist = [];
// be sure to escape your whitelisted data
policyWhitelist.push("<script type=\"text/javascript\">");
// . . . other functioning to clear up
// other vulnerabilities . . .
// This will now return trusted HTML data along with anything you wish to whitelist.
if (string.includes("<script") && !policyWhitelist.some(item => string === item)) {
string.replace(/<script.*/g, "")
}
return string;
}
});
Use this function like so:
$.ajax({
// something . . .
success: function (response) {
var htmlContent = escapeHTMLPolicy.createHTML(response);
var htmlNode = htmlContent.toString();
$(targetDiv).html(htmlNode);
}
});
Upvotes: -3