forked from Vasco0x4/AIDA
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaida.py
More file actions
executable file
·509 lines (412 loc) · 19.1 KB
/
Copy pathaida.py
File metadata and controls
executable file
·509 lines (412 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#!/usr/bin/env python3
"""
AIDA CLI Launcher - Professional Python Implementation
AI-Driven Security Assessment - Intelligent wrapper for Claude Code
"""
import os
import sys
import json
import subprocess
from pathlib import Path
from typing import Optional
def ensure_cli_dependencies():
"""Ensure CLI dependencies are installed before importing them"""
AIDA_ROOT = Path(__file__).parent.absolute()
VENV_DIR = AIDA_ROOT / ".venv"
REQUIREMENTS_FILE = AIDA_ROOT / "requirements.txt"
# Check if we can import required packages
try:
import click
import httpx
from rich.console import Console
return # All dependencies available
except ImportError:
pass # Need to install
# Try to use venv if it exists
python_bin = "python3"
if VENV_DIR.exists():
venv_python = VENV_DIR / "bin" / "python"
if venv_python.exists():
python_bin = str(venv_python)
print("🔧 Installing CLI dependencies...", file=sys.stderr)
# Create venv if it doesn't exist
if not VENV_DIR.exists():
print(f"📦 Creating virtual environment at {VENV_DIR}...", file=sys.stderr)
try:
subprocess.run([sys.executable, "-m", "venv", str(VENV_DIR)], check=True, capture_output=True)
except subprocess.CalledProcessError as e:
print(f"❌ Failed to create venv: {e}", file=sys.stderr)
print("💡 Install dependencies manually: pip install -r requirements.txt", file=sys.stderr)
sys.exit(1)
# Update python_bin to use new venv
python_bin = str(VENV_DIR / "bin" / "python")
# Install dependencies
if REQUIREMENTS_FILE.exists():
print(f"📥 Installing from {REQUIREMENTS_FILE.name}...", file=sys.stderr)
try:
subprocess.run(
[python_bin, "-m", "pip", "install", "--quiet", "-r", str(REQUIREMENTS_FILE)],
check=True,
capture_output=True
)
print("✅ Dependencies installed successfully", file=sys.stderr)
except subprocess.CalledProcessError as e:
print(f"❌ Failed to install dependencies: {e}", file=sys.stderr)
print("💡 Try manually: pip install click httpx rich", file=sys.stderr)
sys.exit(1)
# If we installed in venv, we need to re-execute with that Python
if python_bin != sys.executable and VENV_DIR.exists():
venv_python = VENV_DIR / "bin" / "python"
if venv_python.exists():
# Re-execute this script with the venv Python
os.execv(str(venv_python), [str(venv_python)] + sys.argv)
# Ensure dependencies before importing heavy packages
ensure_cli_dependencies()
# Now safe to import
import click
import httpx
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich import box
console = Console()
# Configuration
AIDA_ROOT = Path(__file__).parent.absolute()
AIDA_CONFIG_DIR = AIDA_ROOT / ".aida"
PREPROMPT_FILE = AIDA_ROOT / "Docs" / "PrePrompt.txt"
MCP_SERVER_PATH = AIDA_ROOT / "backend" / "mcp" / "aida_mcp_server.py"
MCP_CONFIG_FILE = AIDA_CONFIG_DIR / "mcp-config.json"
DEFAULT_MODEL = "claude-sonnet-4-5"
DEFAULT_PERMISSION = "default"
DEFAULT_BACKEND = "http://localhost:8000/api"
def ensure_backend_venv(quiet=False) -> Path:
"""Ensure backend venv exists with MCP dependencies installed"""
backend_dir = AIDA_ROOT / "backend"
venv_dir = backend_dir / "venv"
requirements_file = backend_dir / "requirements.txt"
# Check if venv exists
if not venv_dir.exists():
if not quiet:
console.print("[yellow]⚠ Backend venv not found, creating...[/yellow]")
try:
subprocess.run(
[sys.executable, "-m", "venv", str(venv_dir)],
check=True,
capture_output=True
)
if not quiet:
console.print("[green]✓ Created backend venv[/green]")
except subprocess.CalledProcessError as e:
if not quiet:
console.print(f"[red]✗ Failed to create backend venv: {e}[/red]")
raise
# Install backend dependencies if requirements.txt exists
python_bin = venv_dir / "bin" / "python"
if requirements_file.exists():
# Check if MCP is installed
try:
result = subprocess.run(
[str(python_bin), "-c", "import mcp"],
capture_output=True,
timeout=5
)
if result.returncode != 0:
# MCP not installed, install dependencies
if not quiet:
console.print("[yellow]Installing backend dependencies (including MCP)...[/yellow]")
try:
result = subprocess.run(
[str(python_bin), "-m", "pip", "install", "-r", str(requirements_file)],
check=True,
capture_output=True,
text=True,
timeout=120
)
if not quiet:
console.print("[green]✓ Backend dependencies installed[/green]")
except subprocess.CalledProcessError as e:
if not quiet:
console.print(f"[yellow]⚠ Could not install backend dependencies[/yellow]")
if e.stderr and not quiet:
# Show the actual error from pip
console.print(f"[dim]Error details:[/dim]")
for line in e.stderr.strip().split('\n')[-5:]: # Last 5 lines
console.print(f"[dim] {line}[/dim]")
console.print("[yellow]→ MCP server may not work. Install manually if needed:[/yellow]")
console.print(f"[dim] cd {backend_dir} && source venv/bin/activate && pip install -r requirements.txt[/dim]")
except subprocess.TimeoutExpired:
if not quiet:
console.print("[yellow]⚠ Backend dependency installation timed out[/yellow]")
except Exception as e:
if not quiet:
console.print(f"[yellow]⚠ Could not verify MCP installation: {e}[/yellow]")
return python_bin
def detect_python_bin(quiet=False) -> str:
"""Detect Python binary (prefer venv) - returns absolute path"""
venv_paths = [
AIDA_ROOT / "backend" / "venv" / "bin" / "python",
AIDA_ROOT / ".venv" / "bin" / "python",
]
for path in venv_paths:
if path.exists():
if not quiet:
console.print(f"[dim]✓ Using venv Python: {path.name}[/dim]")
return str(path.absolute()) # Return absolute path
if not quiet:
console.print("[yellow]⚠ Using system python3[/yellow]")
return "python3"
def check_exegol_installed() -> bool:
"""Check if Exegol containers exist on the system (doesn't need to be running)"""
try:
# Check by container name starting with 'exegol-'
result = subprocess.run(
["docker", "ps", "-a", "--format", "{{.Names}}"],
capture_output=True,
text=True,
timeout=5
)
if result.returncode == 0:
containers = result.stdout.strip().split('\n')
for container in containers:
if container.lower().startswith('exegol-'):
return True
return False
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def generate_mcp_config(db_url: str, quiet=False) -> None:
"""Generate MCP configuration file with proper backend venv"""
AIDA_CONFIG_DIR.mkdir(exist_ok=True)
# Ensure backend venv exists with MCP dependencies
try:
python_bin = ensure_backend_venv(quiet)
python_bin_str = str(python_bin.absolute())
except Exception as e:
if not quiet:
console.print(f"[red]✗ Could not setup backend venv: {e}[/red]")
console.print("[yellow]Falling back to system Python[/yellow]")
python_bin_str = "python3"
config = {
"mcpServers": {
"aida-mcp": {
"command": python_bin_str,
"args": [str(MCP_SERVER_PATH.absolute())],
"env": {
"PYTHONPATH": str((AIDA_ROOT / "backend").absolute()),
"DATABASE_URL": db_url
}
}
}
}
MCP_CONFIG_FILE.write_text(json.dumps(config, indent=2))
if not quiet:
console.print(f"[dim]✓ MCP config: {MCP_CONFIG_FILE.name}[/dim]")
console.print(f"[dim] Python: {python_bin_str}[/dim]")
def resolve_workspace(assessment_name: str, backend_url: str) -> Optional[dict]:
"""Resolve assessment workspace via API"""
try:
with httpx.Client(timeout=5.0) as client:
response = client.get(
f"{backend_url}/workspace/resolve",
params={"assessment_name": assessment_name}
)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
return None
else:
# Silent API error, will be handled by caller
return None
except httpx.ConnectError:
console.print("\n[red]✗ Failed to connect to AIDA backend[/red]\n")
console.print("[yellow]Troubleshooting:[/yellow]")
console.print(" 1. Check: [cyan]docker-compose ps[/cyan]")
console.print(" 2. Start: [cyan]docker-compose up -d[/cyan]")
console.print(" 3. Test: [cyan]curl http://localhost:8000/health[/cyan]\n")
sys.exit(1)
def show_assessment_not_found(assessment_name: str, backend_url: str):
"""Display detailed error when assessment workspace cannot be resolved"""
console.print(f"\n[red]✗ Cannot load assessment '{assessment_name}'[/red]\n")
# Check if Exegol is installed
if not check_exegol_installed():
console.print("[yellow]⚠ Exegol container not detected on this system[/yellow]\n")
console.print("[bold]AIDA requires Exegol to execute pentesting commands.[/bold]")
console.print("Without Exegol, the AI cannot run security tools.\n")
sys.exit(1)
@click.command()
@click.option("-a", "--assessment", help="Load specific assessment")
@click.option("-m", "--model", default=None, help="Model to use (optional, Claude Code default if not specified)")
@click.option("--permission-mode", default=None, help=f"Permission mode (default: {DEFAULT_PERMISSION})")
@click.option("--base-url", help="Custom API base URL")
@click.option("--api-key", help="API authentication token")
@click.option("--no-mcp", is_flag=True, help="Disable MCP server")
@click.option("--debug", is_flag=True, help="Enable debug mode")
@click.option("-q", "--quiet", is_flag=True, help="Quiet mode (minimal output)")
@click.argument("prompt", nargs=-1)
def main(assessment, model, permission_mode, base_url, api_key, no_mcp, debug, quiet, prompt):
"""AIDA CLI Launcher - AI-Driven Security Assessment"""
# Clear terminal for clean start
os.system('clear' if os.name != 'nt' else 'cls')
# Configuration with env var fallbacks
# Only use default model if external API is configured
explicit_model = model or os.getenv("AIDA_MODEL")
base_url = base_url or os.getenv("ANTHROPIC_BASE_URL")
api_key = api_key or os.getenv("ANTHROPIC_AUTH_TOKEN")
# If using external API but no model specified, use default
if (base_url or api_key) and not explicit_model:
explicit_model = DEFAULT_MODEL
permission_mode = permission_mode or os.getenv("AIDA_PERMISSION_MODE", DEFAULT_PERMISSION)
backend_url = os.getenv("BACKEND_API_URL", DEFAULT_BACKEND)
db_url = os.getenv("DATABASE_URL", "postgresql://aida:aida@localhost:5432/aida_assessments")
# Check dependencies
if not subprocess.run(["which", "claude"], capture_output=True).returncode == 0:
console.print("[red]✗ Claude Code CLI not found[/red]")
console.print("Install: [cyan]curl -fsSL https://claude.ai/install.sh | bash[/cyan]\n")
sys.exit(1)
# Interactive assessment selection if none provided
if not assessment:
console.print()
console.print("[bold cyan]AIDA Security Assessment Assistant[/bold cyan]\n")
# Fetch available assessments
try:
with httpx.Client(timeout=5.0) as client:
response = client.get(f"{backend_url}/assessments")
if response.status_code != 200:
console.print("[red]Failed to fetch assessments from backend[/red]\n")
sys.exit(1)
assessments = response.json()
if not assessments:
console.print("[yellow]No assessments found![/yellow]\n")
console.print("Create your first assessment:")
console.print(" → Open [link=http://localhost:5173]http://localhost:5173[/link]")
console.print(' → Click "New Assessment"\n')
sys.exit(1)
# Display selection menu
console.print("[bold]Select an assessment:[/bold]\n")
table = Table(show_header=False, box=None, padding=(0, 2))
table.add_column(style="cyan bold", justify="right", width=4)
table.add_column()
table.add_column(style="dim", no_wrap=True)
for i, a in enumerate(assessments, 1):
container = a.get('container_name', 'N/A')
table.add_row(f"{i}.", a['name'], f"({container})")
console.print(table)
console.print()
# Get user input
try:
choice = console.input("[bold]Enter number (or 'q' to quit): [/bold]")
if choice.lower() == 'q':
console.print("\nCancelled.\n")
sys.exit(0)
idx = int(choice) - 1
if 0 <= idx < len(assessments):
assessment = assessments[idx]['name']
console.print(f"\n[green]✓[/green] Selected: [cyan]{assessment}[/cyan]\n")
else:
console.print("\n[red]Invalid selection[/red]\n")
sys.exit(1)
except (ValueError, KeyboardInterrupt):
console.print("\n\nCancelled.\n")
sys.exit(0)
except httpx.ConnectError:
console.print("[red]✗ Failed to connect to AIDA backend[/red]")
console.print("\nStart the backend:")
console.print(" → [cyan]docker-compose up -d[/cyan]\n")
sys.exit(1)
# Load PrePrompt
if not PREPROMPT_FILE.exists():
console.print(f"[red]✗ PrePrompt not found: {PREPROMPT_FILE}[/red]\n")
sys.exit(1)
preprompt = PREPROMPT_FILE.read_text()
# MCP Configuration
if not no_mcp:
if not MCP_SERVER_PATH.exists():
console.print(f"[red]✗ MCP server not found: {MCP_SERVER_PATH}[/red]\n")
sys.exit(1)
generate_mcp_config(db_url, quiet)
# Workspace resolution
workspace_path = str(AIDA_ROOT)
assessment_id = None
if assessment:
if not quiet and debug:
console.print(f"[dim]Resolving workspace for: {assessment}[/dim]")
result = resolve_workspace(assessment, backend_url)
if not result or not result.get("success"):
show_assessment_not_found(assessment, backend_url)
# Extract workspace info
workspace_path = result["host_path"]
assessment_id = result["assessment_id"]
container_name = result["container_name"]
if not quiet and debug:
console.print(f"[dim]✓ Container: {container_name}[/dim]")
console.print(f"[dim]✓ Workspace: {workspace_path}[/dim]\n")
# Enhance preprompt with minimal assessment context
preprompt += f"""
## **Assessment Loaded**
**{assessment}** (ID: {assessment_id}) - Container: {container_name}
The assessment workspace is ready. Use your standard tools to work with files and execute commands.
"""
# Build Claude Code command
claude_args = [
"claude",
"--system-prompt", preprompt,
"--permission-mode", permission_mode,
]
# Only add model if explicitly specified (for external APIs)
if explicit_model:
claude_args.extend(["--model", explicit_model])
if not no_mcp:
claude_args.extend(["--mcp-config", str(MCP_CONFIG_FILE)])
if debug:
claude_args.append("--debug")
# Add AIDA project to accessible dirs if in workspace
if workspace_path != str(AIDA_ROOT):
claude_args.extend(["--add-dir", str(AIDA_ROOT)])
# Add prompt args
if prompt:
claude_args.extend(prompt)
# Set API env vars
env = os.environ.copy()
if base_url:
env["ANTHROPIC_BASE_URL"] = base_url
if api_key:
env["ANTHROPIC_AUTH_TOKEN"] = api_key
# Display launch banner
if not quiet:
console.print()
# Main info panel
panel_content = f"""[bold cyan]AIDA Security Assessment Assistant[/bold cyan]
[dim]Permission:[/dim] {permission_mode}
[dim]MCP Server:[/dim] {"[green]Enabled[/green]" if not no_mcp else "[yellow]Disabled[/yellow]"}
[dim]Directory:[/dim] {workspace_path}"""
if explicit_model:
panel_content = f"""[bold cyan]AIDA Security Assessment Assistant[/bold cyan]
[dim]Model:[/dim] {explicit_model}
[dim]Permission:[/dim] {permission_mode}
[dim]MCP Server:[/dim] {"[green]Enabled[/green]" if not no_mcp else "[yellow]Disabled[/yellow]"}
[dim]Directory:[/dim] {workspace_path}"""
if assessment:
panel_content += f"\n[dim]Assessment:[/dim] [cyan]{assessment}[/cyan] [dim](ID: {assessment_id})[/dim]"
if base_url:
panel_content += f"\n[dim]API:[/dim] {base_url}"
panel = Panel(
panel_content,
border_style="blue",
box=box.DOUBLE,
padding=(1, 2)
)
console.print(panel)
console.print()
# Launch Claude Code
if not quiet:
console.print("[dim]Starting Claude Code...[/dim]\n")
else:
# Minimal output in quiet mode
console.print(f"[cyan]AIDA[/cyan] → {assessment or 'AIDA Project'}\n")
try:
os.chdir(workspace_path)
os.execvpe("claude", claude_args, env)
except Exception as e:
console.print(f"[red]Failed to launch Claude Code: {e}[/red]")
sys.exit(1)
if __name__ == "__main__":
main()