Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

fix: align dashboard contracts and reliable report exports

Mafifrizi9586c89ad469
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index be89ca7..68307fd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -23,7 +23,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
- python-version: "3.13"
+ python-version: "3.12"
- run: python -m pip install --upgrade pip
- run: pip install -e ".[dev]"
- run: python -m compileall ares tests
diff --git a/QUICKSTART.md b/QUICKSTART.md
index 837a50b..f66e962 100644
--- a/QUICKSTART.md
+++ b/QUICKSTART.md
@@ -32,8 +32,11 @@ Notes:
- The setup script is the Linux/macOS bootstrap path. On Windows, use the
PowerShell commands above to create `.venv` and install the editable package.
+- Use Python 3.12.x for the release path. Package metadata allows Python
+ 3.10-3.12, but the dashboard and Windows AD/Impacket lab validation are
+ tested on Python 3.12.x.
- Some offensive-security integrations are optional. `ares doctor` will tell you which optional packages or native tools are missing for AD, cloud, container, or password-cracking workflows.
-- PDF support uses WeasyPrint when available and has a local browser fallback in the API.
+- PDF support uses WeasyPrint when available and has a local Edge/Chrome/Chromium browser fallback in the API. On Windows, use Python 3.12.x and run `ares doctor` if PDF export cannot find a backend or writable browser profile.
## 3. Configure Secrets
@@ -324,7 +327,7 @@ Windows virtualenv example:
.\.venv\Scripts\ares.exe doctor
```
-`ares doctor` checks Python, key dependencies, optional module integrations, native tools, network socket support, environment configuration, and the local database.
+`ares doctor` checks Python, key dependencies, optional module integrations, native tools, PDF export capability, network socket support, environment configuration, and the local database.
A yellow warning means an optional integration is missing. A red failure means a required dependency or configuration item needs attention.
@@ -333,6 +336,7 @@ Common examples:
| Message | Meaning |
| --- | --- |
| `impacket` missing or old | AD/SMB modules need the optional impacket dependency. |
+| `Windows AD/Impacket Python` warning | Windows AD lab validation is tested on Python 3.12.x. |
| `pip-audit not installed` | Dependency audit is unavailable; core API can still start. |
| `hashcat not in PATH` | Password-cracking helpers cannot use hashcat until installed. |
| `.env configured` failed | Required environment values are missing. |
diff --git a/README.md b/README.md
index 6d5bda6..7071bf7 100644
--- a/README.md
+++ b/README.md
@@ -302,7 +302,7 @@ Security page, but role assignment is done at account creation time through
### Reporting
- HTML, Markdown, and JSON report output.
-- PDF output through WeasyPrint when available, with a Chromium-compatible
+- PDF output through WeasyPrint when available, with an Edge/Chrome/Chromium
browser fallback for local environments that do not have WeasyPrint native
libraries installed.
- ARES branding in generated reports with footer-safe page spacing.
@@ -487,8 +487,8 @@ Validation lab passed.
### 5. Check Prerequisites With Doctor
`ares doctor` checks the runtime you are about to operate: Python, required
-packages, optional module dependencies, common service sockets, environment
-configuration, settings loading, and database connectivity.
+packages, optional module dependencies, PDF export capability, common service
+sockets, environment configuration, settings loading, and database connectivity.
```bash
ares doctor
@@ -529,7 +529,7 @@ Backend:
```bash
python -m venv .venv
source .venv/bin/activate
-pip install -e ".[dev]"
+pip install -e ".[dev,pdf]"
pytest tests/unit -q
```
@@ -554,8 +554,10 @@ Platform notes:
- Windows: use PowerShell and `.\.venv\Scripts\python.exe`.
- Linux, Kali, and macOS: use `source .venv/bin/activate`.
-- The package targets Python 3.10+. Keep one project virtual environment per
- OS instead of copying `.venv` directories between machines.
+- The package metadata allows Python 3.10-3.12, but the tested release path for
+ the dashboard and Windows AD/Impacket lab modules is Python 3.12.x.
+- Keep one project virtual environment per OS instead of copying `.venv`
+ directories between machines. Use Python 3.12.x for release validation.
- Optional AD, cloud, container, Windows, and PDF dependencies are not required
for the core dashboard to start.
diff --git a/ares/api/server.py b/ares/api/server.py
index 14aae1b..aba381a 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -52,7 +52,7 @@ from ares.api.rbac import (
require_operator,
require_team_lead,
)
-from ares.core.campaign import Campaign
+from ares.core.campaign import Campaign, Finding
from ares.core.config import AresSettings, get_settings
from ares.core.engine import AresEngine
from ares.core.logger import get_logger
@@ -86,6 +86,61 @@ def _campaign_from_db_row(row: dict[str, Any]) -> Campaign:
return Campaign(**data)
+def _finding_from_db_row(row: dict[str, Any], *, report_confirmed: bool = False) -> Finding:
+ import json as _json
+
+ evidence: dict[str, Any] = {}
+ raw_evidence = row.get("evidence_json")
+ if isinstance(raw_evidence, str) and raw_evidence.strip():
+ try:
+ parsed = _json.loads(raw_evidence)
+ evidence = parsed if isinstance(parsed, dict) else {"raw": parsed}
+ except (TypeError, ValueError):
+ evidence = {"raw": raw_evidence}
+ elif isinstance(raw_evidence, dict):
+ evidence = raw_evidence
+
+ data = {
+ "id": row.get("id", ""),
+ "title": row.get("title", ""),
+ "description": row.get("description", ""),
+ "severity": row.get("severity", "info"),
+ "confidence": row.get("confidence", 1.0) or 1.0,
+ "mitre_technique": row.get("mitre_technique"),
+ "mitre_tactic": row.get("mitre_tactic"),
+ "evidence": evidence,
+ "remediation": row.get("remediation") or "",
+ "false_positive": bool(row.get("false_positive", False)),
+ "validated": bool(row.get("validated", False)) or report_confirmed,
+ "host": row.get("host"),
+ "module_id": row.get("module_id") or "",
+ "cvss_score": row.get("cvss_score", 0.0) or 0.0,
+ "cvss_vector": row.get("cvss_vector") or "",
+ "trace_id": row.get("trace_id") or "",
+ }
+ if row.get("discovered_at"):
+ data["discovered_at"] = row["discovered_at"]
+ return Finding(**data)
+
+
+async def _campaign_for_report(db: AresDatabase, row: dict[str, Any]) -> Campaign:
+ campaign = _campaign_from_db_row(row)
+ # Reports must use the same persisted findings visible in the dashboard. Older
+ # DB rows and some module-run paths may not have the validated flag populated,
+ # but API-triggered module results are already confirmed before persistence.
+ rows, _ = await db.list_findings(
+ campaign.id,
+ page=1,
+ per_page=10000,
+ false_positive=False,
+ )
+ campaign.findings = [
+ _finding_from_db_row(finding_row, report_confirmed=True)
+ for finding_row in rows
+ ]
+ return campaign
+
+
def _setup_otel(app: FastAPI, settings: Any) -> None:
"""Initialize OpenTelemetry tracing if endpoint is configured."""
if not settings.ares_otel_endpoint:
@@ -850,6 +905,14 @@ class CampaignCreate(BaseModel):
client: str = Field("Internal", max_length=128)
targets: list[str] = Field(default_factory=list, max_length=256)
scope_cidrs: list[str] = Field(default_factory=list, max_length=256)
+ noise_profile: str = Field("stealth", pattern=r"^(stealth|normal|aggressive)$")
+
+ @field_validator("noise_profile", mode="before")
+ @classmethod
+ def normalize_noise_profile(cls, v: Any) -> Any:
+ if isinstance(v, str):
+ return v.strip().lower()
+ return v
@field_validator("name")
@classmethod
@@ -962,6 +1025,7 @@ async def create_campaign(
targets=body.targets,
scope=scope,
operator=actor.username,
+ noise_profile=body.noise_profile,
)
await db.save_campaign(c)
await db.audit(actor.username, "campaign_created", f"id={c.id} name={c.name}", c.id)
@@ -1822,6 +1886,7 @@ def _delete_report_artifacts_for_campaign(campaign_id: str) -> int:
async def generate_report(
campaign_id: str,
fmt: str = Query("html", pattern="^(html|pdf|markdown|json)$"),
+ include_sensitive_evidence: bool = Query(False),
actor: AuthenticatedUser = _api_key_write_dep,
_rate: None = Depends(rate_limit("report")),
db: AresDatabase = Depends(get_db),
@@ -1832,10 +1897,13 @@ async def generate_report(
if not campaign:
raise HTTPException(404, "Campaign not found")
await _require_campaign_access(campaign, actor)
- from ares.core.campaign import Campaign as CM
-
- c_obj = CM(**{k: v for k, v in campaign.items() if k in CM.model_fields})
- gen = ReportGenerator()
+ if include_sensitive_evidence and actor.role != "team_lead":
+ raise HTTPException(
+ status_code=403,
+ detail="Including sensitive report evidence requires team_lead role.",
+ )
+ c_obj = await _campaign_for_report(db, campaign)
+ gen = ReportGenerator(include_sensitive_evidence=include_sensitive_evidence)
valid_fmts = {"html", "pdf", "markdown", "json"}
if fmt not in valid_fmts:
raise HTTPException(
diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.py
index f712311..75a602f 100644
--- a/ares/cli/typer_main.py
+++ b/ares/cli/typer_main.py
@@ -58,6 +58,21 @@ app = typer.Typer(
)
console = Console()
+PYTHON_MIN_VERSION = (3, 10)
+PYTHON_MAX_VERSION_EXCLUSIVE = (3, 13)
+AD_IMPACKET_TESTED_PYTHON = (3, 12)
+
+
+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 = getattr(info, "major")
+ minor = getattr(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)
@@ -1100,12 +1115,38 @@ def doctor() -> None:
# Python version
import sys
pv = sys.version_info
- if pv >= (3, 10):
- check(f"Python {pv.major}.{pv.minor}.{pv.micro}", "ok")
+ 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.10-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 {pv.major}.{pv.minor}", "fail",
- f"3.10+ required — current: {pv.major}.{pv.minor}. "
- "Install via pyenv: pyenv install 3.11.9 && pyenv local 3.11.9")
+ 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 [
@@ -1191,6 +1232,82 @@ def doctor() -> None:
check(f"{import_name.split('.')[0]} ({module_label})", "warn",
import_failure_detail(import_name, exc, "pip install ares-redteam[cloud]"))
+ # PDF export capability
+ try:
+ weasyprint = importlib.import_module("weasyprint")
+ check(
+ "PDF WeasyPrint",
+ "ok",
+ getattr(weasyprint, "__version__", "") or "available",
+ )
+ except Exception as exc:
+ check(
+ "PDF WeasyPrint",
+ "warn",
+ import_failure_detail(
+ "weasyprint",
+ exc,
+ "pip install ares-redteam[pdf] or use Chromium browser fallback",
+ ),
+ )
+
+ 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",
+ )
+
+ try:
+ from ares.modules.reporting.report_gen import ReportGenerator
+
+ pdf_generator = ReportGenerator()
+ pdf_browsers = ReportGenerator._pdf_browser_candidates()
+ if pdf_browsers:
+ check("PDF browser detected", "ok", str(pdf_browsers[0]))
+ else:
+ check(
+ "PDF browser detected",
+ "warn",
+ "No Edge/Chrome/Chromium found; set ARES_PDF_BROWSER",
+ )
+
+ 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))
+ 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")
@@ -1796,6 +1913,7 @@ def _run_python_setup(
root: Path | None = None,
platform_name: str | None = None,
os_name: str | None = None,
+ version_info: object | None = None,
) -> None:
import os
import secrets
@@ -1804,14 +1922,34 @@ def _run_python_setup(
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: {sys.version.split()[0]} ({sys.executable})")
+ console.print(f"Python: {runtime_version} ({sys.executable})")
- if sys.version_info < (3, 10):
- console.print("[red]ERROR[/red] Python 3.10+ is required.")
+ if not (PYTHON_MIN_VERSION <= python_minor < PYTHON_MAX_VERSION_EXCLUSIVE):
+ console.print("[red]ERROR[/red] Python 3.10-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.10-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"
diff --git a/ares/core/campaign.py b/ares/core/campaign.py
index b0cb8b9..4e3db23 100644
--- a/ares/core/campaign.py
+++ b/ares/core/campaign.py
@@ -145,6 +145,14 @@ class Campaign(BaseModel):
scope: list[ScopeEntry] = Field(default_factory=list)
status: CampaignStatus = CampaignStatus.CREATED
noise_profile: NoiseProfile = NoiseProfile.STEALTH
+
+ @field_validator("noise_profile", mode="before")
+ @classmethod
+ def normalize_noise_profile(cls, v: Any) -> Any:
+ if isinstance(v, str):
+ return v.strip().lower()
+ return v
+
findings: list[Finding] = Field(default_factory=list)
audit_log: list[AuditEntry] = Field(default_factory=list)
notes: str = ""
diff --git a/ares/core/engine.py b/ares/core/engine.py
index e518349..8f04bb0 100644
--- a/ares/core/engine.py
+++ b/ares/core/engine.py
@@ -387,6 +387,7 @@ class AresEngine:
confirmed: list[Finding] = []
for f in findings:
if not f.false_positive:
+ f.validated = True
campaign.add_finding(f)
confirmed.append(f)
if self.db:
diff --git a/ares/core/security.py b/ares/core/security.py
index 7b4eb8f..dfb7680 100644
--- a/ares/core/security.py
+++ b/ares/core/security.py
@@ -523,8 +523,10 @@ def secure_mkstemp(
import tempfile
fd, path = tempfile.mkstemp(suffix=suffix, prefix=prefix)
- os.fchmod(fd, 0o600) # owner read/write only — BEFORE any data written
- os.chmod(path, 0o600) # Windows reflects file modes through chmod(path)
+ if hasattr(os, "fchmod"):
+ os.fchmod(fd, 0o600) # owner read/write only — BEFORE any data written
+ else:
+ os.chmod(path, 0o600) # Windows reflects file modes through chmod(path)
_restrict_windows_acl(path)
scope = campaign_id or _GLOBAL_SCOPE
with _ARTIFACT_LOCK:
diff --git a/ares/db/database.py b/ares/db/database.py
index db52a9c..9b5f4b4 100644
--- a/ares/db/database.py
+++ b/ares/db/database.py
@@ -356,15 +356,17 @@ class AresDatabase:
await self._conn.execute("""
INSERT OR REPLACE INTO findings
(id,campaign_id,module_id,title,description,severity,cvss_score,cvss_vector,
- confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id)
- VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
+ confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id,
+ validated,false_positive)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""", (f.id, campaign_id, module_id or getattr(f, "module_id", ""),
f.title, f.description,
f.severity.value if hasattr(f.severity, "value") else str(f.severity),
getattr(f, "cvss_score", 0.0), getattr(f, "cvss_vector", ""),
f.confidence, f.mitre_technique, f.mitre_tactic,
json.dumps(f.evidence), f.remediation, f.host,
- getattr(f, "trace_id", "")))
+ getattr(f, "trace_id", ""), int(bool(getattr(f, "validated", False))),
+ int(bool(getattr(f, "false_positive", False)))))
await self._conn.commit()
async def list_findings(
@@ -410,6 +412,7 @@ class AresDatabase:
params_list: list[Any] = [campaign_id]
if confirmed_only:
conditions.append("validated=1")
+ conditions.append("false_positive=0")
where = " AND ".join(conditions)
async with self._conn.execute(
f"SELECT * FROM findings WHERE {where} ORDER BY discovered_at DESC",
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index 00986c2..f411c3e 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -348,18 +348,22 @@ class PostgresDatabase:
await conn.execute("""
INSERT INTO findings
(id,campaign_id,module_id,title,description,severity,cvss_score,cvss_vector,
- confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id)
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)
+ confidence,mitre_technique,mitre_tactic,evidence_json,remediation,host,trace_id,
+ validated,false_positive)
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)
ON CONFLICT(id) DO UPDATE SET
title=EXCLUDED.title, description=EXCLUDED.description,
- severity=EXCLUDED.severity, evidence_json=EXCLUDED.evidence_json
+ severity=EXCLUDED.severity, evidence_json=EXCLUDED.evidence_json,
+ validated=EXCLUDED.validated, false_positive=EXCLUDED.false_positive
""", f.id, campaign_id, module_id or getattr(f, "module_id", ""),
f.title, f.description,
f.severity.value if hasattr(f.severity, "value") else str(f.severity),
getattr(f, "cvss_score", 0.0), getattr(f, "cvss_vector", ""),
f.confidence, f.mitre_technique, f.mitre_tactic,
json.dumps(f.evidence), f.remediation, f.host,
- getattr(f, "trace_id", ""))
+ getattr(f, "trace_id", ""),
+ int(bool(getattr(f, "validated", False))),
+ int(bool(getattr(f, "false_positive", False))))
async def list_findings(
self,
@@ -394,7 +398,11 @@ class PostgresDatabase:
return [self._row_to_dict(r) for r in rows], total or 0
async def get_findings(self, campaign_id: str, confirmed_only: bool = False) -> list[dict]:
- where = "campaign_id=$1" + (" AND validated=1" if confirmed_only else "")
+ where = (
+ "campaign_id=$1 AND validated=1 AND false_positive=0"
+ if confirmed_only
+ else "campaign_id=$1"
+ )
async with self._pool.acquire() as conn:
rows = await conn.fetch(
f"SELECT * FROM findings WHERE {where} ORDER BY discovered_at DESC",
diff --git a/ares/modules/base.py b/ares/modules/base.py
index 9d3620d..08fa06b 100644
--- a/ares/modules/base.py
+++ b/ares/modules/base.py
@@ -112,6 +112,25 @@ class BaseModule(abc.ABC):
if ctx.target: available.add("target")
if ctx.domain: available.add("domain")
if getattr(ctx, "vault", None): available.add("vault")
+ params = getattr(ctx, "params", {}) or {}
+
+ def _present(*names: str) -> bool:
+ return any(params.get(name) not in (None, "", []) for name in names)
+
+ has_username = _present("username", "ssh_user", "sql_user")
+ has_secret = _present(
+ "password", "secret", "nt_hash", "lm_hash",
+ "krbtgt_hash", "key_path", "ssh_key", "ssh_pass",
+ )
+ has_domain = bool(ctx.domain) or _present("domain")
+ if has_username and has_secret:
+ available.add("credentials")
+ if has_domain:
+ available.add("domain_creds")
+ # Privilege level cannot be proven before the remote auth
+ # attempt; explicit domain credentials satisfy the input
+ # contract, while the module/runtime enforces real access.
+ available.add("domain_admin_creds")
# credentials/domain_creds: available if vault has entries
vault = getattr(ctx, "vault", None)
if vault and hasattr(vault, "_store") and vault._store:
diff --git a/ares/modules/lateral/mssql.py b/ares/modules/lateral/mssql.py
index 1c5a42e..45bbc29 100644
--- a/ares/modules/lateral/mssql.py
+++ b/ares/modules/lateral/mssql.py
@@ -86,11 +86,13 @@ class MSSQLModule(BaseModule):
port = int(ctx.params.get("port", 1433))
command = ctx.params.get("command", "whoami")
technique = ctx.params.get("technique", "xp_cmdshell") # xp_cmdshell|linked|unc_coerce
- listener = ctx.params.get("listener_ip", "") # for UNC coercion
+ linked = ctx.params.get("linked", "")
+ listener = ctx.params.get("listener", "") or ctx.params.get("listener_ip", "") # for UNC coercion
findings, raw = await self.run(
target=target, username=username, password=password,
- port=port, command=command, technique=technique, listener=listener,
+ port=port, command=command, technique=technique,
+ linked=linked, listener=listener,
)
return ModuleResult(
status="success" if findings else "partial",
@@ -101,7 +103,8 @@ class MSSQLModule(BaseModule):
@trace_module("lateral.mssql")
async def run(self, target: str, username: str, password: str,
port: int = 1433, command: str = "whoami",
- technique: str = "xp_cmdshell", listener: str = "",
+ technique: str = "xp_cmdshell", linked: str = "",
+ listener: str = "",
**kwargs: Any):
await self.before_request(target, "default")
logger.info("mssql_start", target=target, technique=technique)
@@ -198,25 +201,25 @@ class MSSQLModule(BaseModule):
)
# Linked server hop
- elif technique == "linked" and info.get("linked_servers"):
+ elif technique == "linked" and (linked or info.get("linked_servers")):
+ linked_server = linked or info["linked_servers"][0]
linked_output = await loop.run_in_executor(
None,
lambda: self._linked_server_sync(
- target, username, password, port,
- info["linked_servers"][0], command,
+ target, username, password, port, linked_server, command,
),
)
if linked_output:
self.finding(
- title = f"MSSQL Linked Server RCE: {info['linked_servers'][0]}",
+ title = f"MSSQL Linked Server RCE: {linked_server}",
description = (
- f"Executed command via linked server '{info['linked_servers'][0]}' "
+ f"Executed command via linked server '{linked_server}' "
f"from {target}: '{command}'"
),
severity = Severity.CRITICAL,
mitre_technique = "T1505.001",
mitre_tactic = "Lateral Movement",
- evidence = {"linked_server": info["linked_servers"][0],
+ evidence = {"linked_server": linked_server,
"output": linked_output[:300]},
host = target, confidence = 0.9,
remediation = "Remove unnecessary linked servers. Disable xp_cmdshell on linked servers.",
diff --git a/ares/modules/linux/ld_preload.py b/ares/modules/linux/ld_preload.py
index d276721..a1254cf 100644
--- a/ares/modules/linux/ld_preload.py
+++ b/ares/modules/linux/ld_preload.py
@@ -91,9 +91,9 @@ class LDPreloadModule(BaseModule):
Thin adapter: extract params from ctx → call run() → return ModuleResult.
"""
from ares.modules.base import ModuleResult
- host = ctx.params.get("host") or getattr(ctx, "target", "localhost")
- ssh_user = ctx.params.get("ssh_user")
- ssh_key = ctx.params.get("ssh_key")
+ host = ctx.params.get("target") or ctx.params.get("host") or getattr(ctx, "target", "localhost")
+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")
+ ssh_key = ctx.params.get("key_path") or ctx.params.get("ssh_key")
ssh_pass = ctx.params.get("ssh_pass") or ctx.params.get("password", "")
ssh_port = ctx.params.get("ssh_port", 22)
if getattr(ctx, "dry_run", False):
diff --git a/ares/modules/linux/nfs_escape.py b/ares/modules/linux/nfs_escape.py
index 39fcdd4..dba6c76 100644
--- a/ares/modules/linux/nfs_escape.py
+++ b/ares/modules/linux/nfs_escape.py
@@ -142,9 +142,9 @@ class NFSEscapeModule(BaseModule):
Thin adapter: extract params from ctx → call run() → return ModuleResult.
"""
from ares.modules.base import ModuleResult
- host = ctx.params.get("host") or getattr(ctx, "target", "localhost")
- ssh_user = ctx.params.get("ssh_user")
- ssh_key = ctx.params.get("ssh_key")
+ host = ctx.params.get("target") or ctx.params.get("host") or getattr(ctx, "target", "localhost")
+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")
+ ssh_key = ctx.params.get("key_path") or ctx.params.get("ssh_key")
ssh_pass = ctx.params.get("ssh_pass") or ctx.params.get("password", "")
ssh_port = ctx.params.get("ssh_port", 22)
if getattr(ctx, "dry_run", False):
diff --git a/ares/modules/linux/service_hijack.py b/ares/modules/linux/service_hijack.py
index a0475ad..6e7beee 100644
--- a/ares/modules/linux/service_hijack.py
+++ b/ares/modules/linux/service_hijack.py
@@ -126,9 +126,9 @@ class ServiceHijackModule(BaseModule):
Thin adapter: extract params from ctx → call run() → return ModuleResult.
"""
from ares.modules.base import ModuleResult
- host = ctx.params.get("host") or getattr(ctx, "target", "localhost")
- ssh_user = ctx.params.get("ssh_user")
- ssh_key = ctx.params.get("ssh_key")
+ host = ctx.params.get("target") or ctx.params.get("host") or getattr(ctx, "target", "localhost")
+ ssh_user = ctx.params.get("username") or ctx.params.get("ssh_user")
+ ssh_key = ctx.params.get("key_path") or ctx.params.get("ssh_key")
ssh_pass = ctx.params.get("ssh_pass") or ctx.params.get("password", "")
ssh_port = ctx.params.get("ssh_port", 22)
if getattr(ctx, "dry_run", False):
diff --git a/ares/modules/params.py b/ares/modules/params.py
index 838a516..3cfff5a 100644
--- a/ares/modules/params.py
+++ b/ares/modules/params.py
@@ -261,19 +261,15 @@ class LinuxPrivescParams(ModuleParams):
class ADCSParams(DomainAuthParams):
"""ad.adcs — ADCS ESC1-ESC8 enumeration and exploitation."""
- ca_server: str = param(
- "CA server hostname or IP", required=False, default="", max_length=253
- )
- mode: str = param(
- "Mode: enumerate|exploit",
+ exploit_esc1: bool = param(
+ "Attempt ESC1 certificate request if vulnerable",
required=False,
- default="enumerate",
- pattern=r"^(enumerate|exploit)$",
+ default=False,
)
- template: str = param(
- "Target certificate template (exploit mode)",
+ target_user: str = param(
+ "User to request a certificate for when exploiting ESC1",
required=False,
- default="",
+ default="Administrator",
max_length=256,
)
@@ -346,12 +342,24 @@ class DelegationAbuseParams(DomainAuthParams):
default="enumerate",
pattern=r"^(enumerate|unconstrained|constrained|rbcd)$",
)
- target_host: str = param(
- "Target computer for delegation abuse",
+ target_computer: str = param(
+ "Target computer object for RBCD delegation abuse",
required=False,
default="",
max_length=253,
)
+ impersonate_user: str = param(
+ "User to impersonate via S4U",
+ required=False,
+ default="Administrator",
+ max_length=256,
+ )
+ target_service: str = param(
+ "Service SPN prefix to request",
+ required=False,
+ default="cifs",
+ max_length=64,
+ )
class LAPSEnumParams(DomainAuthParams):
@@ -405,11 +413,20 @@ class AzureADParams(ModuleParams):
tenant_id: str | None = param("Azure tenant ID", required=False, default=None)
client_id: str | None = param("App client ID", required=False, default=None)
- mode: str = param(
- "Auth mode: device_code|client_credentials",
+ client_secret: SecretParam | None = param(
+ "App client secret", required=False, default=None, secret=True
+ )
+ access_token: SecretParam | None = param(
+ "Existing Microsoft Graph access token",
+ required=False,
+ default=None,
+ secret=True,
+ )
+ technique: str = param(
+ "Technique: enumerate|device_code|sp_audit",
required=False,
- default="device_code",
- pattern=r"^(device_code|client_credentials)$",
+ default="enumerate",
+ pattern=r"^(enumerate|device_code|sp_audit)$",
)
diff --git a/ares/modules/reporting/report_gen.py b/ares/modules/reporting/report_gen.py
index 3ae1809..9212a86 100644
--- a/ares/modules/reporting/report_gen.py
+++ b/ares/modules/reporting/report_gen.py
@@ -16,9 +16,11 @@ from __future__ import annotations
import json
import os
+import re
import shutil
import subprocess
import tempfile
+import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -59,6 +61,32 @@ REMEDIATION_SLA = {
}
BROWSER_PDF_TIMEOUT_SECONDS = 15
+PDF_ARTIFACT_WAIT_SECONDS = 3.0
+_REDACTED_EVIDENCE = "[REDACTED sensitive evidence]"
+_SENSITIVE_EVIDENCE_KEYS = {
+ "hash",
+ "hashes",
+ "sample_hash",
+ "raw_hash",
+ "kerberos_hashes",
+ "asrep_hashes",
+ "ntlm_hashes",
+ "nt_hash",
+ "lm_hash",
+ "krbtgt_hash",
+ "password",
+ "secret",
+ "token",
+ "access_token",
+ "refresh_token",
+ "private_key",
+ "key_material",
+ "ccache",
+ "ticket",
+}
+_SAFE_HASH_METADATA_KEYS = {"hash_count", "hashcat_cmd", "hashcat_mode"}
+_KERBEROS_HASH_RE = re.compile(r"\$krb5(?:asrep|tgs)\$", re.IGNORECASE)
+_NTLM_HASH_RE = re.compile(r"\b[a-fA-F0-9]{32}\b")
# ── Context builder ───────────────────────────────────────────────────────────
@@ -278,7 +306,65 @@ def _build_remediation_roadmap(findings: list[Any]) -> list[dict[str, Any]]:
return roadmap
-def _evidence_rows(evidence: Any) -> list[dict[str, str]]:
+def _is_sensitive_evidence_key(key: Any) -> bool:
+ normalized = str(key).strip().lower()
+ if normalized in _SAFE_HASH_METADATA_KEYS:
+ return False
+ return (
+ normalized in _SENSITIVE_EVIDENCE_KEYS
+ or normalized.endswith("_hash")
+ or normalized.endswith("_hashes")
+ )
+
+
+def _redact_sensitive_evidence(
+ value: Any,
+ *,
+ include_sensitive_evidence: bool = False,
+ key: Any = "",
+) -> Any:
+ if include_sensitive_evidence:
+ return value
+ if _is_sensitive_evidence_key(key):
+ return _REDACTED_EVIDENCE
+ if isinstance(value, dict):
+ return {
+ item_key: _redact_sensitive_evidence(
+ item_value,
+ include_sensitive_evidence=include_sensitive_evidence,
+ key=item_key,
+ )
+ for item_key, item_value in value.items()
+ }
+ if isinstance(value, list):
+ return [
+ _redact_sensitive_evidence(
+ item,
+ include_sensitive_evidence=include_sensitive_evidence,
+ key=key,
+ )
+ for item in value
+ ]
+ if isinstance(value, tuple):
+ return tuple(
+ _redact_sensitive_evidence(
+ item,
+ include_sensitive_evidence=include_sensitive_evidence,
+ key=key,
+ )
+ for item in value
+ )
+ if isinstance(value, str) and (
+ _KERBEROS_HASH_RE.search(value) or _NTLM_HASH_RE.search(value)
+ ):
+ return _REDACTED_EVIDENCE
+ return value
+
+
+def _evidence_rows(
+ evidence: Any,
+ include_sensitive_evidence: bool = False,
+) -> list[dict[str, str]]:
"""Normalize finding evidence into report-friendly key/value rows."""
if isinstance(evidence, dict):
items = evidence.items()
@@ -289,7 +375,12 @@ def _evidence_rows(evidence: Any) -> list[dict[str, str]]:
rows: list[dict[str, str]] = []
for key, value in items:
- rendered = _format_evidence_value(value)
+ safe_value = _redact_sensitive_evidence(
+ value,
+ include_sensitive_evidence=include_sensitive_evidence,
+ key=key,
+ )
+ rendered = _format_evidence_value(safe_value)
rows.append({"key": str(key).replace("_", " ").title(), "value": rendered})
return rows
@@ -497,7 +588,11 @@ def _render_markdown_report(campaign: Campaign, ctx: dict[str, Any]) -> list[str
"",
]
if finding.evidence:
- lines += ["**Evidence:**", "", "```json", json.dumps(finding.evidence, indent=2, default=str), "```", ""]
+ evidence = _redact_sensitive_evidence(
+ finding.evidence,
+ include_sensitive_evidence=ctx.get("include_sensitive_evidence", False),
+ )
+ lines += ["**Evidence:**", "", "```json", json.dumps(evidence, indent=2, default=str), "```", ""]
if finding.remediation:
lines += [
f"**Remediation (SLA: {REMEDIATION_SLA.get(finding.severity.value, 365)} days):**",
@@ -1616,9 +1711,16 @@ class ReportGenerator:
FORMATS = ("json", "html", "markdown", "pdf")
_FMT_ALIASES = {"md": "markdown"}
- def __init__(self, output_dir: str = "~/.ares/reports") -> None:
+ def __init__(
+ self,
+ output_dir: str = "~/.ares/reports",
+ *,
+ include_sensitive_evidence: bool = False,
+ ) -> None:
self.output_dir = Path(output_dir).expanduser()
self.output_dir.mkdir(parents=True, exist_ok=True)
+ self.include_sensitive_evidence = include_sensitive_evidence
+ self._last_pdf_browser_error = ""
def generate(
self,
@@ -1642,6 +1744,8 @@ class ReportGenerator:
# Also expose under short alias
if fmt == "markdown":
results["md"] = path
+ except AssertionError:
+ raise
except Exception as e:
logger.warning("report_format_failed", fmt=fmt, error=str(e))
return results
@@ -1650,6 +1754,7 @@ class ReportGenerator:
def _gen_json(self, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
ctx = build_report_context(campaign, graph_json)
+ ctx["include_sensitive_evidence"] = self.include_sensitive_evidence
findings = ctx["findings"]
from ares.__version__ import __version__ as _ares_ver
@@ -1715,7 +1820,10 @@ class ReportGenerator:
"confidence": round(f.confidence, 3),
"mitre_technique": f.mitre_technique,
"mitre_tactic": f.mitre_tactic,
- "evidence": f.evidence,
+ "evidence": _redact_sensitive_evidence(
+ f.evidence,
+ include_sensitive_evidence=self.include_sensitive_evidence,
+ ),
"remediation": f.remediation,
"remediation_sla_days": REMEDIATION_SLA.get(f.severity.value, 365),
"module_id": f.module_id,
@@ -1741,7 +1849,10 @@ class ReportGenerator:
) -> str:
env = Environment(loader=BaseLoader(), autoescape=True)
env.filters["tojson"] = lambda v: json.dumps(v, indent=2, default=str)
- env.filters["evidence_rows"] = _evidence_rows
+ env.filters["evidence_rows"] = lambda v: _evidence_rows(
+ v,
+ include_sensitive_evidence=self.include_sensitive_evidence,
+ )
return env.from_string(template).render(
**build_report_context(campaign, graph_json)
)
@@ -1759,6 +1870,7 @@ class ReportGenerator:
self, campaign: Campaign, graph_json: dict[str, Any] | None
) -> Path:
ctx = build_report_context(campaign, graph_json)
+ ctx["include_sensitive_evidence"] = self.include_sensitive_evidence
lines = _render_markdown_report(campaign, ctx)
out = self._out(campaign, "md")
out.write_text("\n".join(lines), encoding="utf-8")
@@ -1840,12 +1952,19 @@ class ReportGenerator:
if self._write_pdf_with_browser(html, pdf_path):
logger.info("report_generated", fmt="pdf", path=str(pdf_path))
return pdf_path
+ detail = self._last_pdf_browser_error
+ if detail:
+ raise ReportDependencyError(detail) from exc
raise ReportDependencyError(
"PDF generation requires the optional WeasyPrint backend or a "
"local Chromium-compatible browser. Install the PDF extra/native "
"runtime, set ARES_PDF_BROWSER, or generate HTML, JSON, or "
"Markdown instead."
) from exc
+ if not pdf_path.exists() or pdf_path.stat().st_size <= 0:
+ raise ReportDependencyError(
+ f"PDF backend did not create a downloadable artifact at {pdf_path}"
+ )
logger.info("report_generated", fmt="pdf", path=str(pdf_path))
return pdf_path
@@ -1853,59 +1972,216 @@ class ReportGenerator:
def _write_pdf_with_browser(self, html: str, pdf_path: Path) -> bool:
"""Use a local Chromium-compatible browser when WeasyPrint is unavailable."""
+ self._last_pdf_browser_error = ""
for browser in self._pdf_browser_candidates():
- with tempfile.TemporaryDirectory(prefix="ares-pdf-browser-") as work_dir:
- work_path = Path(work_dir)
- html_path = work_path / "report.html"
- profile_dir = work_path / "profile"
+ work_path: Path | None = None
+ try:
+ work_path, profile_dir, html_path = self._create_pdf_browser_workspace()
html_path.write_text(html, encoding="utf-8")
- cmd = [
- str(browser),
- "--headless",
- "--disable-gpu",
- "--disable-extensions",
- "--no-first-run",
- "--no-default-browser-check",
- "--print-to-pdf-no-header",
- "--no-pdf-header-footer",
- f"--user-data-dir={profile_dir}",
- f"--print-to-pdf={str(pdf_path.resolve())}",
- html_path.resolve().as_uri(),
- ]
- try:
- completed = subprocess.run(
- cmd,
- capture_output=True,
- check=False,
- text=True,
- timeout=BROWSER_PDF_TIMEOUT_SECONDS,
- )
- except subprocess.TimeoutExpired as exc:
- logger.warning(
- "pdf_browser_failed",
- browser=str(browser),
- error=str(exc),
- timeout_s=BROWSER_PDF_TIMEOUT_SECONDS,
- )
- continue
- except (OSError, subprocess.SubprocessError) as exc:
- logger.warning(
- "pdf_browser_failed", browser=str(browser), error=str(exc)
- )
- continue
- if (
- completed.returncode == 0
- and pdf_path.exists()
- and pdf_path.stat().st_size > 0
- ):
+ except OSError as exc:
+ self._last_pdf_browser_error = (
+ f"PDF browser profile directory was not writable for {browser}: "
+ f"{exc}. Output path was {pdf_path.resolve()}. Set "
+ "ARES_PDF_BROWSER to a working Chromium/Edge/Chrome executable "
+ "or install ARES with the PDF extra/native WeasyPrint dependencies."
+ )
+ logger.warning(
+ "pdf_browser_profile_unusable",
+ browser=str(browser),
+ error=str(exc),
+ )
+ if work_path is not None:
+ shutil.rmtree(work_path, ignore_errors=True)
+ continue
+
+ skip_reason = self._pdf_browser_skip_reason(browser)
+ if skip_reason:
+ self._last_pdf_browser_error = (
+ f"PDF browser fallback skipped {browser}: {skip_reason}. "
+ f"User data dir was {profile_dir}. Output path was "
+ f"{pdf_path.resolve()}. Set ARES_PDF_BROWSER to a working "
+ "Chromium/Edge/Chrome executable or install ARES with the "
+ "PDF extra/native WeasyPrint dependencies."
+ )
+ logger.warning(
+ "pdf_browser_skipped",
+ browser=str(browser),
+ user_data_dir=str(profile_dir),
+ reason=skip_reason,
+ )
+ if work_path is not None:
+ shutil.rmtree(work_path, ignore_errors=True)
+ continue
+
+ cmd = [
+ str(browser),
+ "--headless=new",
+ "--disable-gpu",
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-extensions",
+ "--disable-background-networking",
+ "--disable-sync",
+ "--disable-crash-reporter",
+ "--disable-features=TranslateUI",
+ "--print-to-pdf-no-header",
+ "--no-pdf-header-footer",
+ f"--user-data-dir={str(profile_dir.resolve())}",
+ f"--print-to-pdf={str(pdf_path.resolve())}",
+ html_path.resolve().as_uri(),
+ ]
+ try:
+ completed = self._run_pdf_browser(cmd)
+ if completed.returncode == 0 and self._pdf_artifact_ready(pdf_path):
logger.info("pdf_browser_fallback_used", browser=str(browser))
return True
+ self._last_pdf_browser_error = (
+ f"PDF browser fallback exited with return code "
+ f"{completed.returncode} using {browser}, but no downloadable "
+ f"PDF was created at {pdf_path.resolve()}. User data dir was "
+ f"{profile_dir}. HTML input was {html_path}. Command was: "
+ f"{' '.join(cmd)}. Set ARES_PDF_BROWSER to a working "
+ "Chromium/Edge/Chrome executable or install ARES with the "
+ "PDF extra/native WeasyPrint dependencies."
+ )
logger.warning(
"pdf_browser_failed",
browser=str(browser),
+ user_data_dir=str(profile_dir),
+ html_input=str(html_path),
+ output_path=str(pdf_path.resolve()),
returncode=completed.returncode,
stderr=completed.stderr[-500:],
)
+ except subprocess.TimeoutExpired as exc:
+ self._last_pdf_browser_error = (
+ f"PDF browser fallback timed out after "
+ f"{BROWSER_PDF_TIMEOUT_SECONDS}s using {browser}. "
+ f"User data dir was {profile_dir}. HTML input was {html_path}. "
+ f"Output path was {pdf_path.resolve()}. Set ARES_PDF_BROWSER "
+ "to a working Chromium/Edge/Chrome executable or install "
+ "ARES with the PDF extra/native WeasyPrint dependencies."
+ )
+ logger.warning(
+ "pdf_browser_failed",
+ browser=str(browser),
+ error=str(exc),
+ timeout_s=BROWSER_PDF_TIMEOUT_SECONDS,
+ )
+ continue
+ except (OSError, subprocess.SubprocessError) as exc:
+ self._last_pdf_browser_error = (
+ f"PDF browser fallback failed using {browser}: {exc}. "
+ f"User data dir was {profile_dir}. HTML input was {html_path}. "
+ f"Output path was {pdf_path.resolve()}. Set ARES_PDF_BROWSER "
+ "to a working Chromium/Edge/Chrome executable or install "
+ "ARES with the PDF extra/native WeasyPrint dependencies."
+ )
+ logger.warning(
+ "pdf_browser_failed", browser=str(browser), error=str(exc)
+ )
+ finally:
+ if work_path is not None:
+ shutil.rmtree(work_path, ignore_errors=True)
+ if not self._last_pdf_browser_error:
+ self._last_pdf_browser_error = (
+ "PDF generation requires the optional WeasyPrint backend or a "
+ "local Chromium-compatible browser. Install the PDF extra/native "
+ "runtime, set ARES_PDF_BROWSER, or generate HTML, JSON, or "
+ "Markdown instead."
+ )
+ return False
+
+ def _run_pdf_browser(self, cmd: list[str]) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ cmd,
+ capture_output=True,
+ check=False,
+ text=True,
+ timeout=BROWSER_PDF_TIMEOUT_SECONDS,
+ )
+
+ def _pdf_browser_skip_reason(self, browser: Path) -> str:
+ if (
+ os.name == "nt"
+ and browser.name.lower() == "msedge.exe"
+ and self._windows_session_is_elevated()
+ ):
+ return (
+ "Microsoft Edge can reject dedicated --user-data-dir profiles "
+ "from elevated Windows sessions; use Chrome or set "
+ "ARES_PDF_BROWSER to a non-Edge Chromium executable"
+ )
+ return ""
+
+ @staticmethod
+ def _windows_session_is_elevated() -> bool:
+ if os.name != "nt":
+ return False
+ try:
+ import ctypes
+
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
+ except Exception:
+ return False
+
+ def _create_pdf_browser_workspace(self) -> tuple[Path, Path, Path]:
+ """Create a browser workspace with a probed writable profile directory."""
+ last_error: OSError | None = None
+ for root in self._pdf_browser_workspace_roots():
+ work_path: Path | None = None
+ cleanup_work_path = False
+ try:
+ root.mkdir(parents=True, exist_ok=True)
+ self._probe_writable_dir(root)
+ work_path = Path(
+ tempfile.mkdtemp(prefix="ares-pdf-browser-", dir=str(root))
+ )
+ profile_dir = work_path / "profile"
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ self._probe_writable_dir(profile_dir)
+ return work_path, profile_dir, work_path / "report.html"
+ except OSError as exc:
+ last_error = exc
+ cleanup_work_path = True
+ logger.warning(
+ "pdf_browser_workspace_unusable",
+ root=str(root),
+ error=str(exc),
+ )
+ continue
+ finally:
+ if cleanup_work_path and work_path is not None:
+ shutil.rmtree(work_path, ignore_errors=True)
+ raise OSError(
+ f"No writable PDF browser profile directory was available: {last_error}"
+ )
+
+ def _pdf_browser_workspace_roots(self) -> list[Path]:
+ primary = Path.home() / ".ares" / "runtime" / "pdf-browser"
+ fallback = Path(tempfile.gettempdir()) / "ares" / "pdf-browser"
+ roots = [primary]
+ if fallback != primary:
+ roots.append(fallback)
+ return roots
+
+ @staticmethod
+ def _probe_writable_dir(path: Path) -> None:
+ path.mkdir(parents=True, exist_ok=True)
+ probe = path / ".ares-write-probe"
+ probe.write_text("ok", encoding="utf-8")
+ probe.unlink(missing_ok=True)
+
+ @staticmethod
+ def _pdf_artifact_ready(pdf_path: Path) -> bool:
+ deadline = time.monotonic() + PDF_ARTIFACT_WAIT_SECONDS
+ while time.monotonic() <= deadline:
+ try:
+ if pdf_path.exists() and pdf_path.stat().st_size > 0:
+ return True
+ except OSError:
+ pass
+ time.sleep(0.15)
return False
@staticmethod
diff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.md
index 9c551ea..0ee68d2 100644
--- a/docs/dashboard-guide.md
+++ b/docs/dashboard-guide.md
@@ -299,7 +299,7 @@ Formats:
- HTML.
- Markdown.
- JSON.
-- PDF through WeasyPrint when available, with a Chromium-compatible browser
+- PDF through WeasyPrint when available, with an Edge/Chrome/Chromium browser
fallback for local environments that do not have WeasyPrint native libraries.
HTML and PDF reports render finding evidence as readable tables and key-value
@@ -487,7 +487,7 @@ Use it for:
| Campaign remains after delete | Browser cache or old server process. | Restart ARES and press `Ctrl+F5`. |
| Module says target is not in scope | Selected campaign has no matching scope CIDR. | Create or select a campaign whose scope includes the target, such as `127.0.0.1/32` for local testing. |
| Telemetry looks empty after restart | Telemetry is an in-memory runtime snapshot. | Run modules in the current API process, or use Reports/Campaigns for durable history. |
-| PDF generation fails | No PDF backend or browser fallback is available. | Install the PDF extra/native libraries or run on a machine with an available Chromium-compatible browser; use HTML, Markdown, or JSON meanwhile. |
+| PDF generation fails | No PDF backend or browser fallback is available. | Run `ares doctor` to check WeasyPrint, `ARES_PDF_BROWSER`, browser profile writability, and report output writability; install the PDF extra/native libraries or set `ARES_PDF_BROWSER` to Edge/Chrome/Chromium. |
## Cross-Platform Notes
-The core API, dashboard, database migrations, SDK imports, and unit suite are designed to run on Windows, Linux, and macOS. Optional module dependencies can vary by operating system. Use `ares doctor` on each host to see which optional integrations are available before running modules that need AD, cloud, container, PDF, or native password-cracking tooling.
+The core API, dashboard, database migrations, SDK imports, and unit suite are designed to run on Windows, Linux, and macOS. Package metadata allows Python 3.10-3.12, but the tested release path for the dashboard and Windows AD/Impacket lab modules is Python 3.12.x. Optional module dependencies can vary by operating system. Use `ares doctor` on each host to see which optional integrations are available before running modules that need AD, cloud, container, PDF, or native password-cracking tooling.
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 7b321f4..aab4c29 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -891,6 +891,7 @@ function CampaignsPage() {
const [client, setClient] = useSessionState("ares.dashboard.campaigns.create.client", "Internal");
const [targets, setTargets] = useSessionState("ares.dashboard.campaigns.create.targets", "");
const [scope, setScope] = useSessionState("ares.dashboard.campaigns.create.scope", "");
+ const [noiseProfile, setNoiseProfile] = useSessionState("ares.dashboard.campaigns.create.noiseProfile", "stealth");
const [createWarning, setCreateWarning] = useState("");
const [otherId, setOtherId] = useSessionState("ares.dashboard.campaigns.compareId", "");
const [activeTab, setActiveTab] = useSessionState("ares.dashboard.campaigns.tab", "List");
@@ -920,13 +921,15 @@ function CampaignsPage() {
name: name.trim(),
client: client.trim(),
targets: splitLines(targets),
- scope_cidrs: splitLines(scope)
+ scope_cidrs: splitLines(scope),
+ noise_profile: noiseProfile
}),
onSuccess: (campaign) => {
setSelected(campaign.id);
setName("");
setTargets("");
setScope("");
+ setNoiseProfile("stealth");
setCreateWarning("");
setActiveTab("Scope");
void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
@@ -979,6 +982,11 @@ function CampaignsPage() {
<input className="field" required placeholder="Name" value={name} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setName(e.target.value); }} />
<input className="field" required placeholder="Client" value={client} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setClient(e.target.value); }} />
</div>
+ <select className="field" value={noiseProfile} onChange={(e) => { setCreateWarning(""); setNoiseProfile(e.target.value); }}>
+ <option value="stealth">Stealth</option>
+ <option value="normal">Normal</option>
+ <option value="aggressive">Aggressive</option>
+ </select>
<textarea className="field min-h-20" required placeholder="Targets" value={targets} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setTargets(e.target.value); }} />
<textarea className="field min-h-20" required placeholder="Scope CIDRs" value={scope} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setScope(e.target.value); }} />
{createWarning && <p className="notice notice-danger">{createWarning}</p>}
@@ -2615,6 +2623,7 @@ function CampaignScopeSummary({ campaign, loading }: { campaign?: Campaign; load
<div className="mini-stat-grid">
<MiniStat title="Targets" value={String(targets.length)} detail={targets.slice(0, 3).join(", ") || "none declared"} />
<MiniStat title="Scope CIDRs" value={String(scope.length)} detail={scope.slice(0, 3).join(", ") || "none declared"} />
+ <MiniStat title="Noise Profile" value={String(campaign.noise_profile ?? "stealth")} detail="OPSEC guardrail" />
<MiniStat title="Campaign ID" value={campaign.id.slice(0, 8)} detail="API/report key" />
</div>
</div>
@@ -2652,7 +2661,7 @@ function CampaignTable({ campaigns }: { campaigns: Campaign[] }) {
{campaigns.length > 0 ? (
<div className="table-scroll">
<table className="table">
- <thead><tr><th>#</th><th>Name</th><th>Client</th><th>Status</th><th>Operator</th></tr></thead>
+ <thead><tr><th>#</th><th>Name</th><th>Client</th><th>Status</th><th>Noise</th><th>Operator</th></tr></thead>
<tbody>
{campaigns.map((campaign, index) => (
<tr key={campaign.id}>
@@ -2663,6 +2672,7 @@ function CampaignTable({ campaigns }: { campaigns: Campaign[] }) {
</td>
<td>{campaign.client || "Internal"}</td>
<td><span className={statusBadge(campaign.status)}>{campaign.status ?? "created"}</span></td>
+ <td><span className={opsecBadge(campaign.noise_profile)}>{campaign.noise_profile ?? "stealth"}</span></td>
<td>{campaign.operator || "operator"}</td>
</tr>
))}
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 3a46fee..0a62738 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -165,7 +165,7 @@ export const api = {
health: () => apiRequest<Record<string, unknown>>("/health"),
telemetry: () => apiRequest<Record<string, unknown>>("/telemetry"),
campaigns: () => apiRequest<Campaign[]>("/campaigns"),
- createCampaign: (body: { name: string; client: string; targets: string[]; scope_cidrs: string[] }) =>
+ createCampaign: (body: { name: string; client: string; targets: string[]; scope_cidrs: string[]; noise_profile: string }) =>
apiRequest<Campaign>("/campaigns", {
method: "POST",
headers: { "Content-Type": "application/json" },
diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts
index a1a6b5c..28897c7 100644
--- a/frontend/src/api/types.ts
+++ b/frontend/src/api/types.ts
@@ -21,6 +21,7 @@ export interface Campaign {
targets?: string[];
scope_cidrs?: string[];
scope_json?: string;
+ noise_profile?: string;
status?: string;
created_at?: string;
[key: string]: unknown;
diff --git a/pyproject.toml b/pyproject.toml
index e6e2157..23f283e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -8,7 +8,7 @@ version = "6.0.0"
description = "ARES - Automated Red Team Engagement System"
readme = "README.md"
license = { text = "MIT" }
-requires-python = ">=3.10"
+requires-python = ">=3.10,<3.13"
dependencies = [
# Core
"click>=8.1",
diff --git a/scripts/setup.sh b/scripts/setup.sh
index 0283a22..d730b9e 100644
--- a/scripts/setup.sh
+++ b/scripts/setup.sh
@@ -3,10 +3,20 @@ set -e
echo "=== ARES Setup ==="
-# Check Python 3.10+
-python3 -c "import sys; assert sys.version_info >= (3,10), 'Python 3.10+ required'" 2>/dev/null \
- || { echo "ERROR: Python 3.10+ required"; exit 1; }
+# Check Python 3.10-3.12. The tested release path is Python 3.12.x.
+python3 -c "import sys; assert (3,10) <= sys.version_info[:2] < (3,13), 'Python 3.10-3.12 required'" 2>/dev/null \
+ || { echo "ERROR: Python 3.10-3.12 required"; exit 1; }
echo "[OK] Python $(python3 --version)"
+python3 - <<'PY'
+import sys
+
+if sys.version_info[:2] != (3, 12):
+ print("[!] Package metadata permits Python 3.10-3.12, but the tested")
+ print(" release path for the dashboard and Windows AD/Impacket modules")
+ print(" is Python 3.12.x")
+else:
+ print("[OK] Python 3.12.x detected for the tested release path")
+PY
# Create virtual environment kalau belum ada
if [ ! -d ".venv" ]; then
@@ -20,9 +30,9 @@ source .venv/bin/activate
# Upgrade pip
pip install --upgrade pip -q
-# Install ARES + dev deps
+# Install ARES + dev deps and PDF backend extras
echo "[*] Installing dependencies..."
-pip install -e ".[dev]" -q
+pip install -e ".[dev,pdf]" -q
# Generate .env kalau belum ada
if [ ! -f ".env" ]; then
diff --git a/tests/conftest.py b/tests/conftest.py
index 9676215..e82664b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -44,6 +44,35 @@ def set_test_env():
# ── Temporary directories ─────────────────────────────────────────────────────
[email protected](autouse=True)
+def forbid_unmocked_pdf_browser_launch(monkeypatch: pytest.MonkeyPatch):
+ """Unit tests must mock PDF browser execution instead of launching Chrome/Edge."""
+ from ares.modules.reporting.report_gen import ReportGenerator
+
+ real_runner = ReportGenerator._run_pdf_browser
+ browser_names = {
+ "chrome",
+ "chrome.exe",
+ "chromium",
+ "chromium-browser",
+ "chromium.exe",
+ "google-chrome",
+ "msedge",
+ "msedge.exe",
+ }
+
+ def guarded_runner(self: Any, cmd: list[str]):
+ executable = Path(str(cmd[0]))
+ if executable.name.lower() in browser_names:
+ raise AssertionError(
+ "Unit tests must mock PDF browser execution; attempted to launch "
+ f"{executable}"
+ )
+ return real_runner(self, cmd)
+
+ monkeypatch.setattr(ReportGenerator, "_run_pdf_browser", guarded_runner)
+
+
@pytest.fixture
def tmp_dir(tmp_path: Path) -> Path:
"""Isolated temp directory (alias for tmp_path)."""
diff --git a/tests/unit/db/test_database.py b/tests/unit/db/test_database.py
index a590106..033782f 100644
--- a/tests/unit/db/test_database.py
+++ b/tests/unit/db/test_database.py
@@ -10,6 +10,7 @@ import subprocess
import tempfile
from pathlib import Path
from typing import Any
+from urllib.parse import unquote, urlparse
from unittest.mock import AsyncMock, patch
import pytest
@@ -23,6 +24,7 @@ from ares.db.database import AresDatabase, Credential, Host, Loot
from ares.modules.base import BaseModule
from ares.modules.reporting.report_gen import (
BROWSER_PDF_TIMEOUT_SECONDS,
+ ReportDependencyError,
ReportGenerator,
)
@@ -256,6 +258,22 @@ class TestDatabase:
assert "credential_count" in summary
assert "loot_count" in summary
+ @pytest.mark.asyncio
+ async def test_save_finding_persists_validation_flags(
+ self, db: AresDatabase, campaign: Campaign, confirmed_finding: Finding
+ ) -> None:
+ await db.save_campaign(campaign)
+ confirmed_finding.validated = True
+ confirmed_finding.false_positive = False
+ await db.save_finding(campaign.id, confirmed_finding, confirmed_finding.module_id)
+
+ confirmed = await db.get_findings(campaign.id, confirmed_only=True)
+
+ assert len(confirmed) == 1
+ assert confirmed[0]["id"] == confirmed_finding.id
+ assert confirmed[0]["validated"] == 1
+ assert confirmed[0]["false_positive"] == 0
+
# ── Reporting Tests ───────────────────────────────────────────────────────────
@@ -290,7 +308,18 @@ class TestReportGenerator:
md = path.read_text()
assert "# ARES Report" in md
- def test_generate_all(self, campaign_with_findings: Campaign, tmp_path: Path) -> None:
+ def test_generate_all(
+ self,
+ campaign_with_findings: Campaign,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ def fake_pdf(self: ReportGenerator, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
+ path = self._out(campaign, "pdf")
+ path.write_bytes(b"%PDF-1.4\n% unit fake\n")
+ return path
+
+ monkeypatch.setattr(ReportGenerator, "_gen_pdf", fake_pdf)
gen = ReportGenerator(output_dir=str(tmp_path))
paths = gen.generate_all(campaign_with_findings)
assert "json" in paths
@@ -307,8 +336,9 @@ class TestReportGenerator:
with (
patch.object(gen, "_pdf_browser_candidates", return_value=[browser]),
- patch(
- "ares.modules.reporting.report_gen.subprocess.run",
+ patch.object(
+ gen,
+ "_run_pdf_browser",
side_effect=subprocess.TimeoutExpired(
cmd=[str(browser)], timeout=BROWSER_PDF_TIMEOUT_SECONDS
),
@@ -316,7 +346,175 @@ class TestReportGenerator:
):
assert gen._write_pdf_with_browser("<html></html>", pdf_path) is False
- assert run_browser.call_args.kwargs["timeout"] == BROWSER_PDF_TIMEOUT_SECONDS
+ assert run_browser.call_args.args[0][0] == str(browser)
+ assert f"{BROWSER_PDF_TIMEOUT_SECONDS}s" in gen._last_pdf_browser_error
+ assert not pdf_path.exists()
+
+ def test_pdf_browser_workspace_falls_back_when_first_root_unwritable(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ bad_root = tmp_path / "bad-runtime-root"
+ good_root = tmp_path / "good-runtime-root"
+
+ def fake_probe(path: Path) -> None:
+ if path == bad_root:
+ raise OSError("not writable")
+ path.mkdir(parents=True, exist_ok=True)
+ probe = path / ".probe"
+ probe.write_text("ok", encoding="utf-8")
+ probe.unlink()
+
+ monkeypatch.setattr(
+ gen, "_pdf_browser_workspace_roots", lambda: [bad_root, good_root]
+ )
+ monkeypatch.setattr(gen, "_probe_writable_dir", fake_probe)
+
+ work_path, profile_dir, html_path = gen._create_pdf_browser_workspace()
+
+ assert work_path.parent == good_root
+ assert profile_dir == work_path / "profile"
+ assert profile_dir.is_dir()
+ assert html_path == work_path / "report.html"
+ writable_probe = profile_dir / "writable.txt"
+ writable_probe.write_text("ok", encoding="utf-8")
+ assert writable_probe.read_text(encoding="utf-8") == "ok"
+
+ def test_pdf_browser_fallback_keeps_stable_export_path(self, tmp_path: Path) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ browser = tmp_path / "chromium"
+ browser.write_text("", encoding="utf-8")
+ pdf_path = tmp_path / "stable-report.pdf"
+
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ assert "--headless=new" in command
+ assert "--disable-gpu" in command
+ assert "--no-first-run" in command
+ assert "--no-default-browser-check" in command
+ assert "--disable-extensions" in command
+ assert "--disable-background-networking" in command
+ assert "--disable-sync" in command
+ assert "--disable-crash-reporter" in command
+ assert "--disable-features=TranslateUI" in command
+ assert "--print-to-pdf-no-header" in command
+ profile_arg = next(arg for arg in command if arg.startswith("--user-data-dir="))
+ profile_path = Path(profile_arg.split("=", 1)[1])
+ profile_probe = profile_path / "probe.txt"
+ profile_probe.write_text("ok", encoding="utf-8")
+ profile_probe.unlink()
+ html_uri = command[-1]
+ parsed_html_path = unquote(urlparse(html_uri).path)
+ if len(parsed_html_path) >= 3 and parsed_html_path[0] == "/" and parsed_html_path[2] == ":":
+ parsed_html_path = parsed_html_path[1:]
+ assert Path(parsed_html_path).exists()
+ pdf_arg = next(arg for arg in command if arg.startswith("--print-to-pdf="))
+ Path(pdf_arg.split("=", 1)[1]).write_bytes(b"%PDF-1.4\n%stable\n")
+ assert "ares-pdf-browser-" in html_uri
+ assert Path(pdf_arg.split("=", 1)[1]) == pdf_path.resolve()
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ with (
+ patch.object(gen, "_pdf_browser_candidates", return_value=[browser]),
+ patch.object(gen, "_run_pdf_browser", side_effect=fake_run),
+ ):
+ assert gen._write_pdf_with_browser("<html></html>", pdf_path) is True
+
+ assert pdf_path.exists()
+ assert pdf_path.stat().st_size > 0
+ assert "ares-pdf-browser-" not in str(pdf_path)
+
+ def test_pdf_browser_profile_unwritable_tries_next_browser(self, tmp_path: Path) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ edge = tmp_path / "msedge.exe"
+ chrome = tmp_path / "chrome.exe"
+ edge.write_text("", encoding="utf-8")
+ chrome.write_text("", encoding="utf-8")
+ pdf_path = tmp_path / "report.pdf"
+ work_path = tmp_path / "chrome-work"
+ profile_dir = work_path / "profile"
+ html_path = work_path / "report.html"
+ workspace_calls = 0
+ commands: list[list[str]] = []
+
+ def fake_workspace() -> tuple[Path, Path, Path]:
+ nonlocal workspace_calls
+ workspace_calls += 1
+ if workspace_calls == 1:
+ raise OSError("profile not writable")
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ return work_path, profile_dir, html_path
+
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ commands.append(command)
+ pdf_arg = next(arg for arg in command if arg.startswith("--print-to-pdf="))
+ Path(pdf_arg.split("=", 1)[1]).write_bytes(b"%PDF-1.4\n%chrome\n")
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ with (
+ patch.object(gen, "_pdf_browser_candidates", return_value=[edge, chrome]),
+ patch.object(gen, "_create_pdf_browser_workspace", side_effect=fake_workspace),
+ patch.object(gen, "_run_pdf_browser", side_effect=fake_run),
+ ):
+ assert gen._write_pdf_with_browser("<html></html>", pdf_path) is True
+
+ assert workspace_calls == 2
+ assert len(commands) == 1
+ assert commands[0][0] == str(chrome)
+ assert pdf_path.exists()
+
+ def test_pdf_browser_skips_edge_in_elevated_windows_session(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import ares.modules.reporting.report_gen as report_gen_module
+
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ edge = tmp_path / "msedge.exe"
+ chrome = tmp_path / "chrome.exe"
+ monkeypatch.setattr(report_gen_module.os, "name", "nt")
+ monkeypatch.setattr(gen, "_windows_session_is_elevated", lambda: True)
+
+ assert "Microsoft Edge" in gen._pdf_browser_skip_reason(edge)
+ assert gen._pdf_browser_skip_reason(chrome) == ""
+
+ def test_pdf_browser_success_without_artifact_raises_actionable_error(
+ self, campaign_with_findings: Campaign, tmp_path: Path
+ ) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ browser = tmp_path / "msedge"
+ browser.write_text("", encoding="utf-8")
+
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ with (
+ patch.dict("sys.modules", {"weasyprint": None}),
+ patch.object(gen, "_pdf_browser_candidates", return_value=[browser]),
+ patch.object(gen, "_run_pdf_browser", side_effect=fake_run),
+ ):
+ with pytest.raises(ReportDependencyError) as exc_info:
+ gen.generate(campaign_with_findings, fmt="pdf")
+
+ message = str(exc_info.value)
+ assert str(browser) in message
+ assert str(tmp_path.resolve()) in message
+ assert "User data dir" in message
+ assert "HTML input" in message
+ assert "Command was:" in message
+ assert "no downloadable PDF was created" in message
+ assert "ARES_PDF_BROWSER" in message
+
+ def test_unit_guard_blocks_unmocked_real_pdf_browser_launch(
+ self, tmp_path: Path
+ ) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ browser = tmp_path / "chrome.exe"
+ browser.write_text("", encoding="utf-8")
+ pdf_path = tmp_path / "report.pdf"
+
+ with patch.object(gen, "_pdf_browser_candidates", return_value=[browser]):
+ with pytest.raises(AssertionError, match="must mock PDF browser execution"):
+ gen._write_pdf_with_browser("<html></html>", pdf_path)
+
assert not pdf_path.exists()
def test_json_structure_valid(self, campaign_with_findings: Campaign, tmp_path: Path) -> None:
@@ -330,6 +528,70 @@ class TestReportGenerator:
assert "confidence" in f
assert "mitre_technique" in f
+ def test_default_reports_redact_full_kerberos_hash_evidence(
+ self, campaign: Campaign, tmp_path: Path
+ ) -> None:
+ full_asrep = "[email protected]:abcdef0123456789"
+ full_tgs = "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef0123456789"
+ campaign.add_finding(
+ Finding(
+ title="ASREPRoast Hashes Captured (1)",
+ description="Captured one AS-REP hash.",
+ severity=Severity.HIGH,
+ validated=True,
+ module_id="ad.asreproast",
+ evidence={"hash_count": 1, "sample_hash": full_asrep},
+ )
+ )
+ campaign.add_finding(
+ Finding(
+ title="Kerberoast Hashes Captured (1)",
+ description="Captured one TGS hash.",
+ severity=Severity.CRITICAL,
+ validated=True,
+ module_id="ad.kerberoast",
+ evidence={"hash_count": 1, "accounts": ["svc-sql"], "sample_hash": full_tgs},
+ )
+ )
+
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ json_path = gen.generate(campaign, fmt="json")
+ html_path = gen.generate(campaign, fmt="html")
+
+ json_text = json_path.read_text(encoding="utf-8")
+ html_text = html_path.read_text(encoding="utf-8")
+ assert full_asrep not in json_text
+ assert full_tgs not in json_text
+ assert full_asrep not in html_text
+ assert full_tgs not in html_text
+ assert "ASREPRoast Hashes Captured" in json_text
+ assert "Kerberoast Hashes Captured" in json_text
+ assert "svc-sql" in json_text
+ assert "[REDACTED sensitive evidence]" in json_text
+
+ def test_explicit_sensitive_report_option_preserves_hash_evidence(
+ self, campaign: Campaign, tmp_path: Path
+ ) -> None:
+ full_tgs = "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef0123456789"
+ campaign.add_finding(
+ Finding(
+ title="Kerberoast Hashes Captured (1)",
+ description="Captured one TGS hash.",
+ severity=Severity.CRITICAL,
+ validated=True,
+ module_id="ad.kerberoast",
+ evidence={"sample_hash": full_tgs},
+ )
+ )
+
+ gen = ReportGenerator(
+ output_dir=str(tmp_path),
+ include_sensitive_evidence=True,
+ )
+ path = gen.generate(campaign, fmt="json")
+
+ assert full_tgs in path.read_text(encoding="utf-8")
+
def test_invalid_format_raises(self, campaign: Campaign) -> None:
gen = ReportGenerator()
with pytest.raises(ValueError, match="Unknown format"):
diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.py
index c72cd56..1e9a9b4 100644
--- a/tests/unit/test_api_endpoints.py
+++ b/tests/unit/test_api_endpoints.py
@@ -92,6 +92,7 @@ def _make_mock_db():
db.purge_expired_tokens = AsyncMock(return_value=0)
db.list_campaigns = AsyncMock(return_value=([], 0))
db.get_campaign = AsyncMock(return_value=None)
+ db.list_findings = AsyncMock(return_value=([], 0))
db.delete_campaign = AsyncMock(return_value=False)
db.verify_api_key = AsyncMock(return_value=None)
return db
@@ -349,6 +350,9 @@ class TestAPIKeyScopeEnforcement:
}
class FakeReportGenerator:
+ def __init__(self, *args, **kwargs):
+ pass
+
def generate(self, campaign, fmt="html"):
path = tmp_path / f"{campaign.id}_report.{fmt}"
path.write_text("report", encoding="utf-8")
@@ -402,6 +406,9 @@ class TestAPIKeyScopeEnforcement:
}
class FakeReportGenerator:
+ def __init__(self, *args, **kwargs):
+ pass
+
def generate(self, campaign, fmt="html"):
path = tmp_path / f"{campaign.id}_report.{fmt}"
path.write_text("report", encoding="utf-8")
@@ -559,6 +566,36 @@ class TestRBACEnforcement:
assert "scope_cidrs" in r.text
db.save_campaign.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_create_campaign_normalizes_uppercase_noise_profile(self, aclient):
+ c, db, _ = aclient
+ db.is_access_token_revoked.return_value = False
+ captured: dict[str, Any] = {}
+
+ async def capture_campaign(campaign: Any) -> None:
+ captured["campaign"] = campaign
+
+ db.save_campaign.side_effect = capture_campaign
+
+ try:
+ r = await c.post(
+ "/campaigns",
+ json={
+ "name": "AD Lab Attack Simulation",
+ "client": "Internal",
+ "targets": ["10.10.10.20"],
+ "scope_cidrs": ["10.10.10.0/24"],
+ "noise_profile": "NORMAL",
+ },
+ headers=_auth("op_user", "operator"),
+ )
+ finally:
+ db.save_campaign.side_effect = None
+
+ assert r.status_code == 200
+ assert r.json()["noise_profile"] == "normal"
+ assert captured["campaign"].noise_profile.value == "normal"
+
@pytest.mark.asyncio
async def test_delete_campaign_requires_team_lead(self, aclient):
c, db, _ = aclient
@@ -850,6 +887,97 @@ class TestModuleRunEndpoint:
assert [entry.cidr for entry in campaign.scope] == ["127.0.0.1/32"]
assert campaign.targets == ["127.0.0.1"]
+ @pytest.mark.asyncio # type: ignore[untyped-decorator]
+ async def test_kerberoast_dashboard_payload_passes_api_validation(
+ self, aclient: Any
+ ) -> None:
+ c, db, app = aclient
+ from ares.api.server import get_engine
+ from ares.modules.ad.kerberoast import KerberoastModule
+
+ captured: dict[str, Any] = {}
+
+ class FakeRegistry:
+ def get(self, module_id: str) -> Any:
+ return KerberoastModule if module_id == "ad.kerberoast" else None
+
+ class FakeResult:
+ findings: list[Any] = []
+ status = "success"
+
+ def model_dump(self) -> dict[str, Any]:
+ return {
+ "module_id": "ad.kerberoast",
+ "status": "success",
+ "findings": [],
+ "validation_results": [],
+ "raw_output": {"reached": True},
+ "error": "",
+ "duration_ms": 0,
+ }
+
+ class FakeEngine:
+ registry = FakeRegistry()
+
+ async def run_module(
+ self,
+ module_id: str,
+ campaign: Any,
+ params: dict[str, Any],
+ actor_role: str = "",
+ ) -> FakeResult:
+ captured["module_id"] = module_id
+ captured["params"] = params
+ captured["actor_role"] = actor_role
+ return FakeResult()
+
+ db.is_access_token_revoked.return_value = False
+ db.get_campaign.return_value = {
+ "id": "camp-kerberoast",
+ "name": "Kerberoast API",
+ "client": "Internal",
+ "operator": "admin",
+ "noise_profile": "normal",
+ "status": "created",
+ "scope_json": '[{"cidr": "10.0.0.0/8", "description": ""}]',
+ "targets_json": '["10.0.0.5"]',
+ "notes": "",
+ "created_at": "2026-06-27 02:15:19",
+ "updated_at": "2026-06-27 02:15:19",
+ }
+ app.dependency_overrides[get_engine] = lambda: FakeEngine()
+ try:
+ r = await c.post(
+ "/modules/ad.kerberoast/run",
+ json={
+ "campaign_id": "camp-kerberoast",
+ "params": {
+ "dc": "10.0.0.5",
+ "domain": "corp.local",
+ "username": "svc-roast",
+ "password": "Passw0rd!",
+ "use_ldaps": False,
+ "target_user": "sqlsvc",
+ },
+ "dry_run": False,
+ },
+ headers=_auth("admin", "team_lead"),
+ )
+ finally:
+ app.dependency_overrides.pop(get_engine, None)
+
+ assert r.status_code == 200
+ assert captured["module_id"] == "ad.kerberoast"
+ assert captured["actor_role"] == "team_lead"
+ assert captured["params"] == {
+ "dc": "10.0.0.5",
+ "domain": "corp.local",
+ "username": "svc-roast",
+ "password": "Passw0rd!",
+ "use_ldaps": False,
+ "target_user": "sqlsvc",
+ }
+
@pytest.mark.asyncio # type: ignore[untyped-decorator]
async def test_module_run_updates_telemetry_snapshot(
self, aclient: Any, monkeypatch: Any
@@ -972,6 +1100,253 @@ class TestReportEndpoints:
filenames = [item["filename"] for item in r.json()["reports"]]
assert filenames == [owned.name]
+ @pytest.mark.asyncio # type: ignore[untyped-decorator]
+ async def test_generate_json_report_hydrates_confirmed_db_findings(
+ self, aclient: Any, tmp_path: Any, monkeypatch: Any
+ ) -> None:
+ c, db, _ = aclient
+ import ares.modules.reporting.report_gen as report_gen
+
+ real_report_generator = report_gen.ReportGenerator
+ campaign_id = "camp-ad-lab"
+ db.is_access_token_revoked.return_value = False
+ db.get_campaign.return_value = {
+ "id": campaign_id,
+ "name": "AD Lab Attack Simulation",
+ "client": "Internal",
+ "operator": "admin",
+ "noise_profile": "normal",
+ "status": "created",
+ "scope_json": '[{"cidr": "10.10.10.0/24", "description": "AD lab"}]',
+ "targets_json": '["10.10.10.20"]',
+ "notes": "",
+ }
+ db.list_findings.return_value = (
+ [
+ {
+ "id": "finding-asrep",
+ "campaign_id": campaign_id,
+ "module_id": "ad.asreproast",
+ "title": "ASREPRoast Hashes Captured (1)",
+ "description": "Captured one AS-REP hash.",
+ "severity": "high",
+ "confidence": 1.0,
+ "mitre_technique": "T1558.004",
+ "mitre_tactic": "Credential Access",
+ "evidence_json": '{"hash_count": 1, "sample_hash": "[email protected]:abcdef"}',
+ "remediation": "Require Kerberos pre-authentication.",
+ "host": "10.10.10.20",
+ "validated": 0,
+ "false_positive": 0,
+ "discovered_at": "2026-07-12T01:00:00+00:00",
+ },
+ {
+ "id": "finding-kerb",
+ "campaign_id": campaign_id,
+ "module_id": "ad.kerberoast",
+ "title": "Kerberoast Hashes Captured (1)",
+ "description": "Captured one TGS hash.",
+ "severity": "critical",
+ "confidence": 1.0,
+ "mitre_technique": "T1558.003",
+ "mitre_tactic": "Credential Access",
+ "evidence_json": '{"hash_count": 1, "accounts": ["svc-sql"], "sample_hash": "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef"}',
+ "remediation": "Rotate service account credentials.",
+ "host": "10.10.10.20",
+ "validated": 0,
+ "false_positive": 0,
+ "discovered_at": "2026-07-12T01:01:00+00:00",
+ },
+ ],
+ 2,
+ )
+
+ def generator_factory(*args: Any, **kwargs: Any) -> Any:
+ return real_report_generator(output_dir=str(tmp_path), **kwargs)
+
+ monkeypatch.setattr(report_gen, "ReportGenerator", generator_factory)
+
+ r = await c.post(
+ f"/reports/{campaign_id}?fmt=json",
+ headers=_auth("admin", "team_lead"),
+ )
+
+ assert r.status_code == 200
+ path = tmp_path / r.json()["filename"]
+ assert path.exists()
+ data = __import__("json").loads(path.read_text(encoding="utf-8"))
+ assert data["summary"]["total_confirmed"] == 2
+ assert data["summary"]["by_severity"]["high"] == 1
+ assert data["summary"]["by_severity"]["critical"] == 1
+ assert data["summary"]["by_module"]["ad.asreproast"] == 1
+ assert data["summary"]["by_module"]["ad.kerberoast"] == 1
+ assert data["findings"]
+ assert data["key_findings"]
+ assert data["campaign"]["targets"] == ["10.10.10.20"]
+ assert data["campaign"]["scope"][0]["cidr"] == "10.10.10.0/24"
+ assert "$krb5asrep$" not in path.read_text(encoding="utf-8")
+ assert "$krb5tgs$" not in path.read_text(encoding="utf-8")
+ assert "validated" not in db.list_findings.await_args.kwargs
+ assert db.list_findings.await_args.kwargs["false_positive"] is False
+
+ @pytest.mark.asyncio # type: ignore[untyped-decorator]
+ async def test_dashboard_run_findings_and_report_use_same_persisted_db_path(
+ self, aclient: Any, tmp_path: Any, monkeypatch: Any
+ ) -> None:
+ c, _, app = aclient
+ import ares.modules.reporting.report_gen as report_gen
+ from ares.api.server import get_db, get_engine
+ from ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severity
+ from ares.core.engine import EngineModuleResult, ModuleStatus
+ from ares.db.database import AresDatabase
+
+ real_report_generator = report_gen.ReportGenerator
+ real_db = await AresDatabase.create(tmp_path / "ares.db")
+ original_db = getattr(app.state, "db", None)
+ campaign = Campaign(
+ name="AD Lab Attack Simulation",
+ client="Internal",
+ operator="admin",
+ targets=["10.10.10.20"],
+ scope=[ScopeEntry(cidr="10.10.10.0/24")],
+ noise_profile=NoiseProfile.NORMAL,
+ )
+ await real_db.save_campaign(campaign)
+
+ class FakeRegistry:
+ def get(self, module_id: str) -> Any:
+ return None
+
+ class FakeEngine:
+ registry = FakeRegistry()
+
+ async def run_module(
+ self,
+ module_id: str,
+ campaign: Any,
+ params: dict[str, Any],
+ actor_role: str = "",
+ ) -> EngineModuleResult:
+ if module_id == "ad.asreproast":
+ finding = Finding(
+ title="ASREPRoast Hashes Captured (1)",
+ description="Captured one AS-REP hash.",
+ severity=Severity.HIGH,
+ validated=True,
+ module_id=module_id,
+ mitre_technique="T1558.004",
+ mitre_tactic="Credential Access",
+ evidence={
+ "hash_count": 1,
+ "sample_hash": "[email protected]:abcdef",
+ },
+ remediation="Require Kerberos pre-authentication.",
+ host="10.10.10.20",
+ )
+ else:
+ finding = Finding(
+ title="Kerberoast Hashes Captured (1)",
+ description="Captured one TGS hash.",
+ severity=Severity.CRITICAL,
+ validated=True,
+ module_id=module_id,
+ mitre_technique="T1558.003",
+ mitre_tactic="Credential Access",
+ evidence={
+ "hash_count": 1,
+ "accounts": ["svc-sql"],
+ "sample_hash": "$krb5tgs$23$*svc-sql$LAB.LOCAL$svc/sql*abcdef",
+ },
+ remediation="Rotate service account credentials.",
+ host="10.10.10.20",
+ )
+ return EngineModuleResult(
+ module_id=module_id,
+ status=ModuleStatus.DONE,
+ findings=[finding],
+ raw_output={"confirmed": 1},
+ duration_ms=12.0,
+ )
+
+ def generator_factory(*args: Any, **kwargs: Any) -> Any:
+ return real_report_generator(output_dir=str(tmp_path / "reports"), **kwargs)
+
+ app.state.db = real_db
+ app.dependency_overrides[get_db] = lambda: real_db
+ app.dependency_overrides[get_engine] = lambda: FakeEngine()
+ monkeypatch.setattr(report_gen, "ReportGenerator", generator_factory)
+ try:
+ common_params = {
+ "dc": "10.10.10.20",
+ "domain": "lab.local",
+ "username": "lab\\operator",
+ "password": "CorrectHorseBatteryStaple!",
+ "use_ldaps": False,
+ }
+ asrep = await c.post(
+ f"/modules/ad.asreproast/run",
+ headers=_auth("admin", "team_lead"),
+ json={
+ "campaign_id": campaign.id,
+ "params": common_params,
+ "dry_run": False,
+ },
+ )
+ kerb = await c.post(
+ f"/modules/ad.kerberoast/run",
+ headers=_auth("admin", "team_lead"),
+ json={
+ "campaign_id": campaign.id,
+ "params": {**common_params, "target_user": "svc-sql"},
+ "dry_run": False,
+ },
+ )
+ assert asrep.status_code == 200
+ assert kerb.status_code == 200
+
+ # Legacy/current dashboard rows may be visible even if the validated
+ # flag is not populated; report hydration must not use a stricter
+ # finder than the dashboard list.
+ await real_db.conn.execute(
+ "UPDATE findings SET validated=0 WHERE campaign_id=?",
+ (campaign.id,),
+ )
+ await real_db.conn.commit()
+
+ findings_response = await c.get(
+ f"/campaigns/{campaign.id}/findings",
+ headers=_auth("admin", "team_lead"),
+ )
+ assert findings_response.status_code == 200
+ assert len(findings_response.json()) == 2
+
+ report_response = await c.post(
+ f"/reports/{campaign.id}?fmt=json",
+ headers=_auth("admin", "team_lead"),
+ )
+ finally:
+ app.dependency_overrides.pop(get_db, None)
+ app.dependency_overrides.pop(get_engine, None)
+ app.state.db = original_db
+ await real_db.close()
+
+ assert report_response.status_code == 200
+ path = tmp_path / "reports" / report_response.json()["filename"]
+ data = __import__("json").loads(path.read_text(encoding="utf-8"))
+ assert data["summary"]["total_confirmed"] == 2
+ assert data["summary"]["by_module"]["ad.asreproast"] == 1
+ assert data["summary"]["by_module"]["ad.kerberoast"] == 1
+ assert data["summary"]["by_severity"]["high"] == 1
+ assert data["summary"]["by_severity"]["critical"] == 1
+ assert len(data["findings"]) >= 2
+ assert len(data["key_findings"]) >= 2
+ assert data["campaign"]["targets"] == ["10.10.10.20"]
+ assert data["campaign"]["scope"][0]["cidr"] == "10.10.10.0/24"
+ assert "T1558.003" in path.read_text(encoding="utf-8")
+ assert "T1558.004" in path.read_text(encoding="utf-8")
+ assert "$krb5asrep$" not in path.read_text(encoding="utf-8")
+ assert "$krb5tgs$" not in path.read_text(encoding="utf-8")
+
@pytest.mark.asyncio # type: ignore[untyped-decorator]
async def test_report_download_rejects_encoded_traversal(
self, aclient: Any, tmp_path: Any, monkeypatch: Any
diff --git a/tests/unit/test_cli_doctor.py b/tests/unit/test_cli_doctor.py
index 7b3e53d..8d3c020 100644
--- a/tests/unit/test_cli_doctor.py
+++ b/tests/unit/test_cli_doctor.py
@@ -4,10 +4,16 @@ import importlib.metadata
import os
import sys
import types
+from collections import namedtuple
+from pathlib import Path
+import pytest
import typer
+VersionInfo = namedtuple("version_info", "major minor micro releaselevel serial")
+
+
def test_doctor_uses_distribution_metadata_for_impacket(monkeypatch, tmp_path, capsys):
from ares.cli.typer_main import doctor
@@ -74,6 +80,84 @@ def test_doctor_reports_broken_optional_import_and_continues(monkeypatch, tmp_pa
assert "socket AF_INET/389" in output
+def test_doctor_guides_windows_ad_impacket_to_python_312(monkeypatch, tmp_path, capsys):
+ from ares.cli.typer_main import doctor
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / ".env").write_text("ARES_SECRET_KEY=test\n", encoding="utf-8")
+ monkeypatch.setattr(sys, "version_info", VersionInfo(3, 11, 9, "final", 0))
+
+ try:
+ doctor()
+ except typer.Exit:
+ pass
+
+ output = capsys.readouterr().out
+ assert "Python 3.11.9" in output
+ assert "Package metadata permits Python 3.10-3.12" in output
+ normalized = " ".join(output.split())
+ assert "Windows AD/Impacket" in normalized
+ assert "Python 3.12" in normalized
+ assert "Windows AD/Impacket Python" in output
+ assert "Python 3.12.x" in output
+
+
+def test_doctor_reports_pdf_capability(monkeypatch, tmp_path, capsys):
+ from ares.cli.typer_main import doctor
+ from ares.modules.reporting import report_gen
+
+ browser = tmp_path / "chrome.exe"
+ browser.write_text("", encoding="utf-8")
+ fake_weasyprint = types.ModuleType("weasyprint")
+ fake_weasyprint.__version__ = "test-pdf"
+
+ class FakeReportGenerator:
+ def __init__(self) -> None:
+ self.output_dir = tmp_path / "reports"
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
+ @staticmethod
+ def _pdf_browser_candidates() -> list[Path]:
+ return [browser]
+
+ @staticmethod
+ def _probe_writable_dir(path: Path) -> None:
+ path.mkdir(parents=True, exist_ok=True)
+ probe = path / ".probe"
+ probe.write_text("ok", encoding="utf-8")
+ probe.unlink()
+
+ def _create_pdf_browser_workspace(self) -> tuple[Path, Path, Path]:
+ work_path = tmp_path / "pdf-work"
+ profile_dir = work_path / "profile"
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ return work_path, profile_dir, work_path / "report.html"
+
+ def _run_pdf_browser(self, cmd: list[str]): # pragma: no cover - must not run
+ raise AssertionError("doctor must not launch a PDF browser")
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / ".env").write_text("ARES_SECRET_KEY=test\n", encoding="utf-8")
+ monkeypatch.setenv("ARES_PDF_BROWSER", str(browser))
+ monkeypatch.setitem(sys.modules, "weasyprint", fake_weasyprint)
+ monkeypatch.setattr(report_gen, "ReportGenerator", FakeReportGenerator)
+
+ try:
+ doctor()
+ except typer.Exit:
+ pass
+
+ output = capsys.readouterr().out
+ assert "PDF WeasyPrint" in output
+ assert "test-pdf" in output
+ assert "PDF ARES_PDF_BROWSER" in output
+ assert "chrome.exe" in output
+ assert "exists=True" in output
+ assert "PDF browser detected" in output
+ assert "PDF browser profile temp dir writable" in output
+ assert "PDF report output dir writable" in output
+
+
def test_setup_entrypoint_routes_to_python_native_setup(monkeypatch):
from ares.cli import typer_main
@@ -128,3 +212,26 @@ def test_python_setup_posix_keeps_shell_helper_optional(tmp_path, capsys):
assert "Developer helper available: scripts/setup.sh (optional)." in output
assert "/bin/bash" not in output
assert (tmp_path / ".env").exists()
+
+
+def test_python_setup_rejects_python_313_before_writing_env(tmp_path, capsys):
+ from ares.cli.typer_main import _run_python_setup
+
+ (tmp_path / ".env.example").write_text(
+ "ARES_SECRET_KEY=\nARES_ENCRYPTION_KEY=\nARES_DEFAULT_ADMIN_PASSWORD=\n",
+ encoding="utf-8",
+ )
+
+ with pytest.raises(SystemExit):
+ _run_python_setup(
+ root=tmp_path,
+ platform_name="win32",
+ os_name="nt",
+ version_info=VersionInfo(3, 13, 0, "final", 0),
+ )
+
+ output = capsys.readouterr().out
+ assert "Python: 3.13.0" in output
+ assert "Python 3.10-3.12 is required" in output
+ assert "Python 3.12.x" in output
+ assert not (tmp_path / ".env").exists()
diff --git a/tests/unit/test_cli_reporting_goal_planning.py b/tests/unit/test_cli_reporting_goal_planning.py
index 9311709..5b3fba8 100644
--- a/tests/unit/test_cli_reporting_goal_planning.py
+++ b/tests/unit/test_cli_reporting_goal_planning.py
@@ -212,8 +212,15 @@ class TestReportGenerator:
for i in range(1, 4):
assert f"Test Finding {i}" in md
- def test_generate_all_formats(self):
+ def test_generate_all_formats(self, monkeypatch):
from ares.modules.reporting.report_gen import ReportGenerator
+
+ def fake_pdf(self, campaign, graph_json):
+ path = self._out(campaign, "pdf")
+ path.write_bytes(b"%PDF-1.4\n% unit fake\n")
+ return path
+
+ monkeypatch.setattr(ReportGenerator, "_gen_pdf", fake_pdf)
campaign = _make_campaign(n_findings=1)
with tempfile.TemporaryDirectory() as tmpdir:
gen = ReportGenerator(output_dir=tmpdir)
diff --git a/tests/unit/test_engine.py b/tests/unit/test_engine.py
index 3189b28..612933b 100644
--- a/tests/unit/test_engine.py
+++ b/tests/unit/test_engine.py
@@ -73,6 +73,78 @@ class TestAsyncEngine:
assert result.status == ModuleStatus.FAILED
assert "not found" in (result.error or "")
+ @pytest.mark.asyncio
+ async def test_kerberoast_flat_dashboard_params_reach_execution(
+ self, settings: AresSettings, campaign: Campaign
+ ) -> None:
+ """Flat dashboard fields must satisfy Kerberoast's credential contract."""
+ from ares.modules.ad.kerberoast import KerberoastModule
+ from ares.modules.base import ModuleResult
+
+ engine = AresEngine(settings=settings)
+ engine.load_modules()
+ captured: dict[str, Any] = {}
+
+ async def fake_execute(self_unused: Any, ctx: Any) -> ModuleResult:
+ captured["params"] = dict(ctx.params)
+ return ModuleResult(
+ status="success",
+ raw={"reached": True},
+ module_id="ad.kerberoast",
+ )
+
+ params = {
+ "dc": "10.0.0.5",
+ "domain": "corp.local",
+ "username": "svc-roast",
+ "password": "Passw0rd!",
+ "use_ldaps": False,
+ "target_user": "sqlsvc",
+ }
+ with patch.object(KerberoastModule, "execute", fake_execute):
+ result = await engine.run_module(
+ "ad.kerberoast",
+ campaign,
+ params,
+ actor_role="team_lead",
+ )
+
+ assert result.status == ModuleStatus.DONE
+ assert captured["params"] == params
+
+ @pytest.mark.asyncio
+ async def test_kerberoast_still_blocks_stealth_profile(
+ self, settings: AresSettings, campaign: Campaign
+ ) -> None:
+ from ares.core.campaign import NoiseProfile
+ from ares.modules.ad.kerberoast import KerberoastModule
+
+ campaign.noise_profile = NoiseProfile.STEALTH
+ engine = AresEngine(settings=settings)
+ engine.load_modules()
+
+ async def unexpected_execute(self_unused: Any, ctx: Any) -> Any:
+ raise AssertionError("stealth profile must block before execution")
+
+ params = {
+ "dc": "10.0.0.5",
+ "domain": "corp.local",
+ "username": "svc-roast",
+ "password": "Passw0rd!",
+ "use_ldaps": False,
+ "target_user": "sqlsvc",
+ }
+ with patch.object(KerberoastModule, "execute", unexpected_execute):
+ result = await engine.run_module(
+ "ad.kerberoast",
+ campaign,
+ params,
+ actor_role="team_lead",
+ )
+
+ assert result.status == ModuleStatus.FAILED
+ assert "blocked in STEALTH profile" in (result.error or "")
+
@pytest.mark.asyncio
async def test_run_module_timeout(
self, settings: AresSettings, campaign: Campaign
diff --git a/tests/unit/test_final_hardening.py b/tests/unit/test_final_hardening.py
index d48cd4f..dc2e189 100644
--- a/tests/unit/test_final_hardening.py
+++ b/tests/unit/test_final_hardening.py
@@ -139,6 +139,23 @@ class TestCleanupGuarantee:
finally:
cleanup_credential_artifacts("reopen-test")
+ def test_secure_mkstemp_falls_back_when_fchmod_unavailable(self, monkeypatch):
+ """Windows/Python builds without os.fchmod must still create secure temp files."""
+ from ares.core.security import secure_mkstemp, cleanup_credential_artifacts
+ self._reset_tracking()
+ monkeypatch.delattr(os, "fchmod", raising=False)
+
+ p, fd = secure_mkstemp(suffix=".ccache", campaign_id="no-fchmod-test")
+ os.close(fd)
+ try:
+ assert os.path.exists(p)
+ if os.name != "nt":
+ assert stat.S_IMODE(os.stat(p).st_mode) == 0o600
+ else:
+ assert os.access(p, os.R_OK | os.W_OK)
+ finally:
+ cleanup_credential_artifacts("no-fchmod-test")
+
def test_cleanup_always_runs_on_success(self):
"""Cleanup works after successful operation."""
from ares.core.security import secure_mkstemp, cleanup_credential_artifacts
diff --git a/tests/unit/test_module_coverage.py b/tests/unit/test_module_coverage.py
index e62ce72..e6b18af 100644
--- a/tests/unit/test_module_coverage.py
+++ b/tests/unit/test_module_coverage.py
@@ -491,3 +491,157 @@ class TestLocalAdminCredsConsistency:
)
except ImportError:
pass # optional deps not installed — skip
+
+
+class TestDashboardModuleSchemaContracts:
+ CONTRACT_MODULES = [
+ "ad.asreproast",
+ "ad.kerberoast",
+ "ad.adcs",
+ "ad.delegation_abuse",
+ "cloud.azure_ad",
+ "lateral.mssql",
+ "lateral.ntlm_relay",
+ "lateral.wmiexec",
+ "lateral.winrm",
+ "lateral.rdp",
+ "credential.golden_ticket",
+ "linux.ld_preload",
+ "linux.nfs_escape",
+ "linux.service_hijack",
+ ]
+
+ def test_required_module_schemas_are_renderable_by_dashboard_form(self):
+ from pathlib import Path
+
+ from ares.modules.params import MODULE_PARAMS
+
+ frontend = Path("frontend/src/App.tsx").read_text(encoding="utf-8")
+ assert "Object.entries(schema ?? {})" in frontend
+ assert "field.required" in frontend
+ assert "required={field.required}" in frontend
+ assert "buildModuleRunPayload(campaignId, params, dryRun)" in frontend
+
+ missing = [module_id for module_id in self.CONTRACT_MODULES if module_id not in MODULE_PARAMS]
+ assert not missing
+
+ for module_id in self.CONTRACT_MODULES:
+ schema = MODULE_PARAMS[module_id].schema_for_api()
+ assert schema, f"{module_id} must expose dashboard param_schema"
+ for name, field in schema.items():
+ assert "required" in field, f"{module_id}.{name} missing required flag"
+ assert "type" in field, f"{module_id}.{name} missing renderable type"
+
+ required_fields = {
+ name for name, field in schema.items() if field.get("required") is True
+ }
+ assert required_fields <= set(schema), module_id
+
+ def test_confirmed_schema_keys_match_runtime_contracts(self):
+ from ares.modules.params import MODULE_PARAMS
+
+ adcs_schema = MODULE_PARAMS["ad.adcs"].schema_for_api()
+ assert {"exploit_esc1", "target_user"} <= set(adcs_schema)
+ assert {"ca_server", "mode", "template"}.isdisjoint(adcs_schema)
+
+ delegation_schema = MODULE_PARAMS["ad.delegation_abuse"].schema_for_api()
+ assert {"target_computer", "impersonate_user", "target_service"} <= set(
+ delegation_schema
+ )
+ assert "target_host" not in delegation_schema
+
+ azure_ad_schema = MODULE_PARAMS["cloud.azure_ad"].schema_for_api()
+ assert {"client_secret", "access_token", "technique"} <= set(
+ azure_ad_schema
+ )
+ assert "mode" not in azure_ad_schema
+
+ def test_mssql_execute_uses_dashboard_schema_field_names(self):
+ from ares.modules.lateral.mssql import MSSQLModule
+
+ mod, _ = _make_module(MSSQLModule)
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return [], {"ok": True}
+
+ mod.run = fake_run
+ _run(
+ mod.execute(
+ _ctx(
+ params={
+ "target": "10.0.0.25",
+ "username": "sa",
+ "password": "Passw0rd!",
+ "technique": "linked",
+ "linked": "SQL-LINK-01",
+ "listener": "10.0.0.10",
+ }
+ )
+ )
+ )
+
+ assert captured["linked"] == "SQL-LINK-01"
+ assert captured["listener"] == "10.0.0.10"
+
+ def test_golden_ticket_form_fields_satisfy_shared_credential_requires(self):
+ from ares.modules.credential.golden_ticket import GoldenTicketModule
+
+ mod, _ = _make_module(GoldenTicketModule)
+ _run(
+ mod.validate(
+ _ctx(
+ params={
+ "target": "10.0.0.5",
+ "domain": "corp.local",
+ "username": "Administrator",
+ "krbtgt_hash": "0123456789abcdef0123456789abcdef",
+ "domain_sid": "S-1-5-21-1111111111-2222222222-3333333333",
+ }
+ )
+ )
+ )
+
+ @pytest.mark.parametrize(
+ "module_path,class_name",
+ [
+ ("ares.modules.linux.ld_preload", "LDPreloadModule"),
+ ("ares.modules.linux.nfs_escape", "NFSEscapeModule"),
+ ("ares.modules.linux.service_hijack", "ServiceHijackModule"),
+ ],
+ )
+ def test_linux_ssh_modules_use_dashboard_schema_field_names(
+ self, module_path, class_name
+ ):
+ import importlib
+
+ module = importlib.import_module(module_path)
+ cls = getattr(module, class_name)
+ mod, _ = _make_module(cls)
+ captured = {}
+
+ async def fake_run(**kwargs):
+ captured.update(kwargs)
+ return [], {"ok": True}
+
+ mod.run = fake_run
+ _run(
+ mod.execute(
+ _ctx(
+ params={
+ "target": "10.0.0.30",
+ "username": "ubuntu",
+ "password": "Passw0rd!",
+ "key_path": "C:/keys/id_rsa",
+ "ssh_port": 2222,
+ }
+ )
+ )
+ )
+
+ assert captured["host"] == "10.0.0.30"
+ assert captured["ssh_user"] == "ubuntu"
+ assert captured["ssh_key"] == "C:/keys/id_rsa"
+ assert captured["ssh_pass"] == "Passw0rd!"
+ assert captured["ssh_port"] == 2222