Home > Mobile >  XSS - Does loading external HTML by setting innerHTML on DOM element prevent attack?
XSS - Does loading external HTML by setting innerHTML on DOM element prevent attack?

Time:03-25

If I will need to load some untrusted external HTML content and render them on the DOM, will using the innerHTML property be adequate protection against malicious scripts?

Through my own testing and this article, <script> tags inside HTML that is set via innerHTML to an existing element in the DOM (main or shadow) is not executed. So even if the script is there, would not executing it prevent security risks?

For added measure, it can also help to find all <script> tags and remove them in the DOM. Is this even necessary?

CodePudding user response:

No, that's not good enough. Inline handlers can still execute - most notably, those that'll execute immediately. For example:

const untrustworthyContent = `
<div>
  <img src one rror="alert('evil');">
</div>
`;
document.querySelector('div').innerHTML = untrustworthyContent;
<div></div>

And anything can be put into such an inline handler attribute, including loading other malicious scripts.

For added measure, it can also help to find all tags and remove them in the DOM. Is this even necessary?

Best to do it thoroughly. Remove all <script> tags and inline handlers before even thinking about rendering.

  • Related