Cross-site scripting (XSS) is a web security vulnerability that allows attackers to inject malicious JavaScript code into trusted websites. XSS attacks are initiated when an attacker sends a malicious script to an unsuspecting user over a web application. Since the user is unaware that the script carries harmful code, they interact with their browser and execute the script.
This malicious script can now collect cookies and other sensitive information from the user’s session without them knowing. The attacker can then use this collected information to wreck havoc for the user. Since the injected script can change HTML content on the website as well, both websites and users are at risk.
XSS attacks thrive on one small mistake by a website’s designer: unescaped user input. Sites often interact with users by taking information through text fields. Attackers can inject JavaScript code embedded in HTML tags into these text fields. If this has not been taken into account during web design, the code will be executed in the browser like standard JavaScript. This JavaScript snippet is now part of the website’s HTML and, as soon as a user interacts with it, they will become vulnerable.
Below is an example of vulnerable HTML in a site that takes user input to collect their lunch order:
<% String order = request.getParameter("ord"); %>
...
Lunch: <%= order %>
In the script above, order
stores user input. If a user enters a script, <script>alert('XSS Attack!')</script>
, instead of text into the browser, this script will become part of the website’s HTML:
Lunch: <%= <script>alert('XSS Attack!')</script> %>
Now, when a user visits the website, they will see the alert message, “XSS Attack!”.
Good web design can protect both users and websites from irreparable damage. XSS attacks can be prevented by: