Pentest Script Generator logo

Pentest Script Generator

Community
ptn1411
pentest-script-generator

Tự động tạo pentest script và verify script từ báo cáo lỗ hổng Strix (vuln-XXXX.md). Kích hoạt khi người dùng đưa vào file vuln-XXXX.md, mô tả lỗ hổng bằng văn bản, dán raw HTTP request từ Burp Suite, hoặc nói 'viết script test', 'tạo pentest script', 'tạo verify script', 'generate test từ vuln'. Output: pentest_TYPE_vulnXXXX.py (TC-01..TC-N, cleanup, JSON export, dry-run) và verify_vulnXXXX.py (exit 0/1/2). Dùng cho authorized security research và bug bounty.

Overview

Publisherptn1411
Repositoryskill
Skill namepentest-script-generator
Stars
275
Forks
133
Bundled files
Instructions only
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by ptn1411 on GitHub. Read the source before you install it.

Installation

Install the Pentest Script Generator AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/ptn1411/skill/tree/main/cowork/pentest-script-generator
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ptn1411/skill.git /tmp/skill
mkdir -p .claude/skills
cp -r /tmp/skill/cowork/pentest-script-generator .claude/skills/pentest-script-generator
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Pentest Script Generator in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Pentest Script Generator on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Pentest Script Generator is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Pentest Script Generator — SOP (Strix-native v2)

Generate two professional Python scripts for each vuln-XXXX.md report. Updated from analysis of 196 real-world vulnerabilities.

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


Step 1 — Parse vuln-XXXX.md (Strix schema)

Schema produced by tracer.py → create_vulnerability_report():

# <title>
**ID:** vuln-XXXX
**Severity:** CRITICAL | HIGH | MEDIUM | LOW
**Found:** <ISO timestamp UTC>
**Target:** <base URL>
**Endpoint:** <path>          ← optional
**Method:** <HTTP method>     ← optional
**CVE:** CVE-YYYY-NNNNN       ← optional
**CWE:** CWE-NNN              ← optional
**CVSS:** <float>

## Description
## Impact
## Technical Analysis
## Proof of Concept
<poc_description>
```<poc_script_code — ALWAYS PRESENT>```
## Code Analysis    ← optional, whitebox
## Remediation

Key rule: poc_script_code is always present — use it as the primary source for test logic. If Endpoint is missing → extract from Technical Analysis or PoC code.


Step 2 — Identify vulnerability type

Authorization / Access Control

TypeTrigger KeywordsTC Pattern
BFLAadmin endpoint, non-admin users can access, BFLALow-priv token → admin route
IDOR/BOLAcross-user, order id, user_id paramSwap resource ID to another user
Unauth APIunauthenticated access, no auth requiredRequest with no Authorization header
Supabase PostgRESTanon apikey, PostgREST, RLS bypassCall REST with public apikey
Firestore RulesFirestore, RLS misconfigurationRead/write with anonymous user
Unauth Order Opsorder cancellation, order statusGET/POST order endpoint without token

Business Logic

TypeTrigger KeywordsTC Pattern
Price Tamperingprice tampering, client-side pricePOST order with price=1
Payment Bypasspayment bypass, free license, paid withoutCreate order, skip payment step
Negative Totalnegative totals, wallet creditSend negative amount
Rounding Errorrounding error, free creditTry decimal edge-case values
Rate Limit BypassX-Forwarded-For, IP spoofingAdd X-Forwarded-For: 1.2.3.X header
OTP Brute Forcemissing OTP brute-force protectionSend many wrong OTPs in sequence
Registration Farmingunlimited trial, credit farmingCreate multiple accounts for trial

Injection / XSS

TypeTrigger KeywordsTC Pattern
Stored XSSstored xss, innerHTML, marked.parseUpload payload with unique marker
DOM XSSDOM-based, innerHTML, url paramPlaywright + javascript: URL
Reflected XSSreflected xss, POST body reflectionGET/POST with payload in param
JSONP InjectionJSONP callback, arbitrary JSCall callback with random function name
Script Injectioninstaller script, key parameterSend bash command substitution payload
SQLiSQL injection, remember_token cookieSQLi payload via cookie/param

SSRF

TypeTrigger KeywordsTC Pattern
Blind SSRFblind SSRF, OAST, webhookSend webhook.site domain
SSRF IMDScloud metadata, IMDS, 169.254Send http://169.254.169.254/
SSRF Internalinternal network, port scanningSend 127.0.0.1.nip.io variants
SSRF xmlrpcwordpress xmlrpc, pingbackPOST xmlrpc.php with internal URL

Account Takeover

TypeTrigger KeywordsTC Pattern
Password Reset Leakplaintext password, password in responsePOST forgot-password → check response for password field
Account Enumerationdifferential error, user enumerationTry existing vs non-existing email, compare response
Session FixationPHPSESSID not rotated, session fixationCapture session before login, verify PHPSESSID changes after
Token Not Revokedtoken remains valid after logoutLogout → replay old token on API
OTP DisclosedOTP in response, OTP disclosedPOST forgot → check response for OTP field
Default Credentialsdefault credentials, admin:adminLogin with default credential pairs

CORS / Cookie

TypeTrigger KeywordsTC Pattern
CORS Arbitrary Originarbitrary origin reflection, CORS misconfigurationSend Origin: https://evil.com, check Access-Control-Allow-Origin
Cookie Missing Securemissing Secure flag, session cookie HTTPSend HTTP request, check Set-Cookie flags
CSRFCSRF, state-changing GETSend request without CSRF token

Information Disclosure

TypeTrigger KeywordsTC Pattern
Source Mapsourcemap, sourcesContentGET .js.map file, check sourcesContent
Hardcoded Key in JShardcoded API key, JS bundleFetch JS file, grep for key patterns
Laravel DebugLaravel debug, stack trace, IgnitionGET endpoint with Accept: text/html
Vite Dev ServerVite dev server, /@fsGET /@vite/client, /@fs/etc/passwd
Backup Archivebackup archive, .zip, .sql dumpGET /htdocs.zip, /backup.sql
phpinfo Exposurephpinfo, /info.phpGET /info.php

Infrastructure

TypeTrigger KeywordsTC Pattern
Cloudflare Origin Bypassorigin exposure, WAF bypassResolve subdomain, call origin IP directly
Exposed DBexposed MySQL, MariaDB, Redis publicCheck open ports, read banner
Kubernetes ExposedKubernetes API, TCP/6443GET /version, /healthz
WordPress User EnumWordPress REST API, user enumerationGET /wp-json/wp/v2/users

Step 3 — Identify auth mechanism

PoC SignalAuth TypeHow to obtain
Authorization: Bearer eyJ...JWTregister → login → access_token
apikey= or x-api-keyAPI KeyFrom config/profile endpoint
Supabase anon keySupabase anonFrom JS bundle or network tab
Cookie PHPSESSID / sessionPHP sessionLogin form → capture cookie
recaptchaToken: ""reCAPTCHA bypassSend empty string
No token in PoCUnauthenticatedNo Authorization header needed
X-Forwarded-ForRate limit bypassAdd spoofed IP header

Step 4 — Standard code template (use for all pentest scripts)

python
#!/usr/bin/env python3
"""
============================================================================
  Penetration Test Script — vuln-XXXX — <title>
  Target   : <target>
  Severity : <SEVERITY>  |  CVSS: <score>
  CWE      : <CWE-NNN>
============================================================================
  Description: <1-2 sentences>

  Test Cases:
    TC-01: ...
    TC-0N: Cleanup

  Usage:
    pip install requests colorama
    python pentest_TYPE_vulnXXXX.py [--base-url URL] [--dry-run] [--output-dir DIR]

  ⚠️  RUN ONLY ON AUTHORIZED TEST TARGETS  ⚠️
============================================================================
"""
import argparse, json, os, time, sys
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Optional

try:
    import requests; from requests.exceptions import RequestException
except ImportError:
    print("[!] pip install requests"); sys.exit(1)

try:
    from colorama import Fore, Style, init as colorama_init; colorama_init(autoreset=True)
except ImportError:
    class _Stub:
        def __getattr__(self, _): return ""
    Fore = Style = _Stub()


class Verdict(Enum):
    VULN="VULNERABLE"; SAFE="SAFE"; ERROR="ERROR"; INFO="INFO"; SKIP="SKIPPED"

@dataclass
class TestResult:
    test_id: str; name: str; verdict: Verdict
    status_code: Optional[int]=None; detail: str=""
    response_preview: str=""; raw_response: Any=None
    timestamp: str=field(default_factory=lambda: datetime.now(timezone.utc).isoformat())


def _print_result(r: TestResult):
    c={Verdict.VULN:Fore.RED,Verdict.SAFE:Fore.GREEN,Verdict.ERROR:Fore.YELLOW,
       Verdict.INFO:Fore.BLUE,Verdict.SKIP:Fore.WHITE}.get(r.verdict,"")
    i={Verdict.VULN:"✗ VULNERABLE",Verdict.SAFE:"✓ SAFE",Verdict.ERROR:"⚠ ERROR",
       Verdict.INFO:"ℹ INFO",Verdict.SKIP:"⊘ SKIPPED"}.get(r.verdict,"?")
    print(f"\n{c}[{r.test_id}] {r.name}\n  Result  : {i}")
    if r.status_code: print(f"  HTTP    : {r.status_code}")
    if r.detail:      print(f"  Detail  : {r.detail}")
    if r.response_preview: print(f"  Response: {r.response_preview[:300]}")

def _summary(results, vuln_id):
    v=sum(1 for r in results if r.verdict==Verdict.VULN)
    s=sum(1 for r in results if r.verdict==Verdict.SAFE)
    e=sum(1 for r in results if r.verdict==Verdict.ERROR)
    print(f"\n{'═'*68}\n  SUMMARY — {vuln_id}")
    for r in results:
        c=Fore.RED if r.verdict==Verdict.VULN else Fore.GREEN if r.verdict==Verdict.SAFE \
          else Fore.YELLOW if r.verdict==Verdict.ERROR else Fore.BLUE
        print(f"  {c}[{r.verdict.value:12s}] {r.test_id}: {r.name}")
    print(f"\n  Vulnerable: {v}  |  Safe: {s}  |  Error: {e}")
    if v: print(f"\n  {Fore.RED}⚠  CONCLUSION: VULNERABILITY CONFIRMED ({v} endpoint(s))")

def _export(results, vuln_id, target, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    p = os.path.join(output_dir, f"pentest_{vuln_id}_report.json")
    with open(p,"w",encoding="utf-8") as f:
        json.dump({"vulnerability_id":vuln_id,"target":target,
            "timestamp":datetime.now(timezone.utc).isoformat(),
            "summary":{"total":len(results),
                "vulnerable":sum(1 for r in results if r.verdict==Verdict.VULN),
                "safe":sum(1 for r in results if r.verdict==Verdict.SAFE)},
            "results":[{"test_id":r.test_id,"name":r.name,"verdict":r.verdict.value,
                "status_code":r.status_code,"detail":r.detail,
                "raw_response":r.raw_response,"timestamp":r.timestamp}
                for r in results]},f,indent=2,ensure_ascii=False,default=str)
    print(f"\n  {Fore.CYAN}📄 Report: {p}")

Step 5 — TC patterns by vulnerability type

BFLA / IDOR

TC-01: Register test account (recaptchaToken="" if bypass available)
TC-02: Login → capture JWT access_token
TC-03: Decode JWT → confirm role = "user"
TC-04: Call admin endpoint with user token → expect 403; 200 = VULNERABLE
TC-05: Control: call properly-enforced endpoint → confirm 403
TC-06: (IDOR) Swap resource ID to another user's resource
TC-07: Cleanup

Unauthenticated API / Supabase

TC-01: GET endpoint with NO Authorization header → expect 401/403; 200 = VULNERABLE
TC-02: GET with valid token → expect 200 (confirm endpoint functions)
TC-03: GET with invalid token → expect 401
# Supabase variant:
TC-01: GET /rest/v1/{table} with header "apikey: <anon_key>" → inspect returned data
TC-02: No apikey header → expect 401

Business Logic — Price Tampering

TC-01: Create order with original price → expect success (baseline)
TC-02: Create order with price=1 (tampered) → if success = VULNERABLE
TC-03: Create order with price=-1 (negative) → observe response
TC-04: Cleanup — cancel created orders

Business Logic — Payment Bypass

TC-01: Check if confirm-payment endpoint requires valid payment token
TC-02: POST confirm with arbitrary order_id → expect 403/404; 200 = VULNERABLE
TC-03: Check order status after confirm
TC-04: Cleanup

Account Takeover — Password Reset Leak

TC-01: POST /forgot-password with victim email
TC-02: Check response body for "password" field → VULNERABLE if present
TC-03: Attempt login with password from response → confirms full ATO
TC-04: (Optional) Try non-existent email → compare response (enumeration check)

Account Takeover — Token Not Revoked After Logout

TC-01: Login → capture access_token
TC-02: Call authenticated API → expect 200 (token valid)
TC-03: POST /logout (or /api/auth/logout)
TC-04: Replay old token on authenticated API → expect 401; 200 = VULNERABLE

Rate Limit Bypass via X-Forwarded-For

TC-01: Send N requests with real IP → record when blocked
TC-02: Send N+1 requests with X-Forwarded-For: <random_IP> → if not blocked = VULNERABLE
TC-03: Test X-Real-IP, CF-Connecting-IP header variants

CORS Arbitrary Origin

TC-01: GET endpoint with Origin: https://evil.com
        → check Access-Control-Allow-Origin: https://evil.com = VULNERABLE
TC-02: GET with Origin: null → check response
TC-03: GET with no Origin → baseline
TC-04: If credentials: check Access-Control-Allow-Credentials: true (escalates severity)

Stored XSS (Upload)

TC-01: Get auth token (if required)
TC-02: Upload SVG/HTML file with payload + unique marker
TC-03: Fetch CDN URL → check Content-Type and payload presence
TC-04: (Playwright) Browser-verify JS execution via dialog event
TC-05: Cleanup — DELETE uploaded file

SSRF (Blind)

TC-01: Get auth token
TC-02: Trigger with OAST domain (webhook.site) → print manual check instructions
TC-03: Trigger with 127.0.0.1.nip.io, 10.0.0.1.nip.io
TC-04: (if applicable) Trigger with http://169.254.169.254/latest/meta-data/
TC-05: Print manual checklist
TC-06: Cleanup

Information Disclosure — Source Map

TC-01: GET /main-XXXX.js → check for "//# sourceMappingURL=" comment
TC-02: GET /main-XXXX.js.map → check for "sourcesContent" field
TC-03: Analyze sourcesContent for hardcoded secrets (key, password, apikey)

Information Disclosure — Laravel Debug / Vite Dev Server

TC-01: GET endpoint with Accept: text/html → check for Ignition/debug page
TC-02: GET /@vite/client → 200 = Vite dev server exposed
TC-03: GET /@fs/etc/passwd → check for file read
TC-04: GET /info.php → check for phpinfo() output

WordPress

TC-01: GET /wp-json/wp/v2/users?per_page=100 → user enumeration
TC-02: GET /?author=1 → redirect-based user enumeration
TC-03: POST /xmlrpc.php with system.listMethods payload
TC-04: POST /xmlrpc.php with pingback SSRF payload → OAST domain

Cloudflare Origin Bypass

TC-01: Resolve subdomain (e.g., api.example.com) → obtain origin IP
TC-02: GET http://<origin_IP>/ directly → compare with CDN response
TC-03: Check WAF/rate-limit bypass on direct origin access

Session Fixation

TC-01: GET login page → capture PHPSESSID from Set-Cookie
TC-02: POST login with credentials + same pre-login session cookie
TC-03: Check PHPSESSID after login → UNCHANGED = VULNERABLE

Step 6 — Generate verify_vulnXXXX.py

Minimal script: 1–3 requests, exit 0/1/2:

python
#!/usr/bin/env python3
"""
Verify Script — vuln-XXXX — <title>
Exit codes: 0=SAFE  1=VULNERABLE  2=ERROR
Usage: python verify_vulnXXXX.py [--base-url URL]
"""
import sys, argparse, requests
requests.packages.urllib3.disable_warnings()

DEFAULT = "<TARGET>"

def verify(base_url: str) -> int:
    try:
        r = requests.get(f"{base_url}/endpoint", timeout=15, verify=False)
        if r.status_code == 200:
            print(f"[VULNERABLE] {r.status_code} — <reason>")
            print(f"  {r.text[:300]}")
            return 1
        elif r.status_code in (401, 403):
            print(f"[SAFE] {r.status_code} — endpoint properly protected")
            return 0
        print(f"[UNKNOWN] {r.status_code}")
        return 2
    except Exception as e:
        print(f"[ERROR] {e}"); return 2

if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--base-url", default=DEFAULT)
    sys.exit(verify(p.parse_args().base_url))

Step 7 — File naming convention

Vulnerability TypeType Prefix
BFLAbfla
IDOR / BOLAidor
Unauthenticated APIunauth
Stored XSSxss_stored
DOM XSSxss_dom
Reflected XSSxss_reflected
SSRFssrf
Business Logic (price/payment)bizlogic
Account Takeoverato
CORScors
SQL Injectionsqli
Information Disclosureinfodisclosure
Rate Limitratelimit
Session/Cookiesession
WordPress-specificwordpress
Supabase-specificsupabase
Infrastructureinfra

Save output to: <project_dir>/vulnerabilities/


Step 8 — Workflow

1. READ   → Parse vuln-XXXX.md (or description / raw HTTP request)
2. DETECT → Identify vuln type from trigger keywords
3. AUTH   → Identify auth mechanism from PoC signals
4. WRITE  → Generate pentest_TYPE_vulnXXXX.py
            - Header with metadata (ID, Severity, CVSS, CWE, Target)
            - Verdict enum + TestResult dataclass
            - TC-01..TC-N methods (exploit + control + cleanup)
            - _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 (see Step 9)

Step 9 — Final report to user (ALWAYS in Vietnamese)

After generating both files, present this summary 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 scriptUse argparse + env vars
Skip cleanup TCAlways add cleanup as last TC
Claim vuln without HTTP evidenceLog status_code + response preview
Use requests.get without timeoutAlways timeout=15
Skip dry-run modeAlways support --dry-run flag
Generate script without verify scriptAlways generate both
Present results to user in EnglishAlways present final summary in Vietnamese

Frequently asked questions

What does the Pentest Script Generator AI skill do?

Tự động tạo pentest script và verify script từ báo cáo lỗ hổng Strix (vuln-XXXX.md). Kích hoạt khi người dùng đưa vào file vuln-XXXX.md, mô tả lỗ hổng bằng văn bản, dán raw HTTP request từ Burp Suite, hoặc nói 'viết script test', 'tạo pentest script', 'tạo verify script', 'generate test từ vuln'. Output: pentest_TYPE_vulnXXXX.py (TC-01..TC-N, cleanup, JSON export, dry-run) và verify_vulnXXXX.py (exit 0/1/2). Dùng cho authorized security research và bug bounty.

Why use Pentest Script Generator on TypingMind?

Because you install it once and use it with any model. Pentest Script Generator is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Pentest Script Generator in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/ptn1411/skill/tree/main/cowork/pentest-script-generator. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Pentest Script Generator?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Pentest Script Generator?

As many as you like. As long as a model supports skills, you can use Pentest Script Generator with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Pentest Script Generator AI skill free?

It is published on GitHub by ptn1411. Check the repository for licensing terms. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇