diff --git a/backend/models/schemas.py b/backend/models/schemas.py index 842c2f7..2432430 100644 --- a/backend/models/schemas.py +++ b/backend/models/schemas.py @@ -582,6 +582,7 @@ class OrgNode(BaseModel): # Identity name: str + email: str | None = None # planning address; used to target a campaign at this person role: str # job title department: str hierarchy_level: int = 0 # 0 = individual contributor, higher = more authority @@ -731,6 +732,7 @@ class LiveCampaignCreate(BaseModel): ends_at: datetime max_turns: int = Field(default=4, ge=0, le=6) language: str = "en" + use_qr: bool = False # quishing: the lure is a QR code encoding the tracked URL brand_override_reason: str | None = Field(default=None, max_length=1000) @@ -747,3 +749,41 @@ class LiveCampaign(LiveCampaignCreate): # Opaque token in the Reply-To address, used to match inbound replies (P3). reply_token: str = Field(default_factory=lambda: secrets.token_urlsafe(12)) created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat()) + + +class CampaignTemplate(BaseModel): + """The content of a campaign, without the per-run time window. Used as the + body that a schedule materialises into a fresh campaign each cycle.""" + + model_config = ConfigDict(extra="forbid") + name: str = Field(min_length=1, max_length=120) + objective: str + principles: list[str] = Field(min_length=1) + sender_name: str = Field(min_length=1, max_length=80) + sender_email: str = Field(min_length=3, max_length=254) + subject: str = Field(min_length=1, max_length=200) + body_html: str = Field(min_length=1, max_length=20000) + recipients: list[str] = Field(min_length=1, max_length=5000) + max_turns: int = Field(default=4, ge=0, le=6) + language: str = "en" + use_qr: bool = False + + +class CampaignSchedule(BaseModel): + """A recurring campaign. Each cycle it materialises a fresh campaign in + `pending_approval` — never auto-sent, so the two-person approval guardrail + (G2) still holds; the schedule only automates the drafting cadence.""" + + model_config = ConfigDict(extra="ignore") + id: str = Field(default_factory=lambda: str(uuid.uuid4())) + organization_id: str | None = None + name: str = Field(min_length=1, max_length=120) + interval_days: int = Field(ge=1, le=365) + window_days: int = Field(default=5, ge=1, le=30) # active window of each run + next_run: str # ISO timestamp of the next materialisation + active: bool = True + template: dict # a CampaignTemplate + created_by: str + last_run_at: str | None = None + last_campaign_id: str | None = None + created_at: str = Field(default_factory=lambda: datetime.now(UTC).isoformat()) diff --git a/backend/requirements.txt b/backend/requirements.txt index 44e3278..0808db4 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -25,3 +25,4 @@ PyYAML==6.0.3 httpx==0.28.1 aiosmtplib==5.1.3 dnspython==2.9.0 # TXT lookups for live-campaign domain verification +segno==1.6.6 # pure-Python QR codes for "quishing" campaigns (no Pillow) diff --git a/backend/routes/attack_surface.py b/backend/routes/attack_surface.py index 95aea2e..6a69212 100644 --- a/backend/routes/attack_surface.py +++ b/backend/routes/attack_surface.py @@ -38,11 +38,19 @@ async def get_analysis(user: User = Depends(require_trainer)): return await attack_surface.analyze(_org(user)) +@router.get("/targets") +async def get_targets(user: User = Depends(require_trainer)): + """Emailable people on the map, ranked most-susceptible first — to seed a + campaign aimed at the human weak points.""" + return {"targets": await attack_surface.targets(_org(user))} + + # ---------------------------------------------------------------- nodes class NodeIn(BaseModel): name: str + email: str | None = None role: str = "" department: str = "" hierarchy_level: int = 0 diff --git a/backend/routes/live.py b/backend/routes/live.py index 73d4b8a..25824a9 100644 --- a/backend/routes/live.py +++ b/backend/routes/live.py @@ -5,12 +5,22 @@ `killed` reachable from any non-final state. See docs/design/live-campaigns.md. """ +import io +from datetime import UTC, datetime, timedelta from typing import Any -from fastapi import APIRouter, Depends, HTTPException, Query +import segno +from fastapi import APIRouter, Depends, HTTPException, Query, Response from pydantic import BaseModel, Field -from models.schemas import LiveCampaign, LiveCampaignCreate, User, VerifiedDomain +from models.schemas import ( + CampaignSchedule, + CampaignTemplate, + LiveCampaign, + LiveCampaignCreate, + User, + VerifiedDomain, +) from services import audit from services.ai_gateway import AIGateway from services.auth import require_admin, require_trainer @@ -18,6 +28,7 @@ from services.live import conversation from services.live import domains as domain_svc from services.live import launch as launch_svc +from services.live import scheduler as sched_svc from services.live.domains import email_domain from services.live.gophish import GophishClient, GophishError from services.live.preflight import has_errors, run_preflight @@ -171,6 +182,20 @@ async def list_templates(current_user: User = Depends(require_trainer)): return await db.live_templates.find({}, {"_id": 0}).sort("name", 1).to_list(100) +@router.get("/qr") +async def qr_image(data: str = Query(..., min_length=1, max_length=2000)): + """Render a QR code PNG for `data`. Public (no auth) so a recipient's mail + client can load it into a "quishing" email; `data` is the GoPhish-tracked + URL, so a scan is attributed to that recipient exactly like a click.""" + buf = io.BytesIO() + segno.make(data, error="m").save(buf, kind="png", scale=5, border=2) + return Response( + content=buf.getvalue(), + media_type="image/png", + headers={"Cache-Control": "no-store"}, + ) + + @router.get("/campaigns") async def list_campaigns(current_user: User = Depends(require_trainer)): # List view omits the heavy fields (body, full recipient list) and keeps a count. @@ -411,6 +436,91 @@ async def live_analytics(current_user: User = Depends(require_trainer)): } +# ==================== RECURRING SCHEDULES ==================== + + +class ScheduleCreate(BaseModel): + name: str = Field(min_length=1, max_length=120) + interval_days: int = Field(ge=1, le=365) + window_days: int = Field(default=5, ge=1, le=30) + start_in_days: int = Field(default=0, ge=0, le=365) + template: CampaignTemplate + + +class ScheduleUpdate(BaseModel): + active: bool | None = None + interval_days: int | None = Field(default=None, ge=1, le=365) + window_days: int | None = Field(default=None, ge=1, le=30) + + +@router.get("/schedules") +async def list_schedules(current_user: User = Depends(require_trainer)): + return ( + await db.campaign_schedules.find(_scope(current_user), {"_id": 0}) + .sort("created_at", -1) + .to_list(200) + ) + + +@router.post("/schedules", status_code=201) +async def create_schedule(body: ScheduleCreate, current_user: User = Depends(require_trainer)): + next_run = (datetime.now(UTC) + timedelta(days=body.start_in_days)).isoformat() + schedule = CampaignSchedule( + organization_id=current_user.organization_id, + name=body.name, + interval_days=body.interval_days, + window_days=body.window_days, + next_run=next_run, + template=body.template.model_dump(), + created_by=current_user.id, + ) + await db.campaign_schedules.insert_one(schedule.model_dump()) + await audit.record(current_user.id, "live.schedule.create", schedule.id, {"name": body.name}) + return schedule.model_dump() + + +@router.patch("/schedules/{schedule_id}") +async def update_schedule( + schedule_id: str, body: ScheduleUpdate, current_user: User = Depends(require_trainer) +): + updates = {k: v for k, v in body.model_dump(exclude_unset=True).items() if v is not None} + if not updates: + raise HTTPException(422, "No fields to update") + res = await db.campaign_schedules.update_one( + {"id": schedule_id, **_scope(current_user)}, {"$set": updates} + ) + if not res.matched_count: + raise HTTPException(404, "Schedule not found") + return {"updated": schedule_id, **updates} + + +@router.delete("/schedules/{schedule_id}") +async def delete_schedule(schedule_id: str, current_user: User = Depends(require_trainer)): + res = await db.campaign_schedules.delete_one({"id": schedule_id, **_scope(current_user)}) + if not res.deleted_count: + raise HTTPException(404, "Schedule not found") + await audit.record(current_user.id, "live.schedule.delete", schedule_id) + return {"deleted": schedule_id} + + +@router.post("/schedules/{schedule_id}/run-now") +async def run_schedule_now(schedule_id: str, current_user: User = Depends(require_trainer)): + """Materialise one campaign from the schedule immediately (still pending_approval).""" + schedule = await db.campaign_schedules.find_one( + {"id": schedule_id, **_scope(current_user)}, {"_id": 0} + ) + if not schedule: + raise HTTPException(404, "Schedule not found") + cid = await sched_svc.materialize(schedule) + if not cid: + raise HTTPException(422, "Schedule template is invalid — edit the schedule") + await db.campaign_schedules.update_one( + {"id": schedule_id}, + {"$set": {"last_run_at": datetime.now(UTC).isoformat(), "last_campaign_id": cid}}, + ) + return {"created_campaign": cid} + + # ==================== CONVERSATION & REVIEW QUEUE (P3) ==================== @@ -542,6 +652,9 @@ class LiveConfig(BaseModel): gophish_api_key: str = Field(min_length=1, max_length=200) verify_tls: bool = False phish_url: str = Field(min_length=1, max_length=300) + # Public URL of THIS backend, used to serve QR images into "quishing" emails. + # Optional unless a campaign uses QR. e.g. http://localhost:9442 + public_base_url: str = "" smtp_host: str = Field(min_length=1, max_length=200) smtp_username: str = "" smtp_password: str = "" diff --git a/backend/server.py b/backend/server.py index 8621257..d9e9874 100644 --- a/backend/server.py +++ b/backend/server.py @@ -368,6 +368,8 @@ async def lifespan(app: FastAPI): await db.phish_reports.create_index("id", unique=True) await db.phish_reports.create_index([("organization_id", 1), ("created_at", -1)]) await db.phish_reports.create_index([("organization_id", 1), ("verdict", 1)]) + await db.campaign_schedules.create_index("id", unique=True) + await db.campaign_schedules.create_index([("active", 1), ("next_run", 1)]) # G14: live campaign telemetry expires after 180 days await db.live_events.create_index("at", expireAfterSeconds=180 * 24 * 3600) await db.live_events.create_index([("campaign_id", 1), ("type", 1)]) @@ -398,8 +400,10 @@ async def lifespan(app: FastAPI): import asyncio from services.live.inbound import run_poller + from services.live.scheduler import run_scheduler poller_task = asyncio.create_task(run_poller()) + scheduler_task = asyncio.create_task(run_scheduler()) yield @@ -408,6 +412,8 @@ async def lifespan(app: FastAPI): if poller_task: poller_task.cancel() + if scheduler_task: + scheduler_task.cancel() client.close() diff --git a/backend/services/attack_surface.py b/backend/services/attack_surface.py index 40115eb..5a4b4fb 100644 --- a/backend/services/attack_surface.py +++ b/backend/services/attack_surface.py @@ -166,6 +166,32 @@ async def build_graph(org_id: str, *, refresh: bool = True) -> dict: return {"nodes": nodes, "edges": edges} +async def targets(org_id: str) -> list[dict]: + """People on the map who have a reachable email, ranked most-susceptible first + — the recipient list for a campaign aimed at the human weak points.""" + graph = await build_graph(org_id) + out: list[dict] = [] + for n in graph["nodes"]: + if n.get("is_asset"): + continue + email = n.get("email") + if not email and n.get("user_id"): + user = await db.users.find_one({"id": n["user_id"]}, {"_id": 0, "email": 1}) + email = (user or {}).get("email") + if email: + out.append( + { + "name": n["name"], + "role": n.get("role"), + "email": email, + "susceptibility": n.get("susceptibility"), + "band": n.get("band"), + } + ) + out.sort(key=lambda x: x["susceptibility"] or 0, reverse=True) + return out + + # ============================ pathfinding ================================== INTERNET = "__internet__" # virtual source: an attacker outside the org @@ -401,6 +427,7 @@ async def seed_demo_org(org_id: str) -> dict: node = OrgNode( org_id=org_id, name=name, + email=None if is_asset else f"{key}@acme.test", # sandbox planning address role=role, department=dept, hierarchy_level=level, diff --git a/backend/services/live/launch.py b/backend/services/live/launch.py index f41606d..c67c6ad 100644 --- a/backend/services/live/launch.py +++ b/backend/services/live/launch.py @@ -38,6 +38,30 @@ def _obj_name(campaign_id: str) -> str: return f"pretexta-{campaign_id}" +# The {{.URL}} token stays literal so GoPhish substitutes the per-recipient +# tracked link into the QR image's src — a scan is then attributed exactly like +# a click. GoPhish URL-encodes the substituted value for a query parameter. +_QR_BLOCK = ( + '
Scan the QR code with your phone\'s ' + "camera to continue.
hi {{.URL}}
", "use_qr": True}, + {"public_base_url": "http://host:9442/"}, + ) + # The literal GoPhish token is preserved so it is substituted per recipient. + assert "http://host:9442/api/live/qr?data={{.URL}}" in body + assert "hi {{.URL}}
" in body # original body kept + + +def test_body_with_qr_noop_without_flag_or_base(): + assert _body_with_qr({"id": "c", "body_html": "x", "use_qr": False}, {}) == "x" + assert ( + _body_with_qr({"id": "c", "body_html": "x", "use_qr": True}, {"public_base_url": ""}) == "x" + ) + + +async def test_create_campaign_accepts_use_qr(api): + from datetime import UTC, datetime, timedelta + + _, h = await make_user("trainer") + await api.post("/api/live/domains", json={"domain": "acme.test"}, headers=h) + now = datetime.now(UTC) + payload = { + "name": "QR drill", + "objective": "click_link", + "principles": ["authority"], + "sender_name": "IT", + "sender_email": "it@acme.test", + "subject": "Scan to verify", + "body_html": "Scan: {{.URL}}
", + "recipients": ["a@acme.test"], + "starts_at": (now + timedelta(hours=1)).isoformat(), + "ends_at": (now + timedelta(days=2)).isoformat(), + "use_qr": True, + } + r = await api.post("/api/live/campaigns", json=payload, headers=h) + assert r.status_code == 200 + from services.database import db + + camp = await db.live_campaigns.find_one({"id": r.json()["id"]}) + assert camp["use_qr"] is True diff --git a/backend/tests/test_live_scheduler.py b/backend/tests/test_live_scheduler.py new file mode 100644 index 0000000..187c63a --- /dev/null +++ b/backend/tests/test_live_scheduler.py @@ -0,0 +1,117 @@ +"""Recurring campaign schedules: materialisation, the due loop, and the API.""" + +from datetime import UTC, datetime, timedelta + +from services.database import db +from services.live import scheduler +from tests.conftest import make_user + +TEMPLATE = { + "name": "Monthly helpdesk drill", + "objective": "click_link", + "principles": ["authority"], + "sender_name": "IT Helpdesk", + "sender_email": "helpdesk@acme.test", + "subject": "Password reset required", + "body_html": "Reset: {{.URL}}
", + "recipients": ["alice@acme.test", "bob@acme.test"], + "max_turns": 0, + "language": "en", +} + + +async def _schedule(**over): + doc = { + "id": over.get("id", "sch-1"), + "organization_id": None, + "name": "sched", + "interval_days": 30, + "window_days": 5, + "next_run": datetime.now(UTC).isoformat(), + "active": True, + "template": TEMPLATE, + "created_by": "sys", + } + doc.update(over) + await db.campaign_schedules.insert_one(doc) + return doc + + +# ---------- materialisation ---------- + + +async def test_materialize_creates_pending_approval_campaign(api): + s = await _schedule() + cid = await scheduler.materialize(s) + camp = await db.live_campaigns.find_one({"id": cid}, {"_id": 0}) + assert camp["status"] == "pending_approval" # never auto-sent (G2) + assert camp["objective"] == "click_link" + assert camp["scheduled_from"] == "sch-1" + assert camp["recipients"] == ["alice@acme.test", "bob@acme.test"] + + +async def test_materialize_bad_template_returns_none(api): + s = await _schedule(id="bad", template={"name": "x"}) # missing required fields + assert await scheduler.materialize(s) is None + + +# ---------- the due loop ---------- + + +async def test_run_due_materialises_and_advances(api): + await _schedule(next_run=(datetime.now(UTC) - timedelta(minutes=1)).isoformat()) + created = await scheduler.run_due() + assert len(created) == 1 + s = await db.campaign_schedules.find_one({"id": "sch-1"}, {"_id": 0}) + # next_run advanced ~interval_days into the future + assert datetime.fromisoformat(s["next_run"]) > datetime.now(UTC) + timedelta(days=29) + assert s["last_campaign_id"] == created[0] + + +async def test_run_due_skips_future_and_inactive(api): + await _schedule(id="future", next_run=(datetime.now(UTC) + timedelta(days=10)).isoformat()) + await _schedule( + id="off", active=False, next_run=(datetime.now(UTC) - timedelta(days=1)).isoformat() + ) + created = await scheduler.run_due() + assert created == [] + + +# ---------- API ---------- + + +async def test_schedule_crud(api): + _, h = await make_user("trainer", organization_id="acme") + body = { + "name": "Monthly", + "interval_days": 30, + "window_days": 5, + "start_in_days": 0, + "template": TEMPLATE, + } + created = (await api.post("/api/live/schedules", json=body, headers=h)).json() + sid = created["id"] + assert created["active"] is True and created["interval_days"] == 30 + + listed = (await api.get("/api/live/schedules", headers=h)).json() + assert len(listed) == 1 + + # run-now materialises a pending_approval campaign + run = await api.post(f"/api/live/schedules/{sid}/run-now", headers=h) + assert run.status_code == 200 + cid = run.json()["created_campaign"] + assert (await db.live_campaigns.find_one({"id": cid}))["status"] == "pending_approval" + + # pause it + await api.patch(f"/api/live/schedules/{sid}", json={"active": False}, headers=h) + assert (await db.campaign_schedules.find_one({"id": sid}))["active"] is False + + # delete + assert (await api.delete(f"/api/live/schedules/{sid}", headers=h)).status_code == 200 + assert await db.campaign_schedules.count_documents({"id": sid}) == 0 + + +async def test_schedules_require_staff(api): + _, h = await make_user("user") + assert (await api.get("/api/live/schedules", headers=h)).status_code == 403 + assert (await api.post("/api/live/schedules", json={}, headers=h)).status_code == 403 diff --git a/docs/api.md b/docs/api.md index add5cc0..31c8da6 100644 --- a/docs/api.md +++ b/docs/api.md @@ -103,6 +103,11 @@ Audit — `/api/audit` (admin): `GET /` (entries), `GET /verify` (chain integrit `PATCH /{id}` (triage). `DELETE /api/live/campaigns/{id}` removes a finished campaign. - `GET /api/live/analytics` — historical behaviour across launched campaigns: report-rate trend, per-campaign comparison, and repeat offenders. +- `/api/live/schedules` — recurring campaigns (staff): CRUD + `POST /{id}/run-now`. + Each cycle materialises a campaign in `pending_approval` (never auto-sent, G2). +- `GET /api/live/qr?data=