'Inject html code into website through input field
Lets say that i have a website with an input text box where i can write whatever. The stuff that i write here will be displayed on another website. Please see the following example.
If i write the following into text box:
<div style="height:50px;width:50px;background-color:red"></div>
It looks like this on the other website:
How can i make it display a red box (code) instead of a string?
Solution 1:[1]
What you're describing is very dangerous. It could reveal XSS vulnerabilities to your website.
Setting HTML content dangerously works by setting the innerHTML on any DOM element, or innerText on script tags. If you would like to protect against XSS, one way to do it is to set content using textContent.
const handleUserInput = (input) => {
const { body } = document;
body.innerHTML = input; // very dangerous;
body.innerText = input; // dangerous, if used on <script>
body.textContent = input; // wraps in text node, safe.
}
What's happening in your provided example, is that the user input is being sanitized. While this is one way to prevent XSS, it's best to follow other best-practices to prevent such vulnerabilities as websites vulnerable to XSS attacks can allow attackers to access user sessions, identifying information, and more.
There are ways to bypass sanitizing input, depending on the patterns, and engines you use. You can view the XSS Filter Evasion Cheat Sheet. Note that using this without the clients permission may be considered hacking under the law, and should only be done for security research, and approved testing purposes.
If you are implementing this in order to be able to display HTML content on another web page, you should re-think this, and instead make pre-built components that only store input in memory, and only set text node values on the client side. It can open a world of vulnerabilities to your site.
If you are dead-set on this solution for your website, you must remove the user input HTML sanitization on your end, whether that is happening on the frontend, or backend.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

