XSS Security Lab

Reflected XSS Vulnerability Demonstration

Test Your Knowledge

🔴 VULNERABLE - Reflected XSS

GET Parameter Reflection

Reflected XSS via innerHTML injection

The page reads the ?q= parameter from the URL and injects it directly into the DOM using innerHTMLNO sanitization applied.

🎯 Goal: Execute JavaScript (pop an alert box) by crafting a malicious URL parameter.
No payload yet. Add ?q=... to the URL.
📝 Input Value ?q= (none)
Quick Test Hello World Clear

✅ Solution & Explanation

Working Payloads:

  • ?q=<img src=x onerror=alert('XSS')> — Image error event
  • ?q=<body onload=alert(document.cookie)> — Body onload
  • ?q=<svg onload=alert(1)> — SVG onload
  • ?q=<input onfocus=alert(1) autofocus> — Input autofocus

🔍 Why it works: The app takes ?q=... and uses innerHTML without escaping. The browser interprets any HTML/JS injected.

Vulnerable Code:

// Vulnerable JavaScript:
const query = new URLSearchParams(location.search).get('q');
document.getElementById('output').innerHTML = query;

🛡️ Fix (Secure Code):

// Option 1: Use textContent
document.getElementById('output').textContent = query;

// Option 2: Escape HTML entities
function escapeHtml(str) {
    return str.replace(/[&<>]/g, m => ({
        '&': '&', '<': '<', '>': '>'
    }[m]));
}
document.getElementById('output').innerHTML = escapeHtml(query);

Key Takeaways:
Always sanitize or escape user input before rendering it in the DOM. Avoid using innerHTML with untrusted data.