Search code examples
javascripthtmlsecurityxsswebsecurity

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


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?


Solution

  • 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 onerror="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.