Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions backend/models/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)


Expand All @@ -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())
1 change: 1 addition & 0 deletions backend/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
8 changes: 8 additions & 0 deletions backend/routes/attack_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
117 changes: 115 additions & 2 deletions backend/routes/live.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,30 @@
`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
from services.database import db
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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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) ====================


Expand Down Expand Up @@ -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 = ""
Expand Down
6 changes: 6 additions & 0 deletions backend/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)])
Expand Down Expand Up @@ -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

Expand All @@ -408,6 +412,8 @@ async def lifespan(app: FastAPI):

if poller_task:
poller_task.cancel()
if scheduler_task:
scheduler_task.cancel()
client.close()


Expand Down
27 changes: 27 additions & 0 deletions backend/services/attack_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
26 changes: 25 additions & 1 deletion backend/services/live/launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
'<div style="text-align:center;margin:24px 0">'
'<img src="{base}/api/live/qr?data={{{{.URL}}}}" alt="Scan to continue" '
'width="180" height="180" style="border:0"/>'
'<p style="font-size:13px;color:#555">Scan the QR code with your phone\'s '
"camera to continue.</p></div>"
)


def _body_with_qr(campaign: dict, config: dict) -> str:
"""For a quishing campaign, append a QR image that encodes the tracked URL."""
body = campaign["body_html"]
if not campaign.get("use_qr"):
return body
base = (config.get("public_base_url") or "").rstrip("/")
if not base:
logger.warning(f"Campaign {campaign['id']} uses QR but public_base_url is unset; skipping")
return body
return body + _QR_BLOCK.format(base=base)


def _reply_to_address(config: dict, campaign: dict) -> str | None:
"""Reply-To that routes replies back to this campaign via plus-addressing."""
local = config.get("reply_local")
Expand Down Expand Up @@ -74,7 +98,7 @@ async def launch_campaign(campaign: dict, actor_id: str) -> dict:
config["gophish_base_url"], config["gophish_api_key"], config.get("verify_tls", False)
) as gp:
await gp.create_group(name, targets)
await gp.create_template(name, campaign["subject"], campaign["body_html"])
await gp.create_template(name, campaign["subject"], _body_with_qr(campaign, config))
await gp.create_page(name, TEACHABLE_MOMENT_HTML, redirect_url="")
headers = [
{"key": "From", "value": f"{campaign['sender_name']} <{campaign['sender_email']}>"}
Expand Down
Loading
Loading