DOM innerHTML Vulnerability
The inner HTML property is part of the Document Object Model (DOM) that allows Javascript code to manipulate a website. To be specific, it allows reading and replacing everything within a given DOM element (HTML tag).
However, DOM manipulation using innerHTML is more failure-prone than manipulations based on individual DOM objects. I want to focus on the vulnerability aspect to it.
Let’s say you’re using JavaScript DOM to create HTML, and you decided to use innerHTML instead of creating each element individually. You risk the sanctity of your site because innerHTML can be manipulated to inject additional unintended HTML/Script Tags that may contain viruses or malicious attacks.
One such attack is Cross-Site Scripting.
Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.
An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site. These scripts can even rewrite the content of the HTML page.
The idea behind an XSS attack within innerHTML is that malicious code would get injected into your site and then execute. This is possible because innerHTML renders complete markup and not just text.
Users can potentially put something malicious into your API via your innerHTML (if u create a form and innerHTML it onto a div) because they can rewrite the form with links . Or even just write HTML that the API wasn’t suppose to catch.
InnerHTML is dangerous security wise because if someone with malicious intent comes along, and decides to change it, you just gave them a whole chunk of “open space” to work with, they just have to delete your code, and write whatever tags with links and put it as the new innerHTML or your code block.
One super easy approach: use textContent
instead of innerHTML
. This gets and injects only text content, not markup, from and into a DOM node.
At the end of the day, An ounce of prevention is worth a pound of cure. Write out your hand-crafted artisanal DOM node creation for peace of mind.
Resources:
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML