Skip to content

AI-powered penetration testing assistant using local LLM on linux (Parrot OS)

Python

initial commit: metatron v1.0 - AI pentest assistant

sooryathejas69cc23dfe6ad
diff --git a/Modelfile b/Modelfile
new file mode 100644
index 0000000..07e71bd
--- /dev/null
+++ b/Modelfile
@@ -0,0 +1,9 @@
+FROM huihui_ai/qwen3.5-abliterated:9b
+
+PARAMETER num_ctx 16384
+PARAMETER temperature 0.7
+PARAMETER top_k 10
+PARAMETER top_p 0.9
+export OLLAMA_GPU_LAYERS=80
+export OLLAMA_NUM_THREAD=8
+ollama run metatron-qwen
diff --git a/db.py b/db.py
new file mode 100644
index 0000000..0a8d138
--- /dev/null
+++ b/db.py
@@ -0,0 +1,345 @@
+#!/usr/bin/env python3
+"""
+METATRON - db.py
+MariaDB connection + all read/write/edit/delete operations
+Database: metatron
+"""
+
+import mysql.connector
+from datetime import datetime
+
+
+# ─────────────────────────────────────────────
+# CONNECTION
+# ─────────────────────────────────────────────
+
+def get_connection():
+ """Returns a MariaDB connection. No password (local setup)."""
+ return mysql.connector.connect(
+ host="localhost",
+ user="metatron",
+ password="123",
+ database="metatron"
+ )
+
+
+# ─────────────────────────────────────────────
+# WRITE FUNCTIONS
+# ─────────────────────────────────────────────
+
+def create_session(target: str) -> int:
+ """Insert new row into history. Returns sl_no."""
+ conn = get_connection()
+ c = conn.cursor()
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ c.execute(
+ "INSERT INTO history (target, scan_date, status) VALUES (%s, %s, %s)",
+ (target, now, "active")
+ )
+ conn.commit()
+ sl_no = c.lastrowid
+ conn.close()
+ return sl_no
+
+
+def save_vulnerability(sl_no: int, vuln_name: str, severity: str,
+ port: str, service: str, description: str) -> int:
+ """Insert a vulnerability. Returns its id."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("""
+ INSERT INTO vulnerabilities (sl_no, vuln_name, severity, port, service, description)
+ VALUES (%s, %s, %s, %s, %s, %s)
+ """, (sl_no, vuln_name, severity, port, service, description))
+ conn.commit()
+ vuln_id = c.lastrowid
+ conn.close()
+ return vuln_id
+
+
+def save_fix(sl_no: int, vuln_id: int, fix_text: str, source: str = "ai"):
+ """Insert a fix linked to a vulnerability."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("""
+ INSERT INTO fixes (sl_no, vuln_id, fix_text, source)
+ VALUES (%s, %s, %s, %s)
+ """, (sl_no, vuln_id, fix_text, source))
+ conn.commit()
+ conn.close()
+
+
+def save_exploit(sl_no: int, exploit_name: str, tool_used: str,
+ payload: str, result: str, notes: str):
+ """Insert an exploit attempt."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("""
+ INSERT INTO exploits_attempted (sl_no, exploit_name, tool_used, payload, result, notes)
+ VALUES (%s, %s, %s, %s, %s, %s)
+ """, (sl_no, exploit_name, tool_used, payload, result, notes))
+ conn.commit()
+ conn.close()
+
+
+def save_summary(sl_no: int, raw_scan: str, ai_analysis: str, risk_level: str):
+ """Insert the full session summary."""
+ conn = get_connection()
+ c = conn.cursor()
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ c.execute("""
+ INSERT INTO summary (sl_no, raw_scan, ai_analysis, risk_level, generated_at)
+ VALUES (%s, %s, %s, %s, %s)
+ """, (sl_no, raw_scan, ai_analysis, risk_level, now))
+ conn.commit()
+ conn.close()
+
+
+# ─────────────────────────────────────────────
+# READ FUNCTIONS
+# ─────────────────────────────────────────────
+
+def get_all_history():
+ """Return all rows from history ordered by newest first."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("SELECT sl_no, target, scan_date, status FROM history ORDER BY sl_no DESC")
+ rows = c.fetchall()
+ conn.close()
+ return rows
+
+
+def get_session(sl_no: int) -> dict:
+ """Return everything linked to a sl_no across all tables."""
+ conn = get_connection()
+ c = conn.cursor()
+
+ c.execute("SELECT * FROM history WHERE sl_no = %s", (sl_no,))
+ history = c.fetchone()
+
+ c.execute("SELECT * FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
+ vulns = c.fetchall()
+
+ c.execute("SELECT * FROM fixes WHERE sl_no = %s", (sl_no,))
+ fixes = c.fetchall()
+
+ c.execute("SELECT * FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
+ exploits = c.fetchall()
+
+ c.execute("SELECT * FROM summary WHERE sl_no = %s", (sl_no,))
+ summary = c.fetchone()
+
+ conn.close()
+
+ return {
+ "history": history,
+ "vulns": vulns,
+ "fixes": fixes,
+ "exploits": exploits,
+ "summary": summary
+ }
+
+
+def get_vulnerabilities(sl_no: int):
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("SELECT * FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
+ rows = c.fetchall()
+ conn.close()
+ return rows
+
+
+def get_fixes(sl_no: int):
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("SELECT * FROM fixes WHERE sl_no = %s", (sl_no,))
+ rows = c.fetchall()
+ conn.close()
+ return rows
+
+
+def get_exploits(sl_no: int):
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("SELECT * FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
+ rows = c.fetchall()
+ conn.close()
+ return rows
+
+
+# ─────────────────────────────────────────────
+# EDIT FUNCTIONS
+# ─────────────────────────────────────────────
+
+def edit_vulnerability(vuln_id: int, field: str, value: str):
+ """Edit a single field in vulnerabilities by id."""
+ allowed = {"vuln_name", "severity", "port", "service", "description"}
+ if field not in allowed:
+ print(f"[!] Invalid field: {field}. Allowed: {allowed}")
+ return
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute(
+ f"UPDATE vulnerabilities SET {field} = %s WHERE id = %s",
+ (value, vuln_id)
+ )
+ conn.commit()
+ conn.close()
+ print(f"[+] vulnerabilities.{field} updated for id={vuln_id}")
+
+
+def edit_fix(fix_id: int, fix_text: str):
+ """Edit the fix_text of a fix by id."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("UPDATE fixes SET fix_text = %s WHERE id = %s", (fix_text, fix_id))
+ conn.commit()
+ conn.close()
+ print(f"[+] fix id={fix_id} updated.")
+
+
+def edit_exploit(exploit_id: int, field: str, value: str):
+ """Edit a single field in exploits_attempted by id."""
+ allowed = {"exploit_name", "tool_used", "payload", "result", "notes"}
+ if field not in allowed:
+ print(f"[!] Invalid field: {field}. Allowed: {allowed}")
+ return
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute(
+ f"UPDATE exploits_attempted SET {field} = %s WHERE id = %s",
+ (value, exploit_id)
+ )
+ conn.commit()
+ conn.close()
+ print(f"[+] exploits_attempted.{field} updated for id={exploit_id}")
+
+
+def edit_summary_risk(sl_no: int, risk_level: str):
+ """Update the risk level on a summary."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("UPDATE summary SET risk_level = %s WHERE sl_no = %s", (risk_level, sl_no))
+ conn.commit()
+ conn.close()
+ print(f"[+] Summary risk_level updated for SL#{sl_no}")
+
+
+# ─────────────────────────────────────────────
+# DELETE FUNCTIONS
+# ─────────────────────────────────────────────
+
+def delete_vulnerability(vuln_id: int):
+ """Delete a single vulnerability and its linked fixes."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("DELETE FROM fixes WHERE vuln_id = %s", (vuln_id,))
+ c.execute("DELETE FROM vulnerabilities WHERE id = %s", (vuln_id,))
+ conn.commit()
+ conn.close()
+ print(f"[+] Vulnerability id={vuln_id} and its fixes deleted.")
+
+
+def delete_exploit(exploit_id: int):
+ """Delete a single exploit attempt."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("DELETE FROM exploits_attempted WHERE id = %s", (exploit_id,))
+ conn.commit()
+ conn.close()
+ print(f"[+] Exploit id={exploit_id} deleted.")
+
+
+def delete_fix(fix_id: int):
+ """Delete a single fix."""
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("DELETE FROM fixes WHERE id = %s", (fix_id,))
+ conn.commit()
+ conn.close()
+ print(f"[+] Fix id={fix_id} deleted.")
+
+
+def delete_full_session(sl_no: int):
+ """
+ Wipe everything linked to a sl_no across all 5 tables.
+ Order matters — delete children before parent (FK constraints).
+ """
+ conn = get_connection()
+ c = conn.cursor()
+ c.execute("DELETE FROM fixes WHERE sl_no = %s", (sl_no,))
+ c.execute("DELETE FROM exploits_attempted WHERE sl_no = %s", (sl_no,))
+ c.execute("DELETE FROM vulnerabilities WHERE sl_no = %s", (sl_no,))
+ c.execute("DELETE FROM summary WHERE sl_no = %s", (sl_no,))
+ c.execute("DELETE FROM history WHERE sl_no = %s", (sl_no,))
+ conn.commit()
+ conn.close()
+ print(f"[+] Full session SL#{sl_no} deleted from all tables.")
+
+
+# ─────────────────────────────────────────────
+# DISPLAY HELPERS
+# ─────────────────────────────────────────────
+
+def print_history(rows):
+ print("\n" + "─"*65)
+ print(f"{'SL#':<6} {'TARGET':<28} {'DATE':<22} {'STATUS'}")
+ print("─"*65)
+ for row in rows:
+ print(f"{row[0]:<6} {row[1]:<28} {str(row[2]):<22} {row[3]}")
+ print()
+
+
+def print_session(data: dict):
+ h = data["history"]
+ print(f"\n{'═'*60}")
+ print(f" SL# {h[0]} | Target: {h[1]} | {h[2]} | {h[3]}")
+ print(f"{'═'*60}")
+
+ print("\n[ VULNERABILITIES ]")
+ if data["vulns"]:
+ for v in data["vulns"]:
+ print(f" id={v[0]} | {v[2]} | Severity: {v[3]} | Port: {v[4]} | Service: {v[5]}")
+ print(f" {v[6]}")
+ else:
+ print(" None recorded.")
+
+ print("\n[ FIXES ]")
+ if data["fixes"]:
+ for f in data["fixes"]:
+ print(f" id={f[0]} | vuln_id={f[2]} | [{f[4]}] {f[3]}")
+ else:
+ print(" None recorded.")
+
+ print("\n[ EXPLOITS ATTEMPTED ]")
+ if data["exploits"]:
+ for e in data["exploits"]:
+ print(f" id={e[0]} | {e[2]} | Tool: {e[3]} | Result: {e[5]}")
+ print(f" Payload: {e[4]}")
+ print(f" Notes: {e[6]}")
+ else:
+ print(" None recorded.")
+
+ print("\n[ SUMMARY ]")
+ if data["summary"]:
+ s = data["summary"]
+ print(f" Risk Level : {s[4]}")
+ print(f" Generated : {s[5]}")
+ print(f"\n AI Analysis:\n {s[3][:500]}{'...' if len(str(s[3])) > 500 else ''}")
+ else:
+ print(" None recorded.")
+ print()
+
+
+# ─────────────────────────────────────────────
+# QUICK CONNECTION TEST
+# ─────────────────────────────────────────────
+
+if __name__ == "__main__":
+ try:
+ conn = get_connection()
+ print("[+] MariaDB connection successful.")
+ print("[+] Database: metatron")
+ conn.close()
+ except Exception as e:
+ print(f"[!] Connection failed: {e}")
diff --git a/llm.py b/llm.py
new file mode 100644
index 0000000..1c7df11
--- /dev/null
+++ b/llm.py
@@ -0,0 +1,372 @@
+#!/usr/bin/env python3
+"""
+METATRON - llm.py
+Ollama interface for metatron-qwen model.
+Builds prompts, handles AI responses, runs tool dispatch loop.
+Model: metatron-qwen (fine-tuned from huihui_ai/qwen3.5-abliterated:9b)
+"""
+
+import re
+import requests
+import json
+from tools import run_tool_by_command, run_nmap, run_curl_headers
+from search import handle_search_dispatch
+
+OLLAMA_URL = "http://localhost:11434/api/generate"
+MODEL_NAME = "metatron-qwen"
+MAX_TOKENS = 4096
+MAX_TOOL_LOOPS = 9 # max times AI can call tools per session
+OLLAMA_TIMEOUT = 600
+
+# ─────────────────────────────────────────────
+# SYSTEM PROMPT
+# ─────────────────────────────────────────────
+
+SYSTEM_PROMPT = """You are METATRON, an elite AI penetration testing assistant running on Parrot OS.
+You are precise, technical, and direct. No fluff.
+
+You have access to real tools. To use them, write tags in your response:
+
+ [TOOL: nmap -sV 192.168.1.1] → runs nmap or any CLI tool
+ [SEARCH: CVE-2021-44228 exploit] → searches the web via DuckDuckGo
+
+Rules:
+- Always analyze scan data thoroughly before suggesting exploits
+- List vulnerabilities with: name, severity (critical/high/medium/low), port, service
+- For each vulnerability, suggest a concrete fix
+- If you need more information, use [SEARCH:] or [TOOL:]
+- Format vulnerabilities clearly so they can be saved to a database
+- Be specific about CVE IDs when you know them
+- Always give a final risk rating: CRITICAL / HIGH / MEDIUM / LOW
+
+Output format for vulnerabilities (use this exactly):
+VULN: <name> | SEVERITY: <level> | PORT: <port> | SERVICE: <service>
+DESC: <description>
+FIX: <fix recommendation>
+
+Output format for exploits:
+EXPLOIT: <name> | TOOL: <tool> | PAYLOAD: <payload or description>
+RESULT: <expected result>
+NOTES: <any notes>
+
+End your analysis with:
+RISK_LEVEL: <CRITICAL|HIGH|MEDIUM|LOW>
+SUMMARY: <2-3 sentence overall summary>
+"""
+
+
+# ─────────────────────────────────────────────
+# OLLAMA API CALL
+# ─────────────────────────────────────────────
+
+def ask_ollama(prompt: str, context: list = None) -> str:
+ """
+ Send a prompt to metatron-qwen via Ollama API.
+ context: list of previous message dicts for multi-turn conversation.
+ Returns the AI response string.
+ """
+ try:
+ payload = {
+ "model": MODEL_NAME,
+ "prompt": prompt,
+ "stream": False,
+ "options": {
+ "num_predict": MAX_TOKENS,
+ "temperature": 0.7,
+ "top_p": 0.9,
+ }
+ }
+
+ print(f"\n[*] Sending to {MODEL_NAME}...")
+ resp = requests.post(OLLAMA_URL, json=payload, timeout=OLLAMA_TIMEOUT)
+ resp.raise_for_status()
+
+ data = resp.json()
+ response = data.get("response", "").strip()
+
+ if not response:
+ return "[!] Model returned empty response."
+
+ return response
+
+ except requests.exceptions.ConnectionError:
+ return "[!] Cannot connect to Ollama. Is it running? Try: ollama serve"
+ except requests.exceptions.Timeout:
+ return "[!] Ollama timed out. Model may be loading, try again."
+ except requests.exceptions.HTTPError as e:
+ return f"[!] Ollama HTTP error: {e}"
+ except Exception as e:
+ return f"[!] Unexpected error: {e}"
+
+
+# ─────────────────────────────────────────────
+# TOOL DISPATCH
+# ─────────────────────────────────────────────
+
+def extract_tool_calls(response: str) -> list:
+ """
+ Extract all [TOOL: ...] and [SEARCH: ...] tags from AI response.
+ Returns list of tuples: [("TOOL", "nmap -sV x.x.x.x"), ("SEARCH", "CVE...")]
+ """
+ calls = []
+
+ tool_matches = re.findall(r'\[TOOL:\s*(.+?)\]', response)
+ search_matches = re.findall(r'\[SEARCH:\s*(.+?)\]', response)
+
+ for m in tool_matches:
+ calls.append(("TOOL", m.strip()))
+ for m in search_matches:
+ calls.append(("SEARCH", m.strip()))
+
+ return calls
+
+
+def run_tool_calls(calls: list) -> str:
+ """
+ Execute all tool/search calls and return combined results string.
+ """
+ if not calls:
+ return ""
+
+ results = ""
+ for call_type, call_content in calls:
+ print(f"\n [DISPATCH] {call_type}: {call_content}")
+
+ if call_type == "TOOL":
+ output = run_tool_by_command(call_content)
+ elif call_type == "SEARCH":
+ output = handle_search_dispatch(call_content)
+ else:
+ output = f"[!] Unknown call type: {call_type}"
+
+ results += f"\n[{call_type} RESULT: {call_content}]\n"
+ results += "─" * 40 + "\n"
+ results += output.strip() + "\n"
+
+ return results
+
+
+# ─────────────────────────────────────────────
+# PARSER — extract structured data from AI output
+# ─────────────────────────────────────────────
+
+def parse_vulnerabilities(response: str) -> list:
+ """
+ Parse VULN: lines from AI response into dicts.
+ Returns list of vulnerability dicts ready for db.save_vulnerability()
+ """
+ vulns = []
+ lines = response.splitlines()
+
+ i = 0
+ while i < len(lines):
+ line = lines[i].strip()
+
+ if line.startswith("VULN:"):
+ vuln = {
+ "vuln_name": "",
+ "severity": "medium",
+ "port": "",
+ "service": "",
+ "description": "",
+ "fix": ""
+ }
+
+ # parse header line: VULN: name | SEVERITY: x | PORT: x | SERVICE: x
+ parts = line.split("|")
+ for part in parts:
+ part = part.strip()
+ if part.startswith("VULN:"):
+ vuln["vuln_name"] = part.replace("VULN:", "").strip()
+ elif part.startswith("SEVERITY:"):
+ vuln["severity"] = part.replace("SEVERITY:", "").strip().lower()
+ elif part.startswith("PORT:"):
+ vuln["port"] = part.replace("PORT:", "").strip()
+ elif part.startswith("SERVICE:"):
+ vuln["service"] = part.replace("SERVICE:", "").strip()
+
+ # look ahead for DESC: and FIX: lines
+ j = i + 1
+ while j < len(lines) and j <= i + 5:
+ next_line = lines[j].strip()
+ if next_line.startswith("DESC:"):
+ vuln["description"] = next_line.replace("DESC:", "").strip()
+ elif next_line.startswith("FIX:"):
+ vuln["fix"] = next_line.replace("FIX:", "").strip()
+ j += 1
+
+ if vuln["vuln_name"]:
+ vulns.append(vuln)
+
+ i += 1
+
+ return vulns
+
+
+def parse_exploits(response: str) -> list:
+ """
+ Parse EXPLOIT: lines from AI response into dicts.
+ Returns list of exploit dicts ready for db.save_exploit()
+ """
+ exploits = []
+ lines = response.splitlines()
+
+ i = 0
+ while i < len(lines):
+ line = lines[i].strip()
+
+ if line.startswith("EXPLOIT:"):
+ exploit = {
+ "exploit_name": "",
+ "tool_used": "",
+ "payload": "",
+ "result": "unknown",
+ "notes": ""
+ }
+
+ parts = line.split("|")
+ for part in parts:
+ part = part.strip()
+ if part.startswith("EXPLOIT:"):
+ exploit["exploit_name"] = part.replace("EXPLOIT:", "").strip()
+ elif part.startswith("TOOL:"):
+ exploit["tool_used"] = part.replace("TOOL:", "").strip()
+ elif part.startswith("PAYLOAD:"):
+ exploit["payload"] = part.replace("PAYLOAD:", "").strip()
+
+ j = i + 1
+ while j < len(lines) and j <= i + 4:
+ next_line = lines[j].strip()
+ if next_line.startswith("RESULT:"):
+ exploit["result"] = next_line.replace("RESULT:", "").strip()
+ elif next_line.startswith("NOTES:"):
+ exploit["notes"] = next_line.replace("NOTES:", "").strip()
+ j += 1
+
+ if exploit["exploit_name"]:
+ exploits.append(exploit)
+
+ i += 1
+
+ return exploits
+
+
+def parse_risk_level(response: str) -> str:
+ """Extract RISK_LEVEL from AI response."""
+ match = re.search(r'RISK_LEVEL:\s*(CRITICAL|HIGH|MEDIUM|LOW)', response, re.IGNORECASE)
+ return match.group(1).upper() if match else "UNKNOWN"
+
+
+def parse_summary(response: str) -> str:
+ """Extract SUMMARY line from AI response."""
+ match = re.search(r'SUMMARY:\s*(.+)', response, re.IGNORECASE)
+ return match.group(1).strip() if match else response[:500]
+
+
+# ─────────────────────────────────────────────
+# MAIN ANALYSIS FUNCTION
+# ─────────────────────────────────────────────
+
+def analyse_target(target: str, raw_scan: str) -> dict:
+ """
+ Full analysis pipeline:
+ 1. Build initial prompt with scan data
+ 2. Send to metatron-qwen
+ 3. Run tool dispatch loop if AI requests tools
+ 4. Parse structured output
+ 5. Return everything ready for db.py to save
+
+ Returns dict with:
+ - full_response : complete AI text
+ - vulnerabilities : list of parsed vuln dicts
+ - exploits : list of parsed exploit dicts
+ - risk_level : CRITICAL/HIGH/MEDIUM/LOW
+ - summary : short summary text
+ - raw_scan : original scan dump
+ """
+
+ # ── Step 1: initial prompt ──────────────────
+ initial_prompt = f"""{SYSTEM_PROMPT}
+
+TARGET: {target}
+
+RECON DATA:
+{raw_scan}
+
+Analyze this target completely. Use [TOOL:] or [SEARCH:] if you need more information.
+List all vulnerabilities, fixes, and suggest exploits where applicable.
+"""
+
+ full_conversation = initial_prompt
+ final_response = ""
+
+ # ── Step 2: tool dispatch loop ──────────────
+ for loop in range(MAX_TOOL_LOOPS):
+ response = ask_ollama(full_conversation)
+
+ print(f"\n{'─'*60}")
+ print(f"[METATRON - Round {loop + 1}]")
+ print(f"{'─'*60}")
+ print(response)
+
+ final_response = response
+
+ # check for tool calls
+ tool_calls = extract_tool_calls(response)
+ if not tool_calls:
+ print("\n[*] No tool calls. Analysis complete.")
+ break
+
+ # run all tool calls
+ tool_results = run_tool_calls(tool_calls)
+
+ # feed results back into conversation
+ full_conversation = (
+ f"{full_conversation}\n\n"
+ f"[YOUR PREVIOUS RESPONSE]\n{response}\n\n"
+ f"[TOOL RESULTS]\n{tool_results}\n\n"
+ f"Continue your analysis with this new information. "
+ f"If analysis is complete, give the final RISK_LEVEL and SUMMARY."
+ )
+
+ # ── Step 3: parse structured output ─────────
+ vulnerabilities = parse_vulnerabilities(final_response)
+ exploits = parse_exploits(final_response)
+ risk_level = parse_risk_level(final_response)
+ summary = parse_summary(final_response)
+
+ print(f"\n[+] Parsed: {len(vulnerabilities)} vulns, {len(exploits)} exploits | Risk: {risk_level}")
+
+ return {
+ "full_response": final_response,
+ "vulnerabilities": vulnerabilities,
+ "exploits": exploits,
+ "risk_level": risk_level,
+ "summary": summary,
+ "raw_scan": raw_scan
+ }
+
+
+# ─────────────────────────────────────────────
+# QUICK TEST
+# ─────────────────────────────────────────────
+
+if __name__ == "__main__":
+ print("[ llm.py test — direct AI query ]\n")
+
+ # test if ollama is reachable
+ try:
+ r = requests.get("http://localhost:11434", timeout=5)
+ print("[+] Ollama is running.")
+ except Exception:
+ print("[!] Ollama not reachable. Run: ollama serve")
+ exit(1)
+
+ target = input("Test target: ").strip()
+ test_scan = f"Test recon for {target} — nmap and whois data would appear here."
+ result = analyse_target(target, test_scan)
+
+ print(f"\nRisk Level : {result['risk_level']}")
+ print(f"Summary : {result['summary']}")
+ print(f"Vulns found: {len(result['vulnerabilities'])}")
+ print(f"Exploits : {len(result['exploits'])}")
diff --git a/metatron.py b/metatron.py
new file mode 100644
index 0000000..d8af535
--- /dev/null
+++ b/metatron.py
@@ -0,0 +1,427 @@
+#!/usr/bin/env python3
+"""
+METATRON - metatron.py
+Main CLI entry point. Wires db.py + tools.py + search.py + llm.py together.
+Run with: python metatron.py
+"""
+
+import os
+import sys
+from db import (
+ get_connection,
+ create_session,
+ save_vulnerability,
+ save_fix,
+ save_exploit,
+ save_summary,
+ get_all_history,
+ get_session,
+ get_vulnerabilities,
+ get_fixes,
+ get_exploits,
+ edit_vulnerability,
+ edit_fix,
+ edit_exploit,
+ edit_summary_risk,
+ delete_vulnerability,
+ delete_exploit,
+ delete_fix,
+ delete_full_session,
+ print_history,
+ print_session
+)
+from tools import interactive_tool_run, format_recon_for_llm, run_default_recon
+from llm import analyse_target
+
+
+# ─────────────────────────────────────────────
+# BANNER
+# ─────────────────────────────────────────────
+
+def banner():
+ os.system("clear")
+ print("""
+\033[91m
+ ███╗ ███╗███████╗████████╗ █████╗ ████████╗██████╗ ██████╗ ███╗ ██╗
+ ████╗ ████║██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔══██╗██╔═══██╗████╗ ██║
+ ██╔████╔██║█████╗ ██║ ███████║ ██║ ██████╔╝██║ ██║██╔██╗ ██║
+ ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║ ██║ ██╔══██╗██║ ██║██║╚██╗██║
+ ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
+ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
+\033[0m
+ \033[90mAI Penetration Testing Assistant | Model: metatron-qwen | Parrot OS\033[0m
+ \033[90m─────────────────────────────────────────────────────────────────────\033[0m
+""")
+
+
+# ─────────────────────────────────────────────
+# HELPERS
+# ─────────────────────────────────────────────
+
+def divider(label=""):
+ if label:
+ print(f"\n\033[33m{'─'*20} {label} {'─'*20}\033[0m")
+ else:
+ print(f"\033[90m{'─'*60}\033[0m")
+
+
+def prompt(text):
+ return input(f"\033[36m{text}\033[0m").strip()
+
+
+def success(text):
+ print(f"\033[92m[+] {text}\033[0m")
+
+
+def warn(text):
+ print(f"\033[93m[!] {text}\033[0m")
+
+
+def error(text):
+ print(f"\033[91m[✗] {text}\033[0m")
+
+
+def info(text):
+ print(f"\033[94m[*] {text}\033[0m")
+
+
+def confirm(question: str) -> bool:
+ ans = prompt(f"{question} [y/N]: ").lower()
+ return ans == "y"
+
+
+# ─────────────────────────────────────────────
+# NEW SCAN
+# ─────────────────────────────────────────────
+
+def new_scan():
+ divider("NEW SCAN")
+ target = prompt("[?] Enter target IP or domain: ")
+ if not target:
+ warn("No target entered.")
+ return
+
+ # check if target was scanned before
+ history = get_all_history()
+ past = [row for row in history if row[1] == target]
+ if past:
+ warn(f"Target '{target}' has been scanned before ({len(past)} time(s)).")
+ if not confirm("Continue with a new scan?"):
+ return
+
+ # create session in history table first
+ sl_no = create_session(target)
+ success(f"Session created — SL# {sl_no}")
+
+ # run recon tools
+ divider("RECON")
+ info("Choose recon tools to run:")
+ raw_scan = interactive_tool_run(target)
+
+ if not raw_scan.strip():
+ warn("No scan data collected. Aborting.")
+ delete_full_session(sl_no)
+ return
+
+ # send to AI
+ divider("AI ANALYSIS")
+ result = analyse_target(target, raw_scan)
+
+ # ── save everything to DB ──────────────────
+ divider("SAVING TO DATABASE")
+
+ # save vulnerabilities and their fixes
+ for vuln in result["vulnerabilities"]:
+ vuln_id = save_vulnerability(
+ sl_no,
+ vuln["vuln_name"],
+ vuln["severity"],
+ vuln["port"],
+ vuln["service"],
+ vuln["description"]
+ )
+ if vuln.get("fix"):
+ save_fix(sl_no, vuln_id, vuln["fix"], source="ai")
+ success(f"Saved vuln: {vuln['vuln_name']} [{vuln['severity']}]")
+
+ # save exploits
+ for exp in result["exploits"]:
+ save_exploit(
+ sl_no,
+ exp["exploit_name"],
+ exp["tool_used"],
+ exp["payload"],
+ exp["result"],
+ exp["notes"]
+ )
+ success(f"Saved exploit: {exp['exploit_name']}")
+
+ # save summary
+ save_summary(
+ sl_no,
+ result["raw_scan"],
+ result["full_response"],
+ result["risk_level"]
+ )
+
+ success(f"All data saved. SL# {sl_no} | Risk: {result['risk_level']}")
+ divider()
+
+ # show results and offer edit/delete
+ data = get_session(sl_no)
+ print_session(data)
+
+ if confirm("Edit or delete anything in this session?"):
+ edit_delete_menu(sl_no)
+
+
+# ─────────────────────────────────────────────
+# VIEW HISTORY
+# ─────────────────────────────────────────────
+
+def view_history():
+ divider("SCAN HISTORY")
+ rows = get_all_history()
+
+ if not rows:
+ warn("No scans in database yet.")
+ return
+
+ print_history(rows)
+
+ sl_no_str = prompt("Enter SL# to view details (or press Enter to go back): ")
+ if not sl_no_str:
+ return
+
+ try:
+ sl_no = int(sl_no_str)
+ except ValueError:
+ error("Invalid SL#.")
+ return
+
+ data = get_session(sl_no)
+ if not data["history"]:
+ error(f"SL# {sl_no} not found.")
+ return
+
+ print_session(data)
+
+ if confirm("Edit or delete anything in this session?"):
+ edit_delete_menu(sl_no)
+
+
+# ─────────────────────────────────────────────
+# EDIT / DELETE MENU
+# ─────────────────────────────────────────────
+
+def edit_delete_menu(sl_no: int):
+ while True:
+ divider(f"EDIT / DELETE — SL# {sl_no}")
+ print(" [1] Edit a vulnerability")
+ print(" [2] Edit a fix")
+ print(" [3] Edit an exploit")
+ print(" [4] Edit risk level")
+ print(" [5] Delete a vulnerability")
+ print(" [6] Delete a fix")
+ print(" [7] Delete an exploit")
+ print(" [8] Delete FULL session (all tables)")
+ print(" [9] Back")
+ divider()
+
+ choice = prompt("Choice: ")
+
+ # ── EDIT VULNERABILITY ─────────────────
+ if choice == "1":
+ vulns = get_vulnerabilities(sl_no)
+ if not vulns:
+ warn("No vulnerabilities recorded for this session.")
+ continue
+
+ print("\n[ VULNERABILITIES ]")
+ for v in vulns:
+ print(f" id={v[0]} | {v[2]} | {v[3]} | port {v[4]} | {v[5]}")
+
+ vid = prompt("Enter vulnerability id to edit: ")
+ if not vid.isdigit():
+ error("Invalid id.")
+ continue
+
+ print(" Fields: vuln_name / severity / port / service / description")
+ field = prompt("Field to edit: ").strip()
+ value = prompt(f"New value for '{field}': ")
+ edit_vulnerability(int(vid), field, value)
+
+ # ── EDIT FIX ──────────────────────────
+ elif choice == "2":
+ fixes = get_fixes(sl_no)
+ if not fixes:
+ warn("No fixes recorded for this session.")
+ continue
+
+ print("\n[ FIXES ]")
+ for f in fixes:
+ print(f" id={f[0]} | vuln_id={f[2]} | {f[3][:80]}")
+
+ fid = prompt("Enter fix id to edit: ")
+ if not fid.isdigit():
+ error("Invalid id.")
+ continue
+
+ new_text = prompt("New fix text: ")
+ edit_fix(int(fid), new_text)
+
+ # ── EDIT EXPLOIT ──────────────────────
+ elif choice == "3":
+ exploits = get_exploits(sl_no)
+ if not exploits:
+ warn("No exploits recorded for this session.")
+ continue
+
+ print("\n[ EXPLOITS ]")
+ for e in exploits:
+ print(f" id={e[0]} | {e[2]} | tool: {e[3]} | result: {e[5]}")
+
+ eid = prompt("Enter exploit id to edit: ")
+ if not eid.isdigit():
+ error("Invalid id.")
+ continue
+
+ print(" Fields: exploit_name / tool_used / payload / result / notes")
+ field = prompt("Field to edit: ").strip()
+ value = prompt(f"New value for '{field}': ")
+ edit_exploit(int(eid), field, value)
+
+ # ── EDIT RISK LEVEL ───────────────────
+ elif choice == "4":
+ print(" Options: CRITICAL / HIGH / MEDIUM / LOW")
+ risk = prompt("New risk level: ").upper()
+ if risk not in ("CRITICAL", "HIGH", "MEDIUM", "LOW"):
+ error("Invalid risk level.")
+ continue
+ edit_summary_risk(sl_no, risk)
+
+ # ── DELETE VULNERABILITY ──────────────
+ elif choice == "5":
+ vulns = get_vulnerabilities(sl_no)
+ if not vulns:
+ warn("No vulnerabilities to delete.")
+ continue
+
+ print("\n[ VULNERABILITIES ]")
+ for v in vulns:
+ print(f" id={v[0]} | {v[2]} | {v[3]}")
+
+ vid = prompt("Enter vulnerability id to delete: ")
+ if not vid.isdigit():
+ error("Invalid id.")
+ continue
+
+ if confirm(f"Delete vulnerability id={vid} and its linked fixes?"):
+ delete_vulnerability(int(vid))
+
+ # ── DELETE FIX ────────────────────────
+ elif choice == "6":
+ fixes = get_fixes(sl_no)
+ if not fixes:
+ warn("No fixes to delete.")
+ continue
+
+ print("\n[ FIXES ]")
+ for f in fixes:
+ print(f" id={f[0]} | vuln_id={f[2]} | {f[3][:80]}")
+
+ fid = prompt("Enter fix id to delete: ")
+ if not fid.isdigit():
+ error("Invalid id.")
+ continue
+
+ if confirm(f"Delete fix id={fid}?"):
+ delete_fix(int(fid))
+
+ # ── DELETE EXPLOIT ────────────────────
+ elif choice == "7":
+ exploits = get_exploits(sl_no)
+ if not exploits:
+ warn("No exploits to delete.")
+ continue
+
+ print("\n[ EXPLOITS ]")
+ for e in exploits:
+ print(f" id={e[0]} | {e[2]} | result: {e[5]}")
+
+ eid = prompt("Enter exploit id to delete: ")
+ if not eid.isdigit():
+ error("Invalid id.")
+ continue
+
+ if confirm(f"Delete exploit id={eid}?"):
+ delete_exploit(int(eid))
+
+ # ── DELETE FULL SESSION ───────────────
+ elif choice == "8":
+ if confirm(f"\n\033[91mPermanently delete ENTIRE session SL# {sl_no} from all tables?\033[0m"):
+ delete_full_session(sl_no)
+ success(f"Session SL# {sl_no} wiped.")
+ return # go back to main menu
+
+ # ── BACK ──────────────────────────────
+ elif choice == "9":
+ break
+
+ else:
+ warn("Invalid choice.")
+
+
+# ─────────────────────────────────────────────
+# DB CONNECTION CHECK
+# ─────────────────────────────────────────────
+
+def check_db():
+ try:
+ conn = get_connection()
+ conn.close()
+ return True
+ except Exception as e:
+ error(f"MariaDB connection failed: {e}")
+ error("Make sure MariaDB is running: sudo systemctl start mariadb")
+ return False
+
+
+# ─────────────────────────────────────────────
+# MAIN MENU
+# ─────────────────────────────────────────────
+
+def main_menu():
+ while True:
+ banner()
+ print(" \033[92m[1]\033[0m New Scan")
+ print(" \033[92m[2]\033[0m View History")
+ print(" \033[92m[3]\033[0m Exit")
+ divider()
+
+ choice = prompt("metatron> ")
+
+ if choice == "1":
+ new_scan()
+ input("\n\033[90mPress Enter to continue...\033[0m")
+
+ elif choice == "2":
+ view_history()
+ input("\n\033[90mPress Enter to continue...\033[0m")
+
+ elif choice == "3":
+ print("\n\033[91m[*] Shutting down Metatron. Stay legal.\033[0m\n")
+ sys.exit(0)
+
+ else:
+ warn("Invalid choice.")
+
+
+# ─────────────────────────────────────────────
+# ENTRY POINT
+# ─────────────────────────────────────────────
+
+if __name__ == "__main__":
+ if not check_db():
+ sys.exit(1)
+ main_menu()
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..76003eb
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,21 @@
+anyio==4.13.0
+beautifulsoup4==4.14.3
+certifi==2026.2.25
+charset-normalizer==3.4.6
+click==8.3.1
+duckduckgo_search==8.1.1
+h11==0.16.0
+httpcore==1.0.9
+httpx==0.28.1
+idna==3.11
+lxml==6.0.2
+markdown-it-py==4.0.0
+mdurl==0.1.2
+mysql-connector-python==9.6.0
+primp==1.2.1
+Pygments==2.20.0
+requests==2.33.1
+rich==14.3.3
+soupsieve==2.8.3
+typing_extensions==4.15.0
+urllib3==2.6.3
diff --git a/search.py b/search.py
new file mode 100644
index 0000000..89ad1ca
--- /dev/null
+++ b/search.py
@@ -0,0 +1,175 @@
+#!/usr/bin/env python3
+"""
+METATRON - search.py
+Free web search via DuckDuckGo — no API key needed.
+Also fetches and extracts plain text from URLs.
+Used by LLM tool dispatch when AI writes [SEARCH: query]
+"""
+
+import requests
+from bs4 import BeautifulSoup
+from duckduckgo_search import DDGS # pip install duckduckgo-search
+
+
+# ─────────────────────────────────────────────
+# DDG SEARCH
+# ─────────────────────────────────────────────
+
+def web_search(query: str, max_results: int = 5) -> str:
+ """
+ Search DuckDuckGo and return formatted results.
+ No API key. No rate limit issues for reasonable usage.
+ Returns a string ready to paste into LLM prompt.
+ """
+ print(f" [*] Searching: {query}")
+ try:
+ with DDGS() as ddgs:
+ results = list(ddgs.text(query, max_results=max_results))
+
+ if not results:
+ return "[!] No search results found."
+
+ output = f"[WEB SEARCH RESULTS FOR: {query}]\n"
+ output += "─" * 50 + "\n"
+ for i, r in enumerate(results, 1):
+ output += f"\n[{i}] {r['title']}\n"
+ output += f" URL : {r['href']}\n"
+ output += f" Snippet : {r['body']}\n"
+
+ return output
+
+ except Exception as e:
+ return f"[!] Search failed: {e}"
+
+
+# ─────────────────────────────────────────────
+# CVE SPECIFIC SEARCH
+# ─────────────────────────────────────────────
+
+def search_cve(cve_id: str) -> str:
+ """
+ Search for a specific CVE.
+ Queries DDG then also hits cve.mitre.org directly.
+ """
+ print(f" [*] Looking up {cve_id}...")
+
+ # DDG search first
+ ddg_results = web_search(f"{cve_id} vulnerability exploit details", max_results=3)
+
+ # Direct MITRE fetch
+ mitre_url = f"https://cve.mitre.org/cgi-bin/cvename.cgi?name={cve_id}"
+ mitre_data = fetch_page(mitre_url, max_chars=2000)
+
+ return f"{ddg_results}\n\n[MITRE CVE LOOKUP: {cve_id}]\n{mitre_data}"
+
+
+def search_exploit(service: str, version: str) -> str:
+ """
+ Search for known exploits for a service + version combo.
+ e.g. search_exploit("apache", "2.4.49")
+ """
+ query = f"{service} {version} exploit CVE vulnerability 2023 2024"
+ return web_search(query, max_results=5)
+
+
+def search_fix(vuln_name: str) -> str:
+ """
+ Search for mitigation/fix for a vulnerability.
+ """
+ query = f"how to fix {vuln_name} security mitigation patch"
+ return web_search(query, max_results=3)
+
+
+# ─────────────────────────────────────────────
+# PAGE FETCHER
+# ─────────────────────────────────────────────
+
+def fetch_page(url: str, max_chars: int = 3000) -> str:
+ """
+ Fetch a URL and return extracted plain text.
+ Strips all HTML tags. Truncated to max_chars for LLM context.
+ """
+ try:
+ headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/120.0"}
+ resp = requests.get(url, headers=headers, timeout=15)
+ resp.raise_for_status()
+
+ soup = BeautifulSoup(resp.text, "html.parser")
+
+ # remove nav/footer/script noise
+ for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
+ tag.decompose()
+
+ text = soup.get_text(separator="\n", strip=True)
+
+ # collapse blank lines
+ lines = [l for l in text.splitlines() if l.strip()]
+ clean = "\n".join(lines)
+
+ if len(clean) > max_chars:
+ clean = clean[:max_chars] + f"\n... [truncated at {max_chars} chars]"
+
+ return clean
+
+ except requests.exceptions.ConnectionError:
+ return "[!] Could not connect to URL — check network."
+ except requests.exceptions.Timeout:
+ return "[!] Page fetch timed out."
+ except requests.exceptions.HTTPError as e:
+ return f"[!] HTTP error: {e}"
+ except Exception as e:
+ return f"[!] Fetch failed: {e}"
+
+
+# ─────────────────────────────────────────────
+# TOOL DISPATCH HANDLER
+# ─────────────────────────────────────────────
+
+def handle_search_dispatch(query: str) -> str:
+ """
+ Called by llm.py when AI writes [SEARCH: something].
+ Smartly routes to CVE lookup, exploit search, or general search.
+ """
+ query = query.strip()
+
+ # CVE pattern — CVE-YYYY-NNNNN
+ import re
+ cve_pattern = re.compile(r'CVE-\d{4}-\d{4,7}', re.IGNORECASE)
+ cve_match = cve_pattern.search(query)
+ if cve_match:
+ return search_cve(cve_match.group())
+
+ # exploit keywords
+ if any(word in query.lower() for word in ["exploit", "poc", "payload", "rce", "lfi", "sqli"]):
+ return web_search(query + " exploit poc github", max_results=5)
+
+ # fix/patch keywords
+ if any(word in query.lower() for word in ["fix", "patch", "mitigate", "harden", "secure"]):
+ return search_fix(query)
+
+ # default general search
+ return web_search(query, max_results=5)
+
+
+# ─────────────────────────────────────────────
+# QUICK TEST
+# ─────────────────────────────────────────────
+
+if __name__ == "__main__":
+ print("[ search.py test ]\n")
+ print("[1] General search")
+ print("[2] CVE lookup")
+ print("[3] Fetch a URL")
+ choice = input("Choice: ").strip()
+
+ if choice == "1":
+ q = input("Query: ").strip()
+ print(web_search(q))
+
+ elif choice == "2":
+ cve = input("CVE ID (e.g. CVE-2021-44228): ").strip()
+ print(search_cve(cve))
+
+ elif choice == "3":
+ url = input("URL: ").strip()
+ print(fetch_page(url))
diff --git a/tools.py b/tools.py
new file mode 100644
index 0000000..c71e5b1
--- /dev/null
+++ b/tools.py
@@ -0,0 +1,254 @@
+#!/usr/bin/env python3
+"""
+METATRON - tools.py
+Recon tool runners — all output returned as strings to feed into the LLM.
+Tools used: nmap, whois, whatweb, curl, dig, nikto
+OS: Parrot OS (all these tools are pre-installed or easily available)
+"""
+
+import subprocess
+
+
+# ─────────────────────────────────────────────
+# BASE RUNNER
+# ─────────────────────────────────────────────
+
+def run_tool(command: list, timeout: int = 120) -> str:
+ """
+ Execute a shell command, return combined stdout + stderr as string.
+ Never crashes the program — always returns something.
+ """
+ try:
+ result = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=timeout
+ )
+ output = result.stdout.strip()
+ errors = result.stderr.strip()
+
+ if output and errors:
+ return output + "\n[STDERR]\n" + errors
+ elif output:
+ return output
+ elif errors:
+ return errors
+ else:
+ return "[!] Tool returned no output."
+
+ except subprocess.TimeoutExpired:
+ return f"[!] Timed out after {timeout}s: {' '.join(command)}"
+ except FileNotFoundError:
+ return f"[!] Tool not found: {command[0]} — install it with: sudo apt install {command[0]}"
+ except Exception as e:
+ return f"[!] Unexpected error running {command[0]}: {e}"
+
+
+# ─────────────────────────────────────────────
+# INDIVIDUAL TOOLS
+# ─────────────────────────────────────────────
+
+def run_nmap(target: str) -> str:
+ """
+ nmap -sV -sC -T4 --open
+ -sV : detect service versions
+ -sC : run default scripts (basic vuln checks)
+ -T4 : aggressive timing (faster)
+ --open : only show open ports
+ """
+ print(f" [*] nmap -sV -sC -T4 --open {target}")
+ return run_tool(["nmap", "-sV", "-sC", "-T4", "--open", target], timeout=180)
+
+
+def run_whois(target: str) -> str:
+ """
+ whois — domain registration, registrar, IP ownership info
+ """
+ print(f" [*] whois {target}")
+ return run_tool(["whois", target], timeout=30)
+
+
+def run_whatweb(target: str) -> str:
+ """
+ whatweb -a 3 — fingerprint web technologies, CMS, frameworks, headers
+ -a 3 : aggression level 3 (active but not destructive)
+ """
+ print(f" [*] whatweb -a 3 {target}")
+ return run_tool(["whatweb", "-a", "3", target], timeout=60)
+
+
+def run_curl_headers(target: str) -> str:
+ """
+ curl -sI — fetch HTTP headers only
+ Reveals: server software, X-Powered-By, cookies, security headers (or lack of them)
+ """
+ print(f" [*] curl -sI http://{target}")
+ output = run_tool([
+ "curl", "-sI",
+ "--max-time", "10",
+ "--location", # follow redirects
+ f"http://{target}"
+ ], timeout=20)
+
+ # also try https
+ https_output = run_tool([
+ "curl", "-sI",
+ "--max-time", "10",
+ "--location",
+ "-k", # ignore cert errors
+ f"https://{target}"
+ ], timeout=20)
+
+ return f"[HTTP Headers]\n{output}\n\n[HTTPS Headers]\n{https_output}"
+
+
+def run_dig(target: str) -> str:
+ """
+ dig — DNS records: A, MX, NS, TXT
+ Useful for subdomains, mail servers, SPF/DKIM info
+ """
+ print(f" [*] dig {target} ANY")
+ a_record = run_tool(["dig", "+short", "A", target], timeout=15)
+ mx_record = run_tool(["dig", "+short", "MX", target], timeout=15)
+ ns_record = run_tool(["dig", "+short", "NS", target], timeout=15)
+ txt_record= run_tool(["dig", "+short", "TXT", target], timeout=15)
+
+ return (
+ f"[A Records]\n{a_record}\n\n"
+ f"[MX Records]\n{mx_record}\n\n"
+ f"[NS Records]\n{ns_record}\n\n"
+ f"[TXT Records]\n{txt_record}"
+ )
+
+
+def run_nikto(target: str) -> str:
+ """
+ nikto -h — web server vulnerability scanner
+ Checks for outdated software, dangerous files, misconfigurations
+ WARNING: noisy tool, only run with permission
+ """
+ print(f" [*] nikto -h {target} (this may take a while...)")
+ return run_tool(["nikto", "-h", target, "-nointeractive"], timeout=300)
+
+
+# ─────────────────────────────────────────────
+# MAIN RECON PIPELINE
+# ─────────────────────────────────────────────
+
+TOOLS_MENU = {
+ "1": ("nmap", run_nmap),
+ "2": ("whois", run_whois),
+ "3": ("whatweb", run_whatweb),
+ "4": ("curl headers", run_curl_headers),
+ "5": ("dig DNS", run_dig),
+ "6": ("nikto", run_nikto),
+}
+
+
+def run_default_recon(target: str) -> dict:
+ """
+ Run the standard recon pipeline (everything except nikto).
+ Returns a dict of {tool_name: output_string}.
+ Nikto is excluded by default — too slow/noisy for auto-run.
+ """
+ print(f"\n[*] Starting recon on: {target}")
+ print("─" * 50)
+
+ results = {}
+ results["nmap"] = run_nmap(target)
+ results["whois"] = run_whois(target)
+ results["whatweb"] = run_whatweb(target)
+ results["curl_headers"] = run_curl_headers(target)
+ results["dig"] = run_dig(target)
+
+ print("─" * 50)
+ print("[+] Recon complete.\n")
+ return results
+
+
+def run_single_tool(tool_key: str, target: str) -> str:
+ """Run one tool by its menu key. Used by AI tool dispatch."""
+ if tool_key in TOOLS_MENU:
+ name, func = TOOLS_MENU[tool_key]
+ return func(target)
+ return f"[!] Unknown tool key: {tool_key}"
+
+
+def format_recon_for_llm(results: dict) -> str:
+ """
+ Flatten the recon results dict into one clean string
+ to paste into the LLM prompt.
+ """
+ output = ""
+ for tool, data in results.items():
+ output += f"\n{'='*50}\n"
+ output += f"[ {tool.upper()} OUTPUT ]\n"
+ output += f"{'='*50}\n"
+ output += data.strip() + "\n"
+ return output
+
+
+def run_tool_by_command(command_str: str) -> str:
+ """
+ Called by LLM tool dispatch when AI writes [TOOL: nmap -sV 1.2.3.4].
+ Splits the string and runs it safely.
+ """
+ parts = command_str.strip().split()
+ if not parts:
+ return "[!] Empty command."
+
+ # safety check — block destructive commands
+ blocked = ["rm", "dd", "mkfs", "shutdown", "reboot", "wget", "curl -o", "chmod"]
+ if parts[0] in blocked:
+ return f"[!] Blocked command: {parts[0]}"
+
+ return run_tool(parts)
+
+
+# ─────────────────────────────────────────────
+# INTERACTIVE TOOL SELECTOR (called from CLI)
+# ─────────────────────────────────────────────
+
+def interactive_tool_run(target: str) -> str:
+ """
+ Let user manually pick which tools to run.
+ Returns combined output string.
+ """
+ print("\n[ SELECT TOOLS TO RUN ]")
+ for key, (name, _) in TOOLS_MENU.items():
+ print(f" [{key}] {name}")
+ print(" [a] Run all (except nikto)")
+ print(" [n] Run all + nikto (slow)")
+
+ choice = input("\nChoice(s) e.g. 1 2 4 or a: ").strip().lower()
+
+ if choice == "a":
+ results = run_default_recon(target)
+ return format_recon_for_llm(results)
+
+ if choice == "n":
+ results = run_default_recon(target)
+ results["nikto"] = run_nikto(target)
+ return format_recon_for_llm(results)
+
+ combined = {}
+ for key in choice.split():
+ if key in TOOLS_MENU:
+ name, func = TOOLS_MENU[key]
+ print(f"\n[*] Running {name}...")
+ combined[name] = func(target)
+ else:
+ print(f"[!] Unknown option: {key}")
+
+ return format_recon_for_llm(combined)
+
+
+# ─────────────────────────────────────────────
+# QUICK TEST
+# ─────────────────────────────────────────────
+
+if __name__ == "__main__":
+ target = input("Enter test target (IP or domain): ").strip()
+ results = run_default_recon(target)
+ print(format_recon_for_llm(results))