Buckets:

download
raw
15 kB
#!/usr/bin/env python3
"""Main entry point for Kimi Pentest CLI."""
import sys
from pathlib import Path
from typing import Optional
import typer
from rich.console import Console
from rich.panel import Panel
from .api.client import APIClient
from .auth.manager import AuthManager
from .config import Config
from .ui.app import PentestApp
# Create Typer app
app = typer.Typer(
name="kimi-pentest",
help="Kimi Pentest - AI-Powered Penetration Testing Framework",
no_args_is_help=True,
)
# Create console for output
console = Console()
@app.callback()
def main_callback(
config_file: Optional[Path] = typer.Option(None, "--config", "-c", help="Path to config file"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose output"),
):
"""Kimi Pentest CLI - AI-Powered Penetration Testing Framework."""
pass
@app.command()
def tui(
api_url: Optional[str] = typer.Option(None, "--api-url", "-a", help="API base URL"),
):
"""Launch the Text User Interface (TUI)."""
config = Config()
if api_url:
config.api_url = api_url
# Launch TUI
pentest_app = PentestApp(config)
pentest_app.run()
@app.command()
def login(
method: str = typer.Argument("api-key", help="Login method: api-key, device, or password"),
api_key: Optional[str] = typer.Option(
None, "--api-key", "-k", help="API key for authentication"
),
email: Optional[str] = typer.Option(None, "--email", "-e", help="Email for password login"),
password: Optional[str] = typer.Option(None, "--password", "-p", help="Password for login"),
):
"""Authenticate with the Kimi Pentest API."""
config = Config()
auth_manager = AuthManager(config)
if method == "api-key":
if not api_key:
api_key = typer.prompt("API Key", hide_input=True)
success, message = auth_manager.login_with_api_key(api_key)
if success:
console.print(
Panel(
f"[green]✓[/green] {message}",
title="Login Successful",
border_style="green",
)
)
else:
console.print(
Panel(
f"[red]✗[/red] {message}",
title="Login Failed",
border_style="red",
)
)
sys.exit(1)
elif method == "device":
from .auth.device_flow import DeviceFlowAuth
device_auth = DeviceFlowAuth(config)
def on_code(url: str, code: str):
console.print(
Panel(
f"[cyan]1.[/cyan] Open: [link]{url}[/link]\n"
f"[cyan]2.[/cyan] Enter code: [bold]{code}[/bold]",
title="Device Authentication",
border_style="cyan",
)
)
success, message, tokens = device_auth.authenticate(
client_id="kimi-pentest-cli", on_code=on_code
)
if success:
auth_manager.store_tokens(tokens)
console.print(
Panel(
f"[green]✓[/green] {message}",
title="Login Successful",
border_style="green",
)
)
else:
console.print(
Panel(
f"[red]✗[/red] {message}",
title="Login Failed",
border_style="red",
)
)
sys.exit(1)
elif method == "password":
if not email:
email = typer.prompt("Email")
if not password:
password = typer.prompt("Password", hide_input=True)
success, message = auth_manager.login_with_password(email, password)
if success:
console.print(
Panel(
f"[green]✓[/green] {message}",
title="Login Successful",
border_style="green",
)
)
else:
console.print(
Panel(
f"[red]✗[/red] {message}",
title="Login Failed",
border_style="red",
)
)
sys.exit(1)
else:
console.print(f"[red]Unknown login method: {method}[/red]")
sys.exit(1)
@app.command()
def logout():
"""Logout and clear stored credentials."""
config = Config()
auth_manager = AuthManager(config)
auth_manager.logout()
console.print(
Panel(
"[green]✓[/green] Logged out successfully",
title="Logout",
border_style="green",
)
)
@app.command()
def status():
"""Check authentication status."""
config = Config()
auth_manager = AuthManager(config)
if auth_manager.is_authenticated():
user = auth_manager.get_current_user()
console.print(
Panel(
f"[green]● Authenticated[/green]\n"
f"User: {user.get('email', 'Unknown')}\n"
f"API URL: {config.api_url}",
title="Status",
border_style="green",
)
)
else:
console.print(
Panel(
"[red]● Not authenticated[/red]\n"
"Run [bold]kimi-pentest login[/bold] to authenticate",
title="Status",
border_style="red",
)
)
@app.command()
def scan(
target: str = typer.Argument(..., help="Target to scan"),
scan_type: str = typer.Option("port_scan", "--type", "-t", help="Scan type"),
ai_analysis: bool = typer.Option(True, "--ai/--no-ai", help="Enable AI analysis"),
wait: bool = typer.Option(False, "--wait", "-w", help="Wait for scan to complete"),
):
"""Start a new security scan."""
config = Config()
auth_manager = AuthManager(config)
if not auth_manager.is_authenticated():
console.print("[red]Not authenticated. Run 'kimi-pentest login' first.[/red]")
sys.exit(1)
api_client = APIClient(base_url=config.api_url, auth_manager=auth_manager)
try:
response = api_client.post(
"/scans",
json={
"target": target,
"scan_type": scan_type,
"options": {
"ai_analysis": ai_analysis,
},
},
)
scan_id = response.get("id")
console.print(
Panel(
f"[green]✓[/green] Scan started\n"
f"ID: {scan_id}\n"
f"Target: {target}\n"
f"Type: {scan_type}",
title="Scan Created",
border_style="green",
)
)
if wait:
console.print("[cyan]Waiting for scan to complete...[/cyan]")
# Poll for completion
import time
while True:
status = api_client.get(f"/scans/{scan_id}")
if status.get("status") in [
"completed",
"failed",
"cancelled",
]:
break
time.sleep(2)
console.print(f"[green]Scan {status.get('status')}![/green]")
except Exception as e:
console.print(f"[red]Failed to start scan: {e}[/red]")
sys.exit(1)
@app.command()
def scans(
limit: int = typer.Option(10, "--limit", "-l", help="Number of scans to show"),
status: Optional[str] = typer.Option(None, "--status", "-s", help="Filter by status"),
):
"""List recent scans."""
config = Config()
auth_manager = AuthManager(config)
if not auth_manager.is_authenticated():
console.print("[red]Not authenticated. Run 'kimi-pentest login' first.[/red]")
sys.exit(1)
api_client = APIClient(base_url=config.api_url, auth_manager=auth_manager)
try:
params = {"limit": limit}
if status:
params["status"] = status
response = api_client.get("/scans", params=params)
items = response.get("items", [])
if not items:
console.print("[yellow]No scans found[/yellow]")
return
from rich.table import Table
table = Table(title="Recent Scans")
table.add_column("ID", style="cyan")
table.add_column("Target")
table.add_column("Type")
table.add_column("Status")
table.add_column("Progress")
for scan in items:
status_color = {
"pending": "yellow",
"running": "blue",
"completed": "green",
"failed": "red",
}.get(scan.get("status"), "white")
table.add_row(
scan.get("id", "")[:8],
scan.get("target", "Unknown"),
scan.get("scan_type", "Unknown"),
f"[{status_color}]{scan.get('status', 'unknown').upper()}[/{status_color}]",
f"{scan.get('progress', 0)}%",
)
console.print(table)
except Exception as e:
console.print(f"[red]Failed to list scans: {e}[/red]")
sys.exit(1)
@app.command()
def vulns(
scan_id: Optional[str] = typer.Option(None, "--scan", "-s", help="Filter by scan ID"),
severity: Optional[str] = typer.Option(None, "--severity", help="Filter by severity"),
limit: int = typer.Option(20, "--limit", "-l", help="Number of vulnerabilities to show"),
):
"""List vulnerabilities."""
config = Config()
auth_manager = AuthManager(config)
if not auth_manager.is_authenticated():
console.print("[red]Not authenticated. Run 'kimi-pentest login' first.[/red]")
sys.exit(1)
api_client = APIClient(base_url=config.api_url, auth_manager=auth_manager)
try:
params = {"limit": limit}
if scan_id:
params["scan_id"] = scan_id
if severity:
params["severity"] = severity
response = api_client.get("/vulnerabilities", params=params)
items = response.get("items", [])
if not items:
console.print("[yellow]No vulnerabilities found[/yellow]")
return
from rich.table import Table
table = Table(title="Vulnerabilities")
table.add_column("Name")
table.add_column("Severity")
table.add_column("Target")
table.add_column("CVSS")
for vuln in items:
severity_color = {
"critical": "red",
"high": "red",
"medium": "yellow",
"low": "green",
"info": "blue",
}.get(vuln.get("severity"), "white")
table.add_row(
vuln.get("name", "Unknown")[:40],
f"[{severity_color}]{vuln.get('severity', 'unknown').upper()}[/{severity_color}]",
vuln.get("target", "Unknown")[:30],
str(vuln.get("cvss_score", "N/A")),
)
console.print(table)
except Exception as e:
console.print(f"[red]Failed to list vulnerabilities: {e}[/red]")
sys.exit(1)
@app.command()
def report(
scan_id: Optional[str] = typer.Option(
None, "--scan", "-s", help="Scan ID to generate report for"
),
report_type: str = typer.Option("full", "--type", "-t", help="Report type"),
format: str = typer.Option("pdf", "--format", "-f", help="Report format"),
output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output file path"),
):
"""Generate a security report."""
config = Config()
auth_manager = AuthManager(config)
if not auth_manager.is_authenticated():
console.print("[red]Not authenticated. Run 'kimi-pentest login' first.[/red]")
sys.exit(1)
api_client = APIClient(base_url=config.api_url, auth_manager=auth_manager)
try:
data = {
"type": report_type,
"format": format,
}
if scan_id:
data["scan_id"] = scan_id
response = api_client.post("/reports", json=data)
report_id = response.get("id")
console.print(f"[cyan]Generating report...[/cyan] (ID: {report_id})")
# Wait for report generation
import time
while True:
status = api_client.get(f"/reports/{report_id}")
if status.get("status") == "completed":
break
elif status.get("status") == "failed":
console.print("[red]Report generation failed[/red]")
sys.exit(1)
time.sleep(1)
# Download report
report_data = api_client.get(f"/reports/{report_id}/download")
if not output:
from datetime import datetime
output = Path(f"report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{format}")
with open(output, "wb" if format in ["pdf"] else "w") as f:
f.write(report_data)
console.print(
Panel(
f"[green]✓[/green] Report saved to: [bold]{output}[/bold]",
title="Report Generated",
border_style="green",
)
)
except Exception as e:
console.print(f"[red]Failed to generate report: {e}[/red]")
sys.exit(1)
@app.command()
def config(
key: Optional[str] = typer.Argument(None, help="Config key to get/set"),
value: Optional[str] = typer.Argument(None, help="Value to set"),
list_all: bool = typer.Option(False, "--list", "-l", help="List all config"),
):
"""Manage CLI configuration."""
cfg = Config()
if list_all:
console.print(
Panel(
f"API URL: {cfg.api_url}\nWS URL: {cfg.ws_url}\nConfig Dir: {cfg.config_dir}",
title="Configuration",
border_style="cyan",
)
)
elif key and value:
# Set config value
if hasattr(cfg, key):
setattr(cfg, key, value)
cfg.save()
console.print(f"[green]✓[/green] Set {key} = {value}")
else:
console.print(f"[red]Unknown config key: {key}[/red]")
sys.exit(1)
elif key:
# Get config value
if hasattr(cfg, key):
console.print(f"{key} = {getattr(cfg, key)}")
else:
console.print(f"[red]Unknown config key: {key}[/red]")
sys.exit(1)
@app.command()
def version():
"""Show version information."""
from importlib.metadata import version as get_version
try:
ver = get_version("kimi-pentest")
except Exception:
ver = "dev"
console.print(
Panel(
f"[bold]Kimi Pentest CLI[/bold]\nVersion: {ver}\nPython: {sys.version.split()[0]}",
title="Version",
border_style="cyan",
)
)
def cli():
"""Entry point for the CLI."""
app()
if __name__ == "__main__":
cli()

Xet Storage Details

Size:
15 kB
·
Xet hash:
f65ac74c9bfe4bfda5e7ed2bce9572a3c221b87d035cf4f1f30275c270fa8e0f

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