Cross-site scripting (XSS) occurs when an attacker is able to fool a web application into interpreting data as browser scripting code. Cross-site scripting (XSS) is a form of an injection attack but sufficiently prevalent to warrant being discussed separately.
There are several types of XSS attacks, the most common being the stored and the reflected XSS attacks.
In the stored XSS attack, the threat actor manages to store a script in the server’s database (e.g. in the user’s name field) and then waits for the victim to cause the server to display the database record containing the stored XSS exploit.
In a reflected attack, the threat actor typically will trick the victim into clicking on a carefully crafted link (e.g. in an email or another website) that sends the attacker’s malicious script to the target website. If the target website does not properly sanitize the input, and displays it to the victim’s browser, the victim’s browser will trust the script (as it will appear to have originated from the target website), and the attacker’s script can perform malicious acts with the permissions of the user.
The mitigation in both cases is to never trust user input. All input must be carefully screened, preferably using a standard library that will remove or escape components of the input that, if sent back to the browser, would be interpreted as script or code (and not displayed as data).
Not only can XSS vulnerabilities lead to significant security compromises in and of themselves, the existence of an XSS vulnerability can completely defeat common protections against another vulnerability, Cross-Site Request Forgery (CSRF). This vulnerability is discussed in the “Cross-Site Request Forgery” subsection later in this section.