The user’s browser has no way to know that the script should not be trusted, and executes it. The malicious script can then transmit private data, like cookies or other session information, to the attacker; redirect the victim to web content controlled by the attacker; or perform other malicious operations on the user’s machine, all under the guise of the vulnerable site. These scripts can even rewrite the content of the HTML page.
Your site has this:
<b> <%= username %> </b></br>
<div> <%= profileText %> </div>
A benign user enters a comment as intended.
<h3> Thank you for your comments! </h3>
An attacker uses the field to send malicious code to your site.
<h3>Thank you for your comments!</h3>
There are some basic defense strategies for preventing XSS.
The primary defense against cross-site scripting, contextual output encoding converts display data from potentially dangerous code to inert display data.
It does this by converting special characters commonly used in code—like the less-than sign (<)—and replaces them with HTML encoded entities, or escape codes, that tell the system to render those characters as text, not as code.
HTML sanitization takes user-submitted HTML, applies a rule system or whitelist to it, and then returns a new version of the HTML that fits those rules.
In instances where you want to allow your users to submit HTML to your server, this is the better choice to protect against cross-site scripting, as it will render all user input as text only.
For example, you might specify a rule where your application will accept <p><b><i> in user-submitted HTML, and reject all other tags. Now when your users submit HTML, your application will examine the HTML, apply the rule, and produce a new HTML document that preserves only those “safe” tags.
The X-XSS-Protection HTTP Response Header is a standardized response header that will block some forms of XSS attacks. It is not a complete defense but it still useful.