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.

polish reports and campaign validation UX

Mafifriziebc29530ac79
diff --git a/README.md b/README.md
index 18264e1..0eb3ac1 100644
--- a/README.md
+++ b/README.md
@@ -14,7 +14,7 @@ and professional report generation.
[![FastAPI](https://img.shields.io/badge/API-FastAPI-009688?style=for-the-badge&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![React](https://img.shields.io/badge/Dashboard-React-61DAFB?style=for-the-badge&logo=react&logoColor=111111)](https://react.dev)
[![License](https://img.shields.io/badge/License-MIT-22C55E?style=for-the-badge)](LICENSE)
-[![Status](https://img.shields.io/badge/Unit%20Suite-1075%20passing-22C55E?style=for-the-badge)](tests/)
+[![Status](https://img.shields.io/badge/Unit%20Suite-1078%20passing-22C55E?style=for-the-badge)](tests/)
**Built for labs, internal security teams, and authorized engagements only.**
@@ -100,6 +100,41 @@ Dashboard areas:
| EDR/OPSEC | Record bypass outcomes and review EDR/OPSEC telemetry. |
| Live | Watch campaign WebSocket events. |
+Recommended dashboard workflow:
+
+1. Start in `Campaigns` and create a campaign with a name, client, targets,
+ and scope CIDRs.
+2. Use `Modules` to search for a module, pick the campaign, fill the generated
+ parameters, and run it in dry-run mode first.
+3. Use `Graph` only after a campaign exists. To ingest BloodHound or
+ SharpHound data, enter a JSON file or directory path that is local to the
+ machine running the ARES API, then click `Ingest`.
+4. Use `Templates` when you want a repeatable plan. Select a built-in template,
+ optionally provide JSON parameters, and click `Generate Plan`. This creates
+ a structured execution plan for review; it does not silently execute modules.
+5. Use `Strategy` for goal-based planning. Select a campaign, choose a goal
+ such as `domain_admin`, provide explicit authorization notes, and click
+ `Engage`. RBAC and backend authorization checks still apply.
+6. Use `Reports` to generate HTML, PDF, Markdown, or JSON output for a campaign.
+ PDF generation writes the PDF artifact directly; HTML is generated only when
+ you choose the HTML format.
+7. Use `Security` for account administration. API keys are for scripts and
+ integrations; the Security Audit panel reports dependency-audit status for
+ the ARES environment, not findings from a target network.
+8. Use `EDR/OPSEC` to record controlled bypass outcomes and review historical
+ telemetry. This page stores defensive-validation data; it does not generate
+ payloads or bypass logic.
+
+Common page inputs and outputs:
+
+| Area | What you provide | What ARES returns | Use it when |
+| --- | --- | --- | --- |
+| Templates | Template name plus optional JSON parameters. | A reviewable execution plan with stages and module IDs. | You want a consistent plan for a common engagement type. |
+| Strategy | Campaign, goal, and authorization notes. | Active engagement state and strategy events. | You want ARES to plan toward an authorized objective while preserving RBAC checks. |
+| Security Audit | No target input; team-lead access only. | Dependency-audit snapshot, scanner status, and environment warnings. | You want to verify the ARES runtime dependencies and security posture. |
+| EDR/OPSEC | Technique ID, EDR vendor, version, outcome, campaign, and notes. | Historical success-rate telemetry and outcome records. | You want to track defensive visibility and tune OPSEC decisions from controlled tests. |
+| Graph Ingest | Campaign plus local BloodHound/SharpHound JSON path. | Campaign graph nodes, links, and attack-path candidates. | You already collected BloodHound-style data and want it mapped into ARES. |
+
See [docs/dashboard-guide.md](docs/dashboard-guide.md).
### Campaign System
@@ -366,7 +401,7 @@ See [docs/architecture.md](docs/architecture.md) and
Current local verification:
```text
-1075 unit tests passed
+1078 unit tests passed
npm run build passed
validation lab passed
```
diff --git a/ares/api/server.py b/ares/api/server.py
index bc1a3a4..796c46c 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -844,6 +844,41 @@ class CampaignCreate(BaseModel):
cleaned.append(sanitized)
return cleaned
+ @field_validator("scope_cidrs", mode="before")
+ @classmethod
+ def validate_scope_cidrs(cls, v: list) -> list[str]:
+ """
+ Validate campaign scope before endpoint logic constructs ScopeEntry.
+ This keeps invalid operator input on the normal HTTP 422 path instead
+ of surfacing as an unhandled server exception.
+ """
+ from netaddr import AddrFormatError, IPNetwork
+
+ if not isinstance(v, list):
+ raise ValueError("scope_cidrs must be a list")
+ if len(v) > 256:
+ raise ValueError("scope_cidrs: maximum 256 entries allowed")
+ cleaned: list[str] = []
+ for i, entry in enumerate(v):
+ if entry is None:
+ raise ValueError(f"scope_cidrs[{i}]: null values not allowed")
+ if not isinstance(entry, str):
+ raise ValueError(
+ f"scope_cidrs[{i}]: must be a string, not {type(entry).__name__}"
+ )
+ entry = entry.strip()
+ if not entry:
+ continue
+ try:
+ IPNetwork(entry)
+ except (AddrFormatError, ValueError) as exc:
+ raise ValueError(
+ f"scope_cidrs[{i}]: {entry!r} is not a valid CIDR or IP range. "
+ "Examples: '10.0.0.0/24', '192.168.1.10/32'"
+ ) from exc
+ cleaned.append(entry)
+ return cleaned
+
@app.post("/campaigns", tags=["campaigns"])
async def create_campaign(
@@ -923,10 +958,11 @@ async def delete_campaign(
if not deleted:
raise HTTPException(404, "Campaign not found")
+ deleted_reports = _delete_report_artifacts_for_campaign(campaign_id)
await db.audit(
actor.username,
"campaign_deleted",
- f"id={campaign_id} name={c.get('name', '')}",
+ f"id={campaign_id} name={c.get('name', '')} reports_deleted={deleted_reports}",
None,
)
return {"status": "deleted", "campaign_id": campaign_id}
@@ -1663,6 +1699,30 @@ def _safe_report_file_path(
return candidate
+def _delete_report_artifacts_for_campaign(campaign_id: str) -> int:
+ root = _report_root()
+ if not root.exists():
+ return 0
+ prefix = f"{_report_slug(campaign_id)}_"
+ deleted = 0
+ for path in root.iterdir():
+ if not path.is_file():
+ continue
+ if not path.name.startswith(prefix):
+ continue
+ if path.suffix.lstrip(".").lower() not in _REPORT_EXTENSIONS:
+ continue
+ try:
+ path.unlink()
+ except OSError as exc:
+ logger.warning(
+ "report_artifact_delete_failed", path=str(path), error=str(exc)
+ )
+ continue
+ deleted += 1
+ return deleted
+
+
@app.post("/reports/{campaign_id}", tags=["reports"])
async def generate_report(
campaign_id: str,
@@ -1671,7 +1731,7 @@ async def generate_report(
_rate: None = Depends(rate_limit("report")),
db: AresDatabase = Depends(get_db),
) -> dict[str, str]:
- from ares.modules.reporting.report_gen import ReportGenerator
+ from ares.modules.reporting.report_gen import ReportDependencyError, ReportGenerator
campaign = await db.get_campaign(campaign_id)
if not campaign:
@@ -1687,7 +1747,10 @@ async def generate_report(
status_code=422,
detail=f"Unknown format '{fmt}'. Choose: {sorted(valid_fmts)}",
)
- path = gen.generate(c_obj, fmt=fmt)
+ try:
+ path = gen.generate(c_obj, fmt=fmt)
+ except ReportDependencyError as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
await db.audit(actor.username, "report_generated", f"format={fmt}", campaign_id)
# Issue 19: return filename only, not full server filesystem path
return {
diff --git a/ares/modules/reporting/report_gen.py b/ares/modules/reporting/report_gen.py
index a281571..1fb3970 100644
--- a/ares/modules/reporting/report_gen.py
+++ b/ares/modules/reporting/report_gen.py
@@ -15,6 +15,10 @@ Professional pentest report with:
from __future__ import annotations
import json
+import os
+import shutil
+import subprocess
+import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -682,6 +686,248 @@ footer{margin-top:3rem;color:var(--muted);font-size:.82rem;border-top:1px solid
# ── Report Generator ──────────────────────────────────────────────────────────
+_PDF_TEMPLATE = r"""<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<title>ARES Report - {{ campaign.name }}</title>
+<style>
+@page { size: A4; margin: 16mm 14mm 20mm; }
+* { box-sizing: border-box; }
+body {
+ margin: 0;
+ background: #ffffff;
+ color: #111827;
+ font-family: Arial, "Segoe UI", sans-serif;
+ font-size: 10.5px;
+ line-height: 1.45;
+ -webkit-print-color-adjust: exact;
+ print-color-adjust: exact;
+}
+.topbar {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ gap: 16px;
+ padding-bottom: 10px;
+ border-bottom: 3px solid #c1121f;
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand img { width: 86px; height: auto; object-fit: contain; }
+.brand-name { font-size: 22px; font-weight: 900; letter-spacing: .04em; }
+.brand-name span { color: #c1121f; }
+.meta { text-align: right; color: #475569; font-size: 9.5px; }
+h1 { margin: 18px 0 4px; font-size: 26px; line-height: 1.1; }
+h2 {
+ margin: 18px 0 8px;
+ padding-left: 8px;
+ border-left: 4px solid #c1121f;
+ font-size: 15px;
+}
+h3 { margin: 0 0 5px; font-size: 12px; }
+.subtitle { color: #475569; font-size: 11px; }
+.summary-grid {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 8px;
+ margin: 14px 0;
+}
+.card {
+ border: 1px solid #d7dee8;
+ border-radius: 6px;
+ padding: 9px;
+ background: #f8fafc;
+}
+.label { display: block; color: #64748b; font-size: 8.5px; text-transform: uppercase; letter-spacing: .05em; }
+.value { display: block; margin-top: 2px; font-size: 13px; font-weight: 800; }
+.risk-card {
+ display: grid;
+ grid-template-columns: 90px 1fr;
+ gap: 12px;
+ align-items: center;
+ border: 1px solid #d7dee8;
+ border-radius: 8px;
+ padding: 12px;
+ background: #fff7ed;
+}
+.risk-score { color: #c1121f; font-size: 38px; font-weight: 900; text-align: center; }
+.exec {
+ border-left: 4px solid #c1121f;
+ background: #f8fafc;
+ border-radius: 0 6px 6px 0;
+ padding: 10px 12px;
+}
+.severity-row { display: grid; grid-template-columns: repeat(5, 1fr); gap: 7px; }
+.severity {
+ border-radius: 5px;
+ padding: 5px 7px;
+ text-align: center;
+ font-weight: 800;
+ border: 1px solid #d7dee8;
+}
+.critical { color: #991b1b; background: #fee2e2; }
+.high { color: #9a3412; background: #ffedd5; }
+.medium { color: #854d0e; background: #fef3c7; }
+.low { color: #166534; background: #dcfce7; }
+.info { color: #1e40af; background: #dbeafe; }
+table { width: 100%; border-collapse: collapse; margin-top: 6px; }
+th, td { border-bottom: 1px solid #e2e8f0; padding: 6px 5px; vertical-align: top; text-align: left; }
+th { background: #f1f5f9; color: #334155; font-size: 9px; text-transform: uppercase; letter-spacing: .04em; }
+.badge {
+ display: inline-block;
+ border-radius: 4px;
+ padding: 2px 5px;
+ background: #eef2ff;
+ color: #3730a3;
+ font-family: Consolas, monospace;
+ font-size: 9px;
+}
+.finding {
+ break-inside: avoid;
+ margin-top: 10px;
+ border: 1px solid #d7dee8;
+ border-left: 4px solid #c1121f;
+ border-radius: 7px;
+ padding: 10px;
+}
+.finding-head { display: flex; justify-content: space-between; gap: 8px; align-items: flex-start; }
+.evidence {
+ margin-top: 6px;
+ padding: 7px;
+ border-radius: 5px;
+ background: #0f172a;
+ color: #e2e8f0;
+ font-family: Consolas, monospace;
+ font-size: 8.5px;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.remediation {
+ margin-top: 6px;
+ padding: 7px;
+ border-left: 3px solid #16a34a;
+ border-radius: 0 5px 5px 0;
+ background: #f0fdf4;
+}
+.small { color: #64748b; font-size: 9px; }
+.footer {
+ position: fixed;
+ right: 14mm;
+ bottom: 7mm;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: #64748b;
+ font-size: 8px;
+}
+.footer img { width: 82px; height: auto; object-fit: contain; }
+</style>
+</head>
+<body>
+<main>
+ <header class="topbar">
+ <div class="brand">
+ {% if brand_logo_path %}<img src="{{ brand_logo_path }}" alt="ARES">{% endif %}
+ <div class="brand-name"><span>A</span>RES</div>
+ </div>
+ <div class="meta">
+ <strong>Authorized Security Report</strong><br>
+ Generated {{ generated_at }}
+ </div>
+ </header>
+
+ <h1>{{ campaign.name }}</h1>
+ <div class="subtitle">{{ campaign.client }} - {{ campaign.operator }} - {{ campaign.noise_profile.value|upper }}</div>
+
+ <section class="summary-grid">
+ <div class="card"><span class="label">Campaign</span><span class="value">{{ campaign.name }}</span></div>
+ <div class="card"><span class="label">Client</span><span class="value">{{ campaign.client }}</span></div>
+ <div class="card"><span class="label">Findings</span><span class="value">{{ total_findings }}</span></div>
+ <div class="card"><span class="label">Filtered FP</span><span class="value">{{ fp_filtered }}</span></div>
+ </section>
+
+ <section class="risk-card">
+ <div class="risk-score">{{ "%.1f"|format(risk_score) }}</div>
+ <div>
+ <h3>Overall Risk Score</h3>
+ <p class="small">Composite score based on confirmed findings, CVSS enrichment, severity, and campaign context.</p>
+ </div>
+ </section>
+
+ <h2>Executive Summary</h2>
+ <div class="exec">{{ exec_summary }}</div>
+
+ <h2>Severity Breakdown</h2>
+ <div class="severity-row">
+ {% for sev, count in summary.items() %}
+ <div class="severity {{ sev }}">{{ sev.upper() }}<br><span style="font-size:18px">{{ count }}</span></div>
+ {% endfor %}
+ </div>
+
+ <h2>MITRE ATT&CK Coverage</h2>
+ <table>
+ <thead><tr><th>Tactic</th><th>Techniques Demonstrated</th></tr></thead>
+ <tbody>
+ {% for tactic, techs in mitre_map.items() %}
+ <tr>
+ <td><strong>{{ tactic }}</strong></td>
+ <td>{% for t in techs %}<span class="badge">{{ t.technique }}</span> {% endfor %}</td>
+ </tr>
+ {% endfor %}
+ {% if not mitre_map %}<tr><td colspan="2" class="small">No MITRE-mapped findings yet.</td></tr>{% endif %}
+ </tbody>
+ </table>
+
+ <h2>Attack Timeline</h2>
+ <table>
+ <thead><tr><th>Time</th><th>Severity</th><th>Finding</th><th>Module</th></tr></thead>
+ <tbody>
+ {% for f in timeline %}
+ <tr>
+ <td>{{ f.discovered_at.strftime('%Y-%m-%d %H:%M UTC') }}</td>
+ <td><span class="severity {{ f.severity.value }}">{{ f.severity.value.upper() }}</span></td>
+ <td>{{ f.title }}</td>
+ <td>{{ f.module_id }}</td>
+ </tr>
+ {% endfor %}
+ {% if not timeline %}<tr><td colspan="4" class="small">No confirmed findings yet.</td></tr>{% endif %}
+ </tbody>
+ </table>
+
+ <h2>Detailed Findings</h2>
+ {% for f in findings %}
+ <article class="finding">
+ <div class="finding-head">
+ <div>
+ <h3>{{ f.title }}</h3>
+ <div class="small">
+ Module: {{ f.module_id }} - Host: {{ f.host or 'N/A' }}
+ {% if f.mitre_technique %} - MITRE: <span class="badge">{{ f.mitre_technique }}</span>{% endif %}
+ </div>
+ </div>
+ <span class="severity {{ f.severity.value }}">{{ f.severity.value.upper() }}</span>
+ </div>
+ <p>{{ f.description }}</p>
+ {% if f.evidence %}<div class="evidence">{{ f.evidence|tojson }}</div>{% endif %}
+ {% if f.remediation %}<div class="remediation"><strong>Remediation:</strong> {{ f.remediation }}</div>{% endif %}
+ <div class="small">SLA: {{ sla[f.severity.value] }} days - Confidence: {{ "%.0f"|format(f.confidence*100) }}%</div>
+ </article>
+ {% endfor %}
+ {% if not findings %}<p class="small">No detailed findings available for this report.</p>{% endif %}
+
+ <div class="footer">
+ <span>Confidential - Authorized use only</span>
+ {% if brand_logo_path %}<img src="{{ brand_logo_path }}" alt="ARES">{% endif %}
+ </div>
+</main>
+</body>
+</html>"""
+
+
+class ReportDependencyError(RuntimeError):
+ """Raised when an optional report backend is unavailable."""
+
+
class ReportGenerator:
FORMATS = ("json", "html", "markdown", "pdf")
_FMT_ALIASES = {"md": "markdown"}
@@ -790,12 +1036,20 @@ class ReportGenerator:
# ── HTML ──────────────────────────────────────────────────────────────
- def _gen_html(self, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
+ def _render_html(
+ self,
+ campaign: Campaign,
+ graph_json: dict[str, Any] | None,
+ template: str,
+ ) -> str:
env = Environment(loader=BaseLoader(), autoescape=True)
env.filters["tojson"] = lambda v: json.dumps(v, indent=2, default=str)
- html = env.from_string(_HTML_TEMPLATE).render(
+ return env.from_string(template).render(
**build_report_context(campaign, graph_json)
)
+
+ def _gen_html(self, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
+ html = self._render_html(campaign, graph_json, _HTML_TEMPLATE)
out = self._out(campaign, "html")
out.write_text(html, encoding="utf-8")
logger.info("report_generated", fmt="html", path=str(out))
@@ -869,20 +1123,121 @@ class ReportGenerator:
# ── PDF ───────────────────────────────────────────────────────────────
def _gen_pdf(self, campaign: Campaign, graph_json: dict[str, Any] | None) -> Path:
- html_path = self._gen_html(campaign, graph_json)
- pdf_path = html_path.with_suffix(".pdf")
+ html = self._render_html(campaign, graph_json, _PDF_TEMPLATE)
+ pdf_path = self._out(campaign, "pdf")
try:
from weasyprint import HTML as WP
- WP(filename=str(html_path)).write_pdf(str(pdf_path))
- except ImportError:
- logger.warning("weasyprint_not_installed", fallback="returning html path")
- return html_path
+ WP(string=html, base_url=str(self.output_dir.resolve())).write_pdf(
+ str(pdf_path)
+ )
+ except (ImportError, OSError) as exc:
+ logger.warning("pdf_backend_unavailable", error=str(exc))
+ if self._write_pdf_with_browser(html, pdf_path):
+ logger.info("report_generated", fmt="pdf", path=str(pdf_path))
+ return pdf_path
+ 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
logger.info("report_generated", fmt="pdf", path=str(pdf_path))
return pdf_path
# ── Helpers ───────────────────────────────────────────────────────────
+ def _write_pdf_with_browser(self, html: str, pdf_path: Path) -> bool:
+ """Use a local Chromium-compatible browser when WeasyPrint is unavailable."""
+ 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"
+ 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",
+ 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=60,
+ )
+ 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
+ ):
+ logger.info("pdf_browser_fallback_used", browser=str(browser))
+ return True
+ logger.warning(
+ "pdf_browser_failed",
+ browser=str(browser),
+ returncode=completed.returncode,
+ stderr=completed.stderr[-500:],
+ )
+ return False
+
+ @staticmethod
+ def _pdf_browser_candidates() -> list[Path]:
+ 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"
+ ),
+ ]
+ )
+
+ candidates: list[Path] = []
+ seen: set[str] = set()
+ for path in raw:
+ try:
+ resolved = path.resolve()
+ except OSError:
+ continue
+ key = str(resolved).lower()
+ if key not in seen and resolved.is_file():
+ seen.add(key)
+ candidates.append(resolved)
+ return candidates
+
def _out(self, campaign: Campaign, ext: str) -> Path:
import re as _re
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 5da2237..aa61844 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -17,6 +17,7 @@ import {
Workflow
} from "lucide-react";
import {
+ ChangeEvent,
createContext,
FormEvent,
ReactNode,
@@ -55,6 +56,18 @@ function useAuth(): AuthState {
return value;
}
+const REQUIRED_FIELD_MESSAGE = "This field is required.";
+
+type ValidatableElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
+
+function setRequiredMessage<T extends ValidatableElement>(event: FormEvent<T>) {
+ event.currentTarget.setCustomValidity(REQUIRED_FIELD_MESSAGE);
+}
+
+function clearValidationMessage<T extends ValidatableElement>(event: ChangeEvent<T>) {
+ event.currentTarget.setCustomValidity("");
+}
+
function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<UserProfile | null>(null);
const [loading, setLoading] = useState(Boolean(getRefreshToken()));
@@ -283,6 +296,7 @@ function CampaignsPage() {
const [client, setClient] = useState("Internal");
const [targets, setTargets] = useState("");
const [scope, setScope] = useState("");
+ const [createWarning, setCreateWarning] = useState("");
const [otherId, setOtherId] = useState("");
const detail = useQuery({
queryKey: ["campaign", selected],
@@ -307,13 +321,17 @@ function CampaignsPage() {
const create = useMutation({
mutationFn: () =>
api.createCampaign({
- name,
- client,
+ name: name.trim(),
+ client: client.trim(),
targets: splitLines(targets),
scope_cidrs: splitLines(scope)
}),
onSuccess: (campaign) => {
setSelected(campaign.id);
+ setName("");
+ setTargets("");
+ setScope("");
+ setCreateWarning("");
void queryClient.invalidateQueries({ queryKey: ["campaigns"] });
}
});
@@ -340,15 +358,27 @@ function CampaignsPage() {
<div className="grid gap-4 xl:grid-cols-[360px_1fr]">
<section className="panel p-4">
<h2 className="mb-3 text-base font-bold">Create Campaign</h2>
- <form className="grid gap-3" onSubmit={(e) => { e.preventDefault(); create.mutate(); }}>
- <input className="field" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
- <input className="field" placeholder="Client" value={client} onChange={(e) => setClient(e.target.value)} />
- <textarea className="field min-h-24" placeholder="Targets" value={targets} onChange={(e) => setTargets(e.target.value)} />
- <textarea className="field min-h-24" placeholder="Scope CIDRs" value={scope} onChange={(e) => setScope(e.target.value)} />
- <button className="btn btn-primary" type="submit">
+ <form className="grid gap-3" onSubmit={(e) => {
+ e.preventDefault();
+ if (!e.currentTarget.reportValidity()) return;
+ const invalidScopeEntries = findInvalidScopeEntries(scope);
+ if (invalidScopeEntries.length > 0) {
+ setCreateWarning(`Scope CIDRs must be valid IPv4 CIDR/IP entries. Invalid: ${invalidScopeEntries.slice(0, 3).join(", ")}. Example: 10.0.0.0/24`);
+ return;
+ }
+ setCreateWarning("");
+ create.mutate();
+ }}>
+ <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); }} />
+ <textarea className="field min-h-24" required placeholder="Targets" value={targets} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setTargets(e.target.value); }} />
+ <textarea className="field min-h-24" required placeholder="Scope CIDRs" value={scope} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCreateWarning(""); setScope(e.target.value); }} />
+ {createWarning && <p className="text-sm font-semibold text-red-700">{createWarning}</p>}
+ <button className="btn btn-primary" disabled={create.isPending} type="submit">
<ListChecks size={16} /> Create
</button>
</form>
+ <DataPanel title="Create Error" data={create.error} />
</section>
<section className="grid gap-4">
<CampaignPicker campaigns={campaigns.data ?? []} value={selected} onChange={setSelected} />
@@ -372,7 +402,7 @@ function CampaignsPage() {
</button>
<input className="field max-w-xs" placeholder="Compare campaign ID" value={otherId} onChange={(e) => setOtherId(e.target.value)} />
</div>
- <DataPanel title="Delete Result" data={remove.data ?? remove.error} />
+ <DataPanel title="Delete Error" data={remove.error} />
<DataPanel title="Campaign Detail" data={detail.data} />
<DataPanel title="CVSS Summary" data={cvss.data} />
<DataPanel title="Diff" data={diff.data} />
@@ -487,6 +517,7 @@ function ReportsPage() {
const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
const [campaignId, setCampaignId] = useState("");
const [format, setFormat] = useState("html");
+ const [warning, setWarning] = useState("");
const queryClient = useQueryClient();
const reports = useQuery({
queryKey: ["reports", campaignId],
@@ -513,15 +544,24 @@ function ReportsPage() {
return (
<Page title="Reports">
<div className="panel p-4">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
+ <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
<div className="mt-3 flex flex-wrap gap-2">
<select className="field max-w-40" value={format} onChange={(e) => setFormat(e.target.value)}>
{["html", "pdf", "markdown", "json"].map((item) => <option key={item} value={item}>{item}</option>)}
</select>
- <button className="btn btn-primary" disabled={!campaignId} onClick={() => generate.mutate()}>
+ <button className="btn btn-primary" disabled={generate.isPending} onClick={() => {
+ if (!campaignId) {
+ setWarning("Campaign is required.");
+ return;
+ }
+ setWarning("");
+ generate.mutate();
+ }}>
<FileText size={16} /> Generate
</button>
</div>
+ {warning && <p className="mt-2 text-sm font-semibold text-red-700">{warning}</p>}
+ <DataPanel title="Generate Result" data={generate.error ?? generate.data} />
</div>
<section className="panel mt-4 overflow-auto p-4">
<table className="table">
@@ -549,6 +589,7 @@ function GraphPage() {
const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
const [campaignId, setCampaignId] = useState("");
const [jsonPath, setJsonPath] = useState("");
+ const [warning, setWarning] = useState("");
const graph = useQuery({ queryKey: ["graph", campaignId], queryFn: () => api.graph(campaignId), enabled: Boolean(campaignId) });
const paths = useQuery({ queryKey: ["attack-paths", campaignId], queryFn: () => api.attackPaths(campaignId), enabled: Boolean(campaignId) });
const ingest = useMutation({ mutationFn: () => api.ingestBloodhound(campaignId, jsonPath) });
@@ -556,7 +597,7 @@ function GraphPage() {
const links = Array.isArray(graph.data?.links) ? graph.data.links : [];
return (
<Page title="Graph">
- <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={setCampaignId} />
+ <CampaignPicker campaigns={campaigns.data ?? []} value={campaignId} onChange={(id) => { setCampaignId(id); setWarning(""); }} />
<div className="mt-4 grid gap-4 xl:grid-cols-[1fr_360px]">
<section className="panel min-h-[360px] p-4">
<div className="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
@@ -570,12 +611,25 @@ function GraphPage() {
<div className="mt-4 text-sm text-slate-600">{nodes.length} nodes · {links.length} links</div>
</section>
<section className="panel p-4">
- <form className="grid gap-2" onSubmit={(e) => { e.preventDefault(); ingest.mutate(); }}>
- <input className="field" placeholder="BloodHound JSON path" value={jsonPath} onChange={(e) => setJsonPath(e.target.value)} />
- <button className="btn" disabled={!campaignId || !jsonPath} type="submit">
+ <form className="grid gap-2" onSubmit={(e) => {
+ e.preventDefault();
+ if (!campaignId) {
+ setWarning("Campaign is required.");
+ return;
+ }
+ if (!jsonPath.trim()) {
+ setWarning("BloodHound JSON path is required.");
+ return;
+ }
+ setWarning("");
+ ingest.mutate();
+ }}>
+ <input className="field" required placeholder="BloodHound JSON path" value={jsonPath} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setJsonPath(e.target.value); setWarning(""); }} />
+ <button className="btn" disabled={ingest.isPending} type="submit">
<GitGraph size={16} /> Ingest
</button>
</form>
+ {warning && <p className="mt-2 text-sm font-semibold text-red-700">{warning}</p>}
<DataPanel title="Attack Paths" data={paths.data} />
<DataPanel title="Ingest Result" data={ingest.data ?? ingest.error} />
</section>
@@ -928,7 +982,10 @@ function ParamInput({
value={String(value ?? "")}
min={field.min}
max={field.max}
+ required={field.required}
+ onInvalid={setRequiredMessage}
onChange={(event) => {
+ clearValidationMessage(event);
if (type === "number") {
onChange(event.target.value === "" ? "" : Number(event.target.value));
return;
@@ -961,6 +1018,39 @@ function splitLines(value: string): string[] {
.filter(Boolean);
}
+function findInvalidScopeEntries(value: string): string[] {
+ return splitLines(value).filter((entry) => !looksLikeScopeEntry(entry));
+}
+
+function looksLikeScopeEntry(entry: string): boolean {
+ if (entry.includes(":")) {
+ return true;
+ }
+ const [address, prefix] = entry.split("/");
+ if (!isIpv4Address(address)) {
+ return false;
+ }
+ if (prefix === undefined) {
+ return true;
+ }
+ if (!/^\d{1,2}$/.test(prefix)) {
+ return false;
+ }
+ const value = Number(prefix);
+ return value >= 0 && value <= 32;
+}
+
+function isIpv4Address(value: string): boolean {
+ const parts = value.split(".");
+ return parts.length === 4 && parts.every((part) => {
+ if (!/^\d{1,3}$/.test(part)) {
+ return false;
+ }
+ const number = Number(part);
+ return number >= 0 && number <= 255;
+ });
+}
+
function unique(values: string[]): string[] {
return [...new Set(values.filter(Boolean))].sort();
}
diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.py
index 65112b3..c977a7e 100644
--- a/tests/unit/test_api_endpoints.py
+++ b/tests/unit/test_api_endpoints.py
@@ -319,6 +319,27 @@ class TestRBACEnforcement:
r.status_code == 200
), f"Role {role!r} should access /campaigns, got {r.status_code}"
+ @pytest.mark.asyncio
+ async def test_create_campaign_invalid_scope_returns_422(self, aclient):
+ c, db, _ = aclient
+ db.is_access_token_revoked.return_value = False
+ db.save_campaign.reset_mock()
+
+ r = await c.post(
+ "/campaigns",
+ json={
+ "name": "Invalid Scope",
+ "client": "Internal",
+ "targets": ["127.0.0.1"],
+ "scope_cidrs": ["123"],
+ },
+ headers=_auth("op_user", "operator"),
+ )
+
+ assert r.status_code == 422
+ assert "scope_cidrs" in r.text
+ db.save_campaign.assert_not_called()
+
@pytest.mark.asyncio
async def test_delete_campaign_requires_team_lead(self, aclient):
c, db, _ = aclient
@@ -338,8 +359,10 @@ class TestRBACEnforcement:
db.delete_campaign.assert_not_awaited()
@pytest.mark.asyncio
- async def test_delete_campaign_team_lead_deletes(self, aclient):
+ async def test_delete_campaign_team_lead_deletes(self, aclient, tmp_path, monkeypatch):
c, db, _ = aclient
+ import ares.api.server as server
+
db.is_access_token_revoked.return_value = False
db.get_campaign.return_value = {
"id": "camp-delete",
@@ -347,12 +370,22 @@ class TestRBACEnforcement:
"operator": "operator1",
}
db.delete_campaign.return_value = True
+ monkeypatch.setattr(server, "_report_root", lambda: tmp_path.resolve())
+ owned_report = tmp_path / "camp-delete_Delete_Me_20260622_1745.pdf"
+ owned_html_source = tmp_path / "camp-delete_Delete_Me_20260622_1745.html"
+ other_report = tmp_path / "other-campaign_Delete_Me_20260622_1745.pdf"
+ owned_report.write_text("owned pdf", encoding="utf-8")
+ owned_html_source.write_text("owned html", encoding="utf-8")
+ other_report.write_text("other pdf", encoding="utf-8")
r = await c.delete("/campaigns/camp-delete", headers=_auth("admin", "team_lead"))
assert r.status_code == 200
assert r.json()["status"] == "deleted"
db.delete_campaign.assert_awaited_once_with("camp-delete")
+ assert not owned_report.exists()
+ assert not owned_html_source.exists()
+ assert other_report.exists()
# ── Pagination ────────────────────────────────────────────────────────────────
diff --git a/tests/unit/test_cli_reporting_goal_planning.py b/tests/unit/test_cli_reporting_goal_planning.py
index 0710dce..8a29d86 100644
--- a/tests/unit/test_cli_reporting_goal_planning.py
+++ b/tests/unit/test_cli_reporting_goal_planning.py
@@ -191,6 +191,62 @@ class TestReportGenerator:
assert fmt in paths
assert paths[fmt].exists()
+ def test_generate_pdf_requires_pdf_backend(self, monkeypatch):
+ import builtins
+
+ from ares.modules.reporting.report_gen import (
+ ReportDependencyError,
+ ReportGenerator,
+ )
+
+ real_import = builtins.__import__
+
+ def fail_weasyprint_import(name, *args, **kwargs):
+ if name == "weasyprint":
+ raise ImportError("missing test pdf backend")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", fail_weasyprint_import)
+ monkeypatch.setattr(
+ ReportGenerator,
+ "_write_pdf_with_browser",
+ lambda self, html, pdf_path: False,
+ )
+ campaign = _make_campaign(n_findings=1)
+ with tempfile.TemporaryDirectory() as tmpdir:
+ gen = ReportGenerator(output_dir=tmpdir)
+ with pytest.raises(ReportDependencyError, match="PDF generation requires"):
+ gen.generate(campaign, fmt="pdf")
+ assert not list(Path(tmpdir).glob("*.pdf"))
+ assert not list(Path(tmpdir).glob("*.html"))
+
+ def test_generate_pdf_uses_browser_fallback(self, monkeypatch):
+ import builtins
+
+ from ares.modules.reporting.report_gen import ReportGenerator
+
+ real_import = builtins.__import__
+
+ def fail_weasyprint_import(name, *args, **kwargs):
+ if name == "weasyprint":
+ raise OSError("missing native test pdf backend")
+ return real_import(name, *args, **kwargs)
+
+ def fake_browser_pdf(self, html, pdf_path):
+ assert "<!DOCTYPE html>" in html
+ pdf_path.write_bytes(b"%PDF-1.4\n% test pdf\n")
+ return True
+
+ monkeypatch.setattr(builtins, "__import__", fail_weasyprint_import)
+ monkeypatch.setattr(ReportGenerator, "_write_pdf_with_browser", fake_browser_pdf)
+ campaign = _make_campaign(n_findings=1)
+ with tempfile.TemporaryDirectory() as tmpdir:
+ gen = ReportGenerator(output_dir=tmpdir)
+ path = gen.generate(campaign, fmt="pdf")
+ assert path.suffix == ".pdf"
+ assert path.exists()
+ assert not list(Path(tmpdir).glob("*.html"))
+
def test_generate_unknown_format_raises(self):
from ares.modules.reporting.report_gen import ReportGenerator
campaign = _make_campaign()