# Pentest Script Generator

> Auto-generate professional pentest scripts and verify scripts from Strix vulnerability reports (vuln-XXXX.md) or raw vulnerability descriptions. Use when given a vuln-XXXX.md file, pasted HTTP request from Burp Suite, or asked to write pentest script, verify script, test script for a vulnerability. Outputs pentest_TYPE_vulnXXXX.py (TC-01..TC-N, cleanup, evidence saving, JSON export) and verify_vulnXXXX.py (exit 0/1/2).

- Skill: `ptn1411/pentest-script-generator-2` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds@latest add ptn1411/pentest-script-generator-2`
- Raw SKILL.md: https://api.skillmd.com/api/skills/ptn1411/pentest-script-generator-2/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: ptn1411 (https://skillmd.com/u/ptn1411)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/ptn1411/pentest-script-generator-2

---


# Pentest Script Generator

> Generate professional Python pentest scripts from Strix vuln reports or raw vulnerability descriptions.

> **Language rule**: All skill instructions and generated script code use English.
> **Final summary presented to the user must be in Vietnamese.**

## 🔧 Runtime Scripts

| Script | Purpose | Usage |
|--------|---------|-------|
| `scripts/generate.py` | Generate scripts from vuln-XXXX.md | `python scripts/generate.py vuln-0001.md` |

## 📋 Reference Files

| File | Purpose |
|------|---------|
| `references/pentest_template.py` | Full pentest script template |
| `references/verify_template.py` | Verify script template |
| `references/vuln_types.md` | Vulnerability type → test pattern mapping |

---

## 1. Strix vuln-XXXX.md Schema

Parse these fields from the report:

| Field | Required | Notes |
|-------|----------|-------|
| `**ID:**` | ✅ | vuln-XXXX → script filename |
| `**Severity:**` | ✅ | CRITICAL/HIGH/MEDIUM/LOW |
| `**Target:**` | ✅ | Base URL → DEFAULT_BASE_URL |
| `**Endpoint:**` | Optional | Extract from Technical Analysis if missing |
| `**Method:**` | Optional | Extract from PoC if missing |
| `**CWE:**` | Optional | Add to script header |
| `**CVSS:**` | ✅ | Add to script header |
| PoC `poc_script_code` | ✅ | Always present — primary source for test logic |

---

## 2. Vulnerability Type Detection

### Authorization / Access Control

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **BFLA** | admin endpoint, non-admin, BFLA | Low-priv token → admin route |
| **IDOR/BOLA** | cross-user, user_id param, order id | Swap resource ID |
| **Unauth API** | unauthenticated, no auth required | Request without token |
| **Supabase RLS** | anon apikey, PostgREST, RLS bypass | REST with anon key |

### Business Logic

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **Price Tampering** | price tampering, client-side price | POST price=1 |
| **Payment Bypass** | payment bypass, free license | Skip payment step |
| **Negative Total** | negative total, wallet credit | Send negative amount |
| **Rate Limit Bypass** | X-Forwarded-For, IP spoofing | Rotate header IPs |

### Injection / XSS

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **Stored XSS** | stored xss, innerHTML | Upload + fetch + verify |
| **DOM XSS** | DOM-based, url param | Playwright verify |
| **Reflected XSS** | reflected xss, POST body | Param with payload |
| **SQLi** | SQL injection, remember_token | SQLi payload in cookie/param |

### SSRF

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **Blind SSRF** | blind SSRF, OAST, webhook | OAST domain callback |
| **SSRF IMDS** | cloud metadata, 169.254 | http://169.254.169.254/ |
| **SSRF Internal** | internal network | 127.0.0.1 variants |

### Account Takeover

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **Password Reset Leak** | plaintext password in response | POST forgot → check field |
| **Token Not Revoked** | token valid after logout | Logout → replay old token |
| **Session Fixation** | PHPSESSID not rotated | Pre/post login session compare |
| **OTP Disclosed** | OTP in response | POST forgot → check OTP field |

### Information Disclosure

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **Source Map** | sourcemap, sourcesContent | GET .js.map |
| **Laravel Debug** | Laravel debug, Ignition | GET with Accept: text/html |
| **Vite Dev Server** | Vite, /@fs | GET /@vite/client |
| **Backup Archive** | .zip, .sql dump | GET /backup.zip |

### CORS / Session

| Type | Trigger Keywords | TC Pattern |
|------|-----------------|------------|
| **CORS Arbitrary Origin** | arbitrary origin, CORS | Origin: evil.com → check ACAO |
| **Cookie Missing Secure** | missing Secure flag | HTTP request → check Set-Cookie |

---

## 3. Auth Detection

| PoC Signal | Auth Type | Script Pattern |
|------------|-----------|----------------|
| `Bearer eyJ...` | JWT | `POST /login` → `access_token` |
| `apikey=` or `x-api-key` | API Key | From config/env |
| Supabase `anon` key | Supabase | From JS bundle |
| `PHPSESSID` cookie | PHP session | Login form → cookie |
| `recaptchaToken: ""` | reCAPTCHA bypass | Empty string |
| No token needed | Unauthenticated | No header |

---

## 4. Test Case Structure

Every pentest script must follow this TC structure:

```
TC-01: Setup / Get auth token (if needed)
TC-02: Baseline — confirm endpoint works normally
TC-03: Core exploit attempt
TC-04: (Optional) Variation / escalation
TC-05: Control — confirm protected endpoint still enforces
TC-NN: Cleanup — delete/cancel created test data
```

### Verdict Logic

| HTTP Response | Verdict |
|---------------|---------|
| Expected protected (401/403) → got 200 with data | `VULNERABLE` |
| Got 401/403 as expected | `SAFE` |
| Network/parsing error | `ERROR` |
| Test skipped (dry-run) | `SKIPPED` |

---

## 5. Evidence Saving

Every script must save evidence when vulnerabilities are found:

```python
def _save_evidence(data: list[dict], vuln_id: str, label: str, output_dir: str = "."):
    from pathlib import Path
    import csv

    ev_dir = Path(output_dir) / "evidence"
    ev_dir.mkdir(parents=True, exist_ok=True)
    ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")

    # JSON
    json_path = ev_dir / f"{vuln_id}_{label}_{ts}.json"
    with open(json_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False, default=str)

    # CSV (if list of dicts)
    if data and isinstance(data[0], dict):
        csv_path = ev_dir / f"{vuln_id}_{label}_{ts}.csv"
        with open(csv_path, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=data[0].keys())
            w.writeheader(); w.writerows(data)

    print(f"  💾 Evidence: {json_path}")
```

---

## 6. File Naming Convention

| Vuln Type | Prefix | Output Files |
|-----------|--------|-------------|
| BFLA | `bfla` | `pentest_bfla_vuln0001.py` |
| IDOR | `idor` | `pentest_idor_vuln0001.py` |
| Unauth API | `unauth` | `pentest_unauth_vuln0001.py` |
| Stored XSS | `xss_stored` | `pentest_xss_stored_vuln0001.py` |
| DOM XSS | `xss_dom` | |
| Reflected XSS | `xss_reflected` | |
| SSRF | `ssrf` | |
| Business Logic | `bizlogic` | |
| Account Takeover | `ato` | |
| CORS | `cors` | |
| SQL Injection | `sqli` | |
| Info Disclosure | `infodisclosure` | |
| Rate Limit | `ratelimit` | |
| Session/Cookie | `session` | |
| Supabase | `supabase` | |
| Infrastructure | `infra` | |

Save to: `vulnerabilities/` subfolder of the project.

---

## 7. Verify Script Rules

`verify_vulnXXXX.py` must be:
- **Minimal**: 1–3 HTTP requests max
- **Fast**: Complete in < 10 seconds
- **Exit codes**: `0` = SAFE, `1` = VULNERABLE, `2` = ERROR
- **No dependencies** beyond `requests`

---

## 8. Workflow

```
1. READ   → Parse vuln-XXXX.md (or description/HTTP request)
2. DETECT → Identify vuln type from keywords
3. AUTH   → Identify auth mechanism from PoC
4. WRITE  → Generate pentest_TYPE_vulnXXXX.py
            - Header with metadata
            - Verdict/TestResult classes
            - TC-01..TC-N methods
            - _save_evidence() helper
            - _summary() and _export() helpers
            - main() with argparse (--base-url, --dry-run, --output-dir)
5. WRITE  → Generate verify_vulnXXXX.py (minimal, exit 0/1/2)
6. REPORT → Present final summary to user IN VIETNAMESE
```

---

## 9. Output Summary (always in Vietnamese)

After generating both files, present to user **in Vietnamese**:

```
✅ Đã tạo xong cho vuln-XXXX (<tiêu đề>):

  📄 vulnerabilities/vuln-XXXX.md               (Severity: X, CVSS: Y)
  🐍 vulnerabilities/pentest_TYPE_vulnXXXX.py   (N test cases)
  ⚡ vulnerabilities/verify_vulnXXXX.py          (quick verify, exit 0/1/2)

▶  Cách chạy:
   python vulnerabilities/pentest_TYPE_vulnXXXX.py --base-url https://target.com
   python vulnerabilities/verify_vulnXXXX.py --base-url https://target.com

📋 Tóm tắt:
   - Loại lỗ hổng : <TYPE>
   - Auth mechanism: <auth type>
   - Số test cases : N
   - Cleanup       : ✅ included
```

---

## Anti-Patterns

| ❌ Don't | ✅ Do |
|----------|-------|
| Hardcode credentials in script | Use argparse + env vars |
| Skip cleanup TC | Always add cleanup as last TC |
| Claim vuln without HTTP evidence | Log status_code + response preview |
| Use `requests.get` without timeout | Always `timeout=15` |
| Skip dry-run mode | Always support `--dry-run` flag |
| Generate script without verify script | Always generate both |

