I am using the DOMParser in my code as such:
html`${this.domParser.parseFromString(this.richText, 'text/html').body.children}`
After reading the documentation i became a bit worried that Cross site Scripting attacks
were still possible because as the documentation states:
You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.
However it also states that it returns
Either Document or XMLDocument depending on the mimeType argument.
So is using this method going good for securing your site against XSS
?
I am using the DOMParser in my code as such:
html`${this.domParser.parseFromString(this.richText, 'text/html').body.children}`
After reading the documentation i became a bit worried that Cross site Scripting attacks
were still possible because as the documentation states:
You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.
However it also states that it returns
Either Document or XMLDocument depending on the mimeType argument.
So is using this method going good for securing your site against XSS
?
2 Answers
Reset to default 10DOMParser
created documents are created with scripting disabled; the script is parsed, but not run, so it should be safe against XSS. That said, if you're doing this server-side and serving the result to a client, the client won't know about the "noscript" context, so it could be a source of vulnerabilities in the right context.
In this introductory article on trusted-types we can see that DOMParser#parseFromString
is a known XSS sink.
The <script>
blocks won't execute but the parser is unable to tell what constitutes an XSS threat.
You cannot use it to safely inject html into a page:
const parser = new DOMParser();
const html = '<img onerror="alert(`gotcha`)" src="">';
const new_node = parser.parseFromString(html, 'text/html').body.firstChild;
document.querySelector('div').appendChild(new_node);
<div></div>
How to sanitize HTML?
You can use a purpose-built library such as dompurify:
const dirty = '<img onerror="alert(`gotcha`)" src="">';
const clean = DOMPurify.sanitize(dirty);
console.log(clean);
<script src="https://unpkg.com/[email protected]/dist/purify.min.js"></script>
html
doing? Are you appending the result of this parsed document into the main document? If so, DOMParser doesn't offer any protection against XSS. – Kaiido Commented Nov 15, 2020 at 11:30