最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is parsing HTML with DOMParser safe from XSS? - Stack Overflow

programmeradmin0浏览0评论

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?

Share Improve this question edited Nov 15, 2020 at 11:07 customcommander 18.9k5 gold badges67 silver badges93 bronze badges asked Nov 10, 2020 at 15:57 Marc RasmussenMarc Rasmussen 20.6k83 gold badges221 silver badges382 bronze badges 1
  • 1 What is 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
Add a comment  | 

2 Answers 2

Reset to default 10

DOMParser 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>

发布评论

评论列表(0)

  1. 暂无评论