If I am going to be displaying user-generated input on my site, is it safe enough to just display it by doing Element.innerText = "user input"
in javascript, or do I need to additionally filter the input to prevent XSS?
In general, effectively preventing XSS vulnerabilities is likely to involve a combination of the following measures: Filter input on arrival. At the point where user input is received, filter as strictly as possible based on what is expected or valid input. Encode data on output.
Unlike innerHTML, textContent has better performance because its value is not parsed as HTML. For that reason, using textContent can also prevent Cross-Site Scripting (XSS) attacks. Unlike innerText, textContent isn't aware of CSS styling and will not trigger a reflow.
Encoding is probably the most important line of XSS defense, but it is not sufficient to prevent XSS vulnerabilities in every context. You should also validate input as strictly as possible at the point when it is first received from a user.
CSP is a browser security mechanism that aims to mitigate XSS and some other attacks. It works by restricting the resources (such as scripts and images) that a page can load and restricting whether a page can be framed by other pages.
Does 'innerText' prevent XSS?
Not in all cases! The following excerpt is from the OWASP Foundation regarding unsafe usages of innerText
:
One example of an attribute which is thought to be safe is innerText. Some papers or guides advocate its use as an alternative to innerHTML to mitigate against XSS in innerHTML. However, depending on the tag which innerText is applied, code can be executed.
The content provides the following example (which I have modified for clarity)
const tag = document.createElement("script");
tag.innerText = `console.log('Inner Text Used')`;
document.body.appendChild(tag); //executes code
However, in MOST cases, innerText is the method you would use to prevent XSS, and is also documented on OWASP:
... use innerText/textContent. This will solve the problem, and it is the right way to re-mediate DOM based XSS vulnerabilities
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With