21 Feb, 2024

Exploiting cross-site scripting to steal cookies

Exploiting cross-site scripting (XSS) to steal cookies involves taking advantage of vulnerabilities in a web application that allow an attacker to inject malicious scripts into content that is then served to other users. XSS vulnerabilities occur when a web application includes unvalidated or unencoded user input in its output. An attacker can leverage these vulnerabilities to execute arbitrary JavaScript code in the context of the victim’s browser session.

When an attacker successfully injects such a script, it can be crafted to access the cookies of the web application’s users. Since cookies often contain session tokens or other sensitive information that can authenticate a user to a web application, obtaining them can lead to unauthorized access to the user’s account and personal data.

The process typically involves the following steps:

1. Identifying a Vulnerability: The attacker finds a point in the web application where user input is reflected back to the user without proper sanitization or encoding.

2. Crafting the Payload: The attacker creates a malicious script designed to access and exfiltrate the victim’s cookies. This script is tailored to execute within the security context of the web application.

3. Injection: The attacker injects the malicious script into the web application, often by tricking a user into clicking a link, visiting a malicious website, or even embedding the script in a seemingly benign website.

4. Execution: When the victim interacts with the compromised component of the web application (e.g., by visiting a page with the injected script), the malicious script executes in their browser.

5. Exfiltration: The script collects the victim’s cookies and sends them to a server controlled by the attacker, often through a simple HTTP request.

6. Exploitation: With the stolen cookies, the attacker can potentially hijack the victim’s session, gaining unauthorized access to the web application as the victim.

Examples of exploitation

To illustrate the process of exploiting the vulnerability, we will refer to a lab work from PortSwigger that demonstrates a stored XSS vulnerability in the blog commenting function. This vulnerability allows the injection of malicious scripts that are stored and later displayed to other users.

The lab’s goal is to exploit this vulnerability to seize the session cookie of a simulated user who views all published comments. Success is exploiting this vulnerability to steal the cookie, allowing the attacker to impersonate the victim.

The process begins by posting a comment containing a malicious script whose job is to send the user’s cookies to a server controlled by the attacker. After the simulated user views this comment, the attacker can retrieve the cookie from their server.

The final step is to use the stolen cookie to authenticate to the system disguised as the victim, allowing the attacker to hijack her session. This lab will teach you how to conduct such an attack and the importance of protecting against this type of exploitation. 

Let’s start by analysing the mechanism for publishing comments on a blog. Let’s try sending a standard payload to see if this field is really vulnerable.

Ok, now let’s use a special XSS payload that will perform a request to our burp colaborator. It looks like this:

method: 'POST',
mode: 'no-cors',


Let’s check if our script has been successfully embedded into comments.

That’s great! Now let’s go to burp colaborator, and analyse the queries.

Cookies have been successfully stolen! Now, to perform the lab, log in to the account using them.

We have successfully logged into the admin account!

Scanners that detect vulnerabilities

  1. OWASP Zed Attack Proxy (ZAP): This is one of the world’s most popular free security tools and is actively maintained by hundreds of international volunteers. It can help you automatically find security vulnerabilities in web applications while you are developing and security testing.

  2. Burp Suite: Developed by PortSwigger, it’s a favorite among penetration testers. It has both free and professional versions. Burp Suite helps identify various security vulnerabilities, including XSS, and provides detailed reports. It also allows manual testers to modify requests to test how systems respond to changes.

  3. Netsparker: It is a user-friendly scanner that automates the process of identifying vulnerabilities and offers a proof of exploit. It claims to reduce false positives and provides a unique proof-based scanning approach.

  4. Acunetix: Known for its speed and accuracy, Acunetix is a fully automated tool that scans at a fast pace, supports HTML5, JavaScript and single-page applications, providing detailed reports of XSS vulnerabilities among many others.

  5. Veracode: It offers a scalable solution that can scan entire application portfolios in a single, centralized platform. Veracode can be integrated into the software development lifecycle, thus enabling the detection of XSS flaws from the early stages.

  6. Qualys Web Application Scanning (WAS): A cloud-based service that scans web apps to identify vulnerabilities, Qualys WAS is good for businesses looking for a scalable security solution. It not only detects XSS vulnerabilities but also provides continuous monitoring.

  7. Detectify: This tool performs external vulnerability scanning, and it mimics black hat hackers to find weaknesses before they are exploited. It also provides crowd-sourced vulnerability information from ethical hackers.

  8. WebInspect: This is an automated dynamic application security testing  tool that simulates real-world hacking techniques to provide comprehensive vulnerability scanning, especially for large applications.

  9. AppSpider: Part of the Rapid7 product family, it scans apps for vulnerabilities across over 100 technologies and identifies security flaws like XSS, providing security teams with resources for remediation.

  10. Nikto: As an open-source web server scanner, Nikto performs comprehensive tests against web servers for multiple items, including the detection of potential XSS vulnerabilities. It is a good tool for quick scans and is commonly used for security assessment.

Average CVSS score for XSS

The Common Vulnerability Scoring System (CVSS) score for XSS vulnerabilities can vary widely depending on specific factors of the vulnerability, such as the complexity of the attack, the requirements for user interaction, and the impacts on confidentiality, integrity, and availability. However, a general average score is not typically provided because the score is meant to be calculated based on the individual characteristics of each vulnerability.

For instance, if an XSS vulnerability allows an attacker to take over user accounts, the impact on confidentiality and integrity could be considered high, which would result in a higher CVSS score. Conversely, if the XSS vulnerability requires complex user interaction and only affects data integrity minimally, the CVSS score might be lower.

It’s important to note that while CVSS provides a quantitative measure of vulnerability severity, it should be used alongside other qualitative assessments, such as the context of the vulnerability within your specific environment and the potential business impact, to fully understand the risks it poses.

CVES related to XSS

CVE-2020-10385: This vulnerability involved a Stored XSS in the WPForms plugin for WordPress, which could allow attackers to execute malicious scripts in a user’s browser. The issue was related to improper neutralization of input during web page generation​​.

CVE-2021-33829: Discovered in CKEditor 4, this Stored XSS vulnerability was due to the failure of the htmldataprocessor function to remove instances of protected comments recursively, allowing attackers to inject malicious payloads that could be executed in the context of another user’s session​​.

CVE-2022-47416 and CVE-2022-47417: Part of a series of vulnerabilities in a Document Management System, where CVE-2022-47416 was a stored XSS in the in-app chat system, and CVE-2022-47417 involved a stored XSS in the document file name. Both vulnerabilities could be exploited to execute arbitrary scripts in the context of another user’s session, potentially leading to information theft or further attacks​​.

CVE-2022-47418: Another XSS vulnerability in the same Document Management System as above, but this time in document version comments. This allowed attackers to inject malicious scripts that could be executed when a user viewed the document version or history tabs​​.

CVE-2023-0007: Found in PAN-OS software on Panorama appliances by Palo Alto Networks, this Stored XSS vulnerability could allow an authenticated administrator to inject a JavaScript payload into the web interface, which would then execute in the context of another administrator’s browser when viewed​​.

CVE-2023-36881 and CVE-2023-35394: These vulnerabilities were identified in Azure HDInsight. CVE-2023-36881 was related to multiple components within Apache Ambari and could be exploited through manipulation of alert notifications and specific configurations. CVE-2023-35394 was an XSS vulnerability in Azure HDInsight’s Jupyter Notebook service that could lead to remote code execution by bypassing sanitization processes​​.

To study XSS

“XSS Attacks” book by Jeremiah Grossman, Robert Hansen, Anton Rager, Petko Petkov, and Seth Fogie. This comprehensive book covers XSS and related vulnerabilities, ranging from an introduction for beginners to advanced exploitation techniques and the latest attack methods. It’s filled with examples and code snippets to illustrate different vulnerabilities and attacks​​.

Cross-Site Scripting (XSS) Course at HTB Academy (Hack The Box). This course includes 20 modules dedicated to various aspects of web security, including a module specifically focused on XSS. It covers the basics of web applications, using web proxies, information gathering, attacking web applications, JavaScript deobfuscation, and, of course, identifying and exploiting XSS vulnerabilities​​.

Cross-Site Scripting Attack Lab (Elgg) by SEED Security Labs. This hands-on lab provides practical experience with XSS vulnerabilities using the Elgg web application. It demonstrates how attackers can exploit XSS vulnerabilities to inject malicious code into victims’ web browsers and steal user credentials. The lab aims to exploit the XSS vulnerability to launch an attack that spreads an XSS worm among users​​.

Web Security Academy by PortSwigger. This free online training platform for web security includes many interactive labs and educational materials, including 30 labs focused on XSS. The platform offers flexible learning with progress tracking and is produced by a world-class team of web security experts. Web Security Academy provides up-to-date web security knowledge and allows you to practice hacking skills in realistic scenarios​​.

How to be protected from XSS

Encoding Data on Output

Encoding data before it is output to the browser is crucial. Depending on the context, different types of encoding might be necessary. For HTML contexts, characters like < and > should be converted to their corresponding HTML entities (&lt; and &gt;). For JavaScript contexts, non-alphanumeric characters should be Unicode-escaped. This ensures that user-controlled data is treated as data, not executable code​​.

Input Validation

Validating input on arrival is another vital defense layer. This involves checking that the data conforms to expected formats, such as ensuring a URL starts with a safe protocol like HTTP/HTTPS. Input validation should ideally employ whitelists rather than blacklists to ensure that only expected and safe input is allowed​​.

Frameworks and Libraries

Using modern web frameworks and libraries that encourage good security practices can significantly reduce the risk of XSS vulnerabilities. Frameworks often come with built-in mechanisms for templating, auto-escaping, and sanitizing data, which can mitigate XSS risks. However, it’s crucial to be aware of the security gaps that might exist in these frameworks and libraries and ensure they are used securely​​.

HTML Sanitization

When allowing users to input HTML content, such as in a WYSIWYG editor, HTML sanitization is necessary. This process involves stripping out potentially dangerous tags and attributes from the HTML content. Libraries like DOMPurify are recommended for this purpose, but it’s important to keep them updated to protect against new types of attacks​​​​.

Additional Controls

Other controls include setting secure cookie attributes to limit JavaScript’s access to cookies and implementing a Content Security Policy (CSP) to control the sources from which content can be loaded. These measures can help limit the damage from XSS vulnerabilities that might still exist​​.


In summary, XSS (Cross-Site Scripting) vulnerabilities represent a significant threat in web security, exploiting the trust a user has in a particular website. At its core, XSS involves the injection of malicious scripts into otherwise benign and trusted websites, which can lead to a range of malicious activities, such as stealing session cookies, redirecting users to malicious websites, or even performing actions on behalf of the users without their consent.

Protection against XSS requires a comprehensive approach that includes proper data handling practices like output encoding and input validation. Modern web frameworks provide built-in defenses against XSS, but developers must remain vigilant and understand the potential security gaps within these frameworks.

HTML sanitization is particularly crucial when allowing user-generated content that includes HTML, ensuring that any potentially dangerous tags or attributes are neutralized before being rendered on the client side. Additional security measures such as setting secure cookie attributes and implementing a robust Content Security Policy (CSP) can further mitigate the risks associated with XSS vulnerabilities.

The battle against XSS is ongoing, with new techniques and bypasses constantly emerging. Therefore, continuous learning, adherence to best practices, and the use of comprehensive security tools are essential for maintaining robust defenses against XSS attacks. For those seeking to deepen their understanding and enhance their defense strategies, resources such as the OWASP XSS Prevention Cheat Sheet are invaluable.

Understanding XSS, its potential impact, and the strategies for its mitigation is crucial for developers, security professionals, and anyone involved in creating or maintaining web applications. By fostering a security-conscious development culture and implementing rigorous security practices, the risk posed by XSS vulnerabilities can be significantly reduced, leading to safer web environments for all users.

Other Services

Ready to secure?

Let's get in touch