ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
#!/usr/bin/env python3
"""
ARES CLI - Typer-based command line interface.
All subcommands use Python type annotations for automatic --help generation.
Structure:
ares campaign create/list/pause/resume/status
ares target add/list/import
ares module list/run/info/install
ares chain execute/list
ares report generate/list
ares signing sign/verify/add-key/revoke-key
Usage:
ares campaign create --name "Q1 Engagement" --client "Acme Corp"
ares target add 10.0.0.0/24 --tag dc --tag web
ares module list --category ad
ares module run ad.kerberoast --target dc01.corp.local --domain CORP
ares chain execute --goal domain_admin --target 10.0.0.1
ares report generate --campaign <id> --format html
"""
from __future__ import annotations
import asyncio
import getpass
import json
import logging
import os
import shutil
import signal
import socket
import ssl
import subprocess
import sys
import threading
import time
import uuid
import warnings
import webbrowser
from collections.abc import Callable
from pathlib import Path
from typing import Any
from urllib import error as urllib_error
from urllib import parse as urllib_parse
from urllib import request as urllib_request
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", message=".*authlib.*")
import typer
from rich import box
from rich import print as rprint
from rich.console import Console
from rich.markup import escape
from rich.panel import Panel
from rich.syntax import Syntax
from rich.table import Table
app = typer.Typer(
name = "ares",
help = (
"ARES - Automated Red team Engagement System\n\n"
"[bold]Quick start:[/bold]\n"
" ares campaign create --name \"Lab\" --client ACME --targets 10.0.0.0/24\n"
" ares module run ad.enum_users --dc 10.0.0.5 --domain corp.local\n"
" ares report generate --campaign-id <id> --format html\n\n"
"First time? Run: [bold cyan]ares doctor[/bold cyan]"
),
no_args_is_help = True,
pretty_exceptions_enable = False,
rich_markup_mode = "rich",
)
console = Console()
if sys.platform == "win32":
try:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
# Suppress noisy internal library and plugin debug logs in CLI mode unless explicitly requested
_ares_cli_log_level = os.getenv("ARES_LOG_LEVEL", "WARNING").upper()
try:
from ares.core.logger import setup_logger
setup_logger(level=_ares_cli_log_level)
except Exception:
logging.basicConfig(level=getattr(logging, _ares_cli_log_level, logging.WARNING))
PYTHON_MIN_VERSION = (3, 11)
PYTHON_MAX_VERSION_EXCLUSIVE = (3, 13)
AD_IMPACKET_TESTED_PYTHON = (3, 12)
_C_LIVE_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
_C_LIVE_MAX_RESPONSE_BYTES = 1_048_576
class _CLiveCliError(RuntimeError):
"""Fixed, non-sensitive C-LIVE CLI transport failure."""
class _CLiveRejectRedirects(urllib_request.HTTPRedirectHandler):
def redirect_request(
self,
req: Any,
fp: Any,
code: int,
msg: str,
headers: Any,
newurl: str,
) -> None:
del req, fp, code, msg, headers, newurl
return None
def _c_live_api_url() -> tuple[str, bool]:
"""Return the exact configured API origin and whether verified TLS is required."""
value = os.getenv("ARES_API_URL")
if type(value) is not str or not value or value != value.strip():
raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid")
try:
parsed = urllib_parse.urlsplit(value)
host = parsed.hostname
port = parsed.port
except (TypeError, ValueError):
raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid") from None
if (
parsed.scheme not in {"http", "https"}
or host is None
or parsed.username is not None
or parsed.password is not None
or parsed.path not in {"", "/"}
or parsed.query
or parsed.fragment
):
raise _CLiveCliError("c-live-cli:api-url-missing-or-invalid")
host = host.lower()
if parsed.scheme == "http" and host not in _C_LIVE_LOOPBACK_HOSTS:
raise _CLiveCliError("c-live-cli:tls-required")
if ":" in host:
authority = f"[{host}]"
else:
authority = host
if port is not None:
authority = f"{authority}:{port}"
return f"{parsed.scheme}://{authority}", parsed.scheme == "https"
def _c_live_bearer() -> str:
"""Read bearer authority from the environment or a protected prompt only."""
token = os.getenv("ARES_ACCESS_TOKEN")
if token is None:
token = getpass.getpass("ARES bearer token: ")
if (
type(token) is not str
or not token
or token != token.strip()
or len(token.encode("utf-8")) > 16_384
or any(ord(character) < 0x21 or ord(character) == 0x7F for character in token)
):
raise _CLiveCliError("c-live-cli:bearer-missing-or-invalid")
return token
def _c_live_idempotency_key(value: str | None) -> str:
"""Validate a supplied UUIDv4 or generate and display one exactly once."""
if value in {None, ""}:
generated = str(uuid.uuid4())
console.print(f"[cyan]Idempotency-Key:[/] {generated}")
return generated
if type(value) is not str:
raise _CLiveCliError("c-live-cli:idempotency-key-invalid")
try:
parsed = uuid.UUID(value)
except (AttributeError, ValueError):
raise _CLiveCliError("c-live-cli:idempotency-key-invalid") from None
if parsed.version != 4 or str(parsed) != value:
raise _CLiveCliError("c-live-cli:idempotency-key-invalid")
return value
def _c_live_http_post(path: str, body: dict[str, Any], key: str | None) -> dict[str, Any]:
"""Perform exactly one bearer HTTP POST; transport retry is caller-owned."""
base_url, use_tls = _c_live_api_url()
bearer = _c_live_bearer()
idempotency_key = _c_live_idempotency_key(key)
if type(path) is not str or not path.startswith("/") or path.startswith("//"):
raise _CLiveCliError("c-live-cli:path-invalid")
try:
data = json.dumps(
body,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
allow_nan=False,
).encode("utf-8")
except (TypeError, ValueError):
raise _CLiveCliError("c-live-cli:request-invalid") from None
outgoing = urllib_request.Request( # noqa: S310 - origin is strictly constrained above
f"{base_url}{path}",
data=data,
headers={
"Accept": "application/json",
"Authorization": f"Bearer {bearer}",
"Content-Type": "application/json",
"Idempotency-Key": idempotency_key,
},
method="POST",
)
handlers: list[Any] = [_CLiveRejectRedirects()]
if use_tls:
handlers.append(urllib_request.HTTPSHandler(context=ssl.create_default_context()))
opener = urllib_request.build_opener(*handlers)
try:
with opener.open(outgoing, timeout=30) as response: # noqa: S310
raw = response.read(_C_LIVE_MAX_RESPONSE_BYTES + 1)
status = int(response.status)
except urllib_error.HTTPError as exc:
status = int(exc.code)
raw = exc.read(_C_LIVE_MAX_RESPONSE_BYTES + 1)
if len(raw) > _C_LIVE_MAX_RESPONSE_BYTES:
raise _CLiveCliError(f"c-live-cli:http-{status}:response-too-large") from None
try:
decoded = json.loads(raw.decode("utf-8")) if raw else {}
except (UnicodeDecodeError, json.JSONDecodeError):
decoded = {}
code = decoded.get("code") if isinstance(decoded, dict) else None
safe_code = (
code
if type(code) is str
and 1 <= len(code) <= 64
and all(character.isalnum() or character in "_-" for character in code)
else "request-rejected"
)
raise _CLiveCliError(f"c-live-cli:http-{status}:{safe_code}") from None
except (urllib_error.URLError, TimeoutError, OSError):
raise _CLiveCliError("c-live-cli:transport-unavailable") from None
finally:
bearer = ""
if len(raw) > _C_LIVE_MAX_RESPONSE_BYTES:
raise _CLiveCliError("c-live-cli:response-too-large")
try:
decoded = json.loads(raw.decode("utf-8")) if raw else {}
except (UnicodeDecodeError, json.JSONDecodeError):
raise _CLiveCliError("c-live-cli:response-invalid") from None
return {
"status": status,
"body": decoded,
"idempotency_key": idempotency_key,
}
def _display_c_live_http_result(result: dict[str, Any]) -> None:
body = result.get("body")
console.print(
Panel(
json.dumps(body, indent=2, sort_keys=True, default=str),
title=f"C-LIVE HTTP {result.get('status', 'unknown')}",
)
)
def _python_minor(version_info: object | None = None) -> tuple[int, int]:
info = sys.version_info if version_info is None else version_info
try:
major = info.major
minor = info.minor
except AttributeError:
major = info[0] # type: ignore[index]
minor = info[1] # type: ignore[index]
return int(major), int(minor)
# ── Subcommand groups ──────────────────────────────────────────────────────────
campaign_app = typer.Typer(help="Manage red team campaigns", no_args_is_help=True)
target_app = typer.Typer(help="Manage engagement targets", no_args_is_help=True)
module_app = typer.Typer(help="List and run attack modules", no_args_is_help=True)
chain_app = typer.Typer(help="Execute attack chains", no_args_is_help=True)
report_app = typer.Typer(help="Generate engagement reports", no_args_is_help=True)
signing_app = typer.Typer(help="Module signing and verification", no_args_is_help=True)
goal_app = typer.Typer(help="Goal-based autonomous attack planning", no_args_is_help=True)
graph_app = typer.Typer(help="Attack graph queries and visualization", no_args_is_help=True)
dashboard_app = typer.Typer(help="Local dashboard developer tools", no_args_is_help=True)
mcp_app = typer.Typer(help="ARES MCP - Model Context Protocol Gateway", no_args_is_help=False, invoke_without_command=True)
app.add_typer(campaign_app, name="campaign")
app.add_typer(target_app, name="target")
app.add_typer(module_app, name="module")
app.add_typer(chain_app, name="chain")
app.add_typer(report_app, name="report")
app.add_typer(signing_app, name="signing")
app.add_typer(goal_app, name="goal")
app.add_typer(graph_app, name="graph")
app.add_typer(dashboard_app, name="dashboard")
app.add_typer(mcp_app, name="mcp")
# ── Version ────────────────────────────────────────────────────────────────────
def version_callback(show: bool) -> None:
if show:
from ares.__version__ import __version__ as _ver
rprint(f"[bold cyan]ARES[/] v{_ver} - Automated Red team Engagement System")
raise typer.Exit()
@app.callback()
def main(
version: bool = typer.Option(None, "--version", "-v",
callback=version_callback, is_eager=True,
help="Show version and exit"),
) -> None:
"""ARES - Automated Red team Engagement System."""
# ── Campaign commands ──────────────────────────────────────────────────────────
@campaign_app.command("create")
def campaign_create(
name: str = typer.Option(..., "--name", "-n", help="Campaign name"),
client: str = typer.Option("", "--client", "-c", help="Client name"),
operator: str = typer.Option("", "--operator", "-o", help="Lead operator"),
profile: str = typer.Option("normal", "--profile", "-p",
help="Noise profile: stealth | normal | aggressive"),
scope: list[str] = typer.Option([], "--scope", "-s",
help="Scope CIDR (repeatable: -s 10.0.0.0/8)"),
domain: str = typer.Option("", "--domain", "-d", help="AD domain (CORP.LOCAL)"),
) -> None:
"""Create a new red team campaign."""
from ares.cli._store import get_store
store = get_store()
try:
from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry
noise_profiles = {
"stealth": NoiseProfile.STEALTH,
"normal": NoiseProfile.NORMAL,
"aggressive": NoiseProfile.AGGRESSIVE,
}
noise = noise_profiles.get(profile.lower(), NoiseProfile.NORMAL)
scope_entries = [ScopeEntry(cidr=s) for s in scope] if scope else [ScopeEntry(cidr="0.0.0.0/0")]
c = Campaign(
name=name, client=client, operator=operator or "operator",
scope=scope_entries, noise_profile=noise,
domain=domain,
)
store.save_campaign(c)
console.print(Panel(
f"[bold green][+] Campaign created[/]\n"
f" ID: [cyan]{c.id}[/]\n"
f" Name: {c.name}\n"
f" Client: {c.client or ' - '}\n"
f" Profile: [yellow]{profile}[/]\n"
f" Scope: {', '.join(s.cidr for s in c.scope)}",
title="Campaign Created",
box=box.ROUNDED,
))
except Exception as exc:
console.print(f"[bold red]Error:[/] {exc}")
raise typer.Exit(1) # noqa: B904
@campaign_app.command("list")
def campaign_list(
active_only: bool = typer.Option(False, "--active", help="Show only active campaigns"),
) -> None:
"""List all campaigns."""
from ares.cli._store import get_store
store = get_store()
campaigns = store.list_campaigns()
if not campaigns:
console.print("[dim]No campaigns found. Run [cyan]ares campaign create[/] to start.[/]")
return
table = Table(title="Campaigns", show_header=True, box=box.ROUNDED)
table.add_column("ID", style="cyan", width=12)
table.add_column("Name", style="bold", width=24)
table.add_column("Client", width=16)
table.add_column("Profile", style="yellow", width=10)
table.add_column("Findings", justify="right", width=8)
table.add_column("Created", width=16)
for c in campaigns:
table.add_row(
c.get("id", "")[:8],
c.get("name", ""),
c.get("client", " - "),
c.get("noise_profile", "normal"),
str(c.get("finding_count", 0)),
c.get("created_at", ""),
)
console.print(table)
@campaign_app.command("status")
def campaign_status(
campaign_id: str = typer.Argument(..., help="Campaign ID"),
) -> None:
"""Show detailed campaign status."""
from ares.cli._store import get_store
store = get_store()
c = store.get_campaign(campaign_id)
if not c:
console.print(f"[red]Campaign {campaign_id!r} not found[/]")
raise typer.Exit(1)
console.print_json(json.dumps(c, default=str, indent=2))
@campaign_app.command("pause")
def campaign_pause(
campaign_id: str = typer.Argument(..., help="Campaign ID"),
notes: str = typer.Option("", "--notes", help="Pause notes"),
) -> None:
"""Pause a running campaign and save checkpoint."""
from ares.cli._store import get_store
store = get_store()
c = store.get_campaign(campaign_id)
if not c:
console.print(f"[red]Campaign {campaign_id!r} not found[/]")
raise typer.Exit(1)
with console.status("[cyan]Saving checkpoint...[/]"):
cp = store.save_checkpoint(campaign_id, notes=notes)
if cp:
console.print(Panel(
f"[yellow]⏸ Campaign paused[/]\n"
f" Campaign: [cyan]{c['name']}[/]\n"
f" Checkpoint ID: [dim]{cp['checkpoint_id']}[/]\n"
f" Saved at: {cp['saved_at']}\n"
f" Path: [dim]{cp['path']}[/]\n\n"
f"Resume with: [cyan]ares campaign resume {campaign_id[:8]}[/]",
title="Checkpoint Saved",
))
else:
console.print("[red]Failed to save checkpoint[/]")
raise typer.Exit(1)
@campaign_app.command("resume")
def campaign_resume(
campaign_id: str = typer.Argument(..., help="Campaign ID"),
checkpoint_id: str = typer.Option("latest", "--checkpoint", help="Checkpoint ID"),
) -> None:
"""Resume a paused campaign from checkpoint."""
from ares.cli._store import get_store
store = get_store()
with console.status("[cyan]Loading checkpoint...[/]"):
cp = store.load_checkpoint(campaign_id, checkpoint_id)
if not cp:
console.print(f"[red]No checkpoint found for campaign {campaign_id!r}[/]")
console.print("[dim]Run [cyan]ares campaign pause <id>[/] first to save a checkpoint.[/]")
raise typer.Exit(1)
# Mark campaign as active again
import json
from pathlib import Path
campaigns_path = Path.home() / ".ares" / "campaigns"
for p in campaigns_path.glob("*.json"):
data = json.loads(p.read_text(encoding="utf-8"))
if data["id"].startswith(campaign_id):
data["status"] = "active"
p.write_text(json.dumps(data, indent=2), encoding="utf-8")
break
console.print(Panel(
f"[green]▶ Campaign resumed[/]\n"
f" Checkpoint: [dim]{cp['checkpoint_id']}[/]\n"
f" Saved at: {cp['saved_at']}\n"
f" Notes: {cp.get('notes', ' - ') or ' - '}\n\n"
f"Run [cyan]ares module run <id> --campaign {campaign_id[:8]}[/] to continue.",
title="Resumed from Checkpoint",
))
# ── Target commands ────────────────────────────────────────────────────────────
@target_app.command("add")
def target_add(
target: str = typer.Argument(..., help="IP address, CIDR, or hostname"),
campaign_id: str = typer.Option("", "--campaign", "-c", help="Campaign ID"),
tag: list[str] = typer.Option([], "--tag", "-t", help="Tag (repeatable)"),
notes: str = typer.Option("", "--notes", help="Notes"),
) -> None:
"""Add a target to the current campaign."""
from ares.cli._store import get_store
store = get_store()
cid = campaign_id or store.active_campaign_id()
if not cid:
console.print("[red]No active campaign. Pass --campaign or run [cyan]ares campaign create[/][/]")
raise typer.Exit(1)
entry = {"target": target, "tags": tag, "notes": notes}
store.add_target(cid, entry)
console.print(f"[green][+] Target added:[/] {target} -> campaign {cid[:8]}")
@target_app.command("list")
def target_list(
campaign_id: str = typer.Option("", "--campaign", "-c", help="Campaign ID"),
) -> None:
"""List all targets for a campaign."""
from ares.cli._store import get_store
store = get_store()
cid = campaign_id or store.active_campaign_id() or ""
targets = store.list_targets(cid)
if not targets:
console.print("[dim]No targets. Run [cyan]ares target add <ip>[/][/]")
return
table = Table(title=f"Targets (campaign {cid[:8]})", box=box.ROUNDED)
table.add_column("Target", style="cyan")
table.add_column("Tags")
table.add_column("Notes")
for t in targets:
table.add_row(t.get("target", ""), ", ".join(t.get("tags", [])), t.get("notes", ""))
console.print(table)
@target_app.command("import")
def target_import(
file: Path = typer.Argument(..., help="File with targets (one per line, or Nmap XML)"),
campaign_id: str = typer.Option("", "--campaign", "-c"),
) -> None:
"""Import targets from a file (plaintext or Nmap XML)."""
if not file.exists():
console.print(f"[red]File not found: {file}[/]")
raise typer.Exit(1)
lines = file.read_text(encoding="utf-8").strip().splitlines()
targets = [l.strip() for l in lines if l.strip() and not l.startswith("#")]
console.print(f"[green][+] Imported {len(targets)} targets[/]")
# ── Module commands ────────────────────────────────────────────────────────────
@module_app.command("list")
def module_list(
category: str = typer.Option("", "--category", "-c",
help="Filter: ad | linux | cloud | reporting"),
opsec: str = typer.Option("", "--opsec", help="Filter: silent | low | medium | high_noise"),
search: str = typer.Option("", "--search", "-s", help="Search by name or description"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show full metadata"),
) -> None:
"""List available modules."""
from ares.core.plugin.loader import PluginLoader
registry = PluginLoader().load_all()
rows = []
for mod_id, mod_cls in sorted(registry._registry.items()):
if getattr(mod_cls, "ENABLED", True) is False or registry.is_disabled(mod_id):
continue
meta = mod_cls.metadata()
if category and meta.get("category") != category:
continue
if opsec and meta.get("opsec_level") != opsec:
continue
if search and search.lower() not in f"{mod_id} {meta.get('name','')} {meta.get('description','')}".lower():
continue
opsec_val = meta.get("opsec_level", "medium")
opsec_color = {
"silent": "green", "low": "green",
"medium": "yellow", "high_noise": "red",
}.get(opsec_val, "white")
rows.append((
mod_id,
meta.get("name", ""),
f"[{opsec_color}]{opsec_val}[/]",
meta.get("mitre", "")[:16],
meta.get("description", "")[:36],
))
count_label = f" ({len(rows)} loaded)" if not (category or opsec or search) else f" ({len(rows)} matching)"
table = Table(title=f"Available Modules{count_label}", show_header=True, show_lines=True, box=box.ROUNDED)
table.add_column("Module ID", style="cyan", width=28)
table.add_column("Name", width=24)
table.add_column("OpSec", style="yellow", width=10)
table.add_column("MITRE", width=16)
table.add_column("Description", width=36)
for r in rows:
table.add_row(*r)
console.print(table)
@module_app.command("info")
def module_info(
module_id: str = typer.Argument(..., help="Module ID (e.g. ad.kerberoast)"),
) -> None:
"""Show detailed module information."""
from ares.core.plugin.loader import PluginLoader
registry = PluginLoader().load_all()
cls = registry.get(module_id)
if not cls:
console.print(f"[red]Module not found: {module_id!r}[/]")
raise typer.Exit(1)
meta = cls.metadata()
from ares.technique.library import TechniqueMapper
mapper = TechniqueMapper()
techs = mapper.for_module(module_id)
console.print(Panel(
f"[bold]{meta['name']}[/]\n"
f"[dim]{meta['description']}[/]\n\n"
f" ID: [cyan]{meta['id']}[/]\n"
f" Category: {meta['category']}\n"
f" OpSec: [yellow]{meta['opsec_level']}[/]\n"
f" Author: {meta.get('author', 'ARES Team')}\n"
f" Requires: {', '.join(meta.get('requires', [])) or ' - '}\n"
f" Outputs: {', '.join(meta.get('outputs', [])) or ' - '}\n"
f" MITRE: {', '.join(meta.get('mitre_list', []))}\n"
+ ("\n[bold]Techniques:[/]\n" + "\n".join(
f" [cyan]{t.technique_id}[/] {t.name} - [dim]{t.tactic}[/]"
for t in techs
) if techs else ""),
title=f"Module: {module_id}",
))
@module_app.command("run")
def module_run(
module_id: str = typer.Argument(..., help="Module ID"),
target: str = typer.Option(..., "--target", "-t", help="Target host"),
campaign_id: str = typer.Option(..., "--campaign", "-c"),
domain: str = typer.Option("", "--domain", "-d"),
profile: str = typer.Option("normal", "--profile", "-p"),
dry_run: bool = typer.Option(False, "--dry-run", help="Simulate without network"),
param: list[str] = typer.Option([], "--param", help="k=v params (repeatable)"),
idempotency_key: str = typer.Option(
"", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"
),
) -> None:
"""Submit one module request to the authenticated ARES HTTP API."""
params: dict = {}
for p in param:
if "=" in p:
k, v = p.split("=", 1)
params[k.strip()] = v.strip()
with console.status(f"[cyan]Running {module_id} → {target}...[/]"):
result = asyncio.run(_run_module(
module_id,
target,
campaign_id,
domain,
profile,
dry_run,
params,
idempotency_key,
))
if result:
_display_c_live_http_result(result)
else:
raise typer.Exit(1)
@module_app.command("install")
def module_install(
module_spec: str = typer.Argument(..., help="Module spec: namespace/name@version"),
verify: bool = typer.Option(True, "--verify/--no-verify",
help="Verify module signature"),
) -> None:
"""Install a module from the marketplace."""
console.print(f"[cyan]Installing {module_spec}...[/]")
try:
from ares.marketplace.installer import ModuleInstaller
installer = ModuleInstaller()
with console.status(f"[cyan]Resolving {module_spec}...[/]"):
result = installer.install_as_dict(module_spec, verify_signature=verify)
if result and result.get("success"):
console.print(Panel(
f"[green][+] Installed {module_spec}[/]\n"
f" Version: {result.get('version', ' - ')}\n"
f" Path: [dim]{result.get('path', ' - ')}[/]\n"
f" Verified: {'[green]yes[/]' if result.get('verified') else '[yellow]no[/]'}",
title="Module Installed",
box=box.ROUNDED,
))
else:
error = result.get("error", "unknown error") if result else "install returned no result"
console.print(f"[red][-] Install failed:[/] {error}")
raise typer.Exit(1)
except (ImportError, AttributeError) as exc:
console.print(f"[red][-] ModuleInstaller error:[/] {exc}")
raise typer.Exit(1) # noqa: B904
# ── Chain commands ─────────────────────────────────────────────────────────────
@chain_app.command("execute")
def chain_execute(
goal: str = typer.Option(..., "--goal", "-g",
help="Goal: domain_admin | data_exfil | cloud_access | full_compromise"),
target: str = typer.Option(..., "--target", "-t", help="Primary target"),
campaign_id: str = typer.Option(..., "--campaign", "-c"),
domain: str = typer.Option("", "--domain", "-d", help="AD domain (CORP.LOCAL)"),
profile: str = typer.Option("normal", "--profile", "-p"),
dry_run: bool = typer.Option(False, "--dry-run"),
show_plan: bool = typer.Option(False, "--plan-only", help="Show plan without executing"),
idempotency_key: str = typer.Option(
"", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"
),
) -> None:
"""Submit a deterministic ordered chain to the authenticated ARES HTTP API."""
console.print(Panel(
f"[bold]Goal:[/] {goal}\n"
f"[bold]Target:[/] {target}\n"
f"[bold]Profile:[/] {profile}\n"
+ (f"[bold]Domain:[/] {domain}\n" if domain else "")
+ ("[yellow][*] PLAN ONLY[/]" if show_plan else "")
+ ("[yellow][*] DRY RUN[/]" if dry_run else ""),
title="[bold red]Attack Chain Execution[/]",
box=box.ROUNDED,
))
if not dry_run and not show_plan:
confirm = typer.confirm(f"Execute [{goal}] chain against {target}?")
if not confirm:
raise typer.Abort()
asyncio.run(
_run_chain(
goal,
target,
campaign_id,
domain,
profile,
dry_run,
show_plan,
idempotency_key,
)
)
@chain_app.command("list")
def chain_list() -> None:
"""List available attack chain goals and their module sequences."""
try:
from ares.goal.engine import GOAL_DEFINITIONS, Goal
table = Table(title="Available Goals", show_lines=True, box=box.ROUNDED)
table.add_column("Goal", style="cyan", width=20)
table.add_column("Description", width=38)
table.add_column("Modules", style="dim", width=52)
for goal_val in Goal:
defn = GOAL_DEFINITIONS.get(goal_val)
if defn:
chain_str = " → ".join(defn.preferred_chain[:5])
if len(defn.preferred_chain) > 5:
chain_str += f" (+{len(defn.preferred_chain)-5} more)"
table.add_row(goal_val.value, defn.description, chain_str)
console.print(table)
except (ImportError, AttributeError):
# Fallback static table
table = Table(title="Available Goals", box=box.ROUNDED)
table.add_column("Goal", style="cyan", width=20)
table.add_column("Description", width=40)
table.add_column("Chain", style="dim", width=40)
goals = [
("domain_admin", "Compromise a Domain Administrator account",
"enum_users → kerberoast → crack → reuse"),
("data_exfil", "Extract sensitive data from compromised hosts",
"enum_computers → lateral → collect"),
("cloud_access", "Gain access to cloud infrastructure",
"aws/azure/gcp → enum → escalate"),
("full_compromise", "Complete network compromise (all goals)",
"domain_admin → data_exfil → persistence"),
]
for g, desc, chain in goals:
table.add_row(g, desc, chain)
console.print(table)
@chain_app.command("suggest")
def chain_suggest(
target: str = typer.Option(..., "--target", "-t", help="Target host IP"),
goal: str = typer.Option("domain_admin", "--goal", "-g", help="Goal to work toward"),
campaign_id: str = typer.Option("", "--campaign", "-c"),
profile: str = typer.Option("normal", "--profile", "-p"),
limit: int = typer.Option(5, "--limit", "-n", help="Number of suggestions"),
) -> None:
"""AI-style ranked suggestions for next attack modules (AttackPlanner)."""
try:
from ares.core.plugin.loader import ModuleRegistry
from ares.goal.engine import Goal as GoalEnum
from ares.goal.planner import AttackPlanner, PlannerContext
goal_enum = GoalEnum(goal) if goal in [g.value for g in GoalEnum] else GoalEnum.DOMAIN_ADMIN
registry = ModuleRegistry()
planner = AttackPlanner(registry=registry)
ctx = PlannerContext(
goal = goal_enum,
targets = [target],
opsec_profile = profile,
)
suggestions = planner.suggest(ctx, limit=limit)
if not suggestions:
console.print("[dim]No suggestions available - check registry modules.[/]")
return
table = Table(title=f"Suggestions for [{goal}] → {target}", show_lines=True, box=box.ROUNDED)
table.add_column("Rank", width=5, style="dim")
table.add_column("Module", width=24, style="cyan")
table.add_column("Score", width=7, style="yellow", justify="right")
table.add_column("OpSec", width=12)
table.add_column("Rationale", width=44)
for i, s in enumerate(suggestions, 1):
opsec_color = {"silent": "green", "low": "green",
"medium": "yellow", "high_noise": "red"}.get(s.opsec_level, "white")
table.add_row(
str(i), s.module_id,
f"{s.score:.3f}",
f"[{opsec_color}]{s.opsec_level}[/]",
s.rationale[:44],
)
console.print(table)
# Show score breakdown for top result
top = suggestions[0]
console.print(f"\n[dim]Top suggestion breakdown for [cyan]{top.module_id}[/]:[/]")
for factor, val in sorted(top.score_breakdown.items(), key=lambda x: -x[1]):
bar = "█" * int(val * 20)
console.print(f" {factor:<20} {val:.2f} [cyan]{bar}[/]")
except (ImportError, ValueError) as exc:
console.print(f"[red]Suggest error:[/] {exc}")
raise typer.Exit(1) # noqa: B904
# ── Report commands ────────────────────────────────────────────────────────────
@report_app.command("generate")
def report_generate(
campaign_id: str = typer.Option(..., "--campaign", "-c", help="Campaign ID"),
format: str = typer.Option("html", "--format", "-f",
help="Format: html | pdf | json | md | all"),
output: Path = typer.Option(Path("~/.ares/reports").expanduser(), # noqa: B008
"--output", "-o", help="Output directory"),
template: str = typer.Option("default", "--template", help="Report template"),
) -> None:
"""Generate a campaign report (HTML, PDF, JSON, Markdown)."""
from ares.cli._store import get_store
store = get_store()
c = store.get_campaign(campaign_id)
if not c:
console.print(f"[red]Campaign {campaign_id!r} not found[/]")
raise typer.Exit(1)
output = Path(str(output)).expanduser()
output.mkdir(parents=True, exist_ok=True)
with console.status(f"[cyan]Generating {format.upper()} report for [{c['name']}]...[/]"):
result_paths = asyncio.run(_generate_report(campaign_id, format, output))
if result_paths:
console.print(Panel(
"\n".join(f" [green][+][/] [cyan]{fmt.upper()}[/] {path}"
for fmt, path in result_paths.items()),
title=f"Report Generated - {c['name']}",
box=box.ROUNDED,
))
else:
console.print("[red]Report generation failed. Check logs.[/]")
raise typer.Exit(1)
@report_app.command("list")
def report_list(
campaign_id: str = typer.Option("", "--campaign", "-c"),
) -> None:
"""List all generated reports in ~/.ares/reports/."""
from ares.cli._store import get_store
store = get_store()
reports = store.list_reports(campaign_id)
if not reports:
console.print("[dim]No reports yet. Run [cyan]ares report generate --campaign <id>[/][/]")
return
table = Table(title="Generated Reports", box=box.ROUNDED)
table.add_column("Filename", style="cyan", width=44)
table.add_column("Format", style="yellow", width=8)
table.add_column("Size", justify="right", width=10)
table.add_column("Path", style="dim", width=50)
for r in reports:
table.add_row(
r["filename"], r["format"].upper(),
f"{r['size_kb']} KB", r["path"]
)
console.print(table)
# ── Signing commands ───────────────────────────────────────────────────────────
@signing_app.command("generate-key")
def signing_gen_key(
author: str = typer.Option(..., "--author", "-a", help="Author email"),
outdir: Path = typer.Option(Path("."), "--out", "-o", help="Output directory"),
password: bool = typer.Option(True, "--password/--no-password",
help="Encrypt private key with password"),
) -> None:
"""Generate a new Ed25519 signing key pair."""
from ares.core.signing import ModuleSigner
signer = ModuleSigner.generate_keypair(author)
priv_path = outdir / f"{signer.key_id}.key"
pub_path = outdir / f"{signer.key_id}.pub"
pw: bytes | None = None
if password:
pw_str = typer.prompt("Key password", hide_input=True, confirmation_prompt=True)
pw = pw_str.encode()
signer.save_private_key(priv_path, password=pw)
pub_path.write_text(signer.public_key_pem())
console.print(Panel(
f"[green][+] Key pair generated[/]\n\n"
f" Key ID: [cyan]{signer.key_id}[/]\n"
f" Private key: [dim]{priv_path}[/] (keep this SECRET)\n"
f" Public key: [cyan]{pub_path}[/] (share this)\n\n"
f"Add your public key to the ARES registry:\n"
f" [dim]ares signing add-key {signer.key_id} {pub_path} --author {author}[/]",
title="Signing Key Generated",
box=box.ROUNDED,
))
@signing_app.command("sign")
def signing_sign(
module_file: Path = typer.Argument(..., help="Module .py file to sign"),
key_file: Path = typer.Option(..., "--key", "-k", help="Private key file"),
author: str = typer.Option(..., "--author", "-a"),
module_id: str = typer.Option("", "--module-id", help="Module ID (auto-detected if omitted)"),
version: str = typer.Option("0.1.0", "--version"),
) -> None:
"""Sign a module file."""
from ares.core.signing import ModuleSigner
if not module_file.exists():
console.print(f"[red]File not found: {module_file}[/]"); raise typer.Exit(1)
pw_str = typer.prompt("Key password (or press Enter for no password)",
hide_input=True, default="")
pw = pw_str.encode() if pw_str else None
signer = ModuleSigner.load_private_key(key_file, author, password=pw)
sig = signer.sign_file(module_file, module_id=module_id, version=version)
sig_path = module_file.with_suffix(module_file.suffix + ".sig")
sig.save(sig_path)
console.print(f"[green][+] Signed:[/] {module_file.name} -> {sig_path.name}")
console.print(f" Key ID: [cyan]{sig.key_id}[/]")
console.print(f" File hash: [dim]{sig.file_hash[:16]}...[/]")
@signing_app.command("verify")
def signing_verify(
module_file: Path = typer.Argument(..., help="Module .py file to verify"),
policy: str = typer.Option("warn_unsigned", "--policy", "-p",
help="Policy: allow_all | warn_unsigned | require_signed | trusted_only"),
) -> None:
"""Verify a module's signature."""
from ares.core.signing import ModuleVerifier, SigningPolicy
policies = {
"allow_all": SigningPolicy.ALLOW_ALL,
"warn_unsigned": SigningPolicy.WARN_UNSIGNED,
"require_signed": SigningPolicy.REQUIRE_SIGNED,
"trusted_only": SigningPolicy.TRUSTED_ONLY,
}
verifier = ModuleVerifier(policy=policies.get(policy, SigningPolicy.WARN_UNSIGNED))
result = verifier.verify_file(module_file)
color = {"trusted": "green", "community": "yellow",
"unsigned": "dim", "invalid": "red", "revoked": "red"}.get(
result.trust_level.value, "white"
)
tag = {"trusted": "[OK]", "community": "[WARN]", "unsigned": "[*]",
"invalid": "[FAIL]", "revoked": "[REVOKED]"}.get(result.trust_level.value, "[?]")
console.print(
f"[{color}]{tag} {module_file.name}:[/] "
f"[{color}]{result.trust_level.value.upper()}[/]"
+ (f" (author: {result.author})" if result.author else "")
+ (f"\n [red]Error: {result.error}[/]" if result.error else "")
+ ("".join(f"\n [yellow]Warning: {w}[/]" for w in result.warnings))
)
@signing_app.command("add-key")
def signing_add_key(
key_id: str = typer.Argument(..., help="Key ID (fingerprint)"),
pub_key: Path = typer.Argument(..., help="Public key .pub file"),
author: str = typer.Option(..., "--author", "-a"),
operator: str = typer.Option("operator", "--operator"),
) -> None:
"""Add a trusted public key to the registry."""
from ares.core.signing import KeyRegistry
registry = KeyRegistry()
pem = pub_key.read_text(encoding="utf-8")
registry.add_trusted_key(key_id, pem, author, added_by=operator)
console.print(f"[green][+] Trusted key added:[/] {key_id} ({author})")
@signing_app.command("revoke-key")
def signing_revoke_key(
key_id: str = typer.Argument(..., help="Key ID to revoke"),
reason: str = typer.Option("", "--reason", "-r"),
operator: str = typer.Option("operator", "--operator"),
) -> None:
"""Revoke a signing key (all modules signed with it will be rejected)."""
confirm = typer.confirm(f"Revoke key {key_id}? This cannot be undone.")
if not confirm:
raise typer.Abort()
from ares.core.signing import KeyRegistry
registry = KeyRegistry()
registry.revoke_key(key_id, reason=reason, operator=operator)
console.print(f"[red][-] Key revoked:[/] {key_id}")
# ── Async helpers ──────────────────────────────────────────────────────────────
async def _run_module(
module_id: str,
target: str,
campaign_id: str,
domain: str,
profile: str,
dry_run: bool,
params: dict,
idempotency_key: str | None = None,
) -> dict[str, Any] | None:
"""Submit a module request without importing or constructing module code."""
try:
request_params = dict(params)
request_params.update(
{
"target": target,
"domain": domain,
"noise_profile": profile,
}
)
return _c_live_http_post(
f"/modules/{urllib_parse.quote(module_id, safe='')}/run",
{
"campaign_id": campaign_id,
"params": request_params,
"dry_run": bool(dry_run),
},
idempotency_key,
)
except _CLiveCliError as exc:
console.print(f"[red]{exc}[/]")
return None
async def _run_chain(
goal: str,
target: str,
campaign_id: str,
domain: str,
profile: str,
dry_run: bool,
show_plan: bool,
idempotency_key: str | None = None,
) -> None:
"""
Submit one complete deterministic chain without local module execution.
"""
from rich.table import Table as RTable
# Static goal definitions provide a complete, ordered chain without
# invoking GoalEngine planning callbacks or loading executable modules.
try:
from ares.goal.engine import GOAL_DEFINITIONS
from ares.goal.engine import Goal as GoalEnum
goal_enum = GoalEnum(goal)
modules = tuple(GOAL_DEFINITIONS[goal_enum].preferred_chain)
except (ImportError, KeyError, ValueError):
console.print("[red]c-live-cli:chain-intent-invalid[/]")
return
if not modules or any(type(module_id) is not str or not module_id for module_id in modules):
console.print("[red]c-live-cli:chain-intent-invalid[/]")
return
plan_table = RTable(title=f"Attack Plan - [{goal}]", show_lines=True, box=box.ROUNDED)
plan_table.add_column("#", width=4, style="dim")
plan_table.add_column("Module", width=24, style="cyan")
plan_table.add_column("Reason", width=46)
plan_table.add_column("OpSec", width=12, style="yellow")
plan_table.add_column("Status", width=12)
for i, module_id in enumerate(modules, start=1):
plan_table.add_row(
str(i), module_id, "deterministic configured chain", " - ", "[dim]pending[/]",
)
console.print(plan_table)
estimated_duration_min = min(len(modules) * 3, 60)
console.print(
f"\n[dim]Estimated duration: ~{estimated_duration_min} min · "
f"Steps: {len(modules)} · Goal: {goal}[/]\n"
)
if show_plan:
return
plan_body = {
"stages": [
{"name": f"step-{ordinal}", "modules": [module_id]}
for ordinal, module_id in enumerate(modules)
]
}
try:
result = _c_live_http_post(
f"/campaigns/{urllib_parse.quote(campaign_id, safe='')}/run",
{
"plan": plan_body,
"global_params": {
"target": target,
"domain": domain,
"noise_profile": profile,
},
"dry_run": bool(dry_run),
},
idempotency_key,
)
except _CLiveCliError as exc:
console.print(f"[red]{exc}[/]")
return
_display_c_live_http_result(result)
async def _generate_report(
campaign_id: str,
fmt: str,
output: Path,
) -> dict[str, str]:
"""
Generate report(s) via ReportGenerator.
Returns {format: path_str} for each generated file.
"""
from ares.cli._store import load_campaign
from ares.core.campaign import Finding, NoiseProfile, ScopeEntry, Severity
raw = load_campaign(campaign_id)
if not raw:
console.print(f"[red]Campaign {campaign_id!r} not found[/]")
return {}
# Reconstruct Campaign object from stored JSON
try:
from ares.core.campaign import Campaign as CampaignModel
noise_map = {
"stealth": NoiseProfile.STEALTH,
"normal": NoiseProfile.NORMAL,
"aggressive": NoiseProfile.AGGRESSIVE,
}
scope = []
for s in raw.get("scope", [{"cidr": "0.0.0.0/0"}]):
scope.append(ScopeEntry(cidr=s.get("cidr", "0.0.0.0/0")))
campaign = CampaignModel(
id = raw["id"],
name = raw.get("name", "Unnamed"),
client = raw.get("client", ""),
operator = raw.get("operator", "operator"),
scope = scope,
noise_profile= noise_map.get(raw.get("noise_profile", "normal"), NoiseProfile.NORMAL),
domain = raw.get("domain", ""),
)
# Restore findings from JSON
for f_data in raw.get("findings", []):
try:
sev_val = f_data.get("severity", "info")
sev = Severity(sev_val) if sev_val in [s.value for s in Severity] else Severity.INFO
finding = Finding(
title = f_data.get("title", "Finding"),
description = f_data.get("description", ""),
severity = sev,
confidence = float(f_data.get("confidence", 1.0)),
module_id = f_data.get("module_id", ""),
host = f_data.get("host", ""),
evidence = f_data.get("evidence", ""),
remediation = f_data.get("remediation", ""),
mitre_technique = f_data.get("mitre_technique", ""),
mitre_tactic = f_data.get("mitre_tactic", ""),
)
campaign.add_finding(finding)
except (KeyError, ValueError):
pass
except Exception as exc:
console.print(f"[red]Failed to rebuild campaign object:[/] {exc}")
return {}
# Generate
try:
from ares.modules.reporting.report_gen import ReportGenerator
gen = ReportGenerator(output_dir=str(output))
result_paths: dict[str, str] = {}
if fmt == "all":
paths = gen.generate_all(campaign)
result_paths = {f: str(p) for f, p in paths.items()}
else:
path = gen.generate(campaign, fmt=fmt)
result_paths[fmt] = str(path)
return result_paths
except Exception as exc:
console.print(f"[red]Report generation error:[/] {exc}")
import traceback
console.print(f"[dim]{traceback.format_exc()[-400:]}[/]")
return {}
def _display_result(module_id: str, result: dict) -> None:
"""Display module result in a rich panel."""
status_color = "green" if result.get("status") == "success" else "yellow"
findings_list = result.get("new_findings", [])
findings_summary = ""
if findings_list:
for f in findings_list[:3]:
sev = f.get("severity", "info").upper()
title = f.get("title", "")[:50]
findings_summary += f"\n [{sev}] {title}"
if len(findings_list) > 3:
findings_summary += f"\n ... +{len(findings_list)-3} more"
console.print(Panel(
f"[{status_color}]{result.get('status', 'unknown').upper()}[/]\n"
f" Findings: {result.get('findings', 0)}"
+ findings_summary + "\n"
f" Credentials: {result.get('new_credentials', 0)}\n"
f" New hosts: {', '.join(result.get('discovered_hosts', [])) or ' - '}",
title=f"Module Result: {module_id}",
))
# ── doctor command ────────────────────────────────────────────────────────────
def _parse_impacket_version(value: object) -> tuple[str, tuple[int, int]] | None:
"""Extract an Impacket semantic version from metadata or banner text."""
import re
if not value:
return None
match = re.search(r"\bv?(\d+)\.(\d+)(?:\.(\d+))?\b", str(value), re.IGNORECASE)
if match is None:
return None
version_parts = [match.group(1), match.group(2)]
if match.group(3) is not None:
version_parts.append(match.group(3))
return ".".join(version_parts), (int(match.group(1)), int(match.group(2)))
def _impacket_fallback_version(impacket_module: Any) -> str | None:
"""Read safe Impacket source-install version hints when package metadata is absent."""
import importlib
for attr in ("__version__", "VERSION", "BANNER"):
parsed = _parse_impacket_version(getattr(impacket_module, attr, ""))
if parsed is not None:
return parsed[0]
version_obj = getattr(impacket_module, "version", None)
parsed = _parse_impacket_version(version_obj)
if parsed is not None:
return parsed[0]
if version_obj is None:
try:
version_obj = importlib.import_module("impacket.version")
except Exception:
version_obj = None
if version_obj is not None:
for attr in ("__version__", "VERSION", "BANNER"):
parsed = _parse_impacket_version(getattr(version_obj, attr, ""))
if parsed is not None:
return parsed[0]
return None
def _run_pdf_smoke_check(
pdf_generator: Any,
check: Callable[[str, str, str], None],
) -> None:
"""Run the PDF smoke generator and report the result through doctor output."""
from ares.modules.reporting.report_gen import ReportDependencyError
try:
smoke_path = pdf_generator.generate_pdf_smoke()
if smoke_path.read_bytes()[:5] == b"%PDF-":
check(
"PDF smoke",
"ok",
f"{smoke_path} bytes={smoke_path.stat().st_size}",
)
else:
check("PDF smoke", "fail", f"{smoke_path} is not a PDF")
except ReportDependencyError as exc:
check("PDF smoke", "fail", str(exc))
except OSError as exc:
check("PDF smoke", "fail", str(exc))
@app.command("doctor")
def doctor(
pdf_smoke: bool = typer.Option(
False,
"--pdf-smoke",
help="Render a tiny PDF through the same runtime path used by dashboard export.",
),
) -> None:
"""Check all prerequisites and configuration. Run this first."""
import importlib
import os
import shutil
from importlib import metadata as importlib_metadata
from pathlib import Path
from ares.modules.ad.dependencies import AD_INSTALL_HINT, AD_SUPPORT_DEPENDENCIES
console.print("\n[bold]ARES Doctor[/bold] - prerequisite check\n")
ok = warn = fail = 0
def check(label: str, status: str, detail: str = "") -> None:
nonlocal ok, warn, fail
suffix = f" [dim]{escape(str(detail))}[/dim]" if detail else ""
if status == "ok":
console.print(f" [green][OK][/green] {label}" + suffix)
ok += 1
elif status == "warn":
console.print(f" [yellow][WARN][/yellow] {label}" + suffix)
warn += 1
else:
console.print(f" [red][FAIL][/red] {label}" + suffix)
fail += 1
def import_failure_detail(import_name: str, exc: Exception, hint: str = "") -> str:
message = str(exc) or repr(exc)
detail = f"import {import_name} failed: {exc.__class__.__name__}: {message}"
if hint:
detail = f"{detail}; {hint}"
return detail
# Python version
import sys
pv = sys.version_info
python_minor = _python_minor(pv)
py_major, py_minor = python_minor
py_micro = int(getattr(pv, "micro", 0))
python_label = f"{py_major}.{py_minor}.{py_micro}"
if PYTHON_MIN_VERSION <= python_minor < PYTHON_MAX_VERSION_EXCLUSIVE:
if python_minor == AD_IMPACKET_TESTED_PYTHON:
check(
f"Python {python_label}",
"ok",
"Python 3.12.x is the tested release runtime",
)
else:
check(
f"Python {python_label}",
"warn",
"Package metadata permits Python 3.11-3.12, but the full "
"dashboard + Windows AD/Impacket release path is tested on "
"Python 3.12.x",
)
check(
"Windows AD/Impacket Python",
"warn",
"Windows AD lab modules are tested on Python 3.12.x; "
"use 3.12.x if Kerberos/Impacket errors appear",
)
else:
check(
f"Python {py_major}.{py_minor}",
"fail",
"Python 3.13 is not supported for this release path; use Python "
"3.12.x for the full dashboard + Windows AD/Impacket workflow",
)
# Core packages
for pkg, import_name, label in [
("impacket", "impacket", "impacket (AD/SMB modules)"),
("paramiko", "paramiko", "paramiko (SSH modules)"),
("cryptography","cryptography", "cryptography"),
("pydantic", "pydantic", "pydantic"),
("structlog", "structlog", "structlog"),
("networkx", "networkx", "networkx (attack graph)"),
("jinja2", "jinja2", "jinja2 (reporting)"),
]:
try:
mod = importlib.import_module(import_name)
ver = getattr(mod, "__version__", "")
check(label, "ok", ver)
except Exception as exc:
if pkg == "impacket":
check(
label,
"warn",
import_failure_detail(import_name, exc, AD_INSTALL_HINT),
)
elif pkg == "paramiko":
check(
label,
"fail",
import_failure_detail(import_name, exc, "pip install ares-redteam[ad]"),
)
else:
check(label, "warn", import_failure_detail(import_name, exc, f"pip install {pkg}"))
# ── impacket version ──────────────────────────────────────────────────────
try:
import impacket
try:
ver_str = importlib_metadata.version("impacket")
except importlib_metadata.PackageNotFoundError:
ver_str = _impacket_fallback_version(impacket) or ""
version_match = _parse_impacket_version(ver_str)
if version_match and version_match[1] >= (0, 11):
check(f"impacket {version_match[0]}", "ok", ">= 0.11 required")
elif version_match:
check(f"impacket {version_match[0]}", "warn",
f"too old ({version_match[0]}); expected >= 0.11 - upgrade: pip install --upgrade impacket")
else:
check("impacket (AD/SMB modules)", "ok",
"importable; version unknown from source/local install")
except Exception as exc:
check(
"impacket",
"warn",
import_failure_detail("impacket", exc, AD_INSTALL_HINT),
)
# Direct AD support dependencies used by AD modules before runtime.
for import_name, label in AD_SUPPORT_DEPENDENCIES:
if import_name in {"ldap3", "httpx_ntlm"}:
continue
try:
mod = importlib.import_module(import_name)
ver = getattr(mod, "__version__", "")
check(label, "ok", ver or "available")
except Exception as exc:
check(label, "warn", import_failure_detail(import_name, exc, AD_INSTALL_HINT))
# ── ldap3 ─────────────────────────────────────────────────────────────────
try:
import ldap3
check(f"ldap3 {ldap3.__version__}", "ok", "AD LDAP enumeration ready")
except Exception as exc:
check("ldap3", "warn", import_failure_detail("ldap3", exc, AD_INSTALL_HINT))
# ── optional Windows modules ───────────────────────────────────────────────
try:
import pypykatz # noqa: F401 (probe: detect optional dep)
check("pypykatz (windows.lsass_dump)", "ok", "LSASS dump parsing ready")
except Exception as exc:
check("pypykatz (windows.lsass_dump)", "warn",
import_failure_detail("pypykatz", exc, "pip install ares-redteam[windows]"))
try:
import httpx_ntlm # noqa: F401 (probe: detect optional dep)
check("httpx-ntlm (ad.adcs ESC1)", "ok", "ADCS HTTP enrollment ready")
except Exception as exc:
check("httpx-ntlm (ad.adcs ESC1)", "warn",
import_failure_detail("httpx_ntlm", exc, AD_INSTALL_HINT))
# ── cloud SDKs ────────────────────────────────────────────────────────────
for import_name, module_label in [
("boto3", "cloud.aws"),
("azure.identity", "cloud.azure / cloud.azure_ad"),
("google.cloud", "cloud.gcp"),
("msal", "cloud.azure_ad device code"),
]:
try:
importlib.import_module(import_name)
check(f"{import_name.split('.')[0]} ({module_label})", "ok")
except Exception as exc:
check(f"{import_name.split('.')[0]} ({module_label})", "warn",
import_failure_detail(import_name, exc, "pip install ares-redteam[cloud]"))
# PDF export capability
try:
import ares.modules.reporting.report_gen as report_gen_module
from ares.modules.reporting.report_gen import ReportGenerator
pdf_generator = ReportGenerator()
try:
weasyprint = importlib.import_module("weasyprint")
check(
"PDF WeasyPrint",
"ok",
getattr(weasyprint, "__version__", "") or "available",
)
except Exception as exc:
check(
"PDF WeasyPrint",
"warn",
report_gen_module.ReportGenerator._pdf_backend_failure_detail(exc),
)
configured_pdf_browser = os.environ.get("ARES_PDF_BROWSER")
if configured_pdf_browser:
configured_pdf_browser_path = Path(configured_pdf_browser).expanduser()
check(
"PDF ARES_PDF_BROWSER",
"ok" if configured_pdf_browser_path.exists() else "warn",
f"{configured_pdf_browser_path} exists={configured_pdf_browser_path.exists()}",
)
else:
check(
"PDF ARES_PDF_BROWSER",
"warn",
"not set; auto-detecting Edge/Chrome/Chromium",
)
pdf_browsers = ReportGenerator._pdf_browser_candidates()
if pdf_browsers:
check("PDF browser detected", "ok", str(pdf_browsers[0]))
browser_order = " -> ".join(path.name for path in pdf_browsers)
check("PDF browser order", "ok", browser_order)
else:
check(
"PDF browser detected",
"warn",
"No Edge/Chrome/Chromium found; set ARES_PDF_BROWSER",
)
if os.name == "nt":
elevated = pdf_generator._windows_session_is_elevated()
check(
"PDF Windows elevated session",
"warn" if elevated else "ok",
f"elevated={elevated}",
)
edge = next(
(path for path in pdf_browsers if path.name.lower() == "msedge.exe"),
None,
)
if edge is None:
check("PDF Edge current session", "warn", "Edge not detected")
else:
edge_skip_reason = pdf_generator._pdf_browser_skip_reason(edge)
check(
"PDF Edge current session",
"warn" if edge_skip_reason else "ok",
edge_skip_reason or "Edge is usable in this session",
)
pdf_work_path: Path | None = None
try:
pdf_work_path, pdf_profile_dir, _pdf_html_path = (
pdf_generator._create_pdf_browser_workspace()
)
check(
"PDF browser profile temp dir writable",
"ok",
str(pdf_profile_dir),
)
except OSError as exc:
check("PDF browser profile temp dir writable", "warn", str(exc))
finally:
if pdf_work_path is not None:
shutil.rmtree(pdf_work_path, ignore_errors=True)
try:
pdf_generator._probe_writable_dir(pdf_generator.output_dir)
check(
"PDF report output dir writable",
"ok",
str(pdf_generator.output_dir),
)
except OSError as exc:
check("PDF report output dir writable", "warn", str(exc))
if pdf_smoke:
_run_pdf_smoke_check(pdf_generator, check)
except Exception as exc:
check("PDF browser fallback", "warn", str(exc)[:80])
# ── cracking tools ────────────────────────────────────────────────────────
for tool, desc in [("hashcat", "GPU cracking"), ("john", "CPU cracking")]:
path = shutil.which(tool) or shutil.which("john-the-ripper")
if path:
check(f"{tool} ({desc})", "ok", path)
else:
check(f"{tool} ({desc})", "warn",
f"not in PATH - install: apt install {tool} (Linux) / brew install {tool} (macOS)")
# ── network socket support ────────────────────────────────────────────────
import socket as _socket
for port, service in [(389, "LDAP"), (636, "LDAPS"), (445, "SMB"),
(88, "Kerberos"), (1433, "MSSQL"), (5985, "WinRM")]:
try:
s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
s.close()
check(f"socket AF_INET/{port} ({service})", "ok")
except OSError as e:
check(f"socket AF_INET/{port} ({service})", "warn", str(e)[:40])
# .env
env_path = Path(".env")
if env_path.exists():
content = env_path.read_text(encoding="utf-8")
if "CHANGE_ME" in content:
check(".env configured", "fail",
"CHANGE_ME placeholders found - run: ares-setup to generate secure keys")
else:
check(".env configured", "ok")
else:
check(".env file", "fail",
"Missing - run: cp .env.example .env && ares-setup")
# Database
try:
from ares.core.config import get_settings
s = get_settings()
db_path = s.ares_database_url.replace("sqlite+aiosqlite:///", "").replace("sqlite:///", "")
check("Settings loadable", "ok", s.ares_database_url[:40])
if "sqlite" in s.ares_database_url:
check("Database (SQLite)", "ok", db_path or ":memory:")
except SystemExit:
check("Settings loadable", "fail",
"env vars missing - fix: cp .env.example .env && ares-setup")
except Exception as exc:
check("Settings loadable", "warn", str(exc)[:60])
# Browser session policy
try:
from ares.core.browser_sessions import build_browser_session_policy
from ares.core.config import get_settings
_s = get_settings()
_policy = build_browser_session_policy(_s)
check("Browser session policy", "ok", f"{_policy.origin} (debug={_policy.debug})")
except Exception as exc:
check(
"Browser session policy",
"warn",
f"{exc} - fix: set ARES_DEBUG=true for local dev or set valid HTTPS ARES_BROWSER_ORIGIN matching ARES_TRUSTED_HOSTS",
)
# Summary
console.print()
total = ok + warn + fail
if fail == 0 and warn == 0:
console.print(f"[bold green]All {total} checks passed.[/bold green] ARES is ready.\n")
elif fail == 0:
console.print(f"[bold yellow]{ok}/{total} checks OK, {warn} warning(s).[/bold yellow]"
" ARES should work - optional tools missing.\n")
else:
console.print(f"[bold red]{fail} check(s) failed.[/bold red]"
f" Fix the [FAIL] items above, then re-run [cyan]ares doctor[/cyan].\n")
raise typer.Exit(1)
# ── quickstart wizard ─────────────────────────────────────────────────────────
# -- dashboard developer launcher ------------------------------------------------
def find_repo_root(start: Path | None = None) -> Path:
"""Find the repository root from the current directory or one of its parents."""
current = Path.cwd().resolve() if start is None else Path(start).resolve()
candidates = [current, *current.parents]
for candidate in candidates:
if (candidate / "pyproject.toml").exists() and (candidate / "frontend").is_dir():
return candidate
raise FileNotFoundError(
"Could not find the ARES repository root. Run this command from the repo checkout."
)
def resolve_npm_command(
os_name: str | None = None,
program_files_npm: Path | None = None,
which: Callable[[str], str | None] = shutil.which,
) -> str:
"""Resolve the npm executable without using a shell."""
effective_os = os.name if os_name is None else os_name
if effective_os == "nt":
preferred = program_files_npm or Path(r"C:\Program Files\nodejs\npm.cmd")
if preferred.exists():
return str(preferred)
return which("npm.cmd") or which("npm") or "npm.cmd"
return which("npm") or "npm"
def build_backend_command(
api_host: str,
api_port: int,
*,
reload: bool = True,
python_executable: str | None = None,
) -> list[str]:
command = [
python_executable or sys.executable,
"-m",
"uvicorn",
"ares.api.server:app",
"--host",
api_host,
"--port",
str(api_port),
]
if reload:
command.append("--reload")
return command
def build_frontend_command(npm_command: str, ui_host: str, ui_port: int) -> list[str]:
return [
npm_command,
"run",
"dev",
"--",
"--host",
ui_host,
"--port",
str(ui_port),
"--strictPort",
]
def is_port_in_use(host: str, port: int, *, timeout_seconds: float = 0.5) -> bool:
try:
with socket.create_connection((host, port), timeout=timeout_seconds):
return True
except OSError:
return False
def wait_for_port(host: str, port: int, *, timeout_seconds: float = 30.0) -> bool:
deadline = time.monotonic() + timeout_seconds
while time.monotonic() < deadline:
try:
with socket.create_connection((host, port), timeout=0.5):
return True
except OSError:
time.sleep(0.25)
return False
def _popen_kwargs(os_name: str | None = None) -> dict[str, object]:
effective_os = os.name if os_name is None else os_name
if effective_os == "nt":
return {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)}
return {"start_new_session": True}
class _WindowsCleanupJob:
"""Best-effort Windows job object that kills child processes if ARES exits."""
def __init__(self) -> None:
import ctypes
from ctypes import wintypes
self._ctypes = ctypes
self._kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
class _JobBasicLimitInformation(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_longlong),
("PerJobUserTimeLimit", ctypes.c_longlong),
("LimitFlags", wintypes.DWORD),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t),
("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD),
]
class _IoCounters(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ctypes.c_ulonglong),
("WriteOperationCount", ctypes.c_ulonglong),
("OtherOperationCount", ctypes.c_ulonglong),
("ReadTransferCount", ctypes.c_ulonglong),
("WriteTransferCount", ctypes.c_ulonglong),
("OtherTransferCount", ctypes.c_ulonglong),
]
class _JobExtendedLimitInformation(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", _JobBasicLimitInformation),
("IoInfo", _IoCounters),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
self._kernel32.CreateJobObjectW.argtypes = [wintypes.LPVOID, wintypes.LPCWSTR]
self._kernel32.CreateJobObjectW.restype = wintypes.HANDLE
self._kernel32.SetInformationJobObject.argtypes = [
wintypes.HANDLE,
wintypes.INT,
wintypes.LPVOID,
wintypes.DWORD,
]
self._kernel32.SetInformationJobObject.restype = wintypes.BOOL
self._kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
self._kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
self._kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
self._kernel32.CloseHandle.restype = wintypes.BOOL
self.handle = self._kernel32.CreateJobObjectW(None, None)
if not self.handle:
raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed")
info = _JobExtendedLimitInformation()
info.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
ok = self._kernel32.SetInformationJobObject(
self.handle,
9, # JobObjectExtendedLimitInformation
ctypes.byref(info),
ctypes.sizeof(info),
)
if not ok:
error = ctypes.get_last_error()
self.close()
raise OSError(error, "SetInformationJobObject failed")
def assign(self, process: subprocess.Popen) -> None:
process_handle = getattr(process, "_handle", None)
if not process_handle or not self.handle:
return
self._kernel32.AssignProcessToJobObject(self.handle, process_handle)
def close(self) -> None:
if getattr(self, "handle", None):
self._kernel32.CloseHandle(self.handle)
self.handle = None
def _create_windows_cleanup_job(os_name: str | None = None) -> _WindowsCleanupJob | None:
effective_os = os.name if os_name is None else os_name
if effective_os != "nt":
return None
try:
return _WindowsCleanupJob()
except Exception:
return None
def _start_dashboard_process(
label: str,
command: list[str],
cwd: Path,
*,
popen_factory: Callable[..., subprocess.Popen] = subprocess.Popen,
os_name: str | None = None,
env: dict[str, str] | None = None,
) -> subprocess.Popen:
console.print(f"[cyan]{label}[/cyan] {' '.join(command)}")
kwargs: dict[str, object] = dict(_popen_kwargs(os_name))
if env is not None:
kwargs["env"] = env
return popen_factory(
command,
cwd=str(cwd),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.DEVNULL,
text=True,
bufsize=1,
**kwargs,
)
def _stream_dashboard_logs(label: str, process: subprocess.Popen) -> None:
stream = getattr(process, "stdout", None)
if stream is None:
return
try:
for line in stream:
text = str(line).rstrip()
if text:
console.print(f"[dim]{label}[/dim] {text}")
except Exception as exc: # pragma: no cover - best-effort log streaming
console.print(f"[yellow]{label} log stream ended:[/yellow] {exc}")
def terminate_process_tree(
process: subprocess.Popen | None,
*,
os_name: str | None = None,
timeout_seconds: float = 8.0,
) -> None:
if process is None or process.poll() is not None:
return
effective_os = os.name if os_name is None else os_name
if effective_os == "nt":
try:
subprocess.run(
["taskkill", "/PID", str(process.pid), "/T", "/F"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
process.wait(timeout=timeout_seconds)
return
except Exception:
try:
process.kill()
except Exception:
pass
return
try:
os.killpg(process.pid, signal.SIGTERM)
except Exception:
try:
process.terminate()
except Exception:
pass
try:
process.wait(timeout=timeout_seconds)
return
except Exception:
pass
try:
os.killpg(process.pid, signal.SIGKILL)
except Exception:
try:
process.kill()
except Exception:
pass
def _ensure_frontend_dependencies(
frontend_dir: Path,
npm_command: str,
*,
install: bool = False,
run_func: Callable[..., subprocess.CompletedProcess] = subprocess.run,
) -> None:
node_modules = frontend_dir / "node_modules"
if node_modules.exists():
return
if not install:
console.print(
"[red]frontend/node_modules is missing.[/red] "
"Run [cyan]npm ci[/cyan] in the frontend directory, or re-run with "
"[cyan]--install[/cyan]."
)
raise typer.Exit(1)
console.print("[cyan]Installing frontend dependencies with npm ci...[/cyan]")
result = run_func([npm_command, "ci"], cwd=str(frontend_dir), check=False)
if result.returncode != 0:
console.print("[red]npm ci failed; dashboard dev server was not started.[/red]")
raise typer.Exit(result.returncode or 1)
def _install_dashboard_signal_handlers() -> list[tuple[int, object]]:
previous_handlers: list[tuple[int, object]] = []
def _raise_keyboard_interrupt(_signum, _frame) -> None:
raise KeyboardInterrupt
signals = [signal.SIGINT]
sigbreak = getattr(signal, "SIGBREAK", None)
if sigbreak is not None:
signals.append(sigbreak)
for sig in signals:
try:
previous_handlers.append((sig, signal.getsignal(sig)))
signal.signal(sig, _raise_keyboard_interrupt)
except Exception:
pass
return previous_handlers
def _restore_dashboard_signal_handlers(previous_handlers: list[tuple[int, object]]) -> None:
for sig, handler in previous_handlers:
try:
signal.signal(sig, handler)
except Exception:
pass
def _run_dashboard_dev(
*,
api_host: str = "127.0.0.1",
api_port: int = 8080,
ui_host: str = "127.0.0.1",
ui_port: int = 5173,
open_browser: bool = True,
reload: bool = True,
install: bool = False,
root: Path | None = None,
os_name: str | None = None,
popen_factory: Callable[..., subprocess.Popen] = subprocess.Popen,
run_func: Callable[..., subprocess.CompletedProcess] = subprocess.run,
port_in_use_func: Callable[[str, int], bool] = is_port_in_use,
wait_for_port_func: Callable[..., bool] = wait_for_port,
open_browser_func: Callable[[str], object] = webbrowser.open,
sleep_func: Callable[[float], object] = time.sleep,
) -> int:
root_path = find_repo_root(root)
frontend_dir = root_path / "frontend"
if not (frontend_dir / "package.json").exists():
console.print(f"[red]Frontend directory not found:[/red] {frontend_dir}")
raise typer.Exit(1)
for label, host, port in (
("backend", api_host, api_port),
("frontend", ui_host, ui_port),
):
if port_in_use_func(host, port):
console.print(f"[red]Cannot start dashboard: {label} port {host}:{port} is already occupied.[/red]")
console.print(
"[yellow]Likely cause: a stale Python or Node dashboard process is still running.[/yellow]"
)
console.print(
"Cleanup suggestion: Get-Process python,node -ErrorAction SilentlyContinue "
"| Stop-Process -Force -ErrorAction SilentlyContinue"
)
raise typer.Exit(1)
npm_command = resolve_npm_command(os_name=os_name)
_ensure_frontend_dependencies(
frontend_dir,
npm_command,
install=install,
run_func=run_func,
)
backend_url = f"http://{api_host}:{api_port}"
dashboard_url = f"http://{ui_host}:{ui_port}/dashboard/"
backend_command = build_backend_command(api_host, api_port, reload=reload)
frontend_command = build_frontend_command(npm_command, ui_host, ui_port)
console.print("\n[bold]ARES dashboard developer launcher[/bold]")
console.print(f"Backend API URL: {backend_url}")
console.print(f"Dashboard URL: {dashboard_url}")
console.print("Login username: admin")
console.print("Password source: ARES_DEFAULT_ADMIN_PASSWORD from current environment or .env")
if not (root_path / ".env").exists():
console.print("[yellow]Warning:[/yellow] .env was not found in the repo root.")
console.print()
backend_process: subprocess.Popen | None = None
frontend_process: subprocess.Popen | None = None
threads: list[threading.Thread] = []
cleanup_job = _create_windows_cleanup_job(os_name)
previous_signal_handlers = _install_dashboard_signal_handlers()
try:
backend_env = dict(os.environ)
backend_env["ARES_DEBUG"] = "true"
backend_env["ARES_BROWSER_ORIGIN"] = f"http://{ui_host}:{ui_port}"
backend_env["ARES_TRUSTED_HOSTS"] = "localhost,127.0.0.1"
backend_process = _start_dashboard_process(
"backend",
backend_command,
root_path,
popen_factory=popen_factory,
os_name=os_name,
env=backend_env,
)
if cleanup_job is not None:
cleanup_job.assign(backend_process)
frontend_process = _start_dashboard_process(
"frontend",
frontend_command,
frontend_dir,
popen_factory=popen_factory,
os_name=os_name,
)
if cleanup_job is not None:
cleanup_job.assign(frontend_process)
for label, process in (("backend", backend_process), ("frontend", frontend_process)):
thread = threading.Thread(
target=_stream_dashboard_logs,
args=(label, process),
daemon=True,
)
thread.start()
threads.append(thread)
if open_browser:
if not wait_for_port_func(ui_host, ui_port, timeout_seconds=30.0):
console.print(
f"[red]Frontend did not become ready on {ui_host}:{ui_port}; "
"dashboard was not opened.[/red]"
)
return 1
console.print(f"[green]Opening dashboard:[/green] {dashboard_url}")
open_browser_func(dashboard_url)
else:
console.print("[dim]Browser open skipped because --no-open was provided.[/dim]")
while True:
backend_code = backend_process.poll()
frontend_code = frontend_process.poll()
if backend_code is not None:
console.print(f"[red]Backend process exited with code {backend_code}.[/red]")
return backend_code or 1
if frontend_code is not None:
console.print(f"[red]Frontend process exited with code {frontend_code}.[/red]")
return frontend_code or 1
sleep_func(0.25)
except KeyboardInterrupt:
console.print("\n[yellow]Shutting down dashboard dev servers...[/yellow]")
return 0
finally:
terminate_process_tree(frontend_process, os_name=os_name)
terminate_process_tree(backend_process, os_name=os_name)
if cleanup_job is not None:
cleanup_job.close()
_restore_dashboard_signal_handlers(previous_signal_handlers)
for thread in threads:
thread.join(timeout=1.0)
@dashboard_app.command("dev")
def dashboard_dev(
api_host: str = typer.Option("127.0.0.1", "--api-host", help="Backend API host."),
api_port: int = typer.Option(8080, "--api-port", help="Backend API port."),
ui_host: str = typer.Option("127.0.0.1", "--ui-host", help="Frontend dev host."),
ui_port: int = typer.Option(5173, "--ui-port", help="Frontend dev port."),
open_browser: bool = typer.Option(
True,
"--open/--no-open",
help="Open the dashboard URL in the default browser.",
),
reload: bool = typer.Option(
True,
"--reload/--no-reload",
help="Run uvicorn with reload enabled.",
),
install: bool = typer.Option(
False,
"--install",
help="Run npm ci in frontend/ if node_modules is missing.",
),
) -> None:
"""Run the FastAPI backend and Vite dashboard dev server together."""
exit_code = _run_dashboard_dev(
api_host=api_host,
api_port=api_port,
ui_host=ui_host,
ui_port=ui_port,
open_browser=open_browser,
reload=reload,
install=install,
)
if exit_code:
raise typer.Exit(exit_code)
@app.command("quickstart")
def quickstart() -> None:
"""Guided wizard for first-time users - creates your first campaign."""
console.print("\n[bold cyan]ARES Quick Start Wizard[/bold cyan]\n")
name = typer.prompt("Campaign name", default="Lab Assessment")
client = typer.prompt("Client name", default="ACME Corp")
target = typer.prompt("Target IP or CIDR (e.g. 10.10.10.0/24)")
noise = typer.prompt("Noise profile", default="normal",
show_choices=True, type=typer.Choice(["stealth", "normal", "aggressive"]))
console.print("\n[dim]Creating campaign...[/dim]")
try:
from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry
campaign = Campaign(
name=name, client=client, operator="operator",
scope=[ScopeEntry(cidr=target)],
noise_profile=NoiseProfile(noise),
)
cid = campaign.id
except Exception as exc:
console.print(f"[red]Failed to create campaign: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
console.print(f"\n[green][+] Campaign created: {cid}[/green]\n")
console.print("[bold]Next steps:[/bold]")
console.print(f" ares module run ad.enum_users --campaign {cid} --dc {target.split('/')[0]} --domain corp.local")
console.print(f" ares module run ad.kerberoast --campaign {cid} --dc {target.split('/')[0]} --domain corp.local")
console.print(f" ares report generate --campaign-id {cid} --format html")
console.print()
# ── ares-setup entry point ────────────────────────────────────────────────────
def _setup_platform_label(platform_name: str, os_name: str) -> str:
if os_name == "nt" or platform_name.startswith("win"):
return "Windows"
if platform_name == "darwin":
return "macOS"
if platform_name.startswith("linux"):
return "Linux"
return platform_name or os_name
def _setup_encryption_key() -> str:
"""Generate a 256-bit (32-byte) URL-safe encryption key for AES-256-GCM."""
import secrets
return secrets.token_urlsafe(32)
_setup_fernet_key = _setup_encryption_key # backward-compatibility alias
def _setup_admin_password(length: int = 20) -> str:
import secrets
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$"
return "".join(secrets.choice(alphabet) for _ in range(length))
def _extract_env_value(content: str, key: str) -> str | None:
prefix = f"{key}="
for line in content.splitlines():
line = line.strip()
if line.startswith(prefix):
return line[len(prefix):].strip()
return None
def _upsert_env_value(template: str, key: str, value: str) -> str:
prefix = f"{key}="
lines = template.splitlines()
for index, line in enumerate(lines):
if line.strip().startswith(prefix):
lines[index] = f"{prefix}{value}"
break
else:
lines.append(f"{prefix}{value}")
return "\n".join(lines) + "\n"
def _run_python_setup(
root: Path | None = None,
platform_name: str | None = None,
os_name: str | None = None,
version_info: object | None = None,
force: bool = False,
) -> None:
import os
import secrets
root_path = Path.cwd() if root is None else Path(root)
platform_value = sys.platform if platform_name is None else platform_name
os_value = os.name if os_name is None else os_name
platform_label = _setup_platform_label(platform_value, os_value)
python_version_info = sys.version_info if version_info is None else version_info
python_minor = _python_minor(python_version_info)
py_major, py_minor = python_minor
py_micro = int(getattr(python_version_info, "micro", 0))
runtime_version = (
sys.version.split()[0]
if version_info is None
else f"{py_major}.{py_minor}.{py_micro}"
)
console.print("\n[bold]ARES Setup[/bold]")
console.print(f"Platform: {platform_label} ({platform_value}/{os_value})")
console.print(f"Python: {runtime_version} ({sys.executable})")
if not (PYTHON_MIN_VERSION <= python_minor < PYTHON_MAX_VERSION_EXCLUSIVE):
console.print("[red]ERROR[/red] Python 3.11-3.12 is required.")
console.print("Windows AD/Impacket modules are tested on Python 3.12.x.")
raise SystemExit(1)
if python_minor != AD_IMPACKET_TESTED_PYTHON:
console.print(
"[yellow]Warning[/yellow] Package metadata permits Python 3.11-3.12, "
"but the tested release path for the dashboard and Windows "
"AD/Impacket modules is Python 3.12.x."
)
else:
console.print(
"[green]OK[/green] Python 3.12.x detected for the tested release path."
)
env_path = root_path / ".env"
example_path = root_path / ".env.example"
try:
admin_password = None
if env_path.exists():
existing = env_path.read_text(encoding="utf-8")
secret_val = _extract_env_value(existing, "ARES_SECRET_KEY")
enc_val = _extract_env_value(existing, "ARES_ENCRYPTION_KEY")
admin_val = _extract_env_value(existing, "ARES_DEFAULT_ADMIN_PASSWORD")
origin_val = _extract_env_value(existing, "ARES_BROWSER_ORIGIN")
debug_val = _extract_env_value(existing, "ARES_DEBUG")
has_placeholders = (
"CHANGE_ME" in existing
or (admin_val is not None and "YOUR_STRONG_ADMIN_PASSWORD_HERE" in admin_val)
or (origin_val is not None and "example.invalid" in origin_val)
)
missing_critical = (
secret_val is None or secret_val == "" or "CHANGE_ME" in secret_val
or enc_val is None or enc_val == "" or "CHANGE_ME" in enc_val
)
if force or has_placeholders or missing_critical:
updated = existing
# Check ARES_SECRET_KEY
if force or secret_val is None or secret_val == "" or "CHANGE_ME" in secret_val:
new_secret = secrets.token_hex(32)
updated = _upsert_env_value(updated, "ARES_SECRET_KEY", new_secret)
# Check ARES_ENCRYPTION_KEY
if force or enc_val is None or enc_val == "" or "CHANGE_ME" in enc_val:
new_enc = _setup_encryption_key()
updated = _upsert_env_value(updated, "ARES_ENCRYPTION_KEY", new_enc)
# Check ARES_DEFAULT_ADMIN_PASSWORD
if force or admin_val is None or admin_val == "" or "CHANGE_ME" in admin_val or "YOUR_STRONG_ADMIN_PASSWORD_HERE" in admin_val:
admin_password = _setup_admin_password()
updated = _upsert_env_value(updated, "ARES_DEFAULT_ADMIN_PASSWORD", admin_password)
# Clean placeholder browser origin if pointing to example.invalid
if origin_val is not None and "example.invalid" in origin_val:
updated = _upsert_env_value(updated, "ARES_BROWSER_ORIGIN", "")
# Default ARES_DEBUG to true for local installation if unset or invalid
if debug_val is None or debug_val == "" or (debug_val.lower() == "false" and (origin_val is None or "example.invalid" in origin_val or origin_val == "")):
updated = _upsert_env_value(updated, "ARES_DEBUG", "true")
env_path.write_text(updated, encoding="utf-8")
from ares.core.security import restrict_file_to_owner
restrict_file_to_owner(str(env_path))
if force:
console.print("[green]OK[/green] .env regenerated with fresh secure keys (--force).")
else:
console.print("[green]OK[/green] Replaced CHANGE_ME placeholders in .env with secure generated keys.")
if admin_password is not None:
# Never print the generated password to stdout (it lands in
# shell history / terminal scrollback / CI logs). Point the
# operator at the owner-only .env instead. (AUDIT run-1 H11)
console.print(
f"Admin password written to {env_path} "
"(ARES_DEFAULT_ADMIN_PASSWORD). Open it to retrieve the "
"password, then rotate it after first login."
)
else:
console.print("[green]OK[/green] .env already exists; leaving it unchanged.")
admin_password = None
else:
if example_path.exists():
template = example_path.read_text(encoding="utf-8")
else:
console.print("[yellow]Warning[/yellow] .env.example not found; using minimal template.")
template = "ARES_SECRET_KEY=\nARES_ENCRYPTION_KEY=\nARES_DEFAULT_ADMIN_PASSWORD=\n"
admin_password = _setup_admin_password()
template = _upsert_env_value(template, "ARES_SECRET_KEY", secrets.token_hex(32))
template = _upsert_env_value(template, "ARES_ENCRYPTION_KEY", _setup_encryption_key())
template = _upsert_env_value(template, "ARES_DEFAULT_ADMIN_PASSWORD", admin_password)
template = _upsert_env_value(template, "ARES_DEBUG", "true")
origin_in_template = _extract_env_value(template, "ARES_BROWSER_ORIGIN")
if origin_in_template and "example.invalid" in origin_in_template:
template = _upsert_env_value(template, "ARES_BROWSER_ORIGIN", "")
env_path.write_text(template, encoding="utf-8")
from ares.core.security import restrict_file_to_owner
restrict_file_to_owner(str(env_path))
console.print(f"[green]OK[/green] .env created at {env_path} (owner-only permissions)")
# Do not print the generated password to stdout. (AUDIT run-1 H11)
console.print(
f"Admin password written to {env_path} (ARES_DEFAULT_ADMIN_PASSWORD). "
"Open it to retrieve the password, then rotate it after first login."
)
except OSError as exc:
console.print(f"[red]ERROR[/red] setup failed: {exc.__class__.__name__}: {exc}")
raise SystemExit(1) from None
setup_sh = root_path / "scripts" / "setup.sh"
if setup_sh.exists() and (os_value == "nt" or platform_value.startswith("win")):
console.print("[yellow]Info[/yellow] scripts/setup.sh is POSIX-only and was skipped on Windows.")
elif setup_sh.exists():
console.print("[dim]Developer helper available: scripts/setup.sh (optional).[/dim]")
console.print("Next steps:")
console.print(" ares doctor")
if admin_password is not None:
console.print(" Store the generated admin password securely.")
def setup_entrypoint() -> None:
"""Entry point for `ares-setup` using Python-native cross-platform setup."""
import sys
args = sys.argv[1:]
if "--help" in args or "-h" in args:
console.print("[bold]ARES Setup[/bold]")
console.print("Usage: ares-setup [--force | -f]")
console.print("Initializes or updates .env with secure random keys and admin credentials.")
console.print("Options:")
console.print(" --force, -f Force regeneration of ARES_SECRET_KEY, ARES_ENCRYPTION_KEY, and admin password.")
return
force = "--force" in args or "-f" in args
if force:
_run_python_setup(force=True)
else:
_run_python_setup()
# ── backup command ────────────────────────────────────────────────────────────
@app.command("backup")
def backup(
output: str = typer.Option(None, "--output", "-o", help="Output JSON file path"),
) -> None:
"""Export all campaigns and findings to a JSON backup file."""
import asyncio
from ares.core.config import get_settings
from ares.db.database import AresDatabase
async def _run() -> str:
s = get_settings()
async with await AresDatabase.create(s.db_path, s.encryption_key_value) as db:
await db.checkpoint_wal()
path = await db.export_json(output)
return path
try:
out = asyncio.run(_run())
console.print(f"[green][+] Backup saved:[/green] {out}")
except Exception as exc:
console.print(f"[red][-] Backup failed: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
# ── update command (Additive new modules) ─────────────────────────────────────
@app.command("update")
def update_cmd(
module: str | None = typer.Option(None, "--module", "-m", help="Specific new module ID to install"),
dry_run: bool = typer.Option(False, "--dry-run", help="Preview new modules without downloading"),
repo: str = typer.Option("Mafifrizi/ARES", "--repo", help="Official GitHub repository (owner/repo)"),
branch: str = typer.Option("main", "--branch", help="Git branch to synchronize against"),
) -> None:
"""
Synchronize and install newly released ARES attack modules (additive only).
This command only fetches new modules that you do not already possess.
Existing modules, user configuration, and database files remain untouched.
"""
from ares.core.updater import PlatformUpdateManager
mode_tag = "dry-run" if dry_run else "additive-install"
console.print(f"[bold cyan][INF][/bold cyan] ARES Module Update Engine [dim]({repo}@{branch} | {mode_tag})[/dim]")
mgr = PlatformUpdateManager(github_repo=repo, branch=branch)
try:
with console.status("[cyan]Checking remote repository for new attack modules...[/cyan]"):
check_res = mgr.check_updates()
except Exception as exc:
console.print(f"[red][-] Update check failed: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
new_mods = check_res.new_modules
if module:
cleaned = module.strip().lower()
local = mgr.get_local_modules()
target_rel_path = local[cleaned].relative_path.lower() if cleaned in local else None
new_mods = [
m for m in new_mods
if m.module_id.lower() == cleaned
or m.relative_path.lower().endswith(f"{cleaned}.py")
or (target_rel_path and m.relative_path.lower() == target_rel_path)
]
if not new_mods:
console.print("[green][+] All official modules are already installed. No new modules available.[/green]")
console.print(f"[dim]Total local modules: {check_res.local_count} | Remote catalog: {check_res.remote_count}[/dim]")
if check_res.upgradable_modules:
console.print("[yellow][*] Note: Existing modules have revisions available. Run 'ares upgrade --modules' to update them.[/yellow]")
return
console.print(f"[bold cyan][INF][/bold cyan] {len(new_mods)} new module(s) available for installation:")
for item in new_mods:
cat = escape(item.category or "general")
console.print(f" [bold green]+[/bold green] [cyan]{item.module_id}[/cyan] [green]\\[{cat}][/green] [dim]({item.size_bytes} B)[/dim] - [dim]{item.relative_path}[/dim]")
if dry_run:
console.print(f"\n[yellow][*] Dry-run complete. {len(new_mods)} new module(s) can be installed with 'ares update'.[/yellow]")
return
console.print(f"\n[cyan][*] Installing {len(new_mods)} new module(s)...[/cyan]")
res = mgr.update_modules(module_id=module, dry_run=False)
if res.get("status") == "ok":
console.print(f"[green][+] Successfully installed {res.get('installed_count')} new module(s).[/green]")
for mod in res.get("installed_modules", []):
console.print(f" [green]+[/green] {mod}")
else:
console.print(f"[yellow][!] Installed {res.get('installed_count')} module(s) with errors:[/yellow]")
for err in res.get("errors", []):
console.print(f" [red]-[/red] {err}")
# ── upgrade command (In-place patches, UI dashboard, full platform) ───────────
@app.command("upgrade")
def upgrade_cmd(
all: bool = typer.Option(False, "--all", "-a", help="Upgrade full platform (core engine + DB migrations + modules + Web UI)"),
system: bool = typer.Option(False, "--system", "--core", help="Upgrade core framework engine and apply database schema migrations"),
ui: bool = typer.Option(False, "--ui", help="Upgrade Frontend Web UI Dashboard bundle"),
modules: bool = typer.Option(False, "--modules", help="Upgrade existing attack modules to latest versions"),
module: str | None = typer.Option(None, "--module", "-m", help="Specific installed module ID to upgrade"),
check: bool = typer.Option(False, "--check", "-c", help="Check for available system and module updates without modifying disk"),
dry_run: bool = typer.Option(False, "--dry-run", help="Preview upgrades without modifying disk"),
repo: str = typer.Option("Mafifrizi/ARES", "--repo", help="Official GitHub repository (owner/repo)"),
branch: str = typer.Option("main", "--branch", help="Git branch to synchronize against"),
) -> None:
"""
Upgrade ARES core platform system, database schemas, attack modules, or Web UI dashboard.
Ensures zero data loss: Databases, credentials, and custom configurations are strictly preserved.
"""
from ares.core.updater import PlatformUpdateManager
mgr = PlatformUpdateManager(github_repo=repo, branch=branch)
# ── 1. Check mode ──────────────────────────────────────────────────────────
if check:
with console.status("[cyan]Checking remote repository for system updates...[/cyan]"):
try:
chk = mgr.check_system_update()
except Exception as exc:
console.print(f"[red][-] Failed checking for updates: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
console.print(f"[bold cyan][INF][/bold cyan] ARES Platform System Status (v{chk.get('version')} on branch: [green]{chk.get('branch')}[/green])")
console.print(f"[bold cyan][INF][/bold cyan] Local commit: [white]{chk.get('local_commit')}[/white] | Remote commit: [white]{chk.get('remote_commit')}[/white]")
if chk.get("commit_message") and chk.get("commit_message") != "none":
console.print(f"[bold cyan][INF][/bold cyan] Latest change: [dim]{chk.get('commit_message')}[/dim]")
sys_stat = "[yellow]Update available[/yellow]" if chk.get("system_update_available") else "[green]Up to date[/green]"
console.print(f"[bold cyan][INF][/bold cyan] Core system: {sys_stat}")
console.print(f"[bold cyan][INF][/bold cyan] Attack modules: [white]{chk.get('new_modules_count', 0)}[/white] new available, [white]{chk.get('upgradable_modules_count', 0)}[/white] upgradable")
console.print(f"[bold cyan][INF][/bold cyan] Web UI bundle: {'[green]Available[/green]' if chk.get('ui_available') else '[dim]Not indexed[/dim]'}")
if chk.get("system_update_available") or chk.get("new_modules_count", 0) > 0:
console.print("\n[yellow][*] Run [bold]ares upgrade[/bold] to apply the latest system updates.[/yellow]")
else:
console.print("\n[green][+] System is fully up to date with official release.[/green]")
return
# Default to --all if no specific scope is selected
if not all and not system and not ui and not modules and not module:
all = True
action_label = "Full Platform System" if all else ("Core Engine & DB" if system else ("Web UI Dashboard" if ui and not modules else "Attack Modules"))
mode_str = "dry-run" if dry_run else "in-place upgrade"
console.print(f"[bold cyan][INF][/bold cyan] ARES Platform Upgrade Engine [dim]({repo}@{branch} | scope: {action_label} | {mode_str})[/dim]", soft_wrap=True)
# ── 2. Full Platform System Upgrade ────────────────────────────────────────
if all:
with console.status("[cyan]Executing full-system platform upgrade (Core, DB, Modules, UI)...[/cyan]"):
res = mgr.upgrade_all(dry_run=dry_run)
if dry_run:
console.print("[yellow][*] Dry-run simulation completed. No files modified.[/yellow]")
return
sys_res = res.get("system", {})
console.print("\n[bold green][+] Platform System Upgrade Completed[/bold green]\n")
# System Core
sys_status = sys_res.get("status", "ok")
if sys_status == "ok":
console.print(f" [green]*[/green] Core Framework: [bold green]Updated[/bold green] ({sys_res.get('system', {}).get('message', 'Synchronized')})")
elif sys_status == "up_to_date":
console.print(" [green]*[/green] Core Framework: [dim]Already up to date[/dim]")
elif sys_status == "dirty_tree":
console.print(" [yellow]![/yellow] Core Framework: [yellow]Skipped (working tree has modified files)[/yellow]")
else:
console.print(f" [yellow]![/yellow] Core Framework: {sys_res.get('system', {}).get('message', 'Checked')}")
# Database Schema
db_res = sys_res.get("database", {})
if db_res.get("applied"):
console.print(" [green]*[/green] Database Schema: [bold green]Migrated (head)[/bold green]")
else:
console.print(f" [green]*[/green] Database Schema: [dim]{db_res.get('message', 'Verified')}[/dim]")
# Attack Modules & UI
console.print(f" [green]*[/green] Attack Modules: [cyan]{res.get('modules_upgraded', 0)} updated[/cyan], [cyan]{res.get('modules_added', 0)} new added[/cyan]")
console.print(f" [green]*[/green] Web UI Dashboard: [cyan]{res.get('ui_status', 'ok')}[/cyan]")
# Server reload
srv = res.get("server_reload", {})
if srv.get("connected"):
console.print(f" [green]*[/green] Live Server Hot-Reload: [green]Connected ({srv.get('module_count')} modules active)[/green]")
else:
console.print(" [green]*[/green] Live Server: [dim]Offline (changes will apply on next start)[/dim]")
# Post-upgrade diagnostics
diag = res.get("diagnostics", {})
if diag.get("healthy"):
console.print("\n[bold green][+] Post-Upgrade System Diagnostics: HEALTHY (All checks passed)[/bold green]")
for c in diag.get("checks", []):
console.print(f" [green]OK[/green] {c.get('subsystem')}: [dim]{c.get('detail')}[/dim]")
return
# ── 3. System Core Only Upgrade ────────────────────────────────────────────
if system:
with console.status("[cyan]Upgrading core framework engine and applying database migrations...[/cyan]"):
res = mgr.upgrade_system(dry_run=dry_run)
diag = mgr.run_post_upgrade_diagnostics() if not dry_run else {"healthy": True}
if dry_run:
console.print("[yellow][*] Dry-run simulation completed. No files modified.[/yellow]")
return
console.print(f"[green][+] Core engine upgrade: {res.get('status')}[/green]")
console.print(f" - Details: {res.get('system', {}).get('message', 'Complete')}")
console.print(f" - Database: {res.get('database', {}).get('message', 'Complete')}")
if diag.get("healthy"):
console.print("[green][+] Post-upgrade health: PASS[/green]")
return
# ── 4. Web UI Dashboard Only Upgrade ───────────────────────────────────────
if ui:
with console.status("[cyan]Upgrading Frontend Web UI Dashboard bundle...[/cyan]"):
try:
res = mgr.upgrade_ui(dry_run=dry_run)
if dry_run:
console.print(f"[yellow][*] {res.get('message')}[/yellow]")
else:
console.print(f"[green][+] {res.get('message')}[/green]")
console.print(f"[dim]Distribution path: {res.get('target_dir')}[/dim]")
except Exception as exc:
console.print(f"[red][-] UI upgrade failed: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
if not modules and not module:
return
# ── 5. Attack Modules Only Upgrade ─────────────────────────────────────────
if modules or module:
with console.status("[cyan]Checking and upgrading attack modules...[/cyan]"):
try:
res = mgr.upgrade_modules(module_id=module, dry_run=dry_run)
except Exception as exc:
console.print(f"[red][-] Module upgrade failed: {exc}[/red]")
raise typer.Exit(1) # noqa: B904
if dry_run:
console.print(f"[yellow][*] Dry-run complete. {res.get('upgraded_count', 0)} module(s) eligible for upgrade.[/yellow]")
return
if res.get("status") == "ok":
console.print(f"[green][+] Successfully upgraded {res.get('upgraded_count', 0)} module(s).[/green]")
for mod in res.get("upgraded_modules", []):
console.print(f" [green]*[/green] {mod}")
elif res.get("status") == "not_found":
console.print(f"[yellow][!] {res.get('message')}[/yellow]")
else:
console.print("[yellow][!] Upgraded with warnings:[/yellow]")
for err in res.get("errors", []):
console.print(f" [red]-[/red] {err}")
# ── Goal commands ──────────────────────────────────────────────────────────────
@goal_app.command("run")
def goal_run(
goal: str = typer.Argument(..., help="Goal name: domain_admin, data_exfil, cloud_admin, persistence, initial_access, full_compromise"),
campaign_id: str = typer.Option(..., "--campaign-id", "-c", help="Campaign ID to run against"),
dc: str = typer.Option("", "--dc", help="Domain Controller IP"),
domain: str = typer.Option("", "--domain", help="AD domain (CORP.LOCAL)"),
dry_run: bool = typer.Option(False, "--dry-run", help="Show plan without executing"),
idempotency_key: str = typer.Option(
"", "--idempotency-key", help="Canonical lowercase UUIDv4 reused for transport retry"
),
) -> None:
"""Preview locally or submit one goal request to the authenticated API."""
del dc, domain # Strategy API owns target context for the selected campaign.
try:
from ares.goal.engine import GOAL_DEFINITIONS
from ares.goal.engine import Goal as GoalEnum
goal_enum = GoalEnum(goal)
modules = tuple(GOAL_DEFINITIONS[goal_enum].preferred_chain)
except (ImportError, KeyError, ValueError):
console.print("[red]c-live-cli:goal-intent-invalid[/]")
raise typer.Exit(1) from None
if not modules or any(type(module_id) is not str or not module_id for module_id in modules):
console.print("[red]c-live-cli:goal-intent-invalid[/]")
raise typer.Exit(1)
table = Table(title=f"[bold]Goal Preview - {goal}[/bold]", show_lines=True, box=box.ROUNDED)
table.add_column("Step", style="cyan", width=5)
table.add_column("Module", style="green")
table.add_column("Reason")
for ordinal, module_id in enumerate(modules, start=1):
table.add_row(str(ordinal), module_id, "deterministic configured chain")
console.print(table)
console.print(f"\n[dim]Estimated duration: {min(len(modules) * 3, 60)} min[/dim]")
if dry_run:
console.print("[yellow]Preview only - no HTTP request or module code executed.[/yellow]")
return
try:
result = _c_live_http_post(
"/strategy/engage",
{
"campaign_id": campaign_id,
"goal": goal_enum.value,
"llm_backend": "local",
},
idempotency_key,
)
except _CLiveCliError as exc:
console.print(f"[red]{exc}[/]")
raise typer.Exit(1) from None
_display_c_live_http_result(result)
@goal_app.command("list")
def goal_list() -> None:
"""List all available goals and their descriptions."""
from ares.goal.engine import GOAL_DEFINITIONS
table = Table(title="Available Goals", show_lines=False, box=box.ROUNDED)
table.add_column("Goal", style="cyan bold")
table.add_column("Description")
table.add_column("Chain Preview", style="dim")
for defn in GOAL_DEFINITIONS.values():
chain_preview = " → ".join(defn.preferred_chain[:4])
if len(defn.preferred_chain) > 4:
chain_preview += " ..."
table.add_row(defn.goal.value, defn.description, chain_preview)
console.print(table)
@goal_app.command("capabilities")
def goal_capabilities(
module_id: str | None = typer.Argument(None, help="Show deps for specific module"),
) -> None:
"""Show capability dependency graph (REQUIRES / OUTPUTS for all modules)."""
from ares.core.plugin.loader import PluginLoader
from ares.goal.engine import CapabilityGraph
registry = PluginLoader().load_all()
cg = CapabilityGraph.from_registry(registry)
summary = cg.capability_summary()
if module_id:
requires = cg._requires.get(module_id, [])
outputs = cg._outputs.get(module_id, [])
console.print(Panel(
f"[bold]REQUIRES:[/bold] {requires or ['(none)']}\n"
f"[bold]OUTPUTS:[/bold] {outputs or ['(none)']}",
title=f"Module: {module_id}",
box=box.ROUNDED,
))
return
table = Table(title=f"Capability Graph ({summary['total_capabilities']} capabilities)", show_lines=False, box=box.ROUNDED)
table.add_column("Capability", style="cyan")
table.add_column("Produced by", style="green")
for cap, mods in sorted(summary["capabilities"].items()):
table.add_row(cap, ", ".join(mods))
console.print(table)
# ── Graph commands ─────────────────────────────────────────────────────────────
@graph_app.command("show")
def graph_show(
campaign_id: str = typer.Argument(..., help="Campaign ID"),
top_n: int = typer.Option(5, "--top", "-n", help="Number of attack paths to show"),
) -> None:
"""Show top attack paths in the campaign's artifact graph."""
import asyncio
from ares.core.config import get_settings
from ares.db.database import AresDatabase
from ares.graph.attack_graph import AttackGraph
from ares.normalize.artifacts import ArtifactStore, HostArtifact
async def _run() -> None:
s = get_settings()
async with await AresDatabase.create(s.db_path, s.encryption_key_value) as db:
campaign = await db.get_campaign(campaign_id)
if not campaign:
console.print(f"[red]Campaign {campaign_id!r} not found[/red]")
raise typer.Exit(1)
hosts = await db.get_hosts(campaign_id)
store = ArtifactStore()
for h in hosts:
store.add(HostArtifact(
ip_address=h.get("ip_address", ""),
hostname=h.get("hostname", ""),
is_dc=h.get("is_dc", False),
os=h.get("os", ""),
))
graph = AttackGraph()
graph.build_from_store(store)
stats = graph.stats()
console.print(Panel(
f"Nodes: [cyan]{stats['nodes']}[/cyan] "
f"Edges: [cyan]{stats['edges']}[/cyan] "
f"High-value targets: [red]{stats['high_value']}[/red] "
f"Attack paths: [yellow]{stats['attack_paths']}[/yellow]",
title=f"Attack Graph - Campaign {campaign_id[:8]}",
))
paths = graph.top_paths(n=top_n)
if not paths:
console.print("[dim]No attack paths found yet - run recon modules first.[/dim]")
return
for i, p in enumerate(paths, 1):
console.print(f"\n[bold yellow]Path {i}[/bold yellow] "
f"[dim]{p['start']} → {p['end']}[/dim] "
f"score=[cyan]{p['total_score']}[/cyan]")
for step in p.get("steps", []):
atk = f" [dim]via {step['attack']}[/dim]" if step.get("attack") else ""
console.print(f" {step['from']} [dim]──[{step['edge']}]──►[/dim] {step['to']}{atk}")
asyncio.run(_run())
@graph_app.command("path")
def graph_path(
campaign_id: str = typer.Argument(..., help="Campaign ID"),
source: str = typer.Option(..., "--from", "-s", help="Source node label"),
target: str = typer.Option(..., "--to", "-t", help="Target node label"),
) -> None:
"""Find shortest attack path between two nodes."""
import asyncio
from ares.core.config import get_settings
from ares.db.database import AresDatabase
from ares.graph.attack_graph import AttackGraph
from ares.normalize.artifacts import ArtifactStore, HostArtifact
async def _run() -> None:
s = get_settings()
async with await AresDatabase.create(s.db_path, s.encryption_key_value) as db:
hosts = await db.get_hosts(campaign_id)
store = ArtifactStore()
for h in hosts:
store.add(HostArtifact(
ip_address=h.get("ip_address", ""),
hostname=h.get("hostname", ""),
is_dc=h.get("is_dc", False),
))
graph = AttackGraph()
graph.build_from_store(store)
path = graph.find_path(source, target)
if not path:
console.print(f"[red]No path from '{source}' to '{target}'[/red]")
return
report = graph.path_to_report(path)
console.print(Panel(
f"[bold]{report['start']} -> {report['end']}[/bold]\n"
f"Steps: {report['path_length'] - 1} Score: {report['total_score']}\n"
f"Modules: {', '.join(report['attack_modules']) or '(none)'}",
title="Shortest Attack Path",
box=box.ROUNDED,
))
for step in report["steps"]:
atk = f" [dim]← {step['attack']}[/dim]" if step.get("attack") else ""
console.print(f" [green]{step['from']}[/green] [dim]──{step['edge']}──►[/dim] [red]{step['to']}[/red]{atk}")
asyncio.run(_run())
# ── Module create (scaffold) ───────────────────────────────────────────────────
@module_app.command("create")
def module_create(
module_id: str = typer.Argument(..., help="Module ID in dot notation, e.g. ad.my_attack"),
output_dir: str = typer.Option(".", "--output", "-o", help="Directory to create module in"),
author: str = typer.Option("", "--author", "-a", help="Module author name/email"),
category: str = typer.Option("", "--category", "-c", help="Module category (ad, linux, cloud, lateral, exfil)"),
description: str = typer.Option("", "--description", "-d", help="Short description"),
) -> None:
"""
Scaffold a new ARES module with boilerplate code, metadata, and test file.
Example:
ares module create ad.my_attack --author [email protected] --category ad
"""
import re
from pathlib import Path
# Validate module_id format
if not re.match(r'^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$', module_id):
console.print("[red]Module ID must be dot-notation: category.name (e.g. ad.my_attack)[/red]")
raise typer.Exit(1)
cat, name = module_id.split(".", 1)
category = category or cat
class_name = "".join(p.capitalize() for p in name.split("_")) + "Module"
author_str = author or "[email protected]"
desc_str = description or f"Describe what {module_id} does (use --description flag)"
out_dir = Path(output_dir)
module_file = out_dir / f"{name}.py"
test_file = out_dir / f"test_{name}.py"
if module_file.exists():
console.print(f"[yellow]File already exists: {module_file}[/yellow]")
raise typer.Exit(1)
# ── Module scaffold ────────────────────────────────────────────────────
module_code = f'''\
from __future__ import annotations
"""
{class_name} - {desc_str}
MITRE ATT&CK: Fill in technique ID (e.g. T1558.003 for Kerberoasting)
"""
from typing import Any
from ares.sdk import (
BaseModule, ExecutionContext, ModuleResult,
OpsecLevel, Severity, module_metadata,
get_logger, ModuleValidationError, HostUnreachable,
)
logger = get_logger("{module_id}")
@module_metadata(
module_id = "{module_id}",
name = "{class_name.replace("Module", "").replace("_", " ")}",
category = "{category}",
description = "{desc_str}",
author = "{author_str}",
opsec = OpsecLevel.LOW,
requires = [], # e.g. ["domain_creds"]
outputs = [], # e.g. ["credential_list"]
mitre = [], # e.g. ["T1558.003"]
)
class {class_name}(BaseModule):
"""
{desc_str}
Parameters:
target - target host IP or hostname
# Add module-specific params here, e.g.:
# target_port: int = 445, # target port number
"""
async def validate(self, ctx: ExecutionContext) -> None:
"""Validate required parameters before execution."""
ctx.require("target")
# Add parameter validation here, e.g.:
# if not ctx.params.get("domain"):
# raise ModuleValidationError("Missing domain", module_id=self.MODULE_ID, field="domain")
async def execute(self, ctx: ExecutionContext) -> ModuleResult:
"""Main execution logic."""
if ctx.dry_run:
return ModuleResult(
status="dry_run",
module_id=self.MODULE_ID,
raw={{"dry_run": True, "params": ctx.params}},
)
target = ctx.params["target"]
await self.before_request(target, "tcp") # Replace "tcp" with actual protocol: smb, ldap, ssh, http, etc.
try:
# Implement your attack logic here.
# Use self.finding(...) to record each vulnerability found.
# Example finding:
# self.finding(
# title = "Found something",
# description = "Details about the finding",
# severity = Severity.HIGH,
# mitre_technique = "T1XXX",
# host = target,
# evidence = {{"key": "value"}},
# remediation = "How to fix it",
# )
raw: dict[str, Any] = {{"target": target}}
except Exception as exc:
raise HostUnreachable(str(exc), target=target,
module_id=self.MODULE_ID) from exc
return ModuleResult(
status = "success",
findings = self._findings,
module_id = self.MODULE_ID,
raw = raw,
)
async def run(self, **kwargs: Any):
"""Legacy interface - do not modify."""
ctx = ExecutionContext.for_test(**kwargs)
result = await self.execute(ctx)
return result.findings, result.raw
'''
# ── Test scaffold ──────────────────────────────────────────────────────
test_code = f'''\
from __future__ import annotations
"""
Tests for {module_id}
"""
import pytest
from unittest.mock import AsyncMock, patch
from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry
from ares.core.config import AresSettings
from ares.core.noise import NoiseController
from {name} import {class_name}
@pytest.fixture
def campaign():
return Campaign(
name="Test", client="ACME", operator="tester",
scope=[ScopeEntry(cidr="10.0.0.0/8")],
noise_profile=NoiseProfile.NORMAL,
)
@pytest.fixture
def module(campaign):
# AresSettings reads from environment. Set these in your .env or export before running tests:
# ARES_SECRET_KEY, ARES_ENCRYPTION_KEY, ARES_DEFAULT_ADMIN_PASSWORD
# The values below are placeholder defaults so the scaffold test runs standalone
# in CI without a .env file. NEVER use these in production.
import os
os.environ.setdefault("ARES_SECRET_KEY", "scaffold-test-key-min32chars-xx!!")
os.environ.setdefault("ARES_ENCRYPTION_KEY", "scaffold-test-enc-key-min32chars!")
os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD","ScaffoldTest1!")
settings = AresSettings()
return {class_name}(settings=settings, campaign=campaign, noise=NoiseController(campaign))
@pytest.mark.asyncio
async def test_dry_run(module):
"""Dry run should return status=dry_run without touching target."""
findings, raw = await module.run(target="10.0.0.1", dry_run=True)
assert raw.get("dry_run") is True
assert findings == []
@pytest.mark.asyncio
async def test_missing_target_raises(module):
"""Missing required param should raise validation error."""
from ares.core.errors import ModuleValidationError
with pytest.raises((ModuleValidationError, Exception)):
await module.run()
# Add more test cases:
# - test_happy_path: mock the external call, assert findings are created
# - test_no_finding: when nothing vulnerable found, assert findings == []
# - test_error_handling: simulate network error, assert HostUnreachable is raised
'''
out_dir.mkdir(parents=True, exist_ok=True)
module_file.write_text(module_code)
test_file.write_text(test_code)
console.print(Panel(
f"[green][+] Module scaffolded[/green]\n\n"
f" [bold]Module:[/bold] {module_file}\n"
f" [bold]Tests:[/bold] {test_file}\n\n"
f"Next steps:\n"
f" 1. Implement [cyan]execute()[/cyan] in {module_file.name}\n"
f" 2. Fill in [cyan]REQUIRES[/cyan], [cyan]OUTPUTS[/cyan], [cyan]mitre[/cyan] metadata\n"
f" 3. Run tests: [cyan]pytest {test_file.name}[/cyan]\n"
f" 4. Install: [cyan]ares module install ./{module_file.name}[/cyan]",
title=f"ares module create - {module_id}",
box=box.ROUNDED,
))
# ── MCP CLI Commands ─────────────────────────────────────────────────────────
@mcp_app.callback(invoke_without_command=True)
def mcp_default_callback(ctx: typer.Context) -> None:
"""ARES MCP Gateway. Launches interactive console when invoked without subcommands."""
if ctx.invoked_subcommand is None:
if sys.stdin.isatty():
from ares.cli.console import interactive_console_loop
try:
interactive_console_loop()
except KeyboardInterrupt:
console.print("\n[dim]Cancelled[/dim]")
raise typer.Exit(130) # noqa: B904
else:
from ares.cli.mcp_commands import get_doctor_diagnostics
diag = get_doctor_diagnostics()
console.print(f"ARES MCP v6.0.0 (Non-interactive mode) - Status: {diag['status']}")
raise typer.Exit(0)
@mcp_app.command("console")
def mcp_console_cmd() -> None:
"""Launch the ARES MCP Interactive Console (OpenCode/OpenClaw style)."""
from ares.cli.console import interactive_console_loop
try:
interactive_console_loop()
except KeyboardInterrupt:
console.print("\n[dim]Cancelled[/dim]")
raise typer.Exit(130) # noqa: B904
@mcp_app.command("monitor")
@mcp_app.command("tui")
def mcp_monitor_cmd(
campaign: str = typer.Option("Internal-Audit-2026", "--campaign", "-c", help="Active campaign name to monitor"),
scope: str = typer.Option("10.0.1.0/24, 192.168.10.0/24", "--scope", "-s", help="Approved CIDRs scope"),
demo: bool = typer.Option(False, "--demo", help="Run automated demonstration telemetry feed"),
) -> None:
"""Launch the ARES MCP Two-Pane Split Terminal Monitor (OpenClaw style)."""
from ares.cli.mcp_tui import run_mcp_monitor
try:
code = run_mcp_monitor(campaign=campaign, scope=scope, demo=demo)
raise typer.Exit(code)
except KeyboardInterrupt:
console.print("\n[dim]Cancelled[/dim]")
raise typer.Exit(130) # noqa: B904
@app.command("console")
def app_console_cmd() -> None:
"""Launch the ARES MCP Interactive Console (OpenCode/OpenClaw style)."""
from ares.cli.console import interactive_console_loop
try:
interactive_console_loop()
except KeyboardInterrupt:
console.print("\n[dim]Cancelled[/dim]")
raise typer.Exit(130) # noqa: B904
@app.command("monitor")
def app_monitor_cmd(
campaign: str = typer.Option("Internal-Audit-2026", "--campaign", "-c", help="Active campaign name to monitor"),
scope: str = typer.Option("10.0.1.0/24, 192.168.10.0/24", "--scope", "-s", help="Approved CIDRs scope"),
demo: bool = typer.Option(False, "--demo", help="Run automated demonstration telemetry feed"),
) -> None:
"""Launch the ARES MCP Two-Pane Split Terminal Monitor (OpenClaw style)."""
from ares.cli.mcp_tui import run_mcp_monitor
try:
code = run_mcp_monitor(campaign=campaign, scope=scope, demo=demo)
raise typer.Exit(code)
except KeyboardInterrupt:
console.print("\n[dim]Cancelled[/dim]")
raise typer.Exit(130) # noqa: B904
@mcp_app.command("doctor")
def mcp_doctor_cmd(
json_output: bool = typer.Option(False, "--json", help="Output machine-readable JSON status"),
) -> None:
"""Check health, readiness, and security gates of ARES MCP subsystems."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.cli.mcp_commands import get_doctor_diagnostics
diag = get_doctor_diagnostics()
out_console = get_mcp_console(json_mode=json_output)
if json_output:
out_console.print(json.dumps(diag, indent=2))
else:
table = Table(title="ARES MCP Subsystem Readiness Check", box=box.ROUNDED)
table.add_column("Subsystem", style="cyan")
table.add_column("Status", justify="center")
table.add_column("Details")
for item in diag["subsystems"]:
status_style = "green" if item["status"] == "PASS" else "red"
table.add_row(item["subsystem"], f"[{status_style}]{item['status']}[/]", item["details"])
out_console.print(table)
raise typer.Exit(0 if diag["healthy"] else 1)
@mcp_app.command("module-catalog")
@mcp_app.command("catalog")
def mcp_module_catalog_cmd(
category: str | None = typer.Option(None, "--category", "-c", help="Filter by category (ad, cloud, windows, linux, etc.)"),
query: str | None = typer.Option(None, "--query", "-q", help="Search keyword in module ID or class name"),
json_output: bool = typer.Option(False, "--json", help="Output catalog as machine-readable JSON"),
) -> None:
"""Browse 60+ attack modules, OPSEC noise levels, and governance policies."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.cli.mcp_commands import query_module_catalog
modules = query_module_catalog(category=category, query=query)
out_console = get_mcp_console(json_mode=json_output)
if json_output:
out_console.print(json.dumps(modules, indent=2))
raise typer.Exit(0)
table = Table(title=f"ARES Module Catalog ({len(modules)} Modules)", box=box.ROUNDED)
table.add_column("Module ID", style="cyan")
table.add_column("Category", style="yellow")
table.add_column("OPSEC Noise", justify="center")
table.add_column("Governance")
table.add_column("Source Engine Class")
for item in modules:
opsec_val = item["opsec_level"].lower()
opsec_style = {"silent": "green", "low": "green", "medium": "yellow", "high_noise": "red"}.get(opsec_val, "white")
gov_badge = "[yellow]Approval Required[/]" if item["requires_approval"] else "[green]Standard[/]"
table.add_row(
item["module_id"],
item["category"],
f"[{opsec_style}]{item['opsec_level'].upper()}[/]",
gov_badge,
item["source_class"],
)
out_console.print(table)
raise typer.Exit(0)
@mcp_app.command("scope-check")
def mcp_scope_check_cmd(
target: str = typer.Option(..., "--target", "-t", help="Target IP, hostname, or domain to verify"),
cidr: str | None = typer.Option(None, "--cidr", "-c", help="Specific CIDR network rule to test against"),
campaign: str = typer.Option("default-lab", "--campaign", help="Campaign ID"),
strict: bool = typer.Option(True, "--strict/--no-strict", help="Exit with code 1 if target is out of scope"),
json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),
) -> None:
"""Verify deterministically if a target IP, CIDR, or hostname is authorized."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.cli.mcp_commands import check_scope
result = check_scope(target=target, cidr=cidr, campaign_id=campaign)
out_console = get_mcp_console(json_mode=json_output)
if json_output:
out_console.print(json.dumps(result, indent=2))
else:
status_color = "green" if result["in_scope"] else "red"
out_console.print(Panel(
f"[cyan]Target:[/] [bold white]{result['target']}[/]\n"
f"[cyan]Status:[/] [{status_color}]{result['status']}[/]\n"
f"[cyan]Authorized:[/] {'YES' if result['in_scope'] else 'NO'}\n"
f"[cyan]Scope Rules:[/] {', '.join(result['scope_rules'])}",
title=f"[{status_color}]Scope Verification Result[/]",
border_style=status_color,
box=box.ROUNDED,
))
if strict and not result["in_scope"]:
raise typer.Exit(1)
raise typer.Exit(0)
@mcp_app.command("dry-run")
def mcp_dry_run_cmd(
target: str = typer.Option(..., "--target", "-t", help="Target IP or hostname"),
module: str = typer.Option(..., "--module", "-m", help="Module ID (e.g. ad.kerberoast)"),
campaign: str = typer.Option("default-lab", "--campaign", help="Campaign ID"),
params: str = typer.Option("{}", "--params", "-p", help="JSON dictionary string of parameters"),
json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),
) -> None:
"""Simulate module pre-flight execution and obtain a single-use confirmation token."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.cli.mcp_commands import execute_dry_run
try:
parsed_params = json.loads(params)
if not isinstance(parsed_params, dict):
raise ValueError()
except Exception:
console.print("[red]Invalid --params JSON. Must be a valid JSON dictionary string (e.g. '{\"domain\": \"corp.local\"}').[/]")
raise typer.Exit(2) # noqa: B904
data = execute_dry_run(target=target, module_id=module, campaign_id=campaign, params=parsed_params)
out_console = get_mcp_console(json_mode=json_output)
if json_output:
out_console.print(json.dumps(data, indent=2))
else:
token = data.get("confirmation_token", "N/A")
scope_valid = data.get("scope_validation", {}).get("in_scope", True)
opsec = data.get("opsec_assessment", {}).get("noise_level", "low")
status_badge = "[green][OK] IN-SCOPE[/]" if scope_valid else "[red][FAIL] OUT-OF-SCOPE[/]"
out_console.print(Panel(
f"[cyan]Module:[/] [bold white]{module}[/]\n"
f"[cyan]Target:[/] [bold white]{target}[/]\n"
f"[cyan]ScopeGuard:[/] {status_badge}\n"
f"[cyan]OPSEC Noise:[/] [yellow]{opsec.upper()}[/]\n"
f"[cyan]Confirmation Token:[/] [yellow]{token}[/] (Valid for 60s)\n"
f"[cyan]Status:[/] [green]{data.get('status', 'SUCCESS')}[/]",
title="[green]Pre-Flight Dry-Run Card[/]",
border_style="green" if scope_valid else "red",
box=box.ROUNDED,
))
if data.get("is_error"):
raise typer.Exit(1)
raise typer.Exit(0)
@mcp_app.command("setup")
def mcp_setup_cmd(
client: str | None = typer.Option(None, "--client", "-c", help="Target client: cursor, claude, windsurf, or cline"),
json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),
) -> None:
"""1-Click automated configuration for AI IDEs and clients without manual JSON editing."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.cli.mcp_commands import setup_client_configuration
chosen_client = client
if not chosen_client:
if sys.stdin.isatty():
from rich.prompt import Prompt
console.print("[bold white]Select client to configure:[/]")
console.print(" [cyan][1][/] Cursor IDE")
console.print(" [cyan][2][/] Claude Desktop")
console.print(" [cyan][3][/] Windsurf")
console.print(" [cyan][4][/] VS Code (Cline)")
sel = Prompt.ask("Choice", choices=["1", "2", "3", "4"], default="1")
chosen_client = {"1": "cursor", "2": "claude", "3": "windsurf", "4": "cline"}[sel]
else:
console.print("[red]Missing required option --client in non-interactive mode. Available: cursor, claude, windsurf, cline[/]")
raise typer.Exit(2)
code, msg = setup_client_configuration(chosen_client)
out_console = get_mcp_console(json_mode=json_output)
if json_output:
out_console.print(json.dumps({"client": chosen_client, "status": "SUCCESS" if code == 0 else "ERROR", "message": msg, "exit_code": code}, indent=2))
else:
status_color = "green" if code == 0 else "red"
out_console.print(Panel(
f"[{status_color}]{msg}[/]",
title=f"[{status_color}]Client Setup: {chosen_client.capitalize()}[/]",
border_style=status_color,
box=box.ROUNDED,
))
raise typer.Exit(code)
@mcp_app.command("run-tool")
def mcp_run_tool_cmd(
tool_name: str = typer.Argument(..., help="Name of the MCP tool to execute (e.g. ares_list_campaigns)"),
args: str = typer.Option("{}", "--args", "-a", help="JSON dictionary string of tool arguments"),
json_output: bool = typer.Option(False, "--json", help="Output result as JSON"),
) -> None:
"""Execute an ARES operational MCP tool headlessly and output structured results."""
from ares.cli.mcp_cli_utils import get_mcp_console
from ares.mcp import AresMcpServer
try:
parsed_args = json.loads(args)
if not isinstance(parsed_args, dict):
raise ValueError()
except Exception:
console.print("[red]Invalid --args JSON. Must be a valid JSON dictionary string (e.g. '{\"campaign_id\": \"test\"}').[/]")
raise typer.Exit(2) # noqa: B904
server = AresMcpServer()
tools = {t.name: t for t in server.tool_registry.list_tools()}
if tool_name not in tools:
console.print(f"[red]Unknown tool '{tool_name}'. Available tools: {', '.join(tools.keys())}[/]")
raise typer.Exit(2)
result = asyncio.run(server.tool_registry.call_tool(tool_name, parsed_args))
raw_text = result.content[0].text if result.content else "{}"
out_console = get_mcp_console(json_mode=json_output)
if json_output:
try:
out_console.print(json.dumps(json.loads(raw_text), indent=2))
except Exception:
out_console.print(json.dumps({"content": raw_text, "isError": result.isError}, indent=2))
else:
status_color = "red" if result.isError else "green"
try:
formatted = json.dumps(json.loads(raw_text), indent=2)
syntax = Syntax(formatted, "json", theme="monokai", line_numbers=True)
out_console.print(Panel(syntax, title=f"[{status_color}]Result: {tool_name}[/]", border_style=status_color, box=box.ROUNDED))
except Exception:
out_console.print(Panel(raw_text, title=f"[{status_color}]Result: {tool_name}[/]", border_style=status_color, box=box.ROUNDED))
raise typer.Exit(1 if result.isError else 0)
@mcp_app.command("stdio")
def mcp_stdio_cmd() -> None:
"""Run the ARES MCP Server over asynchronous stdio (Claude Desktop / Cursor / Windsurf / Cline / Zed)."""
from ares.mcp import run_stdio_server
try:
asyncio.run(run_stdio_server())
except KeyboardInterrupt:
console.print("\n[dim]Stdio server stopped.[/dim]")
raise typer.Exit(130) # noqa: B904
@mcp_app.command("sse")
def mcp_sse_cmd(
host: str = typer.Option("127.0.0.1", "--host", "-h", help="Host address to bind (default: 127.0.0.1)"),
port: int = typer.Option(8001, "--port", "-p", help="Port to listen on"),
api_key: str | None = typer.Option(None, "--api-key", "-k", help="Optional Bearer API Key for network authentication"),
) -> None:
"""Run the ARES MCP Server over HTTP with Server-Sent Events (SSE)."""
import secrets
import uvicorn
from ares.cli.mcp_cli_utils import warn_cli_secret_exposure
from ares.mcp import AresMcpServer, create_sse_app
is_loopback = host in ("127.0.0.1", "localhost", "::1")
if not is_loopback and not api_key:
api_key = secrets.token_urlsafe(32)
console.print(
Panel(
f"[bold red]SECURITY NOTICE:[/] Binding MCP SSE server to external interface [yellow]{host}[/] "
f"without an explicit --api-key.\n"
f"Generated ephemeral API key:\n\n"
f" [bold green]{api_key}[/]\n\n"
f"Clients must provide this key via 'Authorization: Bearer <key>' or 'x-ares-api-key' header.",
title="[bold yellow]MCP Network Authentication Generated[/]",
border_style="yellow",
box=box.ROUNDED,
)
)
elif api_key:
warn_cli_secret_exposure()
server = AresMcpServer()
sse_app = create_sse_app(server, api_key=api_key)
console.print(Panel(
f"[bold green]ARES MCP Server (SSE Mode)[/]\n\n"
f" [cyan]Endpoint:[/] http://{host}:{port}/sse\n"
f" [cyan]Auth:[/] {'Protected by API Key' if api_key else 'Loopback Only (127.0.0.1)'}\n"
f" [cyan]Clients:[/] Open-WebUI, LibreChat, Remote Agents, Docker\n\n"
f"Press [yellow]Ctrl+C[/] to stop the server.",
title="ares mcp sse",
border_style="green",
box=box.ROUNDED,
))
try:
uvicorn.run(sse_app, host=host, port=port, log_level="info")
except KeyboardInterrupt:
console.print("\n[yellow]SSE server stopped.[/]")
raise typer.Exit(130) # noqa: B904
@mcp_app.command("config")
def mcp_config_cmd(
client: str = typer.Option(
"claude",
"--client",
"-c",
help="Client type: claude, cursor, windsurf, cline, zed, open-webui, librechat, langchain",
),
host: str = typer.Option("http://127.0.0.1:8001", "--host", help="Server URL for network/SSE clients"),
api_key: str = typer.Option("ares_mcp_secret_key", "--api-key", help="API key for network clients"),
) -> None:
"""Generate ready-to-use configuration for Claude Desktop, Cursor, Windsurf, Cline, Zed, and Web agents."""
c_lower = client.strip().lower()
executable = sys.executable
if c_lower in ("claude", "claudedesktop"):
cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}
console.print("[bold green]Paste this into your Claude Desktop configuration file (`claude_desktop_config.json`):[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower == "cursor":
cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}
console.print("[bold green]Paste this into your Cursor MCP configuration (`.cursor/mcp.json`):[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower == "windsurf":
cfg = {"mcpServers": {"ares": {"command": executable, "args": ["-m", "ares.mcp"]}}}
console.print("[bold green]Paste this into Windsurf MCP configuration (`~/.codeium/windsurf/mcp_config.json`):[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower in ("cline", "roo", "roocode"):
cfg = {
"mcpServers": {
"ares": {
"command": executable,
"args": ["-m", "ares.mcp"],
"disabled": False,
"alwaysAllow": ["ares_list_campaigns", "ares_get_campaign_status", "ares_list_findings"],
}
}
}
console.print("[bold green]Paste this into your VS Code Cline settings (`cline_mcp_settings.json`):[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower == "zed":
cfg = {
"experimental": {
"model_context_protocol": {
"servers": [
{
"id": "ares",
"command": executable,
"args": ["-m", "ares.mcp"],
}
]
}
}
}
console.print("[bold green]Paste this into your Zed settings (`~/.config/zed/settings.json`):[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower in ("open-webui", "webui"):
cfg = {
"type": "mcp_sse",
"url": f"{host}/sse",
"headers": {"Authorization": f"Bearer {api_key}"},
}
console.print("[bold green]Open-WebUI Tool Connection Details:[/]\n")
console.print(json.dumps(cfg, indent=2))
raise typer.Exit(0)
if c_lower == "librechat":
yaml_content = f"""mcpServers:
ares:
type: sse
url: {host}/sse
headers:
Authorization: Bearer {api_key}
"""
console.print("[bold green]Paste this into your `librechat.yaml` configuration:[/]\n")
console.print(yaml_content)
raise typer.Exit(0)
if c_lower == "langchain":
from ares.mcp.export import generate_langchain_snippet
console.print("[bold green]LangChain MCP Integration Code Snippet:[/]\n")
console.print(generate_langchain_snippet())
raise typer.Exit(0)
console.print(f"[red]Unknown client '{client}'. Available: claude, cursor, windsurf, cline, zed, open-webui, librechat, langchain[/]")
raise typer.Exit(2)
@mcp_app.command("export-tools")
def mcp_export_tools_cmd(
format: str = typer.Option("openai", "--format", "-f", help="Export format: openai, gemini, or json"),
) -> None:
"""Export ARES MCP tools into OpenAI Function Calling, Gemini, or JSON-Schema format."""
from ares.mcp import AresMcpServer, export_gemini_tools, export_json_schema, export_openai_tools
server = AresMcpServer()
tools = server.tool_registry.list_tools()
fmt = format.strip().lower()
if fmt == "openai":
out = export_openai_tools(tools)
elif fmt == "gemini":
out = export_gemini_tools(tools)
elif fmt in ("json", "json-schema", "schema"):
out = export_json_schema(tools)
else:
console.print(f"[red]Unknown format '{format}'. Use 'openai', 'gemini', or 'json'.[/]")
raise typer.Exit(2)
console.print(json.dumps(out, indent=2))
raise typer.Exit(0)
# ── Entry point ────────────────────────────────────────────────────────────────
def cli() -> None:
"""Main CLI entry point."""
app()
if __name__ == "__main__":
cli()