Buckets:

download
raw
22.3 kB
#!/usr/bin/env python3
"""
Zen AI Pentest - Interactive TUI v2
With Kimi Device Authentication Bridge
No hardcoded API keys - secure device flow!
"""
import json
import os
import shlex
import subprocess
import sys
import tempfile
from typing import Dict, List
from rich import box
# Rich imports
from rich.console import Console
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.prompt import Confirm, Prompt
from rich.table import Table
# Add project to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Try to import Kimi Auth Bridge
try:
from kimi_auth_bridge import KimiAuthBridge
KIMI_AUTH_AVAILABLE = True
except ImportError:
KIMI_AUTH_AVAILABLE = False
console = Console()
class ZenTUIv2:
"""Interactive Zen AI Pentest TUI with Device Auth"""
def __init__(self):
self.target = None
self.services = []
self.auth_bridge = None
if KIMI_AUTH_AVAILABLE:
self.auth_bridge = KimiAuthBridge()
def clear(self):
console.clear()
def banner(self):
banner_text = """
███████╗███████╗███╗ ██╗ █████╗ ███████╗
╚══███╔╝██╔════╝████╗ ██║ ██╔══██╗██╔════╝
███╔╝ █████╗ ██╔██╗ ██║ ███████║███████╗
███╔╝ ██╔══╝ ██║╚██╗██║ ██╔══██║╚════██║
███████╗███████╗██║ ╚████║ ██║ ██║███████║
╚══════╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝╚══════╝
🎯 AI-Powered Penetration Testing Platform 🎯
🔐 Secure Device Authentication 🔐
"""
console.print(Panel(banner_text, style="bold cyan", border_style="cyan"))
def check_auth(self) -> bool:
"""Check if user is authenticated via Kimi CLI"""
if not KIMI_AUTH_AVAILABLE:
console.print("[yellow]⚠️ Kimi Auth Bridge nicht installiert[/yellow]")
console.print("[dim]Installiere: pip install kimi-auth-bridge[/dim]")
return False
if self.auth_bridge.is_authenticated():
token = self.auth_bridge.get_access_token()
console.print("[green]✅ Authentifiziert![/green]")
console.print(f"[dim]Token: {token[:20]}...[/dim]")
return True
else:
console.print("[red]❌ Nicht authentifiziert[/red]")
console.print("[yellow]💡 Führe aus:[/yellow] [bold]kimi login[/bold]")
return False
def main_menu(self) -> str:
console.print("\n[bold yellow]Hauptmenü[/bold yellow]\n")
menu = Table(box=box.ROUNDED, show_header=False)
menu.add_column("#", style="cyan", justify="center")
menu.add_column("Aktion", style="green")
menu.add_column("Beschreibung", style="dim")
options = [
("1", "🔐 Login Status", "Kimi Device Auth Status prüfen"),
("2", "🎯 Quick Scan", "Ziel scannen → Exploits finden"),
("3", "🔍 Service Analyse", "Bekannte Services analysieren"),
("4", "💥 Auto-Exploit", "Gefundene Schwachstellen ausnutzen"),
("5", "🔧 Werkzeuge", "SearchSploit, CVE Lookup, etc."),
("6", "🐚 Shell", "Bash direkt in der TUI"),
("0", "❌ Beenden", "Programm beenden"),
]
for num, action, desc in options:
menu.add_row(num, action, desc)
console.print(menu)
choice = Prompt.ask(
"\n[bold cyan]Wähle eine Option[/bold cyan]",
choices=["0", "1", "2", "3", "4", "5", "6"],
default="1",
)
return choice
def login_status(self):
"""Show login status with Device Auth"""
self.clear()
self.banner()
console.print(
Panel(
"[bold yellow]🔐 Authentifizierungs-Status[/bold yellow]",
border_style="yellow",
)
)
if not KIMI_AUTH_AVAILABLE:
console.print("[red]❌ Kimi Auth Bridge nicht verfügbar[/red]")
console.print("\n[dim]Installiere mit:[/dim]")
console.print("[cyan]pip install -e /tmp/kimi-auth-bridge[/cyan]")
return
if self.auth_bridge.is_authenticated():
token = self.auth_bridge.get_access_token()
user_agent = self.auth_bridge.get_user_agent()
console.print("[green]✅ Erfolgreich authentifiziert![/green]\n")
info = Table(title="Authentifizierungs-Details", box=box.ROUNDED)
info.add_column("Eigenschaft", style="cyan")
info.add_column("Wert", style="green")
info.add_row("Token", f"{token[:30]}...")
info.add_row("User-Agent", user_agent)
info.add_row("Status", "✅ Aktiv")
console.print(info)
# Test API connection
console.print("\n[bold cyan]🔄 Teste API-Verbindung...[/bold cyan]")
try:
import requests
response = requests.get(
"https://api.moonshot.cn/v1/models",
headers={
"Authorization": f"Bearer {token}",
"User-Agent": user_agent,
},
timeout=10,
)
if response.status_code == 200:
console.print("[green]✅ API-Verbindung erfolgreich![/green]")
data = response.json()
if "data" in data:
models = [m.get("id", "unknown") for m in data["data"][:3]]
console.print(f"[dim]Verfügbare Modelle: {', '.join(models)}...[/dim]")
else:
console.print(f"[yellow]⚠️ API-Status: {response.status_code}[/yellow]")
except Exception as e:
console.print(f"[red]❌ API-Test fehlgeschlagen: {e}[/red]")
else:
console.print("[red]❌ Nicht authentifiziert[/red]\n")
console.print("[yellow]Um dich zu authentifizieren:[/yellow]")
console.print("1. Führe aus: [bold cyan]kimi login[/bold cyan]")
console.print("2. Folge den Anweisungen im Browser")
console.print("3. Starte diese TUI erneut\n")
def quick_scan(self):
"""Quick scan workflow"""
self.clear()
self.banner()
console.print(
Panel(
"[bold yellow]🎯 Quick Scan Workflow[/bold yellow]",
border_style="yellow",
)
)
# Check auth first
if KIMI_AUTH_AVAILABLE and not self.auth_bridge.is_authenticated():
console.print("[yellow]⚠️ Nicht authentifiziert - Scan läuft lokal ohne AI[/yellow]\n")
target = Prompt.ask(
"[bold green]Ziel-IP oder Hostname[/bold green]",
default="192.168.1.245",
)
self.target = target
if not Confirm.ask(f"[yellow]Scanne {target}?[/yellow]", default=True):
return
console.print(f"\n[bold cyan]🔍 Starte Portscan auf {target}...[/bold cyan]")
import tempfile
xml_fd, xml_file = tempfile.mkstemp(suffix=".xml", prefix="zen_scan_")
os.close(xml_fd)
with Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
console=console,
) as progress:
task = progress.add_task("[cyan]Scanne Ports mit nmap...", total=None)
try:
subprocess.run(
[
"nmap",
"-sV",
"--top-ports",
"50",
"-oX",
xml_file,
target,
],
capture_output=True,
text=True,
timeout=300,
)
progress.update(task, completed=True)
except Exception as e:
console.print(f"[red]❌ Scan fehlgeschlagen: {e}[/red]")
return
console.print("[bold green]✅ Scan abgeschlossen![/bold green]")
services = self._parse_nmap_xml(xml_file)
self.services = services
if not services:
console.print("[yellow]⚠️ Keine Services gefunden[/yellow]")
return
self._show_services_table(services)
if Confirm.ask(
"\n[bold yellow]Mit Zen-AI auf Exploits analysieren?[/bold yellow]",
default=True,
):
self._analyze_services(services)
def _parse_nmap_xml(self, xml_file: str) -> List[Dict]:
services = []
try:
import xml.etree.ElementTree as ET
# nosec B314: Using defusedxml for safe XML parsing
try:
from defusedxml import ElementTree as DefusedET
tree = DefusedET.parse(xml_file)
# nosemgrep: python.lang.security.use-defused-xml.use-defused-xml
except ImportError:
import xml.etree.ElementTree as ET
tree = ET.parse(xml_file) # nosec B314: Fallback when defusedxml not available
root = tree.getroot()
for host in root.findall("host"):
host_ip = host.find("address").get("addr", "unknown")
ports_elem = host.find("ports")
if ports_elem is None:
continue
for port in ports_elem.findall("port"):
port_num = int(port.get("portid", 0))
protocol = port.get("protocol", "tcp")
state = port.find("state")
if state is not None and state.get("state") == "open":
service_elem = port.find("service")
if service_elem is not None:
services.append(
{
"name": service_elem.get("name", "unknown"),
"port": port_num,
"protocol": protocol,
"version": service_elem.get("version", ""),
"product": service_elem.get("product", ""),
"host": host_ip,
}
)
except Exception as e:
console.print(f"[red]Fehler beim Parsen: {e}[/red]")
return services
def _show_services_table(self, services: List[Dict]):
table = Table(title="Gefundene Services", box=box.ROUNDED)
table.add_column("Port", style="cyan", justify="right")
table.add_column("Protokoll", style="dim")
table.add_column("Service", style="green")
table.add_column("Version", style="yellow")
for svc in services:
table.add_row(
str(svc["port"]),
svc["protocol"],
svc["name"],
svc.get("version", "-"),
)
console.print(table)
def _analyze_services(self, services: List[Dict]):
console.print("\n[bold cyan]🧠 Analysiere Services mit Zen-AI...[/bold cyan]")
json_fd, json_file = tempfile.mkstemp(suffix=".json", prefix="zen_services_")
os.close(json_fd)
with open(json_file, "w") as f:
json.dump(services, f, indent=2)
try:
subprocess.run(
[
"python3",
"zen_ai_pentest.py",
"--analyze-services",
json_file,
],
capture_output=True,
text=True,
timeout=120,
cwd="/home/atakan/Zen-Ai-Pentest",
)
console.print("[bold green]✅ Analyse abgeschlossen![/bold green]")
vuln_file = "/home/atakan/Zen-Ai-Pentest/vulnerability_mapping.json"
if os.path.exists(vuln_file):
self._show_vulnerability_report(vuln_file)
if Confirm.ask(
"\n[bold red]💥 Auto-Exploit starten?[/bold red]",
default=False,
):
self._auto_exploit(vuln_file)
except Exception as e:
console.print(f"[red]❌ Analyse fehlgeschlagen: {e}[/red]")
def _show_vulnerability_report(self, vuln_file: str):
try:
with open(vuln_file, "r") as f:
data = json.load(f)
high_conf = [m for m in data.get("mappings", []) if m.get("confidence_score", 0) >= 0.7]
if high_conf:
console.print(f"\n[bold red]🔴 {len(high_conf)} High-Confidence Exploits gefunden![/bold red]")
table = Table(title="Kritische Schwachstellen", box=box.ROUNDED)
table.add_column("Port", style="cyan")
table.add_column("Service", style="green")
table.add_column("Confidence", style="red")
table.add_column("Exploits", style="yellow")
for m in high_conf[:10]:
svc = m["service"]
exploits = m.get("exploits", [])
table.add_row(
f"{svc['port']}/{svc['protocol']}",
f"{svc['name']} {svc.get('version', '')}",
f"{m['confidence_score']:.0%}",
str(len(exploits)),
)
console.print(table)
else:
console.print("[yellow]⚠️ Keine high-confidence Exploits gefunden[/yellow]")
except Exception as e:
console.print(f"[red]Fehler: {e}[/red]")
def _auto_exploit(self, vuln_file: str):
console.print("\n[bold red]💥 Starte Auto-Exploit...[/bold red]")
console.print("[yellow]⚠️ Dry-Run Modus[/yellow]\n")
try:
result = subprocess.run(
[
"python3",
"zen_ai_pentest.py",
"--msf-auto",
f"{self.target}:{vuln_file}",
"--msf-dry-run",
],
capture_output=True,
text=True,
timeout=120,
cwd="/home/atakan/Zen-Ai-Pentest",
)
output = result.stdout + result.stderr
if "Would execute" in output:
console.print("[bold green]✅ Folgende Exploits würden ausgeführt:[/bold green]\n")
for line in output.split("\n"):
if "Would execute" in line:
exploit = line.split("Would execute:")[1].strip()
console.print(f" [cyan]→ {exploit}[/cyan]")
except Exception as e:
console.print(f"[red]Fehler: {e}[/red]")
def tools_menu(self):
self.clear()
self.banner()
console.print(
Panel(
"[bold yellow]🔧 Werkzeuge[/bold yellow]",
border_style="yellow",
)
)
tools = Table(box=box.ROUNDED)
tools.add_column("#", style="cyan")
tools.add_column("Tool", style="green")
tools.add_row("1", "SearchSploit")
tools.add_row("2", "CVE Lookup")
tools.add_row("3", "Nmap Quick")
tools.add_row("0", "Zurück")
console.print(tools)
choice = Prompt.ask("Tool", choices=["0", "1", "2", "3"])
if choice == "1":
query = Prompt.ask("Suchbegriff", default="wordpress sql injection")
self._run_searchsploit(query)
elif choice == "2":
cve = Prompt.ask("CVE", default="CVE-2011-2523")
self._run_cve_lookup(cve)
elif choice == "3":
target = Prompt.ask("Ziel", default=self.target or "192.168.1.245")
self._quick_nmap(target)
def _run_searchsploit(self, query: str):
console.print(f"\n[bold cyan]🔍 Suche: {query}[/bold cyan]")
try:
result = subprocess.run(
["python3", "zen_ai_pentest.py", "--search-exploit", query],
capture_output=True,
text=True,
timeout=30,
cwd="/home/atakan/Zen-Ai-Pentest",
)
for line in (result.stdout + result.stderr).split("\n"):
if "EDB-" in line or "Found" in line:
console.print(line)
except Exception as e:
console.print(f"[red]Fehler: {e}[/red]")
def _run_cve_lookup(self, cve: str):
console.print(f"\n[bold cyan]🔍 CVE: {cve}[/bold cyan]")
try:
result = subprocess.run(
["python3", "zen_ai_pentest.py", "--search-cve", cve],
capture_output=True,
text=True,
timeout=30,
cwd="/home/atakan/Zen-Ai-Pentest",
)
for line in (result.stdout + result.stderr).split("\n"):
if "EDB-" in line or "Found" in line or "Verified" in line:
console.print(line)
except Exception as e:
console.print(f"[red]Fehler: {e}[/red]")
def _quick_nmap(self, target: str):
console.print(f"\n[bold cyan]🔍 Nmap Quick: {target}[/bold cyan]")
try:
result = subprocess.run(
["nmap", "-F", target],
capture_output=True,
text=True,
timeout=60,
)
console.print(result.stdout)
except Exception as e:
console.print(f"[red]Fehler: {e}[/red]")
def shell_mode(self):
"""Interactive shell mode within TUI"""
self.clear()
self.banner()
console.print(
Panel(
"[bold yellow]🐚 Shell Modus[/bold yellow]\n[dim]Tippe 'exit' oder 'quit' zum Zurückkehren[/dim]",
border_style="yellow",
)
)
import subprocess
while True:
try:
# Get current directory
cwd = os.getcwd()
prompt_text = (
f"\n[bold green]{os.getlogin()}@{os.uname().nodename}[/bold green]:[bold blue]{cwd}[/bold blue]$ "
)
cmd = Prompt.ask(prompt_text, default="")
if not cmd:
continue
if cmd.lower() in ("exit", "quit", "q"):
console.print("[yellow]↩️ Zurück zum Hauptmenü[/yellow]")
break
# Handle cd command
if cmd.startswith("cd "):
try:
new_dir = cmd[3:].strip()
os.chdir(new_dir)
console.print(f"[dim]📁 {os.getcwd()}[/dim]")
except Exception as e:
console.print(f"[red]cd: {e}[/red]")
continue
# Execute command
try:
# Parse command safely to avoid shell injection (B602 fix)
cmd_parts = shlex.split(cmd)
result = subprocess.run(
cmd_parts,
shell=False,
capture_output=True,
text=True,
timeout=60,
)
if result.stdout:
console.print(result.stdout)
if result.stderr:
console.print(f"[red]{result.stderr}[/red]")
console.print(f"[dim]Exit code: {result.returncode}[/dim]")
except subprocess.TimeoutExpired:
console.print("[red]⏱️ Befehl timeout (60s)[/red]")
except Exception as e:
console.print(f"[red]❌ Fehler: {e}[/red]")
except KeyboardInterrupt:
console.print("\n[yellow]↩️ Zurück zum Hauptmenü[/yellow]")
break
except EOFError:
break
def run(self):
try:
while True:
self.clear()
self.banner()
if self.target:
status = f"[bold green]Target: {self.target}[/bold green]"
if self.services:
status += f" | [bold yellow]{len(self.services)} Services[/bold yellow]"
console.print(Panel(status, border_style="green"))
choice = self.main_menu()
if choice == "0":
console.print("\n[bold cyan]👋 Auf Wiedersehen![/bold cyan]")
break
elif choice == "1":
self.login_status()
elif choice == "2":
self.quick_scan()
elif choice == "3":
# Service Analyse
pass
elif choice == "4":
vuln_file = "/home/atakan/Zen-Ai-Pentest/vulnerability_mapping.json"
if os.path.exists(vuln_file):
self._auto_exploit(vuln_file)
else:
console.print("[red]❌ Keine Analyse gefunden.[/red]")
elif choice == "5":
self.tools_menu()
elif choice == "6":
self.shell_mode()
Prompt.ask("\n[dim]Enter zum Fortfahren...[/dim]")
except KeyboardInterrupt:
console.print("\n\n[bold cyan]👋 Auf Wiedersehen![/bold cyan]")
def main():
tui = ZenTUIv2()
tui.run()
if __name__ == "__main__":
main()

Xet Storage Details

Size:
22.3 kB
·
Xet hash:
4ccbf3d15a3a636ec4e70c047c29890c9a1222aea248aacbedb5303c0da0be9b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.