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: harden Windows PDF export preflight

Mafifrizie9bb8c397c1f
diff --git a/QUICKSTART.md b/QUICKSTART.md
index f66e962..5de9e33 100644
--- a/QUICKSTART.md
+++ b/QUICKSTART.md
@@ -36,7 +36,7 @@ Notes:
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 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.
+- 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 from normal non-Administrator PowerShell. If needed, set `ARES_PDF_BROWSER=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe` for the current user or shell. WeasyPrint on Windows needs native GTK/Pango libraries in addition to the pip package.
## 3. Configure Secrets
@@ -337,6 +337,7 @@ Common examples:
| --- | --- |
| `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. |
+| `PDF smoke` failed | Run `ares doctor --pdf-smoke` from normal non-Administrator PowerShell and check the WeasyPrint GTK/Pango or Edge/Chrome fallback guidance. |
| `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 7071bf7..2c0531f 100644
--- a/README.md
+++ b/README.md
@@ -305,6 +305,12 @@ Security page, but role assignment is done at account creation time through
- PDF output through WeasyPrint when available, with an Edge/Chrome/Chromium
browser fallback for local environments that do not have WeasyPrint native
libraries installed.
+- On Windows, use Python 3.12.x from a normal non-Administrator PowerShell for
+ dashboard PDF export. If auto-detection needs help, set
+ `ARES_PDF_BROWSER=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`
+ for the current user or shell.
+- WeasyPrint on Windows needs native GTK/Pango libraries in addition to the pip
+ package; run `ares doctor --pdf-smoke` to verify the active PDF backend.
- ARES branding in generated reports with footer-safe page spacing.
- Findings, readable evidence tables, severity, timeline, MITRE, and
remediation-oriented sections.
@@ -552,7 +558,9 @@ Production build assets are served by FastAPI from `frontend/dist` at
Platform notes:
-- Windows: use PowerShell and `.\.venv\Scripts\python.exe`.
+- Windows: use normal non-Administrator PowerShell and
+ `.\.venv\Scripts\python.exe`. The Windows release path for the dashboard,
+ PDF browser fallback, and Windows AD/Impacket lab modules is Python 3.12.x.
- Linux, Kali, and macOS: use `source .venv/bin/activate`.
- 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.
diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.py
index 75a602f..475fe44 100644
--- a/ares/cli/typer_main.py
+++ b/ares/cli/typer_main.py
@@ -33,7 +33,7 @@ import threading
import time
import webbrowser
from pathlib import Path
-from typing import Callable, Optional
+from typing import Any, Callable, Optional
import typer
from rich.console import Console
@@ -1081,8 +1081,37 @@ def _display_result(module_id: str, result: dict) -> None:
# ── doctor command ────────────────────────────────────────────────────────────
+def _run_pdf_smoke_check(
+ pdf_generator: Any,
+ check: Callable[[str, str, str], None],
+) -> None:
+ """Run the PDF smoke generator and report the result through doctor output."""
+ from ares.modules.reporting.report_gen import ReportDependencyError
+
+ try:
+ smoke_path = pdf_generator.generate_pdf_smoke()
+ if smoke_path.read_bytes()[:5] == b"%PDF-":
+ check(
+ "PDF smoke",
+ "ok",
+ f"{smoke_path} bytes={smoke_path.stat().st_size}",
+ )
+ else:
+ check("PDF smoke", "fail", f"{smoke_path} is not a PDF")
+ except ReportDependencyError as exc:
+ check("PDF smoke", "fail", str(exc))
+ except OSError as exc:
+ check("PDF smoke", "fail", str(exc))
+
+
@app.command("doctor")
-def doctor() -> None:
+def doctor(
+ pdf_smoke: bool = typer.Option(
+ False,
+ "--pdf-smoke",
+ help="Render a tiny PDF through the same runtime path used by dashboard export.",
+ ),
+) -> None:
"""Check all prerequisites and configuration. Run this first."""
import importlib, shutil, os, re
from importlib import metadata as importlib_metadata
@@ -1233,46 +1262,45 @@ def doctor() -> None:
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
+ import ares.modules.reporting.report_gen as report_gen_module
pdf_generator = ReportGenerator()
+ try:
+ weasyprint = importlib.import_module("weasyprint")
+ check(
+ "PDF WeasyPrint",
+ "ok",
+ getattr(weasyprint, "__version__", "") or "available",
+ )
+ except Exception as exc:
+ check(
+ "PDF WeasyPrint",
+ "warn",
+ report_gen_module.ReportGenerator._pdf_backend_failure_detail(exc),
+ )
+
+ configured_pdf_browser = os.environ.get("ARES_PDF_BROWSER")
+ if configured_pdf_browser:
+ configured_pdf_browser_path = Path(configured_pdf_browser).expanduser()
+ check(
+ "PDF ARES_PDF_BROWSER",
+ "ok" if configured_pdf_browser_path.exists() else "warn",
+ f"{configured_pdf_browser_path} exists={configured_pdf_browser_path.exists()}",
+ )
+ else:
+ check(
+ "PDF ARES_PDF_BROWSER",
+ "warn",
+ "not set; auto-detecting Edge/Chrome/Chromium",
+ )
+
pdf_browsers = ReportGenerator._pdf_browser_candidates()
if pdf_browsers:
check("PDF browser detected", "ok", str(pdf_browsers[0]))
+ browser_order = " -> ".join(path.name for path in pdf_browsers)
+ check("PDF browser order", "ok", browser_order)
else:
check(
"PDF browser detected",
@@ -1280,6 +1308,27 @@ def doctor() -> None:
"No Edge/Chrome/Chromium found; set ARES_PDF_BROWSER",
)
+ if os.name == "nt":
+ elevated = pdf_generator._windows_session_is_elevated()
+ check(
+ "PDF Windows elevated session",
+ "warn" if elevated else "ok",
+ f"elevated={elevated}",
+ )
+ edge = next(
+ (path for path in pdf_browsers if path.name.lower() == "msedge.exe"),
+ None,
+ )
+ if edge is None:
+ check("PDF Edge current session", "warn", "Edge not detected")
+ else:
+ edge_skip_reason = pdf_generator._pdf_browser_skip_reason(edge)
+ check(
+ "PDF Edge current session",
+ "warn" if edge_skip_reason else "ok",
+ edge_skip_reason or "Edge is usable in this session",
+ )
+
pdf_work_path: Path | None = None
try:
pdf_work_path, pdf_profile_dir, _pdf_html_path = (
@@ -1305,6 +1354,9 @@ def doctor() -> None:
)
except OSError as exc:
check("PDF report output dir writable", "warn", str(exc))
+
+ if pdf_smoke:
+ _run_pdf_smoke_check(pdf_generator, check)
except Exception as exc:
check("PDF browser fallback", "warn", str(exc)[:80])
diff --git a/ares/modules/reporting/report_gen.py b/ares/modules/reporting/report_gen.py
index 9212a86..6fd48cb 100644
--- a/ares/modules/reporting/report_gen.py
+++ b/ares/modules/reporting/report_gen.py
@@ -62,6 +62,19 @@ REMEDIATION_SLA = {
BROWSER_PDF_TIMEOUT_SECONDS = 15
PDF_ARTIFACT_WAIT_SECONDS = 3.0
+WINDOWS_EDGE_ELEVATED_PDF_MESSAGE = (
+ "PDF browser fallback is not supported from elevated Windows sessions with "
+ "Edge. Run PowerShell normally, set ARES_PDF_BROWSER to a working browser, "
+ "or install WeasyPrint native GTK/Pango dependencies."
+)
+WINDOWS_WEASYPRINT_NATIVE_HINT = (
+ "WeasyPrint imported from pip, but Windows native GTK/Pango libraries are "
+ "missing. Install the native GTK/Pango runtime or use the Edge/Chrome "
+ "browser fallback from normal non-Administrator PowerShell."
+)
+_PDF_SMOKE_HTML = """<!DOCTYPE html>
+<html><head><meta charset="utf-8"><title>ARES PDF smoke</title></head>
+<body><h1>ARES PDF smoke</h1><p>PDF export preflight.</p></body></html>"""
_REDACTED_EVIDENCE = "[REDACTED sensitive evidence]"
_SENSITIVE_EVIDENCE_KEYS = {
"hash",
@@ -1716,10 +1729,18 @@ class ReportGenerator:
output_dir: str = "~/.ares/reports",
*,
include_sensitive_evidence: bool = False,
+ strict_pdf_browser: bool | None = None,
) -> None:
self.output_dir = Path(output_dir).expanduser()
self.output_dir.mkdir(parents=True, exist_ok=True)
self.include_sensitive_evidence = include_sensitive_evidence
+ if strict_pdf_browser is None:
+ strict_pdf_browser = os.environ.get("ARES_PDF_BROWSER_STRICT", "").lower() in {
+ "1",
+ "true",
+ "yes",
+ }
+ self.strict_pdf_browser = strict_pdf_browser
self._last_pdf_browser_error = ""
def generate(
@@ -1750,6 +1771,33 @@ class ReportGenerator:
logger.warning("report_format_failed", fmt=fmt, error=str(e))
return results
+ def generate_pdf_smoke(self) -> Path:
+ """Render a tiny PDF through the same backends used by dashboard export."""
+ smoke_path = self.output_dir / "ares_pdf_smoke.pdf"
+ smoke_path.unlink(missing_ok=True)
+ backend_error = ""
+ try:
+ from weasyprint import HTML as WP
+
+ WP(string=_PDF_SMOKE_HTML, base_url=str(self.output_dir.resolve())).write_pdf(
+ str(smoke_path)
+ )
+ if self._pdf_artifact_ready(smoke_path):
+ return smoke_path
+ backend_error = (
+ f"WeasyPrint did not create a valid PDF artifact at {smoke_path}."
+ )
+ except (ImportError, OSError) as exc:
+ backend_error = self._pdf_backend_failure_detail(exc)
+ logger.warning("pdf_smoke_backend_unavailable", error=backend_error)
+
+ if self._write_pdf_with_browser(_PDF_SMOKE_HTML, smoke_path):
+ return smoke_path
+ detail = self._last_pdf_browser_error or (
+ "No local Chromium-compatible PDF browser was available."
+ )
+ raise ReportDependencyError(f"{backend_error} {detail}".strip())
+
# ── JSON ──────────────────────────────────────────────────────────────
def _gen_json(self, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
@@ -1948,20 +1996,21 @@ class ReportGenerator:
str(pdf_path)
)
except (ImportError, OSError) as exc:
- logger.warning("pdf_backend_unavailable", error=str(exc))
+ backend_detail = self._pdf_backend_failure_detail(exc)
+ logger.warning("pdf_backend_unavailable", error=backend_detail)
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(f"{backend_detail} {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:
+ if not self._pdf_artifact_ready(pdf_path):
raise ReportDependencyError(
f"PDF backend did not create a downloadable artifact at {pdf_path}"
)
@@ -1973,18 +2022,22 @@ 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 = ""
+ errors: list[str] = []
for browser in self._pdf_browser_candidates():
+ strict_current = self._is_strict_configured_pdf_browser(browser)
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")
except OSError as exc:
- self._last_pdf_browser_error = (
+ message = (
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."
)
+ errors.append(message)
+ self._last_pdf_browser_error = "\n".join(errors)
logger.warning(
"pdf_browser_profile_unusable",
browser=str(browser),
@@ -1992,17 +2045,21 @@ class ReportGenerator:
)
if work_path is not None:
shutil.rmtree(work_path, ignore_errors=True)
+ if strict_current:
+ break
continue
skip_reason = self._pdf_browser_skip_reason(browser)
if skip_reason:
- self._last_pdf_browser_error = (
+ message = (
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."
)
+ errors.append(message)
+ self._last_pdf_browser_error = "\n".join(errors)
logger.warning(
"pdf_browser_skipped",
browser=str(browser),
@@ -2011,6 +2068,8 @@ class ReportGenerator:
)
if work_path is not None:
shutil.rmtree(work_path, ignore_errors=True)
+ if strict_current:
+ break
continue
cmd = [
@@ -2035,7 +2094,7 @@ class ReportGenerator:
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 = (
+ message = (
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 "
@@ -2044,6 +2103,8 @@ class ReportGenerator:
"Chromium/Edge/Chrome executable or install ARES with the "
"PDF extra/native WeasyPrint dependencies."
)
+ errors.append(message)
+ self._last_pdf_browser_error = "\n".join(errors)
logger.warning(
"pdf_browser_failed",
browser=str(browser),
@@ -2054,7 +2115,7 @@ class ReportGenerator:
stderr=completed.stderr[-500:],
)
except subprocess.TimeoutExpired as exc:
- self._last_pdf_browser_error = (
+ message = (
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}. "
@@ -2062,27 +2123,32 @@ class ReportGenerator:
"to a working Chromium/Edge/Chrome executable or install "
"ARES with the PDF extra/native WeasyPrint dependencies."
)
+ errors.append(message)
+ self._last_pdf_browser_error = "\n".join(errors)
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 = (
+ message = (
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."
)
+ errors.append(message)
+ self._last_pdf_browser_error = "\n".join(errors)
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 strict_current:
+ break
if not self._last_pdf_browser_error:
self._last_pdf_browser_error = (
"PDF generation requires the optional WeasyPrint backend or a "
@@ -2101,22 +2167,47 @@ class ReportGenerator:
timeout=BROWSER_PDF_TIMEOUT_SECONDS,
)
+ def _is_strict_configured_pdf_browser(self, browser: Path) -> bool:
+ if not self.strict_pdf_browser:
+ return False
+ configured = os.environ.get("ARES_PDF_BROWSER")
+ if not configured:
+ return False
+ try:
+ return browser.resolve() == Path(configured).expanduser().resolve()
+ except OSError:
+ return False
+
def _pdf_browser_skip_reason(self, browser: Path) -> str:
if (
- os.name == "nt"
+ self._is_windows_host()
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 WINDOWS_EDGE_ELEVATED_PDF_MESSAGE
return ""
+ @staticmethod
+ def _pdf_backend_failure_detail(exc: BaseException) -> str:
+ message = str(exc) or repr(exc)
+ lowered = message.lower()
+ native_markers = ("libgobject", "pango", "gtk", "gdk", "cairo")
+ if ReportGenerator._is_windows_host() and any(
+ marker in lowered for marker in native_markers
+ ):
+ return f"{WINDOWS_WEASYPRINT_NATIVE_HINT} Original error: {message}"
+ return (
+ "WeasyPrint PDF backend is unavailable. Install the PDF extra/native "
+ f"runtime or use browser fallback. Original error: {exc.__class__.__name__}: {message}"
+ )
+
+ @staticmethod
+ def _is_windows_host() -> bool:
+ return os.name == "nt"
+
@staticmethod
def _windows_session_is_elevated() -> bool:
- if os.name != "nt":
+ if not ReportGenerator._is_windows_host():
return False
try:
import ctypes
@@ -2177,7 +2268,11 @@ class ReportGenerator:
deadline = time.monotonic() + PDF_ARTIFACT_WAIT_SECONDS
while time.monotonic() <= deadline:
try:
- if pdf_path.exists() and pdf_path.stat().st_size > 0:
+ if (
+ pdf_path.exists()
+ and pdf_path.stat().st_size > 0
+ and pdf_path.read_bytes()[:5] == b"%PDF-"
+ ):
return True
except OSError:
pass
@@ -2189,30 +2284,24 @@ class ReportGenerator:
configured = os.environ.get("ARES_PDF_BROWSER")
raw: list[Path] = []
if configured:
- raw.append(Path(configured))
- for name in (
- "msedge",
- "chrome",
- "chromium",
- "google-chrome",
- "chromium-browser",
- ):
- found = shutil.which(name)
- if found:
- raw.append(Path(found))
- if os.name == "nt":
- raw.extend(
- [
- Path(
- r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
- ),
- Path(r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"),
- Path(r"C:\Program Files\Google\Chrome\Application\chrome.exe"),
- Path(
- r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
- ),
- ]
- )
+ raw.append(Path(configured).expanduser())
+ if ReportGenerator._is_windows_host():
+ raw.extend(ReportGenerator._windows_browser_default_paths())
+ for name in ("msedge", "chrome", "chromium"):
+ found = shutil.which(name)
+ if found:
+ raw.append(Path(found))
+ else:
+ for name in (
+ "chrome",
+ "chromium",
+ "google-chrome",
+ "chromium-browser",
+ "msedge",
+ ):
+ found = shutil.which(name)
+ if found:
+ raw.append(Path(found))
candidates: list[Path] = []
seen: set[str] = set()
@@ -2227,6 +2316,15 @@ class ReportGenerator:
candidates.append(resolved)
return candidates
+ @staticmethod
+ def _windows_browser_default_paths() -> list[Path]:
+ return [
+ Path(r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"),
+ Path(r"C:\Program Files\Microsoft\Edge\Application\msedge.exe"),
+ Path(r"C:\Program Files\Google\Chrome\Application\chrome.exe"),
+ Path(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"),
+ ]
+
def _out(self, campaign: Campaign, ext: str) -> Path:
import re as _re
diff --git a/docs/api-reference.md b/docs/api-reference.md
index b5c5cef..11892b2 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -342,9 +342,12 @@ Supported formats: `html` | `pdf` | `json` | `markdown`
PDF generation uses the report renderer internally and returns a PDF artifact
for `format: "pdf"`. The server uses WeasyPrint when available and can fall
back to a local Chromium-compatible browser in local environments where
-WeasyPrint native libraries are not installed. HTML and PDF reports render
-finding evidence as readable tables and key-value rows where possible. Use
-`json` output when you need raw machine-readable report data.
+WeasyPrint native libraries are not installed. On Windows, use Python 3.12.x
+from normal non-Administrator PowerShell; WeasyPrint needs native GTK/Pango
+libraries in addition to the pip package. Use `ares doctor --pdf-smoke` to
+validate the active PDF backend. HTML and PDF reports render finding evidence
+as readable tables and key-value rows where possible. Use `json` output when
+you need raw machine-readable report data.
**Response:** `200 OK`
```json
diff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.md
index 0ee68d2..f085009 100644
--- a/docs/dashboard-guide.md
+++ b/docs/dashboard-guide.md
@@ -301,6 +301,11 @@ Formats:
- JSON.
- PDF through WeasyPrint when available, with an Edge/Chrome/Chromium browser
fallback for local environments that do not have WeasyPrint native libraries.
+- On Windows, run the dashboard from normal non-Administrator PowerShell with
+ Python 3.12.x. If browser auto-detection needs help, set
+ `ARES_PDF_BROWSER=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe`.
+- WeasyPrint on Windows requires native GTK/Pango libraries in addition to the
+ pip package; use `ares doctor --pdf-smoke` to validate the active backend.
HTML and PDF reports render finding evidence as readable tables and key-value
rows where possible. Use JSON output when you need raw machine-readable data.
@@ -487,7 +492,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. | 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. |
+| PDF generation fails | No PDF backend or browser fallback is available. | Run `ares doctor --pdf-smoke` from normal non-Administrator PowerShell to check WeasyPrint, native GTK/Pango libraries, `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. 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.
+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, Windows PDF browser fallback, 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 aab4c29..9dfb095 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1277,6 +1277,8 @@ function ReportsPage() {
}
});
const persistedGenerateResult = lastGenerateResult?.key === reportResultKey ? lastGenerateResult : null;
+ const generateIssue = generate.error ?? (persistedGenerateResult?.isError ? persistedGenerateResult.payload : undefined);
+ const pdfIssueHint = format === "pdf" ? pdfFailureHint(generateIssue) : "";
const download = useMutation({
mutationFn: async (item: ReportItem) => {
const blob = await api.downloadReport(campaignId, item.filename);
@@ -1333,8 +1335,14 @@ function ReportsPage() {
</button>
</div>
{warning && <p className="notice notice-danger mt-3">{warning}</p>}
+ {pdfIssueHint && (
+ <p className="notice notice-danger mt-3">
+ <AlertTriangle size={16} />
+ {pdfIssueHint}
+ </p>
+ )}
<DataPanel
- title={(generate.error ?? (persistedGenerateResult?.isError ? persistedGenerateResult.payload : undefined)) ? "Generate Error" : "Generate Result"}
+ title={generateIssue ? "Generate Error" : "Generate Result"}
data={generate.error ?? generate.data ?? persistedGenerateResult?.payload}
/>
</section>
@@ -3177,4 +3185,27 @@ function serializeError(value: unknown): unknown {
return value;
}
+function pdfFailureHint(value: unknown): string {
+ if (!value) return "";
+ const serialized = serializeError(value);
+ const text = typeof serialized === "string"
+ ? serialized
+ : JSON.stringify(serialized);
+ const normalized = text.toLowerCase();
+ if (normalized.includes("elevated windows") || normalized.includes("administrator powershell")) {
+ return "PDF export is blocked from this elevated Windows session. Run PowerShell normally, or set ARES_PDF_BROWSER to a working non-Edge browser.";
+ }
+ if (
+ normalized.includes("gtk")
+ || normalized.includes("pango")
+ || normalized.includes("libgobject")
+ ) {
+ return "WeasyPrint needs native GTK/Pango libraries on Windows. Use the browser fallback from normal PowerShell or install those native libraries.";
+ }
+ if (normalized.includes("no downloadable pdf") || normalized.includes("pdf smoke")) {
+ return "PDF export did not create a valid artifact. Run ares doctor --pdf-smoke to verify the local PDF backend and browser fallback.";
+ }
+ return "";
+}
+
export default App;
diff --git a/tests/unit/db/test_database.py b/tests/unit/db/test_database.py
index 033782f..9cbfdc2 100644
--- a/tests/unit/db/test_database.py
+++ b/tests/unit/db/test_database.py
@@ -26,6 +26,8 @@ from ares.modules.reporting.report_gen import (
BROWSER_PDF_TIMEOUT_SECONDS,
ReportDependencyError,
ReportGenerator,
+ WINDOWS_EDGE_ELEVATED_PDF_MESSAGE,
+ WINDOWS_WEASYPRINT_NATIVE_HINT,
)
@@ -423,6 +425,113 @@ class TestReportGenerator:
assert pdf_path.stat().st_size > 0
assert "ares-pdf-browser-" not in str(pdf_path)
+ def test_windows_pdf_browser_order_prefers_edge_before_chrome(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import ares.modules.reporting.report_gen as report_gen_module
+
+ edge = tmp_path / "msedge.exe"
+ chrome = tmp_path / "chrome.exe"
+ edge.write_text("", encoding="utf-8")
+ chrome.write_text("", encoding="utf-8")
+ monkeypatch.delenv("ARES_PDF_BROWSER", raising=False)
+ monkeypatch.setattr(ReportGenerator, "_is_windows_host", staticmethod(lambda: True))
+ monkeypatch.setattr(
+ ReportGenerator,
+ "_windows_browser_default_paths",
+ staticmethod(lambda: [edge, chrome]),
+ )
+ monkeypatch.setattr(report_gen_module.shutil, "which", lambda name: None)
+
+ candidates = ReportGenerator._pdf_browser_candidates()
+
+ assert candidates[:2] == [edge.resolve(), chrome.resolve()]
+
+ def test_pdf_browser_uses_configured_path_first_and_falls_back(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ configured = tmp_path / "configured-chrome.exe"
+ fallback = tmp_path / "msedge.exe"
+ configured.write_text("", encoding="utf-8")
+ fallback.write_text("", encoding="utf-8")
+ monkeypatch.setenv("ARES_PDF_BROWSER", str(configured))
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ pdf_path = tmp_path / "report.pdf"
+ calls: list[Path] = []
+
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ calls.append(Path(command[0]))
+ if Path(command[0]) == fallback:
+ 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%fallback\n")
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ def fast_artifact_ready(path: Path) -> bool:
+ return path.exists() and path.read_bytes().startswith(b"%PDF-")
+
+ with (
+ patch.object(gen, "_pdf_browser_candidates", return_value=[configured, fallback]),
+ patch.object(gen, "_run_pdf_browser", side_effect=fake_run),
+ patch.object(gen, "_pdf_artifact_ready", side_effect=fast_artifact_ready),
+ ):
+ assert gen._write_pdf_with_browser("<html></html>", pdf_path) is True
+
+ assert calls == [configured, fallback]
+ assert pdf_path.read_bytes().startswith(b"%PDF-")
+ assert "configured-chrome.exe" in gen._last_pdf_browser_error
+ assert "no downloadable PDF was created" in gen._last_pdf_browser_error
+
+ def test_strict_configured_pdf_browser_does_not_fall_back(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ configured = tmp_path / "configured-chrome.exe"
+ fallback = tmp_path / "msedge.exe"
+ configured.write_text("", encoding="utf-8")
+ fallback.write_text("", encoding="utf-8")
+ monkeypatch.setenv("ARES_PDF_BROWSER", str(configured))
+ gen = ReportGenerator(output_dir=str(tmp_path), strict_pdf_browser=True)
+ pdf_path = tmp_path / "report.pdf"
+ calls: list[Path] = []
+
+ def fake_run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
+ calls.append(Path(command[0]))
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ with (
+ patch.object(gen, "_pdf_browser_candidates", return_value=[configured, fallback]),
+ patch.object(gen, "_run_pdf_browser", side_effect=fake_run),
+ patch.object(gen, "_pdf_artifact_ready", return_value=False),
+ ):
+ assert gen._write_pdf_with_browser("<html></html>", pdf_path) is False
+
+ assert calls == [configured]
+ assert not pdf_path.exists()
+
+ def test_pdf_smoke_uses_browser_runtime_and_requires_pdf_header(
+ self, tmp_path: Path
+ ) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ browser = tmp_path / "msedge.exe"
+ browser.write_text("", encoding="utf-8")
+ commands: list[list[str]] = []
+
+ 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%smoke\n")
+ 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),
+ ):
+ smoke_path = gen.generate_pdf_smoke()
+
+ assert smoke_path == tmp_path / "ares_pdf_smoke.pdf"
+ assert smoke_path.read_bytes().startswith(b"%PDF-")
+ assert commands
+
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"
@@ -465,17 +574,37 @@ class TestReportGenerator:
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(ReportGenerator, "_is_windows_host", staticmethod(lambda: True))
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(edge) == WINDOWS_EDGE_ELEVATED_PDF_MESSAGE
assert gen._pdf_browser_skip_reason(chrome) == ""
+ def test_pdf_browser_does_not_skip_edge_in_normal_windows_session(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ gen = ReportGenerator(output_dir=str(tmp_path))
+ edge = tmp_path / "msedge.exe"
+ monkeypatch.setattr(ReportGenerator, "_is_windows_host", staticmethod(lambda: True))
+ monkeypatch.setattr(gen, "_windows_session_is_elevated", lambda: False)
+
+ assert gen._pdf_browser_skip_reason(edge) == ""
+
+ def test_windows_weasyprint_native_failure_is_actionable(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(ReportGenerator, "_is_windows_host", staticmethod(lambda: True))
+
+ message = ReportGenerator._pdf_backend_failure_detail(
+ OSError("cannot load library 'libgobject-2.0-0'")
+ )
+
+ assert WINDOWS_WEASYPRINT_NATIVE_HINT in message
+ assert "libgobject-2.0-0" in message
+
def test_pdf_browser_success_without_artifact_raises_actionable_error(
self, campaign_with_findings: Campaign, tmp_path: Path
) -> None:
diff --git a/tests/unit/test_cli_doctor.py b/tests/unit/test_cli_doctor.py
index 8d3c020..e246a12 100644
--- a/tests/unit/test_cli_doctor.py
+++ b/tests/unit/test_cli_doctor.py
@@ -133,6 +133,13 @@ def test_doctor_reports_pdf_capability(monkeypatch, tmp_path, capsys):
profile_dir.mkdir(parents=True, exist_ok=True)
return work_path, profile_dir, work_path / "report.html"
+ @staticmethod
+ def _windows_session_is_elevated() -> bool:
+ return False
+
+ def _pdf_browser_skip_reason(self, browser: Path) -> str:
+ return ""
+
def _run_pdf_browser(self, cmd: list[str]): # pragma: no cover - must not run
raise AssertionError("doctor must not launch a PDF browser")
@@ -158,6 +165,203 @@ def test_doctor_reports_pdf_capability(monkeypatch, tmp_path, capsys):
assert "PDF report output dir writable" in output
+def test_doctor_reports_windows_weasyprint_native_dependency_hint(
+ monkeypatch, tmp_path, capsys
+):
+ import importlib
+
+ from ares.cli.typer_main import doctor
+ from ares.modules.reporting import report_gen
+ from ares.modules.reporting.report_gen import WINDOWS_WEASYPRINT_NATIVE_HINT
+
+ real_import_module = importlib.import_module
+ browser = tmp_path / "msedge.exe"
+ browser.write_text("", encoding="utf-8")
+
+ 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 _pdf_backend_failure_detail(exc: BaseException) -> str:
+ return f"{WINDOWS_WEASYPRINT_NATIVE_HINT} Original error: {exc}"
+
+ @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()
+
+ @staticmethod
+ def _windows_session_is_elevated() -> bool:
+ return False
+
+ def _pdf_browser_skip_reason(self, browser: Path) -> str:
+ return ""
+
+ 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 fake_import_module(import_name: str, package: str | None = None):
+ if import_name == "weasyprint":
+ raise OSError("cannot load library 'libgobject-2.0-0'")
+ return real_import_module(import_name, package)
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / ".env").write_text("ARES_SECRET_KEY=test\n", encoding="utf-8")
+ monkeypatch.setattr(report_gen, "ReportGenerator", FakeReportGenerator)
+ monkeypatch.setattr(importlib, "import_module", fake_import_module)
+
+ try:
+ doctor()
+ except typer.Exit:
+ pass
+
+ output = capsys.readouterr().out
+ assert "PDF WeasyPrint" in output
+ assert "native GTK/Pango" in output
+ assert "libgobject-2.0-0" in output
+
+
+def test_doctor_pdf_smoke_uses_report_generator_and_verifies_pdf(
+ tmp_path, capsys
+):
+ from ares.cli.typer_main import _run_pdf_smoke_check
+
+ calls = {"smoke": 0}
+ records: list[tuple[str, str, str]] = []
+
+ class FakeReportGenerator:
+ def __init__(self) -> None:
+ self.output_dir = tmp_path / "reports"
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
+ def generate_pdf_smoke(self) -> Path:
+ calls["smoke"] += 1
+ smoke_path = self.output_dir / "ares_pdf_smoke.pdf"
+ smoke_path.write_bytes(b"%PDF-1.4\n% smoke\n")
+ return smoke_path
+
+ def fake_check(label: str, status: str, detail: str = "") -> None:
+ records.append((label, status, detail))
+ print(f"[{status.upper()}] {label} {detail}")
+
+ _run_pdf_smoke_check(FakeReportGenerator(), fake_check)
+
+ output = capsys.readouterr().out
+ assert "PDF smoke" in output
+ assert "ares_pdf_smoke.pdf" in output
+ assert "[OK] PDF smoke" in output
+ assert "bytes=" in output
+ assert calls == {"smoke": 1}
+ assert records[0][0] == "PDF smoke"
+ assert records[0][1] == "ok"
+
+
+def test_pdf_smoke_check_reports_invalid_pdf_artifact(tmp_path, capsys):
+ from ares.cli.typer_main import _run_pdf_smoke_check
+
+ records: list[tuple[str, str, str]] = []
+
+ class FakeReportGenerator:
+ def generate_pdf_smoke(self) -> Path:
+ smoke_path = tmp_path / "ares_pdf_smoke.pdf"
+ smoke_path.write_bytes(b"not-a-pdf\n")
+ return smoke_path
+
+ def fake_check(label: str, status: str, detail: str = "") -> None:
+ records.append((label, status, detail))
+ print(f"[{status.upper()}] {label} {detail}")
+
+ _run_pdf_smoke_check(FakeReportGenerator(), fake_check)
+
+ output = capsys.readouterr().out
+ assert "PDF smoke" in output
+ assert "ares_pdf_smoke.pdf" in output
+ assert "[FAIL] PDF smoke" in output
+ assert "not a PDF" in output
+ assert records == [
+ ("PDF smoke", "fail", f"{tmp_path / 'ares_pdf_smoke.pdf'} is not a PDF")
+ ]
+
+
+def test_doctor_pdf_smoke_option_calls_helper(monkeypatch, tmp_path):
+ import importlib
+
+ from ares.cli import typer_main
+ from ares.modules.reporting import report_gen
+
+ calls = {"helper": 0}
+ real_import_module = importlib.import_module
+ browser = tmp_path / "msedge.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()
+
+ @staticmethod
+ def _windows_session_is_elevated() -> bool:
+ return False
+
+ def _pdf_browser_skip_reason(self, browser: Path) -> str:
+ return ""
+
+ 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 directly")
+
+ def fake_import_module(import_name: str, package: str | None = None):
+ if import_name == "weasyprint":
+ return fake_weasyprint
+ return real_import_module(import_name, package)
+
+ def fake_pdf_smoke_check(pdf_generator: object, check: object) -> None:
+ calls["helper"] += 1
+ assert isinstance(pdf_generator, FakeReportGenerator)
+
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / ".env").write_text("ARES_SECRET_KEY=test\n", encoding="utf-8")
+ monkeypatch.setattr(report_gen, "ReportGenerator", FakeReportGenerator)
+ monkeypatch.setattr(importlib, "import_module", fake_import_module)
+ monkeypatch.setattr(typer_main, "_run_pdf_smoke_check", fake_pdf_smoke_check)
+
+ try:
+ typer_main.doctor(pdf_smoke=True)
+ except typer.Exit:
+ pass
+
+ assert calls == {"helper": 1}
+
+
def test_setup_entrypoint_routes_to_python_native_setup(monkeypatch):
from ares.cli import typer_main