diff --git a/.gitignore b/.gitignore index 7c81119..21d3210 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ .vagrant/ # Per-VM dedicated data disks — captures, flows, DVWA state, MySQL data, etc. -# Ignored so they don't bloat Git; each teammate has their own after `vagrant up`. +# Ignored so they don't bloat Git; each clone gets its own after `vagrant up`. .vm-data/ # OS junk diff --git a/CLAUDE.md b/CLAUDE.md index 5d9f6bd..46ed21d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -154,7 +154,7 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum `deploy/snapshot/nt2102-snapshot.tar.gz`, snapshot mode of `live_server.py`, image + CI, `deploy/k8s/`. Verified locally: all 24 `./selftest.sh` steps pass, the container serves the snapshot, 30-user load test OK, manifests pass a server-side dry run on the cluster. **Not yet deployed.** User steps left: commit + merge to `main` → tag `v1.0.0` → make the GHCR package public → `terraform apply` (DNS) → - Argo sync → cluster load test, then fill the cluster numbers into `deploy/README.md`. Decisions: section 9 "Public demo"; guide: `deploy/README.md`. + Argo sync → cluster load test, then fill the cluster numbers into `deploy/README.md`. Decisions: section 9 "Public demo"; overview: `deploy/README.md`. - SG-Det: code default = the **paper's level scale** (user, 2026-11-03): Moderate from 10, [PAPER] §7.2.1. **Live `ocr-live` runs [OURS] Moderate from 4.5 on both hosts since 2026-11-15** (user; `live_sg_moderate_from` in `proxmox.ini`) **with the NET rule OFF** (user, 2026-11-15 05:03Z, `live_sg_require_types=none`; accepts ~5 benign red/day per host): the teammate's 11-15 react2shell run (up to 19.9) @@ -294,7 +294,7 @@ history of earlier progress) and, if relevant, this section. sessions) → `src/pipeline/alg2.py` (optional LLM thread: triage verdict + Alg. 2 l.3–15 report on red windows) → `src/live/history.py` (persistent window history, `sessions/history.jsonl`, range queries via `/api/history`); `etwship.py --replay` + `compare_replay.py` check the live path against the offline - pipeline. Run guide: `src/live/README.md`. + pipeline. Overview: `src/live/README.md`. - Artefacts: `src/out/etw/experiments//` (raw, converted, windowed edges, `windows.csv`, `experiment.json`, `check.json`, `pull.json`, benign ledger in `labels/`), `src/artifacts/runs//` (one model: `models/`, `features/` + scaler, `experiment.json`, `lineage.json`; `exp01` predates this and diff --git a/README.md b/README.md index 1cef927..6e36c72 100644 --- a/README.md +++ b/README.md @@ -1,122 +1,72 @@ # Live attack detection from endpoint audit logs -A self-hosted, end-to-end system that watches a Windows host's kernel activity in real time and raises -an alert on a live attack — from exploit to post-exploitation — as soon as its 5-minute window closes. -Built as a security/ML systems project (NT2102 coursework), on the core detection -method from [OCR-APT](https://doi.org/10.1145/3719027.3765219) (Aly, Mansour, Youssef, ACM CCS 2025). - -**Status: proof of concept, not production-ready.** It proves the detection method works live, end to -end, on one host and one demo attack — it is not a hardened, multi-host security product. See §5. - -## What this demonstrates -- **Offensive security engineering:** a realistic, ATT&CK-mapped attack chain — exploit → discovery → - lateral tooling → C2 → persistence → anti-forensics — using real, signed tools (not malware), delivered - from a dedicated attacker VM against an isolated target. -- **Applied ML on security telemetry:** a provenance-graph pipeline (process/file/network nodes) feeding - a one-class graph neural network trained only on benign behaviour, scoring live traffic with no labeled - attack data required. -- **LLM-assisted triage:** a second-opinion LLM step that turns a statistical anomaly into a - human-readable verdict and incident report — the kind of alert-fatigue reduction SOC tooling needs. - -## 1. Goal - -Most anomaly detectors need labeled attack data, which is scarce and expensive. This project asks: can a -model trained **only on a machine's normal behaviour** catch an attack it has never seen, live, with -enough context for a human to act on it? The target outcome: a web dashboard where a 5-minute window of -activity goes from green to red *during* a live attack, backed by an LLM-written explanation of what -happened and why it's suspicious — not just a score. - -## 2. Demo scenario - -**Setup:** a vulnerable internal web app (command-injection bug) exposed on the monitored host; a -separate attacker VM on an isolated network. - -**Attack:** the attacker exploits the app to get a shell, then runs a realistic post-exploitation chain — -system/network discovery, an internal port scan, downloading and *executing* real admin/pentest tools -(PsExec, rclone, nmap, ncat) as a real attacker would, read-only database enumeration, a C2 beacon, a -persistence mechanism, and finally clearing the event logs and deleting its own tools. - -**Outcome:** all 3 live attack runs against the current model went red, with no human writing a single -detection rule. On each alert the LLM reads the flagged subgraph and writes a verdict and an incident -report — IOCs, affected hosts, and the ATT&CK stages. Over the model's first 24 hours live (279 scored -windows) there were 7 alerts: 4 attack windows from those 3 runs, and 3 false alarms, which the LLM -marked as false positives. Two of the false alarms came from admin work on the host, one from a lone -PowerShell process. These labels come from the known run times and the LLM verdicts, not from ground truth. - -The screenshot below is one red window from the latest run. The LLM's verdict and report are at the top, -built from the model's own output below them: the files, network endpoints and processes that the GNN -flagged as outside normal behaviour, and by how much. +A one-class graph neural network that learns a Windows host's normal kernel activity and turns a live attack +red within its 5-minute window, with an LLM-written incident report. Built on the core method of +[OCR-APT](https://doi.org/10.1145/3719027.3765219) (Aly, Mansour, Youssef, ACM CCS 2025). NT2102 course project. + +**[Live demo](https://projects.datrollout.dev/nt2102/)** (recorded, read-only) · **[Slides](https://uitprojects.github.io/NT2102/)** · Status: proof of concept, lab torn down. + +## Outcome + +- **DVWA → RCE → ATT&CK chain** (`ws-etw-0`): 3 of 3 live runs went red, each with an LLM `attack` verdict. + First 24 h live: 279 windows, 7 alerts (4 attack, 3 benign false alarms). +- **Real react2shell attack** (Next.js RCE on `ws-etw-1`, run by a team member): red at subgraph score 7.24 and 19.86, + LLM `attack` 0.85 / 0.95. In-sample: the alert cut-off was tuned on this run. +- **Public demo**: 4,658 recorded windows (2026-11-02 → 11-15), 63 red, 17 LLM `attack`. Replays the scores + computed live at the time. Nothing is re-scored. ![LLM verdict and report above the flagged nodes, from one live red window](docs/demo-attack.png) -
-Full attack phase breakdown (ATT&CK techniques) - -| phase | technique(s) | what happens | -|---|---|---| -| Initial access / execution | T1190, T1059.001 | Web app command injection → RCE shell | -| Discovery | T1033, T1082, T1057, T1016 | user/system/process/network enumeration | -| Network service scan | T1046 | internal subnet sweep | -| Tool transfer + execution | T1105, T1569.002 | downloads and runs real tools (PsExec as SYSTEM, rclone, nmap, ncat) | -| Credential access / DB | T1552, T1213 | read-only DB enumeration + dump | -| C2 | T1071 | periodic beacon to the attacker | -| Persistence | T1053.005 | scheduled task | -| Defense evasion | T1070.001, T1070.004 | clears the event logs, deletes the downloaded tools | - -
- -## 3. Infrastructure - -Everything runs in an isolated, automated lab built from scratch — the only manual step is installing -Windows and Kali from their ISOs: - -- **Provisioning:** Terraform defines the network and VMs on a home Proxmox hypervisor; Ansible - configures every box (collector agents, the database/web app under test, the training/serving stack, - the attacker toolkit) idempotently — re-running a playbook changes nothing on an already-configured box. -- **Network isolation:** the monitored host, a second Windows endpoint (collection only) and the - training/inference server share one firewalled lab subnet whose VMs cannot reach the home LAN. The - attacker sits on its own subnet. Attack traffic never leaves the lab. -- **Observability backbone:** our own Python ETW collector pushes kernel events to a log-aggregation - service (Loki/Grafana), which decouples collection from training and inference — the same event stream - feeds both the training pipeline and the live detector. -- **Remote access:** a VPN endpoint for off-site administration of the lab. - -## 4. Pipeline - -**Training** turns raw kernel event logs into a detector with no attack data in the loop: build a -provenance graph from a window of normal activity → extract a fixed feature vector per node → train a -graph neural network per node type to recognize "normal" as a tight region in embedding space (one-class -learning) → gate the result against sanity checks before it's ever served live. One command runs the -whole loop end to end. The lab's own tooling (the capture watchdog, the attack label file) is filtered -out before training and scoring, so neither the model nor the LLM learns from the harness. - -**Inference** runs the same pipeline live: stream kernel events in real time → score every node against -the trained model as each 5-minute window closes → group anomalous nodes into connected subgraphs and -score each one → alert when a subgraph crosses a calibrated threshold → on alert, hand the subgraph to an -LLM for a second-opinion verdict and a written report → surface everything on a live web dashboard with -full history. - -## 5. Known constraints - -Shipping this honestly means stating what it is not: - -- **Trained on idle behaviour only** (about 3 days, with attack and remote-session windows excluded). It - makes the demo attack easy to separate from normal, but real, varied day-to-day usage (remote sessions, - admin work) can also look unfamiliar and trigger a false alarm. Two of the 3 false alarms above were - exactly this. -- **The subgraph score grows with node count.** It sums over flagged nodes, so a large benign cluster can - cross the alert threshold just as a small attack can. -- **Features see each node alone.** They count what a node does, not who started it or whether a network - peer is new. The log-clearing step is captured but not flagged: `wevtutil.exe` looks normal by its own - behaviour, so it does not raise the alert. -- **The LLM is a second opinion, not ground truth.** It can over-read: the report above calls rclone - exfiltration, while the attack only used it to download a file. It can also hedge: one attack window - came back `uncertain`, because of a lab file that has since been filtered out. -- **One host is scored live.** The second Windows VM collects data for training, and no model has been - trained on both hosts yet. -- **The evidence is small:** 3 live runs of one scripted attack chain, not a formal evaluation. -- **Not production-hardened:** single-host demo scale, no high availability, no secrets management beyond - a local vault file, no multi-tenant support — built to prove the detection method, not to run a fleet. +## Stack + +Python ETW collector · Loki / Grafana · PyTorch Geometric (RGCN, Deep SVDD loss) · FastAPI + SSE · LLM triage · +Terraform on Proxmox · Ansible · Docker · Kubernetes / Argo CD / Traefik · GitHub Actions + +## Architecture + +``` +Windows VM ETW kernel events (process / file / network) ──push──► Loki +Trainer Loki ─► provenance graph ─► 15 behaviour features per node ─► one OCRGCN per node type + (train: idle benign only) (live: score each 5-min window) + anomalous nodes ─► connected subgraphs + subgraph score (Alg. 1) ─► red window + red window ─► LLM verdict + incident report (Alg. 2) ─► web UI with full history +Demo recorded snapshot ─► same UI, read-only, in a container on k8s +``` + +## Attacks + +| phase | ATT&CK | +|---|---| +| Web command injection → RCE shell | T1190, T1059.001 | +| Discovery | T1033, T1082, T1057, T1016 | +| Internal scan | T1046 | +| Real tool download + run (PsExec, rclone, nmap, ncat) | T1105, T1569.002 | +| DB enumeration + dump | T1552, T1213 | +| C2 beacon · scheduled task | T1071 · T1053.005 | +| Clear event logs, delete tools | T1070.001, T1070.004 | + +Second attack: react2shell Next.js RCE → `node` → PowerShell, winPEAS, service/task enumeration. + +## Limits + +- Benign baseline = mostly idle activity, so real admin work can raise false alarms. +- The subgraph score sums over flagged nodes: large benign clusters can cross the threshold too. +- Thresholds were tuned on the attacks shown (in-sample). No labelled ground truth, no formal evaluation. +- The LLM is a second opinion and can over-read (for example, calling a download "exfiltration"). +- Small evidence: a few runs of two attacks on two hosts. + +## Repository + +| path | what | +|---|---| +| `src/etw-python/` | ETW collector (stdlib + ctypes) | +| `src/pipeline/` | graph, features, OCRGCN training, scoring, Alg. 1, Alg. 2 | +| `src/live/` | live engine, FastAPI server, web UI, snapshot playback | +| `src/atomic-attack-pack/` | the RCE kill chain and its launcher | +| `src/ansible/` · `infrastructure/` | lab provisioning · Proxmox VMs and network (Terraform) | +| `deploy/` | demo image, k8s manifests, Argo CD app | +| `docs/` | design notes, deviations from the paper, explainers | +| `latex/` · `presentation/` | report · slides | ## References diff --git a/deploy/README.md b/deploy/README.md index 73b7cc6..f2d6724 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,140 +1,40 @@ -# Public demo: OCR-APT live detector, recorded snapshot +# deploy/: public demo -`https://projects.datrollout.dev/nt2102/`: a read-only, explorable copy of what the live detector showed from -**2026-11-02 23:10Z to 2026-11-15 20:15Z**. That range runs up to the last real attack that got an LLM `attack` verdict -(teammate on `ws-etw-1`, window 19:55Z) plus the three windows after it. Employers can open any window, see the -anomalous subgraph, the top nodes per type and the LLM report, while the live panels replay the attack session -(2026-11-15 15:10Z → 20:15Z) at one 5-min window every 3 s, in a loop. +A read-only copy of the live detector at **https://projects.datrollout.dev/nt2102/**, so visitors can browse +every recorded window, its anomalous subgraph, top nodes and LLM report. The live panels replay the attack +session of 2026-11-15 15:10Z → 20:15Z, one 5-min window every 3 s. -**What it is and is not.** Every score, alert level and LLM verdict shown is the one the live server computed at the -time, with the model and settings recorded in that session's `session.json`. Nothing is re-scored in the container: -there is no model, no torch, no Loki and no LLM key. The raw ETW logs of 11-15 afternoon are gone (12 h retention), so -re-scoring would not be possible anyway. The 4.5 alert cut-off and the NET rule being off (since 2026-11-15) were tuned -on the 2026-11-15 react2shell run, so that run is in-sample evidence, not an independent test (docs/DEVIATIONS.md D8). -The UI banner says the same. +**It is a replay.** Every score, alert level and LLM verdict is the one computed live at the time, with that +session's model and settings. The container has no model, no torch, no Loki and no LLM key. The 4.5 alert cut-off +was tuned on the react2shell run it shows (in-sample, `docs/DEVIATIONS.md` D8). The UI banner says the same. -``` -trainer: src/live/sessions/ (3.2 GB, raw logs included) - │ lab snapshot build --until 2026-11-15T20:15Z (src/live/snapshot.py: winners only, redacted, sha256 manifest) - ▼ -deploy/snapshot/nt2102-snapshot.tar.gz 5.6 MB, 4,658 windows, 4,583 details, 63 red, 17 LLM "attack" - │ .github/workflows/demo-image.yml (selftests → buildx → ghcr.io/uitprojects/nt2102-demo:X.Y.Z → smoke test) - ▼ -image 239 MB (python:3.12-slim + fastapi/uvicorn/pandas/networkx; no torch) - │ Argo CD (home-lab app-of-app → this repo's deploy/k8s, manual sync) - ▼ -pod: unpack + verify into an emptyDir (~1 s) → live_server.py --snapshot → Traefik (crowdsec, path strip) → visitors -``` - -## The persistence layer (why the same server can serve live data and a snapshot) +## Outcome -The live server's storage is behind three abstract repositories in `src/live/repository.py`. They play the role of -Spring Data repository interfaces: the engine, the cross-host correlator and the HTTP layer only know the interface. +- Snapshot: 2026-11-02 23:10Z → 2026-11-15 20:15Z, 4,658 windows, 63 red, 17 LLM `attack`; 5.6 MB, redacted, sha256 per file. +- Image: 239 MB, `python:3.12-slim`, hash-pinned deps, non-root, read-only root FS. +- Load test (local, 30 users): 61 req/s, 0 errors, p95 ≤ 56 ms, 0.57 core, RSS 134 MiB flat. + Sized at requests 50m / 160Mi, limits 1 CPU / 256Mi. -| Port (ABC) | What it stores | Live implementation | Snapshot implementation | -|---|---|---|---| -| `HistoryRepository` | every window state, queryable by time range; the UI detail of a window | `history.FileHistoryRepository` (`history.jsonl` + `detail.json`) | `snapshot.SnapshotHistoryRepository` (read-only) | -| `CrosshostRepository` | cross-host findings | `file_store.FileCrosshostRepository` (`crosshost.jsonl`) | `snapshot.SnapshotCrosshostRepository` (read-only) | -| `SessionStore` | the engine's own files: `session.json`, raw lines, per-window CSV/JSON, `windows.csv`, LLM verdicts, daily LLM budget | `file_store.FileSessionStore` (`sessions/` folder) | `snapshot.SnapshotSessionStore`: reads work, writes raise `ReadOnlyRepositoryError` | +## Architecture -`repository.open_repositories("files" | "snapshot", ...)` is the only place that picks an implementation. Shared -logic lives in the abstract base: the History query (dedup of restart copies, alerts-only, per-host), the detail merge -and the path-traversal guard. This is a template-method base class, like a Java abstract class with concrete methods. -In live mode `live_server.py` wires the `files` implementations into `Engine` and `Correlator`. The bytes on disk -are unchanged by the refactor, and `engine.py` / `correlate.py` selftests still pass. In snapshot mode -`playback.SnapshotMember` stands in for `Engine` behind the same HTTP routes, so the UI is the same file. - -## Run it locally - -```bash -# straight from the repo (no Docker): needs only the torch-free deps -uv run python src/live/live_server.py --snapshot deploy/snapshot/nt2102-snapshot.tar.gz --data-dir /tmp/nt2102-demo \ - --port 8000 --playback-from 2026-11-15T15:10:00Z -# or the image, with the same hardening as in the cluster -docker build -f deploy/docker/Dockerfile -t nt2102-demo:local . -docker run --rm -p 8000:8000 --read-only --tmpfs /data --tmpfs /tmp --memory 256m --cap-drop ALL nt2102-demo:local ``` - -## Rebuild the snapshot - -On the trainer, after `main` with this code is deployed there (or from a scratch copy of `src/live/{repository,history, -file_store,snapshot}.py` + `src/pipeline/{alg2,cmdlines}.py`, which is how the committed one was built on 2026-11-16): - -```bash -source .venv/bin/activate -lab snapshot build --until 2026-11-15T20:15Z --out /tmp/nt2102-snapshot.tar.gz +live sessions (trainer) ─► snapshot builder: one result per window, redacted, deterministic tar.gz + ─► CI: selftests → build → ghcr.io/uitprojects/nt2102-demo:X.Y.Z → smoke test + ─► Argo CD (manual sync) ─► pod: unpack + verify sha256 into emptyDir ─► live_server.py --snapshot + ─► Traefik: crowdsec, /nt2102 → /nt2102/, strip prefix ─► visitors ``` -- **Which windows are kept:** the History winner per host and window start. Restart duplicates (`.rN`) and replay - sessions are left out. -- **What is copied per window:** `detail.json`, rebuilt from `scores.csv` where it is missing, plus `session.json` - with absolute paths cut to names. Raw lines, edges, features and LLM prompt logs (`calls.jsonl`) stay behind. -- **Redaction:** the passwords in `src/ansible/proxmox.ini`, `$LAB_TOKEN`, and password-looking arguments in - command lines. The output is then re-scanned, and the build fails if a known secret is still in it. -- **Deterministic:** the same input gives the same files and hashes. - -Copy the archive to `deploy/snapshot/` and release a new image tag. - -## Release and deploy - -1. Merge to `main`. CI runs the snapshot-path selftests, builds and pushes `:sha-` and `:edge`, then smoke-tests - the image (`/healthz`, snapshot counts, `POST /ingest` → 403). -2. `git tag v1.0.0 && git push origin v1.0.0` builds `ghcr.io/uitprojects/nt2102-demo:1.0.0`. - **Once:** make the package public in the UITProjects org (Packages → nt2102-demo → settings), because the - homelab pulls without a secret. -3. Argo CD Application (kept in this repo, no home-lab change): `kubectl apply -f deploy/argocd/nt2102-demo.yaml`. - No DNS change: `projects.datrollout.dev` already resolves to the DDNS host (checked 2026-11-17), shared by all project - demos (see "Path routing"). The uncommitted home-lab drafts (app-of-app template `nt2102-demo.yaml`, DNS record `nt2102`) - are not needed; keep only one Application definition. -4. Argo CD: sync `nt2102-demo` (manual sync, the homelab convention; `CreateNamespace` makes `nt2102-demo`). -5. Check: - ```bash - kubectl -n nt2102-demo get pods - curl -sI https://projects.datrollout.dev/nt2102 # 308, Location: …/nt2102/ - curl -sI https://projects.datrollout.dev/nt2102/healthz - curl -sI https://projects.datrollout.dev/ # 404 (no landing page yet) - python deploy/loadtest.py --url https://projects.datrollout.dev/nt2102 --users 10 --duration 300 - ``` +Persistence sits behind three repository interfaces (`src/live/repository.py`: history, cross-host findings, +session files). Live mode uses the file implementations and the demo uses the read-only snapshot ones, so +the HTTP routes and UI are identical in both modes. -New code or a new snapshot: release `v1.0.1`, bump the tag in `deploy/k8s/deployment.yaml`, sync. +## Key files -## Kubernetes objects (`deploy/k8s/`, plain YAML in the homelab style) - -| File | What | +| path | what | |---|---| -| `deployment.yaml` | 1 replica; non-root uid 10001, read-only root FS, all capabilities dropped, seccomp RuntimeDefault, no SA token; emptyDir `/data` (unpacked snapshot) + `/tmp`; startup/readiness/liveness on `/healthz` | -| `service.yaml` | ClusterIP :8000 (`http`) | -| `middleware-path.yaml` | Traefik `RedirectRegex` `slash` (`/nt2102` → `/nt2102/`) + `StripPrefix` `strip` (`/nt2102`) | -| `ingress.yaml` | `projects.datrollout.dev`, path `/nt2102`, websecure + `letsencrypt` resolver, middlewares `traefik-crowdsec` → slash → strip; no rate limit (user, 2026-11-17); no VN geo filter (employers abroad) | - -All four (deployment, service, middleware-path, ingress) pass `kubectl apply --dry-run=server` on the homelab cluster (2026-11-17). - -## Path routing - -One path per project on the shared host `projects.datrollout.dev`. Traefik redirects `/nt2102` → `/nt2102/` and strips the -prefix, so the app serves at `/`. Keep UI URLs relative: `grep -nE '(fetch|EventSource)\(["`]/|(href|src)="/' src/live/static/index.html` -must print nothing. `/` has no router (404). - -## Measured resources (local container, 2026-11-16) - -Load from `deploy/loadtest.py`. Each virtual user keeps one SSE stream open and loops: status → windows of both hosts → -History 6 h → History 7 d alerts-only → 3 window details, with 2–5 s think time. This is far busier than a real visitor. -Container: `--read-only --memory 256m --cap-drop ALL`, snapshot unpacked to tmpfs. - -| Load | Throughput | p95 latency (worst endpoint) | CPU peak | Process RSS | Errors | -|---|---|---|---|---|---| -| idle (playback only) | – | – | ~1 % | 132 MiB | – | -| 10 users, 120 s | 22 req/s | 50 ms (History 7 d) | 0.35 core | 133 MiB | 0 | -| 30 users, 60 s | 61 req/s | 56 ms (History 7 d) | 0.57 core | 134 MiB | 0 | - -Hence `requests: cpu 50m, memory 160Mi` and `limits: cpu 1, memory 256Mi`. Memory is flat under load, because -the whole history (~5k rows) is loaded once at start. The headroom covers the unpack at start. The cluster numbers will -come from `kubectl top pod -n nt2102-demo` after the first sync. Re-run the load test against the public URL then and update this -table. - -## Tests - -`./selftest.sh` runs every module's `--selftest`, including the new `repository`, `file_store`, `snapshot` and -`playback` ones and the snapshot-mode HTTP test in `live_server.py`. They prove the code runs (cut-off, dedup, -redaction, tamper and traversal refused, read-only writes refused, playback over HTTP, no torch import). They say -nothing about how well the detector detects attacks. +| `snapshot/nt2102-snapshot.tar.gz` | recorded results + `manifest.json` | +| `docker/Dockerfile`, `docker/requirements.txt` | demo image (torch-free) | +| `k8s/` | Deployment, Service, Ingress, Traefik path middlewares | +| `argocd/nt2102-demo.yaml` | Argo CD Application | +| `loadtest.py` | SSE + History load test | +| `../.github/workflows/demo-image.yml` | build, push and smoke-test pipeline | diff --git a/deploy/loadtest.py b/deploy/loadtest.py index 035b9cf..d46fcaa 100644 --- a/deploy/loadtest.py +++ b/deploy/loadtest.py @@ -5,7 +5,7 @@ Each virtual user does what a visitor does in the UI: opens the page, keeps ONE SSE stream open (the live panels), then loops: status, the window list of both hosts, a History query (6 h, then 7 d alerts-only), and 3 window details picked from the History result, with a 2-5 s think time. Reports latency percentiles per request type, -errors, and HTTP 429s (none expected: the Ingress has no rate limit since 2026-11-17). +errors, and HTTP 429s (none expected: the Ingress has no rate limit). python deploy/loadtest.py --url http://localhost:8766 --users 10 --duration 300 python deploy/loadtest.py --url https://projects.datrollout.dev/nt2102 --users 10 --duration 300 diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index fb1499e..456a713 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -45,7 +45,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. session stays logged on); all 7 LLM-judged were `false_positive`. Impact: idle means no one logged on. Sign out after RDP, and exclude logon → sign-out from training. A retrain does not fix this. Loki retention raised 72 h → 90 d so a baseline can cover more than 3 days. Details: `docs/notes/logged-on-session-fp-lesson.md`. -- `ws-etw-1` is **not idle-only** (user, 2026-11-12, exp15-ws1): its baseline 11-06 20:30Z → 11-12 12:15Z *includes* the +- `ws-etw-1` is **not idle-only** (exp15-ws1): its baseline 11-06 20:30Z → 11-12 12:15Z *includes* the teammate's setup and admin work (account creation, `icacls`, git clone, Node/npm installs, Edge) and **all their RDP sessions**, plus the VM's current state (react2shell `node` server, a SYSTEM task running `powershell → whoami` every minute, the NetBIOS broadcast). Excluded only: our 6-h rotation canaries and the teammate's exploit / enumeration runs (react2shell RCE children of @@ -53,7 +53,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. `src/artifacts/exclusions/ws-etw-1-20261112.json`. Why: the user's choice, so the model matches how `ws-etw-1` is really used. Impact: on `ws-etw-1` a human RDP session and the teammate's tools used for setup (`net user`, `icacls`, `runas`) are normal, so they will not raise alerts there (and, since `exp16-ws0`, on `ws-etw-0` too — see next bullet); `whoami` under `powershell` is normal too. -- `ws-etw-0` is **now a Domain Controller and no longer idle-only** (user, 2026-11-12, exp16-ws0): it was promoted to the `nt2102.lab` DC +- `ws-etw-0` is **now a Domain Controller and no longer idle-only** (exp16-ws0): it was promoted to the `nt2102.lab` DC at 11-09 10:41Z (verified by Loki + WinRM), so its baseline 11-09 16:49Z → 11-12 15:08Z *includes* all DC steady-state work (ADWS/DFSR/DNS/NTDS, replication) **and admin RDP/console sessions**, excluding only our rotation canaries and the 11-10 14:49–15:05Z DVWA→RCE kill chain (`src/artifacts/exclusions/ws-etw-0-20261112.json`, 67 of 2107 windows). This **supersedes the logged-on-session @@ -123,7 +123,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. documented and intentional OS-command sink, so the exploited RCE is faithful. (Earlier: 10 Atomic/custom scenarios run on the VM.) - [OURS] attack realism, to raise the signal **honestly** (not by detector tuning): the chain is - deliberately high-volume (user, 2026-11-04) and the **T1105 phase downloads and EXECUTES real benign + high-volume and the **T1105 phase downloads and EXECUTES real benign signed tools** — Sysinternals **PsExec** (as SYSTEM: `PsExec64.exe → PSEXESVC.exe → cmd.exe → whoami`) and **rclone** (`copyurl` fetch from the C2), with **nmap/ncat best-effort** (staged on Kali by `roles/kali_attack`, default-off, falling back to the PowerShell TcpClient sweep). Rationale: the graph @@ -152,7 +152,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. the training converter (`src/pipeline/etw2nodlink.py`, same sha256), cuts clock-aligned tumbling 5-min windows, and scores each window with the frozen train scaler, train relation list and per-type models. - - Transport (user decision, 2026-10-17): Grafana Alloy on the VM ships every line, unchanged, to Loki + - Transport: Grafana Alloy on the VM ships every line, unchanged, to Loki on the trainer. `live_server.py --loki-url` follows the newest test run there (`src/live/loki_source.py`). Training pulls the same store (`loki_pull.py` → `build_experiment.py`). The HTTP shipper (`etwship.py`) remains only for `--replay` / `compare_replay.py`. @@ -174,7 +174,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. `Prediction_probability`, 'linear'); [PAPER] §5.2 only says "sum of the scores", but raw scores differ in scale per type (NET is negative). train_min/max from `train_scores.csv` (split = train); the saved model reproduces that file to 1.3e-5. - - Level scale = [PAPER] §7.2.1 since 2026-11-03 (user decision: "exactly the paper"): ≤ 1 Negligible + - Level scale = [PAPER] §7.2.1 since 2026-11-03: ≤ 1 Negligible ([AUTHOR CODE] only), < 10 Minor, 10–100 Moderate, ≤ 1000 Significant, else Critical. A score of exactly 10 is Moderate as the paper text reads ("between 10 and 100"); [AUTHOR CODE] l.394 says `<= 10` Minor, so the two differ only at 10.0 (clamped probs often sum to whole numbers). `--sg-moderate-from` (default 10; `10.0001` = @@ -184,7 +184,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. 11-03T15:25Z): **6 red at ≥ 10 vs 1 red at ≥ 30** (16, 25, 13, 12, 15 + the 129.0 Significant window that is red on both). The exp06 attack windows of 2026-11-02 (max 9.0 / 2.0) stay **Minor (green) at 10 as well**. More red windows also use more of the daily LLM budget (`--llm-max-per-day`, D9). - - **[OURS] live cut-off 4.5 since 2026-11-15 ~02:55Z** (user decision; inventory `live_sg_moderate_from=4.5` in + - **[OURS] live cut-off 4.5 since 2026-11-15 ~02:55Z** (inventory `live_sg_moderate_from=4.5` in `src/ansible/proxmox.ini`; the code default stays 10). Why: the teammate's real react2shell run on `ws-etw-1` (11-14 18:10–19:00Z: `node server.js` → `cmd /d /s /c powershell -EncodedCommand` reverse shell → `tar evil.zip`, `winPEASx64.exe`, `recon.bat` → `RanSim.ps1` encrypt; Sysmon command lines, D14) stayed green at 10: its best @@ -209,7 +209,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. detection; the margin is thin (4.72 vs 4.5) and a rerun may score under it; only 1 of ~10 attack windows is red (the winPEAS/recon window 18:15Z scored 1.44); one day of benign is the whole false-alarm sample; no label oracle (D6), so no P/R/F1. History rows keep their own `moderate_from` (10 before, 4.5 after). - - **NET rule OFF live since 2026-11-15 05:03Z** (user: "I accept sometimes false positive"; inventory + - **NET rule OFF live since 2026-11-15 05:03Z** (inventory `live_sg_require_types=none` → `--sg-require-types none`, both hosts; code default `alg1.REQUIRE_TYPES` stays `net` for offline tools). Why: the teammate's second react2shell run on `ws-etw-1` (11-15 03:35–04:40Z, from VPN client 10.8.0.3: winPEAS, `sc query`, `schtasks /query`, `whoami /all`, node.exe → cmd → `powershell -enc`) scored 13.44 / @@ -336,7 +336,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. (`build_experiment.py`, before windowing) and live scoring (`engine._score`). The attack's RCE PowerShell never reads those paths, so it is kept. Impact: removes the watchdog from the baseline and from live windows; does not address non-watchdog FPs (e.g. TiWorker servicing — addressed by a longer baseline). -- **[OURS] NET alert rule (user, 2026-11-09; `alg1.REQUIRE_TYPES`, `--sg-require-types`; OFF live since 2026-11-15, +- **[OURS] NET alert rule (`alg1.REQUIRE_TYPES`, `--sg-require-types`; OFF live since 2026-11-15, see the cut-off entry above; still the code default offline):** a level-kept (≥ Moderate) subgraph is alerted, and so sent to the LLM (daily budget unchanged), only if it holds ≥ 1 anomalous NET node. Otherwise it stays in the output with `kept = False` and `suppressed = "missing anomalous node type(s): net"`. The window is @@ -377,7 +377,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. - Provider is pluggable (`--llm-provider anthropic|openai|ollama|deepseek|mock`). [PAPER] used GPT-4o-mini (temperature 0) and LLaMA3-8B. The Anthropic backend sends no temperature (current models reject it), so its output is not deterministic. `mock` is a keyword rule for UI tests, not an LLM. - - Provider choice (user, 2026-10-22): **any OpenAI-compatible endpoint** — `--llm-provider openai + - Provider choice: **any OpenAI-compatible endpoint** — `--llm-provider openai --llm-base-url /v1 [--llm-model NAME] [--llm-api-key KEY]`. The key falls back to `$OPENAI_API_KEY`; a keyless endpoint used with a custom `--llm-base-url` gets a harmless dummy key so the SDK is satisfied ([OURS] `_resolve_openai_key`). Same flags on `live_server.py`, `rejudge.sh` and @@ -388,7 +388,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. replay of the session gave the same verdict (0.9, then 0.95 on a second replay: not bit-reproducible). The attack path (triage `attack` → IOCs → report) has **not** run live: the GNN produced no attack subgraph (D8 correction). One window = one data point. - - Model choice (user, 2026-10-25): [OURS] DeepSeek API `deepseek-flash` (= DeepSeek-V4.1-Flash-1017, + - Model choice: [OURS] DeepSeek API `deepseek-flash` (= DeepSeek-V4.1-Flash-1017, `--llm-provider deepseek`, OpenAI-compatible endpoint), not the paper's GPT-4o-mini / LLaMA3-8B. (Cloudflare Workers AI was tried first and dropped: the account's Free plan refuses this model.) By default DeepSeek thinks (effort high), and in thinking mode temperature has no effect, so verdicts and reports are not @@ -401,7 +401,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. - Impact: the GNN alert is never removed. An LLM `false_positive` shows as a struck-through badge on a still-red window. Each red window costs 1 call (benign) or 3 calls (attack) per subgraph, plus 9 when ≥ 2 subgraphs are attacks. It runs on its own thread, so scoring is not delayed. -- Daily budget (user, 2026-11-02, [OURS]): at most `--llm-max-per-day` (default 10) red windows investigated +- Daily budget ([OURS]): at most `--llm-max-per-day` (default 10) red windows investigated per local day, to cap token spend on a 24/7 server. Windows over the budget keep their red GNN alert and get `skipped` instead of a verdict. Impact: on a busy day, later alerts have no LLM report; it limits nothing about the GNN detection. Budget counter in `sessions/llm_budget.json`. @@ -428,7 +428,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. ## D10. Own Python ETW collector (`src/etw-python`, `etwcollect`) instead of SilkETW + Alloy - What: [PAPER] the paper consumes existing audit datasets and names no collector. Until 2026-10-26 we used SilkETW/SilkService v0.8 (Mandiant, archived) writing JSON lines to files, shipped to Loki by Grafana - Alloy. [OURS] (user decision 2026-10-26) one Python process, stdlib + ctypes only, run as the SYSTEM + Alloy. [OURS] one Python process, stdlib + ctypes only, run as the SYSTEM task `etwlab-collector`: - one real-time ETW session with the same 3 providers and keywords (Kernel-Process 0x50, Kernel-File 0x380, Kernel-Network 0x30); payload decoded via TDH schemas cached per event type; @@ -469,10 +469,10 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. every kernel event (`EventsLost` is reported, not prevented). ## D11. Linux endpoint `ubuntu-etw`: auditd + own Python shipper (`src/audit-python`, `auditship`), raw logs only -- RETIRED (user, 2026-11-06): the VM is replaced by a second Windows VM `ws-etw-1` (D12). The code stays in the repo +- RETIRED: the VM is replaced by a second Windows VM `ws-etw-1` (D12). The code stays in the repo unused; the text below is the record of what it was. - What: [PAPER] the paper evaluates Linux hosts only through existing datasets (DARPA TC3 / OpTC - provenance records); it runs no collector. [OURS] (user decision 2026-11-02) a second endpoint VM on the + provenance records); it runs no collector. [OURS] a second endpoint VM on the Proxmox lab, `ubuntu-etw` 10.21.3.11, records syscalls with **auditd** and ships every record unchanged to the trainer's Loki as `{job="auditd", host="ubuntu-etw"}` (structured metadata `type`, `key`; entry time = the record's own `audit(.:)` time). Roles `linux_auditd` + `linux_auditship`, playbook @@ -495,7 +495,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. 64-bit connects, writes under the watched dirs), not a full provenance graph. ## D12. Two Windows hosts: one model per host, each scored live -- What: [PAPER] evaluates each host separately. [OURS] (user, 2026-11-07, replacing the pooled plan of 2026-11-06) `ws-etw-0` and +- What: [PAPER] evaluates each host separately. [OURS] (replacing the pooled plan of 2026-11-06) `ws-etw-0` and `ws-etw-1` push to one Loki and each has its own model: `lab promote --host `, `lab hosts ...`. One `Engine` + `LokiSource` runs per scored VM, with its own model, scaler and clock; history and LLM budget are shared. - Why: matches the paper, keeps `ws-etw-0` on exp08 with no retrain, and avoids one baseline for two different machines @@ -512,15 +512,15 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. passed by tolerating those nodes; never deployed. - `ws-etw-1` model, live since 2026-11-12 ~14:10Z: **`exp15-ws1`**, 11-06 20:30Z → 11-12 12:15Z (teammate setup + RDP included, attack runs excluded, D2), tol 0.01 like `ws-etw-0`. Gate (seed 360 = the deployed model): best_ep 99 on FILE / NET / PROCESS, val_fpr - 0.0004 / 0.0000 / 0.0020. Deployed in two-VM mode (`lab hosts ws-etw-0 ws-etw-1`) by user decision, who allowed deployment even if the + 0.0004 / 0.0000 / 0.0020. Deployed in two-VM mode (`lab hosts ws-etw-0 ws-etw-1`); deployment was allowed even if the gate failed. - `ws-etw-0` model, history: `exp10` (≈63 h idle, 11-06 19:40Z → 11-09 10:25Z) was trained **16 min before** the DC promotion (11-09 10:41:41Z), so it was blind to all AD services — the live red=0 under it was steady-state luck, not a covered baseline. Retired from live use 2026-11-12. **`exp16-ws0`** live since 2026-11-12 ~16:05Z: DC-era benign 11-09 16:49Z → 11-12 15:08Z (DC steady-state + admin sessions, D2), tol 0.01 like `ws-etw-1`. Gate (seed 360 = deployed): best_ep 99 on FILE / NET / PROCESS, val_fpr 0.0002 / 0.0000 / 0.0023; the NET gate — the DC risk — is the strongest (2,130 val nodes) now that the DC's NET is in training. - Deployed two-VM by user decision (deploy allowed even on gate failure). First check: 0 red on both hosts. - **`exp17-ws0`** live since 2026-11-15 ~13:43Z (user decision), replacing exp16-ws0: all DC-era data to 11-15 11:20Z, same settings. + Deployed two-VM (allowed even on gate failure). First check: 0 red on both hosts. + **`exp17-ws0`** live since 2026-11-15 ~13:43Z, replacing exp16-ws0: all DC-era data to 11-15 11:20Z, same settings. Gate pass: best_ep 99 ×3, val_fpr 0.0048 / 0.0067 / 0.0026. Re-score of the same 819 saved live windows at 4.5, NET rule off: benign red 24 → 9 (mostly in-sample), our DVWA attack windows 51–53 → 7.3–7.9 (still red, but below benign GPO-editor windows at 14–15; one 4.55 tail window lost). [INFERENCE] The ngen burst in training makes the attack's 45 short-lived `mysql.exe` look normal. @@ -533,7 +533,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. ## D13. Cross-host correlation (`src/live/correlate.py`) - What: [PAPER] §7: "Detecting lateral movement was beyond the scope of this work, as OCR-APT does not process network traffic - logs", left to future work. [OURS] (user, 2026-11-07; **anomaly-first since 2026-11-15**, user) a stage after per-host SG-Det + logs", left to future work. [OURS] (**anomaly-first since 2026-11-15**) a stage after per-host SG-Det that **starts from an anomaly**: a red window on host A → every NET node in A's **kept** subgraphs (anomalous or connector) whose IP is another monitored host P is a seed → the matching connection is looked up on P → P's nodes around the other end (with P's own model's scores) and A's kept subgraphs go to the LLM as one document: an [OURS] two-host triage prompt, then the @@ -567,7 +567,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. - What: [PAPER] §2 lists command-line arguments among a provenance graph's contextual node attributes; §5.1.1 keeps such attributes **out of the OCRGCN input** (spurious correlations) but "retained for the investigation phase". Our ETW `Microsoft-Windows-Kernel-Process` ProcessStart event has **no CommandLine field** (only ProcessID, ParentProcessID, SessionID, - Flags, ImageName), so the UI and the LLM document showed only `powershell.exe` / `cmd.exe`. [OURS] (user, 2026-11-13) Sysmon is + Flags, ImageName), so the UI and the LLM document showed only `powershell.exe` / `cmd.exe`. [OURS] Sysmon is installed with an **Event ID 1 (ProcessCreate) only** config and read by `etwcollect` as a 4th, optional ETW provider (stem / Loki `provider` = `sysmon`). A join module maps each PROCESS node `p_` to the Sysmon record with the same PID and the latest start ≤ t + 2 s. The live engine shows it under the process in the UI tables, the graph tooltip and the alert card, writes diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index adac1f8..73d6b7c 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -21,12 +21,12 @@ User: project done; publish a read-only demo for employers on the k8s homelab. D `nt2102-demo`, `nt2102Demo.enabled`; its DNS `nt2102` record is not needed. - **Committed `things-need-to-close-project` (2026-11-17).** Not done: push + merge to `main`; tag `v1.0.0` (CI builds `:1.0.0`); make the GHCR package public; `kubectl apply -f deploy/argocd/nt2102-demo.yaml` + manual Argo sync (Application - kept in this repo, no home-lab change: user 2026-11-17); cluster load test. DNS needs nothing: `projects.datrollout.dev` already resolves. `master-nodes-2` NotReady (11-17). + kept in this repo, no home-lab change); cluster load test. DNS needs nothing: `projects.datrollout.dev` already resolves. `master-nodes-2` NotReady (11-17). ## 2026-11-15 False-positive review + `ws-etw-0` retrain → `exp17-ws0` (LIVE) Details: `docs/notes/fp-review-20261115.md`. Plan: `~/.claude/plans/i-need-to-check-wondrous-chipmunk.md`. -- **Live since ~13:43Z (user decision):** `ws-etw-0` = **exp17-ws0** (all DC-era data 11-09 16:49Z → 11-15 11:20Z, 198 of 4,153 windows +- **Live since ~13:43Z:** `ws-etw-0` = **exp17-ws0** (all DC-era data 11-09 16:49Z → 11-15 11:20Z, 198 of 4,153 windows excluded, gate pass). `ws-etw-1` stays **exp15-ws1**: its retrain was aborted by the user (few false positives there). Verified: `/healthz` ok, `/api/status` exp17-ws0 converter `match`, 4.5, NET rule off. Rollback: `lab promote exp16-ws0 --host ws-etw-0`, then restart. - **Re-score of the same 819 ws-etw-0 windows (4.5, rule off):** benign red 24 → 9 (≈8 → 3/day, mostly in-sample); DVWA attack windows @@ -73,7 +73,7 @@ rule (the RCE reused the inbound HTTP socket, a normal-looking NET node). User d `--start-at-task "Install the live-server systemd unit"` path. Verified: unit `--sg-moderate-from 4.5 --sg-require-types none`, `/healthz` ok, `/api/status` `require_types = []`, models exp16-ws0 / exp15-ws1, converter `match`. - **Re-judge (D8 table):** ws-etw-1 rule off → 7 attack-run windows red (on: 1) + 7 other; ws-etw-0 4 → 9 red. ≈ 5 benign red/day - per host; LLM budget raised 15 → 30/day (user, 2026-11-15) so false alarms are less likely to use it up. + per host; LLM budget raised 15 → 30/day so false alarms are less likely to use it up. - **Live after restart** (the server re-read the last hour from Loki into `.r3`/`.r4`): ws-etw-1 04:15Z (7.24) and 04:20Z (19.86) now **red**; ws-etw-0 04:30Z (our DVWA test) red. But ws-etw-1 04:40Z re-scored **3.03** (was 4.66 before the restart) and stays green: [INFERENCE] the re-read starts mid-run, so PROCESS/NET nodes lose earlier events (idle gaps, @@ -127,7 +127,7 @@ are the **reverse** of our earlier records, with a change we never captured: out-of-distribution. red=0 under exp10 was steady-state luck, not a covered baseline — same failure mode as the ws-etw-1 NetBIOS broadcast, larger surface. -**Fix = `exp16-ws0`** (user decisions 2026-11-12): retrain ws-etw-0 on its current DC state; benign **includes DC steady-state + admin +**Fix = `exp16-ws0`**: retrain ws-etw-0 on its current DC state; benign **includes DC steady-state + admin RDP/console sessions** (a D2 variant), exclude only canaries + attack bursts; deploy even if the gate fails. - **Data:** `range-20261109T164900Z-ws-etw-0` — start = the first clean dos-map run (`live-20261109T164916Z`) **after** the promotion/reboot burst, sidestepping the one-time 10:45Z dcpromo churn (60k kproc in 15 min). 2107 windows, **67 excluded** @@ -186,13 +186,13 @@ Plan: `~/.claude/plans/hmm-forget-the-alert-async-wigderson.md`. User decisions `ws-etw-1` 12 windows scored, **0 red**, median sg 0.0, max 1.99, no NET-rule suppression; `ws-etw-0` 12 scored, 0 red. `ocr-live` 1.06 GB. Correlation on (then flow-first: 5 benign `link`s; the layer is anomaly-first since 2026-11-15, D13). Label source for "0 red": operator assertion that nobody acted on either VM then. Not a soak, not a detection result. - **Rollback:** `lab hosts ws-etw-0 && sudo systemctl restart ocr-live` (assignments stay). -- **NEXT ACTION (user, 2026-11-13): verify cross-host with the teammate's REAL attack** — `react2shell` (ws-etw-1) → DC (ws-etw-0), +- **NEXT ACTION: verify cross-host with the teammate's REAL attack** — `react2shell` (ws-etw-1) → DC (ws-etw-0), so the correlation layer (D13) fires on real flows. **Changed 2026-11-13:** the attack is the **teammate's real one, not our injected kill chain**, so we do **not** build a synthetic scenario in `src/atomic-attack-pack/` (the old prereq (b) is dropped) and there is **no self-logged label oracle** (D6) — ground truth = the teammate's account + time window (operator assertion; blocks any P/R/F1 claim). Expected: `ws-etw-1` red (react2shell entry) with the pivot socket `10.21.3.10:` inside a kept subgraph → followed to the DC's process → `one-sided` or (if the DC's model flags it) `corroborated`, LLM explains both sides and cites the real command lines - (D14). Prereqs, in order: (a) roll Sysmon/D14 out to `ws-etw-1` so its entry commands show (user, 2026-11-13); (b) deploy the + (D14). Prereqs, in order: (a) roll Sysmon/D14 out to `ws-etw-1` so its entry commands show; (b) deploy the anomaly-first `correlate.py` (2026-11-15) to the trainer; (c) confirm the attack scores red on **each** host — if react2shell's exploit or the DC pivot does not go red (D6 risk: node server + AD auth are in-distribution), that is a **finding to report, not to hide**. Scope honesty: lateral movement with a known lab credential, not credential theft; DCSync/real cred-dump out of @@ -237,7 +237,7 @@ Walk-through with the reasoning and repeat commands: `docs/notes/ws-etw-1-retrai models the same 2 nodes are over on every seed: one peer, `23.41.37.42:443`, the Defender signature download of 11-08 14:40Z, copied into 3 overlapping windows. In the final model the 2 are the NetBIOS broadcast node `10.21.3.255:138`. The host has 585 distinct NET peers in 62 h and 473 of them appear in ≤ 3 windows, so a validation tail always holds a peer never seen in training. More idle - data does not fix this. **Open decision (user): a stopping-rule setting for this host, or leave `ws-etw-1` unscored.** Not tuned. + data does not fix this. **Open decision: a stopping-rule setting for this host, or leave `ws-etw-1` unscored.** Not tuned. - **Held-out idle** (3 models `exp11v-ws1-s360/361/362` trained without 11-08 21:00Z → 11-09 10:10Z, replayed on those windows, NET rule on, Moderate from 10, vs exp09-ws1; `lab compare`, output in `src/out/etw/eval/ws1-holdout/`): 156 windows scored by all four models, 152 idle + 4 canary. **Idle red: exp09-ws1 2 (22:05Z sg 16.9, 04:15Z sg 67.7); held-out models 0 / 0 / 0 (0.0 ± 0.0).** @@ -260,10 +260,10 @@ Walk-through with the reasoning and repeat commands: `docs/notes/ws-etw-1-retrai - **Not done:** Phase 3 (deploy from `main`, `lab promote --host`, `lab hosts ws-etw-0 ws-etw-1`, 24 h soak). Blocked on the two open items above. Models and eval output live only on the trainer (`src/artifacts/runs/exp11*`, `src/out/etw/eval/ws1-*`). -## Next action (user, 2026-11-09) +## Next action **Deliverables (slides + recorded demo) commit to ONE Windows VM** (`ws-etw-0`, exp08). The second VM and cross-host correlation are -**nice-to-have**, future-work only unless time allows (user, 2026-11-08). +**nice-to-have**, future-work only unless time allows. - **Slides (`presentation/`) compacted to 13 keyword-only slides — DONE** (2026-11-08): intro → core concept (5 steps) → demo (lab, data path, kill chain, video) → thanks. Appendix, results and limits slides removed; their content lives in the report @@ -274,7 +274,7 @@ Walk-through with the reasoning and repeat commands: `docs/notes/ws-etw-1-retrai deviations in Appendix A. One VM (`ws-etw-0`, exp08, 2 layers), benign = idle 3-day, Moderate from 10, exp08 results filled (R2 70.17/54.42 Moderate, LLM `attack` 0.85/0.9; 288 win / 7 alerts / 3 benign FP), D1–D13. Builds clean (`latexmk -pdf main.tex`, 21 pp). Remaining `\todoval`: demo screenshots + LLM-provider name only. (`report.docx` untracked, left alone.) -- **NOW (user, 2026-11-09): exp08 false-alarm burst (RDP/WinRM + a session left logged on) → Loki retention 90 d → retrain `ws-etw-0` as exp10** +- **NOW: exp08 false-alarm burst (RDP/WinRM + a session left logged on) → Loki retention 90 d → retrain `ws-etw-0` as exp10** on all idle data in Loki (≈ 11-06 → 11-09, attacks/RDP/Ansible/canaries excluded, exp08 settings). 8 alerts 10:30–14:10Z, all 7 LLM-judged `false_positive` (servicing after WinRM, `ping`/`ipconfig`, `dsregcmd` hourly after the 10:46Z logon). Lesson: `docs/notes/logged-on-session-fp-lesson.md`. Retention 90 d: **DONE, verified** (`/config` shows `retention_period: 90d`). @@ -291,7 +291,7 @@ Walk-through with the reasoning and repeat commands: `docs/notes/ws-etw-1-retrai Unit `/etc/systemd/system/ocr-live.service` edited by hand: `--loki-host` → `--loki-default-host` (what the PR #14 template renders; backup `/root/ocr-live.service.bak-20261109`). `/etc/nt2102-hosts.json` not written (no correlation in one-VM mode). A later Ansible `--tags project` run from a pushed branch reconciles both. Selftests on the trainer: alg1, engine, history, live_server, correlate OK. -- **[OURS] NET alert rule (user, 2026-11-09): LIVE since 16:08Z (with exp10).** A ≥ Moderate subgraph alerts (and goes to the LLM, budget +- **[OURS] NET alert rule: LIVE since 16:08Z (with exp10).** A ≥ Moderate subgraph alerts (and goes to the LLM, budget unchanged) only if it holds ≥ 1 anomalous NET node; otherwise suppressed and logged with the reason (D8). Offline re-judge (exp08, 10 sessions since 11-05): alert windows 19 → 8, attack windows 5/5, false alarms 14 → 3 (all human sessions). Replaced the first three-type version, which lost the 00:50Z C2 window. @@ -313,7 +313,7 @@ run, `ocr-live` stays on exp08 and `ws-etw-0`. ## 2026-11-07 exp09-ws1 trained for `ws-etw-1`: PROVISIONAL, not promoted (verified on the trainer) -One model per host (user, 2026-11-07): `ws-etw-0` keeps exp08, `ws-etw-1` gets its own. Experiment +One model per host: `ws-etw-0` keeps exp08, `ws-etw-1` gets its own. Experiment `range-20261106T170000Z-ws-etw-1`, 11-06 17:00Z to 11-07 03:00Z, 298 windows, 20 excluded (the two 6-h rotation canaries: `src/artifacts/exclusions/ws-etw-1-20261107.json`). Label source: operator assertion, backed by a scan of all 495 process starts: no RDP, WinRM, installer or choco; the 19:05Z kfile burst is Defender (`MpCmdRun`), kept as normal OS work. @@ -544,7 +544,7 @@ User cut training scope 48 h → **3 h** and set a hard 04:00 +07 (21:00Z) auto- ## Current focus -**Move training + attack to the home Proxmox lab (user, 2026-11-01).** Infrastructure verified: `infrastructure/` +**Move training + attack to the home Proxmox lab.** Infrastructure verified: `infrastructure/` (Terraform) built ws-etw 10.21.3.10 + ubuntu-trainer 10.21.3.20 on VNet `it2102`; `src/ansible/proxmox.ini` provisioned both (ubuntu.yml + windows.yml with vulnlab: first run failed=0, re-runs `changed=0`, verify-windows passes, DVWA :3000 = 200, Grafana = 200, Loki receives kproc/kfile/knet from ws-etw, collector 0 lost events). @@ -559,11 +559,11 @@ for a newly added VNet). The cross-subnet attack path is opened by an `IN ACCEPT to `it2102_rules` (ws-etw accepts the DVWA exploit; Kali accepts the callback via the existing 10.21.3.0/24 accept). The 7 base resources are now in state (user ran `apply`). **Fix pending apply:** creating `it2102k` gave pve-master a new IP `10.21.4.1`, so every VM could reach the node UI/SSH there, bypassing the existing -`10.21.3.1` drop — added an `OUT DROP → 10.21.4.1` to the shared `it2102_rules` (user, 2026-11-03). `plan` = +`10.21.3.1` drop — added an `OUT DROP → 10.21.4.1` to the shared `it2102_rules`. `plan` = **0 add / 5 change / 0 destroy** (the drop added to all 5 VMs' rules; still **pending user `terraform apply`**). Ansible (branch `provision-kali-ansible`): `proxmox.ini` `[attacker]` group + `kali.yml` + `kali_attack` role (copies `src/atomic-attack-pack` → `/opt/attack-pack`, launcher selftest). Auth = Kali's public default -`kali` / `kali` hardcoded in `proxmox.ini` (user, 2026-11-04; not a secret on the lab subnet, like +`kali` / `kali` hardcoded in `proxmox.ini` (not a secret on the lab subnet, like vagrant/vagrant), no vault. **Kali VERIFIED (2026-11-04):** ping ok, `kali.yml` first run failed=0 / re-run changed=0, pack in place, selftest passes on the VM; Kali→DVWA on ws-etw:3000 = 200 (cross-subnet path works). @@ -637,7 +637,7 @@ watchdog exit + `Restart=always`; a restart appended a 2nd raw copy into the sam `.rN` folder; an unbounded catch-up read (≤ 1 h backlog in one step, OOM risk on the 6 GB trainer) → ≤ 20k lines/provider/poll with the clock held for the lagging provider; the UI never re-synced after a reconnect → re-fetch on every SSE open. Added `/healthz`, `OOMScoreAdjust=500`, per-event converter guard, and the [OURS] -**daily LLM budget** `--llm-max-per-day 10` (user, 2026-11-02; D9). `./selftest.sh` 16/16. src/live/README §5. +**daily LLM budget** `--llm-max-per-day 10` (D9). `./selftest.sh` 16/16. src/live/README §5. Deployed on the Proxmox trainer (`7dadd1a`, `-e repo_branch=provide-infrastructure -e live_llm_args=`; the LLM was turned on later: DeepSeek key saved, then `ubuntu.yml --tags project` with the inventory's `live_llm_args`) and verified there: `/healthz` 200; deploy restart → `.r2`, SIGKILL → systemd restart → `.r3`, both 0 duplicate raw @@ -699,7 +699,7 @@ OPEN (the real limitation): - **exp03 vs new data**: exp03 was trained on SilkService captures (wrong NET owners, `N/A` process names, thinned kfile). On etwcollect data every live window is red (sg 62–96 during generated DLL-hashing load, not a detection result). Needs a new benign capture + `exp04` (Next 3 steps). -- Live engine vs Loki push outages (left as is, user 2026-11-02): after a ws-etw → Loki push stall longer than `--loki-idle-s`, the backlog reaches the engine +- Live engine vs Loki push outages (left as is): after a ws-etw → Loki push stall longer than `--loki-idle-s`, the backlog reaches the engine after its windows closed and is dropped as late (522k lines after a 2-min outage on 2026-10-26). Files and Loki keep every line, so a re-build/replay is complete; only the live windows of the outage are thin. - etwcollect lag values go to −3.6 s over 32 min: ETW event timestamps run a few seconds ahead of the system @@ -769,7 +769,7 @@ OPEN (the real limitation): Runs on its own thread in `engine.py`, `--llm-provider` in `live_server.py`, badge + report card in the UI. Plumbing verified with the keyword mock on a replay of `live-20261011T112141Z` (before the scale change; now needs `--sg-moderate-from 10.0001`): 1 red window (11:25 `updater`), verdict attached, - `llm/` files written. Provider chosen (user, 2026-10-25): DeepSeek API `deepseek-flash` + `llm/` files written. Provider chosen: DeepSeek API `deepseek-flash` (`--llm-provider deepseek`, replaces the dropped Cloudflare attempt); code + offline selftest done. First real run (user-verified 2026-10-25): re-judged replay `live-20261011T112141Z` 11:25 `updater` window → `false_positive` (conf 0.88, 1 call, 3.1 s, 2159 tokens, default thinking). One benign window = one data @@ -896,13 +896,13 @@ Repo hygiene: --benign-split test --model exp06` → gate → `lab promote exp06`. Check that idle stays green live. 2. **Attack on Proxmox:** add a Kali VM on it2102 (planned 10.21.3.30; Terraform + attack pack delivery), run the DVWA→RCE chain live, expect red + an LLM verdict. -3. **Real tool download + execution** in the T1105 phase (user, 2026-11-04; implement next session): +3. **Real tool download + execution** in the T1105 phase (implement next session): download + RUN benign real tools (nmap `-sT` / ncat / PsExec; rclone optional) so tool processes + sockets generate new flagged nodes — the signal is execution, not file content. Done: see D6. Branch `provision-kali-ansible`. Earlier backlog (2026-10-31, after the exp05 demo win): -1. **Live UI: render the LLM report as HTML** (user, 2026-10-31). The web UI currently shows the Alg. 2 +1. **Live UI: render the LLM report as HTML**. The web UI currently shows the Alg. 2 report (`sg3_report.md`) as raw markdown text — add markdown→HTML rendering in `src/live/` (the UI / `live_server.py`). 2. **Steady the idle baseline:** exp05's idle set is thin (net `val_fpr=1.0`, 6 net train nodes). Pull a diff --git a/docs/explainers/edges-to-node-features.html b/docs/explainers/edges-to-node-features.html index 8f6c089..797aeeb 100644 --- a/docs/explainers/edges-to-node-features.html +++ b/docs/explainers/edges-to-node-features.html @@ -258,7 +258,7 @@

1Two files come in, only one gets counted

@@ -413,7 +413,7 @@

Lost

  • Total volume, after L2 normalization.
  • Who the counterpart was. OCRGCN recovers this through typed message passing.
  • Order and timing of individual events. The idle features keep a summary; the LLM stage keeps the sequence.
  • -
  • Names, paths and IPs, left out on purpose (§5.1.1).
  • +
  • Names, paths and IPs, left out by design (§5.1.1).
  • diff --git a/docs/notes/cross-host-attack-flow.md b/docs/notes/cross-host-attack-flow.md index e754e03..bf9ceac 100644 --- a/docs/notes/cross-host-attack-flow.md +++ b/docs/notes/cross-host-attack-flow.md @@ -1,7 +1,7 @@ # Cross-host attack flow — network view (proposal, 2026-11-13) **Status: HYPOTHESIS / my imagination.** This is the attack path I want us to run end-to-end so the detector's -cross-host correlation (D13) fires on a *real* flow, not a synthetic one. It is network-focused on purpose. +cross-host correlation (D13) fires on a *real* flow, not a synthetic one. It is network-focused. Nothing here is a detection claim. Open questions for you are marked **[?]** — fill them with what `react2shell` actually allows. diff --git a/docs/notes/fp-review-20261115.md b/docs/notes/fp-review-20261115.md index 03922f9..b89aa25 100644 --- a/docs/notes/fp-review-20261115.md +++ b/docs/notes/fp-review-20261115.md @@ -2,7 +2,7 @@ User ask: check every live false positive; the model looked like it had never seen some benign behaviour, so retrain on all data from the start, and deploy if the new model is better. Plan: `~/.claude/plans/i-need-to-check-wondrous-chipmunk.md`. -Outcome: **`exp17-ws0` live on `ws-etw-0` since 2026-11-15 ~13:43Z** (user decision, despite the attack-score drop below). +Outcome: **`exp17-ws0` live on `ws-etw-0` since 2026-11-15 ~13:43Z** (despite the attack-score drop below). The `ws-etw-1` retrain was **aborted by the user** ("it does not have false positives like ws0"), so `ws-etw-1` stays on `exp15-ws1`. ## Method diff --git a/docs/notes/retrain-2day-fp-lesson.md b/docs/notes/retrain-2day-fp-lesson.md index 7c826fa..2e4fe09 100644 --- a/docs/notes/retrain-2day-fp-lesson.md +++ b/docs/notes/retrain-2day-fp-lesson.md @@ -52,7 +52,7 @@ nothing: then the tail holds behaviour training never saw (`training-runbook.md` ## 5. Operations -- Loki kept 72 h until 2026-11-09, now 90 days (`logged-on-session-fp-lesson.md`). Pull anything worth keeping before it expires. +- Loki keeps 90 days (`logged-on-session-fp-lesson.md`). Pull anything worth keeping before it expires. - `lab pull` names experiments `range-[-]` and refuses an existing folder; `--force` replaces it. - `systemctl` shows `failed` after a plain stop of `ocr-live`: exit 143 on SIGTERM, not a crash. diff --git a/docs/notes/training-runbook.md b/docs/notes/training-runbook.md index 16ef922..2fceb3a 100644 --- a/docs/notes/training-runbook.md +++ b/docs/notes/training-runbook.md @@ -14,7 +14,7 @@ took 4 minutes. ## 1. Pick the range - At least 24 h, so daily OS jobs are in the baseline: 3 days is the target (`retrain-2day-fp-lesson.md`). -- Loki keeps 90 days (`loki_retention`, 72 h until 2026-11-09). Pull before the start of the range expires. +- Loki keeps 90 days (`loki_retention`). Pull before the start of the range expires. - Keep nothing from provisioning or deploys on that VM. Ansible, `choco` and installs flood kfile and are not idle. ## 2. Scan for bursts diff --git a/docs/notes/ws-etw-1-retrain-20261111.md b/docs/notes/ws-etw-1-retrain-20261111.md index 020fe78..833cf1f 100644 --- a/docs/notes/ws-etw-1-retrain-20261111.md +++ b/docs/notes/ws-etw-1-retrain-20261111.md @@ -194,7 +194,7 @@ raw sg 117.0 suppressed by the NET rule, so 0-idle-red is partly load-bearing on is why its gate passes at tol 0.01. The "new peers" idea does not hold: `ws-etw-0` meets as many unseen peers (18 % of its validation NET nodes) and flags none; the features describe behaviour (send/recv counts, idle times), not addresses. -**Fix:** put the VM's current behaviour into training. By user decision the teammate's setup and RDP sessions are included; only our +**Fix:** put the VM's current behaviour into training. The teammate's setup and RDP sessions are included; only our rotation canaries and the teammate's exploit / enumeration runs are excluded (bursts from Loki ProcessStart: `node.exe` descendants = react2shell RCE, and winPEAS / `systeminfo` / `netsh` / `runas`+`whoami` / `icacls` in user sessions, first start − 5 min → last + 5 min). The 11-09 10:19–10:33Z burst also used `net user`, `icacls`, `runas`, but for setup (account, ACLs, git clone, Node/npm install), so it diff --git a/docs/reports/teammate.md b/docs/reports/teammate.md index 07683ed..a409d3a 100644 --- a/docs/reports/teammate.md +++ b/docs/reports/teammate.md @@ -33,7 +33,7 @@ The current "Next 3 steps" are in `docs/PROGRESS.md`. In short: 1. **More benign data**: 2–3 captures at different times (trigger the Google updater, a Defender scan), retrain into `src/artifacts/runs/exp02`, and record the max benign subgraph score per window. -2. **Replay check**: `src/live/README.md` step 4 → `ALL MATCH`. +2. **Replay check**: `compare_replay.py` on the training capture → `ALL MATCH`. 3. **Attack demo**: one Atomic scenario during a live session (`src/atomic-attack-pack/`). Does its window reach ≥ 30? Do not re-tune the cut-off on the attack window. 4. **CVE → RCE scenario** (target demo, not built yet): exploit a lab service, then ATT&CK follow-on. diff --git a/infrastructure/.gitignore b/infrastructure/.gitignore index a457713..22fea55 100644 --- a/infrastructure/.gitignore +++ b/infrastructure/.gitignore @@ -1,5 +1,5 @@ .terraform/ -# terraform.tfstate IS committed (user, 2026-10-31); backups stay ignored +# terraform.tfstate IS committed (no secrets in it); backups stay ignored *.tfstate.* terraform.tfvars *.auto.tfvars diff --git a/infrastructure/README.md b/infrastructure/README.md index 5f9c7f2..78b6df7 100644 --- a/infrastructure/README.md +++ b/infrastructure/README.md @@ -1,207 +1,34 @@ -# infrastructure/: Proxmox VE lab VMs (Terraform) +# infrastructure/: Proxmox lab (Terraform) -Creates on one Proxmox node: +The lab's network and VMs on one Proxmox VE node, `bpg/proxmox` provider. Torn down; the config and the +committed state (no secrets in it) remain as the record. -- SDN Simple zone `nt2102` → VNet **`it2102`** → subnet `10.21.3.0/24` (gateway `10.21.3.1` on the node, - SNAT for internet). -- The Windows Server 2022 ISO, downloaded by PVE from `iso_url`. -- One VM (`ws-etw-0` by default): q35, UEFI (OVMF, Secure Boot keys), TPM 2.0, SATA disk, e1000e NIC on - `it2102`, booting the ISO. **Install Windows by hand from the console.** +## Outcome -Provider: `bpg/proxmox` pinned to `0.119.0`. SDN and ISO use the current `proxmox_sdn_*` / -`proxmox_download_file` names (the `proxmox_virtual_environment_*` ones are deprecated there); the VM stays -`proxmox_virtual_environment_vm` (not deprecated; its successor `proxmox_vm` is experimental). +- One `terraform apply` builds every VM and network; only Windows and Kali need a manual OS install from ISO. +- The lab subnets cannot reach the home LAN or the Proxmox node; attack traffic stays inside the lab. -## Credentials (the only variables, `variables.tf`) +## Architecture -All lab settings are hardcoded in the `locals` block of `main.tf`. The provider logs in as `root@pam` -(`versions.tf`, like `~/code/home-lab/tf/proxmox`) and uses the node SSH key -`~/OneDrive/credentials/ssh/proxmox/id_ed25519` via the SSH agent. Only the endpoint and password are -variables, with no values in git: - -```bash -export TF_VAR_proxmox_endpoint="https://:8006/" -export TF_VAR_proxmox_root_password='' -``` - -## State - -`terraform.tfstate` is committed to git (user, 2026-10-31): no secrets in it (no password/token/private key), -but it does hold the lab topology, MACs and the it2102-vms public key, and the repo is public. Commit it -after every apply, and never run apply from two machines at once (git state has no locking). - -## Use - -```bash -# set local.iso_url in main.tf first (placeholder) -terraform init -terraform plan -terraform apply -``` - -## Install notes - -- The disk is empty, so the firmware falls through to the CD. In the noVNC console, **press a key at - "Press any key to boot from CD or DVD"** or setup is skipped. -- No VirtIO drivers are needed (SATA + e1000e). The VM resource allows only one CD-ROM, so a virtio-win ISO can't - be attached as well. After install, you can switch to VirtIO with drivers installed (`disk_interface`, `nic_model`). -- No DHCP on `it2102`. Set a static IP in Windows: `10.21.3.10/24`, gateway `10.21.3.1`, DNS e.g. `1.1.1.1` - (output `suggested_static_ip`). -- The SDN gateway lives on the Proxmox node, not your laptop. To reach the VM from elsewhere, route - `10.21.3.0/24` via the node or use the console. - -## Firewall (VM 2102, Proxmox VM-level) - -The rules sit on the VM's NIC (`network_device.firewall = true`). They work only while the **datacenter -firewall stays enabled**: it is enabled on `pve-master` (`policy_in: ACCEPT`) and is deliberately not -managed here, because the home-lab VMs share it. First match wins: - -1. OUT DROP → `192.168.1.0/24` (home LAN), logged -2. OUT DROP → `10.21.3.1` (the node via the it2102 VNet gateway: UI :8006, SSH :22), logged. Routing to - the internet through the gateway still works. -3. OUT DROP → `10.21.4.1` (the node via the **it2102k** VNet gateway), logged. The node has an IP on the - Kali VNet too, so without this a VM could reach the UI/SSH at `10.21.4.1` and bypass rule 2. -4. IN ACCEPT ← `10.21.3.0/24` (lab subnet: RDP, DVWA) -5. IN ACCEPT ← `10.21.4.0/24` (Kali attacker subnet: cross-subnet DVWA exploit + RCE callback) -6. Defaults: input DROP, output ACCEPT. Replies to the VM's own connections pass via connection tracking. - -Check from PowerShell inside the VM: - -- `Test-NetConnection 192.168.1.1 -Port 80` → `TcpTestSucceeded : False` (LAN blocked) -- `Test-NetConnection 10.21.3.1 -Port 8006` → `False` (node UI blocked) -- `Test-NetConnection 10.21.4.1 -Port 8006` → `False` (node UI via the Kali-VNet gateway also blocked) -- `Test-NetConnection 1.1.1.1 -Port 443` → `True`, and `Resolve-DnsName microsoft.com` resolves (internet + DNS) - -Drops appear in the Proxmox UI under VM 2102 → Firewall → Log. - -## ubuntu-trainer (VM 2103) - -Ubuntu 24.04 cloud image (pinned `noble/20261017`), 4 cores, 6 GB RAM, 200 GB disk (Loki keeps 72 h at -~2 GB/h), static `10.21.3.20/24` via cloud-init, user `it2102` with the `it2102-vms` key. It gets the same -`it2102:` firewall rules as ws-etw-0 (`local.it2102_rules`): no LAN, no node, inbound only from the lab subnet. - -## Reaching the lab from the workstation (routed path) - -The workstation reaches `10.21.3.0/24` **directly**: the home router routes the subnet to `pve-master`, which -is the it2102 gateway (`10.21.3.1`). The VM firewall only drops traffic the VMs *start* toward the LAN; your -inbound SSH passes, and its replies pass through connection tracking. Verified 2026-11-02 (`ssh` to -a lab VM with no jump): - -```bash -ssh -i ~/OneDrive/credentials/ssh/it2102-vms/id_rsa it2102@10.21.3.20 # ubuntu-trainer ``` - -The first connection asks to trust the host key (cloud-init generates a new one on every rebuild; after a -`destroy`/`apply`, run `ssh-keygen -R ` first). The Ansible inventory `src/ansible/proxmox.ini` uses the -same route (`ansible_host = private_ip`). - -Fallback when the route is missing (e.g. away from home): jump through the node, which sits on it2102 as -10.21.3.1: - -```bash -ssh -i ~/OneDrive/credentials/ssh/it2102-vms/id_rsa -J root@ it2102@10.21.3.20 +SDN zone nt2102 +├── VNet it2102 10.21.3.0/24 ws-etw-0 .10 Windows Server 2022: DC of nt2102.lab + DVWA target +│ ws-etw-1 .11 Windows Server 2022: react2shell web app +│ ubuntu-trainer .20 Loki, Grafana, training, live server (cloud image) +│ nt2102-vpn .50 OpenVPN for remote access (cloud image) +└── VNet it2102k 10.21.4.0/24 kali .30 attacker ``` -## ws-etw-1 (VM 2107) - -Second Windows Server 2022 VM, built like `ws-etw-0`: same shared ISO, q35, UEFI, TPM 2.0, SATA disk, e1000e NIC, -4 cores, 8 GB RAM, 256 GB disk, same `it2102:` firewall rules. It takes over 10.21.3.11 from the removed -`ubuntu-etw`. The VM ID is 2107, not 2104, because Terraform does not order a destroy and a create of two different -addresses. - -Manual steps after `apply` (noVNC console): - -1. Install Windows and set the same Administrator password as `ws-etw-0` (`win_password` in `src/ansible/proxmox.ini` covers both). -2. Set a static IP: `10.21.3.11/24`, gateway `10.21.3.1`, DNS `1.1.1.1`. -3. Do the WinRM bootstrap and Tamper Protection steps in `src/ansible/README.md`, then run Ansible. - -## nt2102-vpn (VM 2105) - -Ubuntu 24.04 VM for an OpenVPN server. It is built the same way as the trainer: shared cloud image, and -cloud-init sets the static `10.21.3.50/24`, gateway `10.21.3.1` and user `it2102` with the `it2102-vms` key. -It has 2 cores, 1 GB RAM and a 10 GB disk. - -```bash -ssh -i ~/OneDrive/credentials/ssh/it2102-vms/id_rsa it2102@10.21.3.50 -``` - -Firewall: the shared `it2102:` rules, plus one rule for this VM only (`local.vpn_rules`): **IN ACCEPT TCP 1194 -from any source** (OpenVPN clients come from outside the lab subnet, DNAT'd as TCP by pve-master). The VM's -`input_policy` is ACCEPT today, so this rule is what keeps the VPN reachable if that policy is ever set to DROP; -OpenVPN must listen on TCP (`proto tcp-server`), not the default UDP. - -- **OpenVPN** was installed by hand on 2026-11-02 (`/etc/openvpn/server/server.conf`: TCP 1194, clients in - `10.8.0.0/24`, PKI under `/etc/openvpn/easy-rsa`). Ansible (`src/ansible/vpn.yml`, role `vpn_routing`) manages only - the routes pushed to clients (lab `10.21.3.0/24` + Kali `10.21.4.0/24`) and the NAT. -- **No SNAT to the lab (2026-11-15):** VPN client traffic to `10.21.3.0/24` / `10.21.4.0/24` keeps its real `10.8.0.x` - source (iptables RETURN above the MASQUERADE, saved in `/etc/iptables/rules.v4`), so lab VMs and Loki see who connected, - not `10.21.3.50`. Replies find their way back through a pve-master route `10.8.0.0/24 via 10.21.3.50 dev it2102` plus - `nt2102:` FORWARD accepts (`src/ansible/proxmox-firewall.yml`). The route is **not persistent** by choice: after a - pve-master reboot or an SDN apply, re-run `proxmox-firewall.yml` (symptom: VPN clients connect but can't reach any VM). - Run `proxmox-firewall.yml` before `vpn.yml --tags nat`. -- Clients on the internet reach it on **external TCP 2102**: the home router forwards TCP 2102 → pve-master - `192.168.1.120:2102`, and pve-master DNATs that to `10.21.3.50:1194` - (`src/ansible/proxmox-firewall.yml`, iptables rules saved with `netfilter-persistent`). Client configs use `remote 2102`. -- The shared OUT DROP to `192.168.1.0/24` also applies to traffic this VM forwards for VPN clients. - Through the tunnel they reach the lab subnet, not the home LAN. - -## kali (VM 2106) - -Kali attacker on its **own** SDN VNet `it2102k` → subnet `10.21.4.0/24` (gateway `10.21.4.1`, SNAT), -separate from the lab subnet `10.21.3.0/24`. 2 cores, 4 GB RAM, 40 GB disk. Built from the **installer -ISO** (there is no Kali cloud image for this path), so — like `ws-etw-0` — it is installed by hand and has -**no cloud-init**: Terraform builds only the hardware. A dedicated `proxmox_sdn_applier.kali` applies the -new VNet to the node on `apply` (the main applier does not re-run for a newly added VNet). - -`kali_iso_url` in `main.tf` is **version-pinned** (`kali-2026.3` when written); confirm/bump it against - before `apply`, like the Windows `iso_url`. - -One-time manual steps after `apply` (noVNC console): - -1. Install Kali from the ISO (guided install; keep Kali's default account **`kali` / `kali`** — Ansible - logs in with it, hardcoded in `src/ansible/proxmox.ini`, not a secret on the lab subnet). -2. Static networking (no DHCP on `it2102k`): IP `10.21.4.30/24`, gateway `10.21.4.1`, DNS e.g. `1.1.1.1` - (output `kali_ip`). -3. Enable SSH: `sudo systemctl enable --now ssh` (Kali allows password auth by default). - -Reaching Kali from the workstation: the home router currently routes **only** `10.21.3.0/24` to -pve-master. Add the same static route for `10.21.4.0/24 → 192.168.1.120` (pve-master LAN IP), **or** jump -through the node: - -```bash -ssh -J root@ kali@10.21.4.30 -``` - -Then provision it (user/password auth, so `sshpass` must be on the control node): - -```bash -sudo apt install sshpass -ansible-playbook -i proxmox.ini kali.yml -``` - -### Firewall (VM 2106) + the cross-subnet attack path - -Kali gets the shared `it2102:` rules (`local.it2102_rules`): no home LAN, no node, inbound only from the -lab + Kali subnets. To let the attack cross between `10.21.4.0/24` and `10.21.3.0/24`, a rule was added to -`it2102_rules` for **all** VMs: `IN ACCEPT ← 10.21.4.0/24`. So `ws-etw-0` accepts Kali's DVWA exploit, and -Kali accepts the `ws-etw-0 → Kali` stage callback (covered by the existing `IN ACCEPT ← 10.21.3.0/24`). -pve-master routes between the two VNet gateways and does not masquerade inter-subnet traffic, so `ws-etw-0` -sees Kali's real `10.21.4.30` source. (Note: this README describes the effective input default as DROP -while `firewall_options` sets `input_policy = ACCEPT` — a doc/code mismatch; the explicit accept rule makes -the path work under either.) - -## Cloud image vs ISO install - -The Ubuntu VMs use a cloud image; the Windows VMs use an installer ISO (there's no Windows Server eval cloud image). +- Per-VM Proxmox firewall (`it2102:` rules): out to the home LAN and the node dropped; in only from the two lab subnets (plus TCP 1194 on nt2102-vpn). +- VPN: pve-master DNATs external TCP 2102 to nt2102-vpn:1194, and clients keep their real 10.8.0.x source in the lab. +- Ubuntu VMs: cloud image + cloud-init (rebuilt with no manual work). Windows and Kali: ISO + manual install. -| | Cloud image + cloud-init (`ubuntu-trainer`, `nt2102-vpn`) | Installer ISO + manual install (`ws-etw-0`, `ws-etw-1`) | -|---|---|---| -| What Proxmox downloads | A finished disk (`.img`, ~600 MB), imported as the VM disk (`import_from`) | An installer (`.iso`, ~5 GB) attached as a CD-ROM | -| Who sets IP, user, SSH key | Terraform, via the `initialization` block → cloud-init on first boot | You, in the installer / Windows settings | -| Manual steps after `apply` | None | Whole install in the console, then static IP + WinRM bootstrap | -| `destroy` + `apply` | Same VM again, nobody needs to touch it | Empty disk again: reinstall by hand | -| Guest config in Terraform | Yes (IP/user/key are in `main.tf`) | No, only the hardware | -| Reuse | One downloaded image serves both Ubuntu VMs | One ISO per OS | +## Key files -Takeaway: the cloud image is the default for anything rebuilt often. The ISO path is the fallback when no -cloud image exists. It can be automated too (`autounattend.xml` or a Packer-built template), but isn't here. +| file | what | +|---|---| +| `main.tf` | all lab values in `locals`: zone, VNets, VMs, firewall rules | +| `variables.tf` | only credentials (`TF_VAR_*`) | +| `versions.tf` | provider pin, root login via SSH agent | +| `terraform.tfstate` | committed state | +| `../src/ansible/proxmox-firewall.yml` · `proxmox-firewall-teardown.yml` | pve-master DNAT + VPN return route, and their removal | diff --git a/presentation/components/LabInfra.vue b/presentation/components/LabInfra.vue index b8eaf60..48fdab5 100644 --- a/presentation/components/LabInfra.vue +++ b/presentation/components/LabInfra.vue @@ -1,8 +1,8 @@ @@ -58,7 +58,7 @@ kịch bản của nhóm - + thành viên (VPN) @@ -71,7 +71,7 @@ ① exploit DVWA - + ④ react2shell RCE diff --git a/presentation/note.txt b/presentation/note.txt index 5402ca8..cb9e5d7 100644 --- a/presentation/note.txt +++ b/presentation/note.txt @@ -154,7 +154,7 @@ Ví dụ FILE có điểm train trong [0.10, 0.23]: Vì p <= 1: điểm >= 10 ⇔ ít nhất ~10 anomalous node trong một câu chuyện liên thông. Thang: Minor < 10, Moderate 10–100, Significant 100–1000, Critical > 1000 [PAPER §7.2.1]. [AUTHOR CODE] dùng > 10 và top-k khi không có gì đạt; đồ án bỏ top-k (live thì mọi window sẽ đỏ). -Mốc [OURS] 30 cũ đã bỏ 2026-11-03 (D8). Live từ 2026-11-15: [OURS] 4.5 trên cả hai host (xem Q13). +Live: [OURS] 4.5 trên cả hai host (D8, xem Q13). Báo cáo: Phụ lục, mục Thuật toán 1. diff --git a/src/README.md b/src/README.md index 5cebd27..351c619 100644 --- a/src/README.md +++ b/src/README.md @@ -1,162 +1,35 @@ -# src/: the OCR-APT demo lab +# src/: code -Everything for the NT2102 demo ("Phát hiện bất thường trên endpoint device log"): detect a demo attack -(e.g. CVE exploit → RCE → ATT&CK techniques) live on a Windows host, using OCR-APT's core method. +Everything that runs: the collector on the Windows VMs, the training pipeline and live detector on the trainer, +the attack, and the provisioning. -- **Windows Server lab VMs** (`ws-etw-0`, `ws-etw-1`): records kernel activity with ETW using our own collector `etw-python/` - (`etwcollect`), which also pushes it to Loki. SilkETW + Grafana Alloy did this until 2026-10-26 (DEVIATIONS D10). -- **Ubuntu trainer** (`ubuntu-trainer`): Loki + Grafana, then logs → graph → behaviour features → one-class - GNN per node type (OCRGCN). -- **Live demo**: scores every 5-minute window, builds alert subgraphs (Alg. 1), optional LLM verdict, web UI. - -Status: `../docs/PROGRESS.md`. Differences from the paper: `../docs/DEVIATIONS.md`. - -## The improve loop: `lab` - -One command walks the whole loop. Set it up once, from the repo root: - -```bash -uv sync # also installs the `lab` command into .venv/bin -source .venv/bin/activate # `lab` is now on PATH (without activating: uv run lab ...) -``` - -Three words, used consistently by every `lab` option: -- **capture**: what the VM recorded, one run in Loki (`x-` from `07`, `live-` from `start-live.ps1`). -- **experiment**: a capture pulled and built, in `out/etw/experiments//`. -- **model**: features plus a trained OCRGCN, in `artifacts/runs//`. - -```bash -lab # overview; `lab -h` = all options + examples -lab status # current model, experiments (provider coverage), models -lab loop # capture -> experiment -> model (interactive: pick the capture, name the model) -lab loop --latest --model exp02 --yes # the same, no questions: newest train capture -lab train --experiment x-20261017T030000Z --model exp03 # retrain an experiment you already have -lab promote exp02 # make it the model the live server loads -sudo systemctl restart ocr-live # (on the trainer) load it -``` - -| step | stage script (writes standalone files you can inspect) | writes | -|---|---|---| -| pull + build | `pipeline/loki_pull.py` → `pipeline/build_experiment.py` | `out/etw/experiments//`: raw, converted and windowed edges, `windows.csv`, `check.json`, `experiment.json` | -| features | `pipeline/encode_to_features.py` | `artifacts/runs//features/` (the scaler is fit on this train data) | -| train | `pipeline/train_gnn_models.py` | `artifacts/runs//models/`, `train_meta.json`, `train_scores.csv` | -| record | `lab` | `artifacts/runs//experiment.json` (a copy) + `lineage.json` (experiment, commands, git commit) | -| promote | `lab` | `artifacts/current.local.json`, the current-model pointer | - -**One folder = one model.** Everything the live server needs is inside `artifacts/runs//`, and a -trained model is never overwritten. - -**Current model:** -- `artifacts/current.local.json` if it exists (per machine, gitignored, written by `lab promote`); -- otherwise `artifacts/current.json` (in git). - -`live_server.py`, `serve.sh`, `rejudge.sh` and the `ocr-live` service all read it, so a new model is one -`lab promote` away. - -## The folders at a glance - -| folder | kind | runs where | in git | -|---|---|---|---| -| `etw-python/` | the ETW collector `etwcollect` (uv project, stdlib + ctypes): ETW -> SilkETW-format lines -> Loki; cloned onto the VM by Ansible | VM | yes | -| `ansible/` | provisions the lab VMs (Windows: etw-python collector, vulnlab; Ubuntu: Loki/Grafana, repo, `ocr-live`; Kali: attack pack); cloud-portable via inventory | control node | yes | -| `lab/` | the `lab` CLI (the loop above) | trainer / host | yes | -| `pipeline/` | stage scripts: Loki pull, convert, window, features, training, scoring, Alg. 1/2 | trainer / host | yes | -| `live/` | live demo: server, engine, Loki source, web UI, replay tools | trainer | yes (`sessions/` no) | -| _(no `scripts/`)_ | benign = idle pulled from Loki; the capture scripts were removed 2026-10-31 (D2) | — | — | -| `artifacts/` | data we keep: trained runs (each with its features), the current-model pointer, paper features | — | yes | -| `out/` | local data: experiments pulled from Loki, raw captures | trainer / host | no | -| `atomic-attack-pack/` | attack scenarios + labelling scheme | VM (isolated) | yes | -| `notebooks/` | EDA notebooks, numbered in reading order | Jupyter | yes | - -## Start here (new member) - -Read in this order (about 30 minutes): - -1. `../docs/notes/data-flow.md`: how Windows logs become the model's input, end to end (raw events → edges → windows → features → tensors). - Then, in a browser: `../docs/explainers/edges-to-node-features.html` (edges → the 15 node features), - `../docs/explainers/live-windows.html` (how one live window is scored; windows vs stride), - `../docs/explainers/training-windows.html` (20-min capture → 5-min windows → purge → one pooled graph → idle features) and - `../docs/explainers/inference.html` (how a score maps back to a real process / file / network node). -2. `../docs/reports/teammate.md`: how to run things, known pitfalls, open tasks. -3. `ansible/README.md` (the lab VMs) and `live/README.md` (the live demo). - -Then pick a path. All commands run from the **repo root** after `uv sync`; `lab` also needs -`source .venv/bin/activate`. - -| you want to… | needs a VM? | do this | -|---|---|---| -| see that the code runs | no | `./selftest.sh` (each step proves "it runs", not "it detects attacks") | -| look at the data | no | `uv run jupyter lab`, then open `src/notebooks/` (start with `04-features-self/`) | -| understand the model | no | read `pipeline/train_gnn_models.py` top to bottom (shapes in comments) | -| see what you have | no | `lab status` | -| watch the demo without the Windows VM | trainer only | feed Loki from a recording: `live/README.md` step 5 (`loki_push.py`) | -| retrain | trainer | `lab loop`, then `lab promote ` | -| run the real live demo | both | `ansible/README.md`, then `live/README.md` step 5 | - -`out/` and `live/sessions/` are not in git. To replay or retrain on our first capture, ask a teammate for a -copy of `out/etw/experiments/20261009T145632Z/`. - -## What is in each folder +## Architecture ``` -src/ -├── etw-python/ the ETW collector `etwcollect` (README.md: commands, modules, format differences) -├── ansible/ site.yml / windows.yml / ubuntu.yml, roles/, inventories (ansible/README.md) -├── lab/cli.py the `lab` command (status, pull, train, loop, promote, current, selftest) -├── pipeline/ stage scripts (Python, code only; each has --selftest) -│ ├── lokiclient.py Loki HTTP calls (+ fake Loki for selftests) -│ ├── loki_pull.py Loki -> experiment raw/ (interactive picker or flags) -│ ├── build_experiment.py raw/ -> converted, windowed edges, check.json, experiment.json -│ ├── etw2nodlink.py SilkETW-format JSON -> edges (the converter; Ansible copies it to the VM too) -│ ├── etwwindow.py edges -> 5-min windows; check_rdf_input.py input-contract check -│ ├── encode_to_features.py edges -> 15 behaviour features per node (paper §5.1.2) -│ ├── train_gnn_models.py trains one OCRGCN per node type -│ ├── score_window.py scores any edge CSV with a trained run (shared with the live demo) -│ ├── alg1.py Alg. 1 subgraphs + subgraph-score filter (in memory); re-judges sessions -│ └── alg2.py LLM triage + Alg. 2 attack report on red windows (optional) -├── live/ live demo (live/README.md) -│ ├── live_server.py FastAPI server: --loki-url, /ingest, /api/*, SSE, UI at / -│ ├── loki_source.py live input: follows the newest test run in Loki -│ ├── engine.py reorder by event time, convert, cut windows, score, call alg1/alg2 -│ ├── loki_push.py test feed: pushes a recorded run into Loki in Alloy's shape -│ ├── etwship.py HTTP --replay (for compare_replay) and --print-dos-map (etwctl uses it) -│ ├── compare_replay.py checks that live results equal the offline pipeline -│ ├── static/index.html the web UI -│ └── sessions// per-session outputs (not in git) -├── artifacts/ data we keep in git -│ ├── current.json the current-model pointer (current.local.json overrides it, not in git) -│ ├── runs// one model: models/, features/, experiment.json, lineage.json, train_*.csv -│ ├── runs/exp01/ the first model (Win10 data); its features are in features/self-dataset/ -│ └── features/ self-dataset/ (exp01's features + scaler), paper/ (NODLINK W10) -├── out/ local data (not in git) -│ ├── etw/experiments// one experiment: raw/, converted/, windowed edges, windows.csv, -│ │ experiment.json, check.json, pull.json (from Loki), labels/ledger.csv -│ ├── etw/raw/{train,test}/ raw SilkETW captures (VM side) -│ └── _old/ early test captures and an un-windowed capture; do not train on them -├── atomic-attack-pack/ 10 attack scenarios (Atomic Red Team + custom), LABELING.md, tools/ -└── notebooks/ EDA: 01-silketw-raw … 05-features-paper +VM etw-python/ (etwcollect) ─► Loki +trainer pipeline/: loki_pull → build_experiment (graph, windows) → encode_to_features (15 per node) + → train_gnn_models (one OCRGCN per node type) → artifacts/runs// + live/: Loki → engine (score windows, alg1 subgraphs, alg2 LLM) → web UI + history + lab/: the `lab` CLI that drives pull → build → features → train → promote ``` -`artifacts/runs/exp01/train_meta.json` and `artifacts/features/*/feature_scaler.json` record the input -paths as they were at training time. They are a record of that run; do not edit them. - -## Data flow - -1. VM: the always-on `start-live.ps1` capture ships every ETW line to Loki on the trainer (benign = idle; no capture script). -2. Trainer: `lab loop` runs `loki_pull.py --build` → `encode_to_features.py` → `train_gnn_models.py`, all into - `artifacts/runs//`. Then `lab promote `. -3. Live: Loki → `live/live_server.py --loki-url` (current model) → `live/sessions//` + web UI. - -The converter (`pipeline/etw2nodlink.py`) is the same file on the VM and the trainer. `experiment.json` -records its sha256 and the live server compares it (`converter_check`). Edit it before a capture, never after. +One folder per trained model (`artifacts/runs//`: models, features + scaler, lineage); a model is never +overwritten. The converter (`pipeline/etw2nodlink.py`) is the same file on the VM and the trainer, and its +sha256 is checked at load. -## Pitfalls +## Folders -| symptom | cause → fix | +| folder | what | |---|---| -| collapsed model, all-zero features | trained on un-windowed edges (e.g. `out/_old/etw/SimulatedW10_train_edges.csv`) → train on an experiment folder (`lab train --experiment`) | -| a provider covers only a minute of the capture | `lab status` warns (e.g. `kfile 1/21m` in `20261009T145632Z`) → check the collector before training on it | -| installer activity flagged in a "benign" test | software installs are not benign → pull a clean *idle* range from Loki (`lab pull --start … --end … --split test`) | -| VM dies, looks like OOM | VMSVGA segfault in `libnvidia-glcore` (3D acceleration) → keep `accelerate3d off`; check `journalctl -k` and `VBox.log.1` first | -| `converter_check: MISMATCH` | the model was trained with another converter version → rebuild + retrain (`lab loop`) | -| live server loads the wrong model | `lab current` shows which pointer is used (`current.local.json` wins) | +| `etw-python/` | ETW collector | +| `pipeline/` | Loki pull, converter, windowing, features, training, scoring, Alg. 1, Alg. 2 | +| `live/` | live detector, web UI, snapshot playback | +| `lab/` | `lab` CLI | +| `artifacts/` | trained models, current-model pointer, paper features | +| `atomic-attack-pack/` | RCE kill chain | +| `ansible/` | lab provisioning | +| `notebooks/` | EDA, numbered in reading order | +| `audit-python/` | retired auditd shipper | + +Every pipeline module has a `--selftest`; `./selftest.sh` runs them all. They prove the code runs, not that it +detects attacks. diff --git a/src/ansible/README.md b/src/ansible/README.md index 8e740f1..4291f94 100644 --- a/src/ansible/README.md +++ b/src/ansible/README.md @@ -1,350 +1,38 @@ -# Ansible: lab provisioning +# src/ansible/: lab provisioning -Provisions the lab VMs (`infrastructure/` builds them on Proxmox, or point this at any cloud VMs in one -subnet): +Configures every lab VM idempotently: a re-run on a configured box reports `changed=0`. Addresses come from the +inventory, so the same roles also target cloud VMs (`inventory.cloud.ini.example` + vault). -| host (group) | address | role | -|---|---|---| -| `ws-etw-0` (`windows`) | 10.21.3.10 | ETW collector **`etwcollect`** (`src/etw-python`, SYSTEM task `etwlab-collector`; it also pushes to Loki), DVWA vulnlab (optional, `-e vulnlab_enabled=true`). No training. | -| `ws-etw-1` (`windows`) | 10.21.3.11 | Same collector, pushes to the same Loki. No DVWA. | -| `ubuntu-trainer` (`ubuntu`) | 10.21.3.20 | **Loki + Grafana** (Docker, host network), repo + `uv sync`, training, `live_server.py` (systemd `ocr-live`, follows Loki). | +## Outcome -> The lab also has a **Kali attacker VM**: `kali` 10.21.4.30 on its own subnet 10.21.4.0/24 (group -> `attacker`), Ansible-managed via `kali.yml` → role `kali_attack`, which copies -> `src/atomic-attack-pack` to `/opt/attack-pack`. See the "Proxmox lab" section below and the pack's -> `README.md`. +- Two Windows collectors, one trainer/live server, one Kali attacker and the VPN, all from playbooks. +- Trainer resource isolation: SSH and training work capped at 50 % RAM in `user.slice`, monitoring reserved and + never swapped, `ocr-live` killed before monitoring. +- Teardown: `proxmox-firewall-teardown.yml` removes the only state that outlives `terraform destroy` + (pve-master DNAT, FORWARD accepts, VPN return route). -``` -etwcollect (SYSTEM task) -> C:\lab-out\etw\raw\\\{kproc,kfile,knet}.json - -> its shipper thread -> Loki :3100 on the trainer <- Grafana :3000 (browse / LogQL) - training: loki_pull.py -> /raw/ -> build_experiment.py -> features -> train - live: live_server.py --loki-url (loki_source.py) -> windows -> UI :8000 -``` - -Before 2026-10-26 SilkService wrote the files and Grafana Alloy shipped them; `win_collector` now removes -both (DEVIATIONS D10). The Loki contract did not change: Loki keeps every line exactly as written, with these labels next to it: - -| kind | keys | use | -|---|---|---| -| labels (indexed) | `job` (`silketw`, `etw-meta`, `workload-ledger`), `host`, `split` (train/test), `run`, `provider` (kproc/kfile/knet) | choose streams: `{job="silketw", run="x-20261017T030000Z"}` | -| structured metadata (not indexed) | `event` (EventName), `pid` (ProcessID), `process` (ProcessName) | filter: `\| event="ProcessStart"`, `\| process="powershell"` | - -A label is one more index dimension, so each distinct value creates a new stream. With `pid` as a label, -every process would make its own stream, which is why `pid` is metadata instead. LogQL examples for -Grafana *Explore*: - -```logql -{job="silketw", split="train"} # every train line -{job="silketw", run="x-20261017T030000Z", provider="kproc"} | event="ProcessStart/Start" -{job="silketw", split="test"} | process="powershell" | json | line_format "{{.EventName}} {{.ProcessID}}" -sum by (provider) (count_over_time({job="silketw", run="live-20261017T040000Z"}[1m])) # lines per minute -{job="etw-meta"} # dos map of each run -``` - -> DVWA (Damn Vulnerable Web Application) is a deliberately vulnerable PHP lab target, installed for -> **defensive detection practice** in an isolated network. `win_vulnlab` installs XAMPP (Apache + PHP + -> MariaDB) via Chocolatey and serves DVWA on `vulnlab_port`; the Kali box drives the exploit during -> the demo, running the launcher from the deployed pack: -> -> ```bash -> # on Kali (pack deployed to /opt/attack-pack by the kali_attack role): -> python3 -I /opt/attack-pack/tools/launch_exploit.py --target http://10.21.3.10:3000 # only input is the URL -> python3 -I /opt/attack-pack/tools/launch_exploit.py --selftest # serve+fetch, no target -> ``` -> -> The launcher targets DVWA's command-injection sink (`/vulnerabilities/exec/`, field `ip`, security=low) -> by default, logging in as admin/password; pass `--exploit-path`/`--exploit-field` only to override. - -> **Ports stay inside the subnet.** ufw enforces this on the trainer: -> - Loki 3100: only from the Windows host. -> - Grafana 3000: only from `admin_cidr`. -> - Live UI 8000. -> -> The vulnlab (3000 on Windows) stays inside the subnet too. Never expose any of these publicly. - -> **Run the control node on Linux (or macOS), not Windows.** Ansible has no native Windows control -> node, so run these playbooks from your Linux host (or WSL2 on a Windows machine). Windows is only -> ever a *managed* target here, over WinRM. Never install Ansible or run `ansible-playbook` on Windows. - -## Status (2026-10-26) - -| level | state | -|---|---| -| it runs (static) | `--syntax-check` passes for every playbook; 15/15 `./selftest.sh` steps pass (incl. `etwcollect selftest`) | -| Ubuntu side | provisioned on the local `ubuntu-trainer`; a second run reports no changes except the `ocr-live` start (see `repo_branch` below). Verified with the recorded capture `20261009T145632Z` fed through `loki_push.py`: (1) pulled lines = original files (count + sha256 of sorted lines, all 3 providers); (2) `build_experiment.py` edges, node attributes and windows identical to the VM-built ones, line for line; (3) live via `--loki-url`: `compare_replay.py` ALL MATCH, 8/8 windows | -| Windows side | verified on `ws-etw-0` (2026-10-26): `windows.yml` 2nd run `changed=0`, `verify-windows.yml` passes, `etwcollect selftest --live` passes, 32-min live run lossless into Loki (counts = file lines) with kfile lag within ±4 s and 0 lost events (PROGRESS) | -| model | being rebuilt from scratch from Loki-pulled data. `exp01` (Win10 data, older converter) shows `converter_check: MISMATCH`, which is expected | - -## Addresses are inventory-driven (cloud-ready) - -Nothing hardcodes an IP. Each host has two addresses: - -- `ansible_host`: how Ansible connects (WinRM 5985 / SSH 22). Public IP/DNS on cloud. -- `private_ip`: the subnet/VPC IP the VMs use to reach each other (etwcollect → Loki). - -`trainer_host` defaults to the Ubuntu host's `private_ip`, and `loki_url` = `http://:3100`. -The trainer also needs `admin_cidr` (who may open Grafana) and `grafana_admin_password`. Both are in -`proxmox.ini` for the lab; for another cloud, `admin_cidr` goes in the cloud inventory and the password in -the vault. To move to another cloud, `cp inventory.cloud.ini.example inventory.cloud.ini`, fill in both -addresses per host, and add `-i inventory.cloud.ini` to every command. - -## One-time setup - -```bash -cd src/ansible -python3 -m venv .venv && source .venv/bin/activate # dedicated control-node venv (keep it off system Python) -pip install -r requirements.txt # ansible-core + pywinrm (WinRM will NOT work without pywinrm) -ansible-galaxy collection install -r requirements.yml # win modules, chocolatey, posix, docker -``` - -Re-activate the venv (`source .venv/bin/activate`) in any new shell before running `ansible` or -`ansible-playbook`. - -**Cloud/Proxmox creds:** -```bash -cp group_vars/vault.yml.example group_vars/vault.yml # fill win_user / win_password / grafana_admin_password -ansible-vault encrypt group_vars/vault.yml # vault.yml is gitignored -# then add to every cloud command: -e @group_vars/vault.yml --ask-vault-pass -``` - -### Proxmox lab (`proxmox.ini`) - -The VMs from `infrastructure/` (Terraform): `ws-etw-0` 10.21.3.10, `ubuntu-trainer` 10.21.3.20, reached over a -routed path to 10.21.3.0/24. The lab logins are hardcoded in `proxmox.ini` on purpose (user, 2026-11-06): the VMs are -reachable from the home LAN and over the VPN, not from the internet, so no vault is used here. The trainer uses the cloud-init user -`it2102` and the `it2102-vms` key. - -A fresh `ws-etw-0` puts its NIC on the Public profile, where the WinRM firewall rule only accepts the local -subnet, so a routed workstation times out on 5985. Once, in RDP as Administrator (PowerShell): - -```powershell -Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private # NIC -> Private profile -Enable-PSRemoting -Force # WinRM listener + firewall rule -``` - -Check with `nc -zv -w3 10.21.3.10 5985`, then run with `-i proxmox.ini` -(Ubuntu first; add `-e vulnlab_enabled=true` for DVWA). - -The second Windows VM `ws-etw-1` 10.21.3.11 is collector only (`vulnlab_host=false`, so DVWA stays off even with -`-e vulnlab_enabled=true`). Install it by hand (`infrastructure/README.md`) with the **same Administrator password** -as `ws-etw-0` (one `win_password` for the group), do the one-time steps above and the Tamper Protection step below, then: - -```bash -ansible-playbook -i proxmox.ini ubuntu.yml # ufw: Loki :3100 from both VMs; ocr-live; /etc/nt2102-hosts.json -ansible-playbook -i proxmox.ini windows.yml -e vulnlab_enabled=true -``` - -`ocr-live` needs a checkout that knows `--loki-default-host`: merge first, or add `-e repo_branch=`. After a rename -of a Windows host, run `C:\scripts\start-live.ps1 -Rotate` on it: a running capture keeps its old `host` label until -a new run reads `etwlab.json`. Check in Grafana: `{job="silketw", host="ws-etw-1"}` shows kproc, kfile and knet. - -`ocr-live` scores the VMs set with `lab hosts`, each with its own model; until then only `live_loki_host` (`ws-etw-0`). -See `src/live/README.md` "Several Windows hosts". -Lines from before the rename stay labelled `host="ws-etw"`. - -The Linux endpoint is retired (DEVIATIONS D11): `target.yml`, the `linux_*` roles and `src/audit-python` stay in the -repo unused; an inventory `[target]` group brings them back. - -The Kali attacker `kali` 10.21.4.30 (group `attacker`, on its **own** subnet 10.21.4.0/24, `infrastructure/` -VM 2106) is Ansible-managed on Proxmox. It uses **username/password** — Kali's public default `kali` / -`kali`, hardcoded in `proxmox.ini` (not a secret on the lab subnet), so `sshpass` must be on the control -node, no vault. -The `kali_attack` role copies `src/atomic-attack-pack` to `/opt/attack-pack` and selftests the launcher: - -```bash -sudo apt install sshpass # once, on the workstation -ansible-playbook -i proxmox.ini kali.yml -# first boot of a fresh kali is manual (IP + ssh): infrastructure/README.md "kali". -# live attack, once ocr-live runs a Proxmox model (DVWA on ws-etw-0; the launcher auto-detects 10.21.4.30): -# ssh kali@10.21.4.30 -# python3 -I /opt/attack-pack/tools/launch_exploit.py --target http://10.21.3.10:3000 -``` - -### Tamper Protection (Windows, manual, once) - -Defender **Tamper Protection** cannot be toggled remotely. Before the first run, RDP into `ws-etw-0` and -turn it OFF: *Windows Security → Virus & threat protection → Manage settings → Tamper Protection = Off*. -The `win_base` role can then disable real-time monitoring; if Tamper Protection is still on, it warns and -continues. - -## Run - -```bash -# Proxmox lab (proxmox.ini; VMs from infrastructure/). Ubuntu FIRST: etwcollect needs Loki to push to. -ansible -i proxmox.ini ubuntu -m ping -ansible -i proxmox.ini windows -m ansible.windows.win_ping # use win_ping on Windows, NOT ping -ansible-playbook -i proxmox.ini ubuntu.yml # Loki + Grafana + repo + ocr-live -ansible-playbook -i proxmox.ini windows.yml -e vulnlab_enabled=true - # etwcollect (uv) + start-live.ps1 + DVWA vulnlab -ansible-playbook -i proxmox.ini proxmox-firewall.yml --diff # pve-master (root key passphrase): DNAT 2102 -> VPN, - # 10.8.0.0/24 return route (not persistent) + nt2102: FORWARD accepts -ansible-playbook -i proxmox.ini vpn.yml --diff # nt2102-vpn: push lab + Kali routes, no SNAT to the lab - # (run AFTER proxmox-firewall.yml; a route change restarts OpenVPN) +## Architecture -# any other cloud (the vault supplies the Windows + Grafana creds): -ansible-playbook -i inventory.cloud.ini site.yml -e @group_vars/vault.yml --ask-vault-pass ``` - -**`repo_branch` must contain the Loki code.** The trainer clones `repo_url` at `repo_branch` -(`group_vars/all.yml`, default `main`), and `ocr-live` starts `live_server.py --loki-url`. A branch -without `src/live/loki_source.py` makes the service fail with an unknown-argument error. Push this branch -and set `repo_branch` to it, or merge it first. One-off, without editing the file: -`ansible-playbook -i proxmox.ini ubuntu.yml --tags project -e repo_branch=`. - -**LLM on `ocr-live`: `live_llm_args`** (default empty = off; `proxmox.ini` sets the DeepSeek flags). -Non-empty also makes `uv sync` install the `llm` group. The API key is never an Ansible variable: save it once -on the trainer (`alg2.py --ping`, `src/live/README.md` §5) BEFORE the flags are applied, or `ocr-live` exits -at start (no terminal to prompt). `-e live_llm_args=` turns the LLM off for one run. - -`python_embed_sha256` and `uv_sha256` in `group_vars/all.yml` are pinned (the latter from the release's -checksum file). - -**Collector source.** `win_collector` git-clones `repo_url@repo_branch` to `C:\lab\NT2102`; `uv sync ---frozen` builds the venv at `C:\Tools\etw-python-venv`, separate from the clone. Re-run `--tags collector` -after a `src/etw-python` change (a re-clone/fast-forward on every run; the venv rebuilds only when -`pyproject.toml` / `uv.lock` changed). - -## Rebuild training data (from scratch, through Loki) - -```powershell -# on ws-etw-0, elevated PowerShell in the RDP desktop session (not WinRM): -# benign = IDLE pulled from Loki (no capture script): keep the desktop idle so the always-on live capture -# ships idle background activity, then on the trainer pull a clean idle range and train: -# lab pull --start 2026-10-31T12:45:00Z --end 2026-10-31T13:02:00Z --split test --host ws-etw-0 --yes -# # a Loki idle pull is --split test -> files are SimulatedW10_test_*; copy them to _train_ before training: -# cp /SimulatedW10_test_edges.csv /SimulatedW10_train_edges.csv # and _node_attrs.csv -# lab train --experiment --model exp0X && lab promote exp0X && sudo systemctl restart ocr-live -``` -The training source is Loki -(`etwcollect push-ledger`) and **copies** the raw files into the experiment folder. - -```bash -# on ubuntu-trainer (ssh in; LOKI_URL is set by /etc/profile.d/lokistack.sh): -cd ~/NT2102 && source .venv/bin/activate # `lab` comes with uv sync (src/lab/cli.py) -lab status # current model, experiments, models; provider coverage -lab loop # interactive: pick the capture in Loki -> build -> features -> train -lab loop --latest --model exp02 --yes # the same without questions (lab loop -h: all options) -lab promote exp02 && sudo systemctl restart ocr-live # the live server now loads exp02 +ws-etw-0 / ws-etw-1 etwcollect (SYSTEM task) ─push─► Loki :3100 on ubuntu-trainer ◄─ Grafana :3000 + Sysmon EID 1 (command lines, UI + LLM only) +ubuntu-trainer Loki + Grafana (Docker, host network, ufw) · Prometheus stack (127.0.0.1) + repo + uv · ocr-live (systemd, follows Loki, web UI :8000) +kali /opt/attack-pack (RCE kill chain + launcher) +nt2102-vpn · pve pushed lab routes, no SNAT to the lab · DNAT TCP 2102 → OpenVPN ``` -`lab loop` = `loki_pull.py --build` (convert, window, check, `experiment.json`: `07` steps 4–7 on the -trainer) → `encode_to_features.py` → `train_gnn_models.py`, all into one run folder -`src/artifacts/runs//` (models, features + scaler, a copy of `experiment.json`, `lineage.json`). -`lab promote` writes `src/artifacts/current.local.json` (gitignored), which `ocr-live` reads; nothing in -`group_vars` names the model. To share a model, commit its model folder and `lab promote --shared` -(writes the tracked `current.json`). - -**Converter hash rule.** -- `experiment.json` records the sha256 of the converter's raw file bytes. The live server compares it with - its own copy and reports the result as `converter_check`. -- Both now run on the trainer, from the same file. -- Ansible copies the same file to the VM, and `.gitattributes` pins it to LF. -- Edit the converter **before** a training capture, never after. After an edit, build again. - -## Demo (on `ws-etw-0`, elevated PowerShell in the RDP desktop session) - -```powershell -C:\scripts\start-live.ps1 -Rotate # optional: fresh live run = a clean session for the demo -# then just use the desktop normally (browse, docs) to produce benign green windows — no scripted workload -``` - -The live capture itself is **always on**: the SYSTEM scheduled task `live_task_name` (`etwlab-live`) runs -`start-live.ps1` at boot and every `live_watchdog_minutes`; it keeps a `test/live-` run capturing, -rotates it every `live_rotate_hours`, deletes raw `live-*` runs idle for `live_keep_days`, and stays away -while `C:\ProgramData\etwlab\live.hold` exists (`07` sets and clears it; `start-live.ps1 -Pause/-Resume` by -hand). `start-live.ps1 -Status` shows the state and the last lines of `live-watchdog.log`. - -The vulnlab (DVWA) serves on `http://:3000/` from boot (XAMPP's Apache + MariaDB Windows -services). Watch the live UI at `http://:8000/`, and the raw lines in Grafana at -`http://:3000/` (Grafana is :3000 on the trainer; DVWA is :3000 on the Windows host — different -machines). Benign -windows stay green; the teammate's attack turns its window red. -## Checks +## Playbooks and roles -**Loki behaviour to know (observed on 3.7.8, handled in `loki.yaml.j2`):** -- Lines with an OLD event time (a late backlog, a replay) are queryable only after their chunk is flushed. - This config flushes idle chunks after 2 min; `loki_push.py` calls `/flush` itself. -- After a Loki restart, queries return nothing for about a minute. - -**Ubuntu (automated by the role + verified 2026-10-17):** -- `docker compose -f /opt/lokistack/compose.yaml ps` shows `loki` and `grafana` up. -- `curl 127.0.0.1:3100/ready` returns `ready`. -- `ufw status` shows 3100 only from the Windows `private_ip` and 3000 only from `admin_cidr`. - -**Windows (by hand, after `site.yml --limit windows`):** -1. `etwctl status` shows `collector: task etwlab-collector`, and while a run captures: kfile lag of a few - seconds, `ETW lost: events 0`, `Loki: ... backlog` near 0. `etwcollect selftest --live` (elevated) passes. -2. After `etwctl start -Split test`, the run folder has `dosmap.meta`: one JSON line such as - `{"\\device\\harddiskvolume4":"c:"}`. -3. Grafana Explore `{job="silketw", host="ws-etw-0"}` shows lines labelled with `split`, `run` and `provider`, - and the line details show `event`, `pid` and `process`. -4. The Loki time of a line equals its `TimeStamp` (etwcollect writes UTC, `+00:00`; SilkETW wrote `+07:00`). -5. `07` → `loki_pull.py --run x- --yes --build` on the trainer. Its `SimulatedW10_train_edges.csv` - should equal the VM's own `07` result, compared as multisets (sorted lines). -6. The `etwlab-live` task (or `start-live.ps1 -Rotate`) + `06`: the live UI shows `session live- (loki, ws-etw-0)` and windows close. - `converter_check: match` appears once `experiment.json` comes from a capture built with this converter. -7. DVWA's login page answers on `http://:3000/login.php` (Apache + MariaDB services up). - -## Layout - -``` -ansible.cfg requirements.yml requirements.txt site.yml windows.yml ubuntu.yml -proxmox.ini inventory.cloud.ini.example -group_vars/ all.yml windows.yml ubuntu.yml vault.yml.example -roles/ - win_base OS config: net profile, UTC+7, no-sleep, RDP, folders, Defender - win_sysmon Sysmon, Event ID 1 (ProcessCreate) only: process command lines for the UI + LLM, never a feature - (DEVIATIONS D14; sysmon_enabled, default true; the collector reads it as optional provider `sysmon`) - win_collector uv + etw-python venv + SYSTEM task etwlab-collector + embeddable Python + etw2nodlink.py/ - etwwindow.py/etwship.py/etwctl; removes the old SilkService + Grafana Alloy - win_shipper start-live.ps1 watchdog + SYSTEM task etwlab-live (always-on live test capture) - win_vulnlab XAMPP (Apache + PHP + MariaDB) + DVWA, served on vulnlab_port (opt-in: vulnlab_enabled) - ubuntu_base UTC+7 + timesyncd, apt deps + uv + ufw rule for the live server - ubuntu_loki Docker + Loki + Grafana (compose, host network) + ufw (Loki from Windows, Grafana from admin_cidr) - ubuntu_monitoring Prometheus + node-exporter + cAdvisor (own compose project, 127.0.0.1 only) + Grafana dashboard - ubuntu_project git clone + uv sync + ocr-live systemd unit (--loki-url + live_llm_args) + session cleanup cron - kali_attack (Proxmox, kali.yml) copy src/atomic-attack-pack -> /opt/attack-pack + launcher selftest -``` -(Not shown: `linux_auditd`/`linux_auditship` run by `target.yml`, unused while no `[target]` host exists; -`kali_attack` by `kali.yml`. Both run on their own, not via `site.yml`.) - -## Trainer monitoring (CPU, memory) - -Grafana `http://:3000/`, dashboard **Trainer resources** (`admin_cidr` only, same login as for Loki). -Deploy or update with `ansible-playbook -i proxmox.ini ubuntu.yml --tags monitoring`. - -``` -node-exporter :9100 (whole VM) \ - -> Prometheus :9090 (15 s scrape, 15 d or 2 GB) -> Grafana :3000 -cAdvisor :8088 (per service) / -``` - -- `/opt/monitoring` is its own compose project and every service binds 127.0.0.1, so there is no ufw rule. A change - here restarts Grafana at most, never Loki (a Loki restart can cost live windows, D8). -- The dashboard is the file `roles/ubuntu_monitoring/files/trainer-resources.json`. UI edits are not saved. -- "Private memory" is cgroup v2 anonymous memory: what a service cannot give back. It reads lower than `ps` RSS, which - also counts file-backed library pages (`ocr-live`, 2026-11-07: 904 MiB private, 1,245 MiB `ps`). Use private memory - for capacity. - -### What keeps training from hurting monitoring - -Everything started over SSH (`lab`, raw pipeline scripts, `uv sync`, Ansible tasks) runs in `user.slice`; `ocr-live` and -Docker run in `system.slice`. So the limits below hold however training is launched. - -| Protection | Setting | Where | -|---|---|---| -| Cap on SSH work | 45 % of RAM soft, 50 % hard, 40 GiB of swap, all cores but one, low CPU and I/O weight | `user.slice` drop-in, `training_*` vars | -| Reserved for monitoring | 864 MiB (Prometheus 256, Grafana 512, cAdvisor 64, node-exporter 32) | `monitoring_mem`, plus `MemoryLow` on `system.slice` | -| Monitoring cannot swap | `memswap_limit` = `mem_limit` | both compose files | -| Killed last | `oom_score_adj` -500 (`ocr-live` is +500) | both compose files | -| Monitoring cannot run away | hard memory limit per container | `monitoring_mem` | - -- `memory.low` needs every parent to have it too, so `MemoryLow` on `system.slice` must stay the sum of the reservations. -- Check `memory.swap.max` = 0 in the containers after a deploy: Grafana once kept `max` despite a correct Docker config - (cause unknown; `docker compose up -d --force-recreate --no-deps grafana` fixed it). -- The caps are a share of RAM: after resizing the VM, re-run `ubuntu.yml --tags monitoring`. -- Swap: 50 GiB `/swapfile` (`swap_size_gib`, role `ubuntu_base`), `vm.swappiness` 10. Changing the size later needs the - old file removed by hand: the task only creates it. - -The converter and windowing tool (`win_collector`) are deployed from `src/pipeline/`, the same files -`build_experiment.py` runs on the trainer. See the converter hash rule above. +| playbook | roles | +|---|---| +| `windows.yml` | `win_base` (OS, RDP, Defender), `win_sysmon`, `win_collector` (uv, etwcollect, converter), `win_shipper` (always-on capture), `win_vulnlab` (XAMPP + DVWA, opt-in) | +| `ubuntu.yml` | `ubuntu_base` (deps, uv, swap), `ubuntu_loki`, `ubuntu_monitoring`, `ubuntu_project` (repo, `ocr-live`) | +| `kali.yml` | `kali_attack` | +| `vpn.yml` | `vpn_routing` | +| `proxmox-firewall.yml` · `proxmox-firewall-teardown.yml` | pve-master rules, and their removal | +| `site.yml` | `windows.yml` + `ubuntu.yml` | +| `verify-windows.yml` | read-only check of every installed tool | +| `target.yml` | retired Linux endpoint (`linux_auditd`, `linux_auditship`) | + +Inventory: `proxmox.ini` (lab, committed; logins are lab-only). Shared values: `group_vars/all.yml`. diff --git a/src/ansible/group_vars/all.yml b/src/ansible/group_vars/all.yml index be473fb..5920148 100644 --- a/src/ansible/group_vars/all.yml +++ b/src/ansible/group_vars/all.yml @@ -18,7 +18,7 @@ server_bind: "0.0.0.0" loki_port: 3100 grafana_port: 3000 # on the Ubuntu host (vulnlab's 3000 is on the Windows host: no clash) loki_url: "http://{{ trainer_host }}:{{ loki_port }}" -loki_retention: "2160h" # 90 d (user, 2026-11-09; was 72h): how long raw ETW stays queryable, also the max age Loki +loki_retention: "2160h" # 90 d: how long raw ETW stays queryable, also the max age Loki # accepts. Loki stores ~445 MB per 3 days for both VMs (compressed), so ~15 GB at 90 d. loki_image: "grafana/loki:3.7.8" grafana_image: "grafana/grafana:13.2.2" @@ -35,7 +35,7 @@ cadvisor_port: 8088 # cAdvisor defaults to 8080; moved off that common prometheus_scrape_interval: "15s" prometheus_retention_time: "15d" prometheus_retention_size: "2GB" -# Resources kept for monitoring, so a training run cannot take them (ubuntu_monitoring role, README "Trainer monitoring"). +# Resources kept for monitoring, so a training run cannot take them (ubuntu_monitoring role). # reservation = RAM the kernel will not reclaim from it (memory.low), limit = the most it may ever use. monitoring_mem: prometheus: { reservation: 256, limit: 1024 } # MiB @@ -50,7 +50,7 @@ training_memory_high: "{{ (ansible_memtotal_mb * 0.45) | int }}" # MiB: slowed training_memory_max: "{{ (ansible_memtotal_mb * 0.50) | int }}" # MiB: RAM it can never pass training_swap_max_gib: 40 # of swap_size_gib: a runaway job cannot take all of it from the live server training_cpu_quota: "{{ (ansible_processor_vcpus - 1) * 100 }}%" # one core always stays free -# Swap on the trainer (user, 2026-11-07: at least 50 GB). Monitoring containers are kept out of it (memswap_limit). +# Swap on the trainer (at least 50 GB). Monitoring containers are kept out of it (memswap_limit). swap_size_gib: 50 swap_file: /swapfile vm_swappiness: 10 # prefer dropping page cache; swap is the safety net, not working memory @@ -64,7 +64,7 @@ tz_windows: "SE Asia Standard Time" # Windows ID: (UTC+07:00) Bangkok, Hanoi, tz_linux: "Asia/Ho_Chi_Minh" # IANA name, UTC+7, no DST # ---- DVWA vulnlab (XAMPP + Damn Vulnerable Web Application, defensive detection target) ------------ -vulnlab_enabled: false # optional demo target; it may already run elsewhere (e.g. a teammate's cloud VM) +vulnlab_enabled: false # optional demo target; it may already run elsewhere (e.g. a cloud VM) vulnlab_port: 3000 # XAMPP Apache listens here (same port on a different host from Grafana's 3000) vulnlab_repo: "https://github.com/digininja/DVWA.git" vulnlab_dir: 'C:\lab\DVWA' # served at the Apache DocumentRoot, so the exploit path is /vulnerabilities/exec/ @@ -97,7 +97,7 @@ raw_root: 'C:\lab-out\etw\raw' collector_task: "etwlab-collector" # SYSTEM scheduled task that runs `python -m etwcollect run` collector_session: "etwlab-collector" # its ETW session name (etwcollect stop stops it by this name) # Where the collector source comes from: a git clone of repo_url@repo_branch to etwpy_clone_dir. -# etwpy_clone_dir is deliberately NOT a var the role branches on (this file outranks the inventory's +# etwpy_clone_dir is NOT a var the role branches on (this file outranks the inventory's # [windows:vars]); win_collector always clones. etwpy_clone_dir: 'C:\lab\NT2102' uv_dir: 'C:\Tools\uv' # uv.exe, its cache and the CPython it downloads @@ -119,12 +119,12 @@ repo_dest: "/home/{{ ansible_user }}/NT2102" # live_llm_args: extra live_server.py LLM flags for ocr-live; unset/empty = LLM off. Non-empty also installs # the `llm` uv group. Deliberately NOT defined in this file: group_vars/all.yml outranks the inventory's # [ubuntu:vars], so a default here would silently override inventory.local.ini. Uses say `| default('')`. -# The API key is NEVER set here: save it once on the trainer (alg2.py --ping prompts, src/live/README.md §5). +# The API key is NEVER set here: save it once on the trainer (alg2.py --ping prompts for it). # live_loki_host: the host ocr-live follows while the pointer has no per-host models (--loki-default-host; `lab hosts` # wins once used); unset = newest run of any host. Same rule, set in # the inventory's [ubuntu:vars], not here. # live_sg_moderate_from: SG-Det cut-off for ocr-live (Moderate from this subgraph score). Same rule, not defined -# here; the unit template defaults it to 10 = [PAPER] §7.2.1 (user, 2026-11-03); 30 = the old [OURS] live scale. +# here; the unit template defaults it to 10 = [PAPER] §7.2.1. # live_sg_require_types: ocr-live --sg-require-types (the [OURS] NET rule, D8). Same rule, not defined here; the unit # template defaults it to net; none = off (paper behaviour, level alone). # Live sessions keep their window results (windows/, windows.csv, sessions/history.jsonl) forever: that is the diff --git a/src/ansible/proxmox-firewall-teardown.yml b/src/ansible/proxmox-firewall-teardown.yml new file mode 100644 index 0000000..89d4e36 --- /dev/null +++ b/src/ansible/proxmox-firewall-teardown.yml @@ -0,0 +1,94 @@ +# Lab teardown: undo proxmox-firewall.yml on pve-master. The Proxmox host survives `terraform destroy`, and +# /etc/iptables/rules.v4 would restore these rules on every boot, so they must be removed here. +# Everything else goes with `terraform destroy`: the Proxmox VM-level `it2102:` rules, the SDN zone/VNets +# and their SNAT, and every rule inside the VMs (ufw on the trainer, Windows firewall, nt2102-vpn iptables). +# Not covered (manual): the home router's port forward TCP 2102 -> pve-master. +# Inventory values only (proxmox.ini), so it also works after the VMs are gone. iptables-persistent stays installed. +# ansible-playbook -i proxmox.ini proxmox-firewall-teardown.yml --check --diff # preview +# ansible-playbook -i proxmox.ini proxmox-firewall-teardown.yml --diff +- name: pve-master remove the NT2102 DNAT, FORWARD accepts and VPN client return route + hosts: pve + become: true + gather_facts: false + vars: + # Must match proxmox-firewall.yml exactly: the iptables module matches a rule on every field, comment included. + vpn_ip: "{{ hostvars['nt2102-vpn'].private_ip }}" + vpn_client_cidr: 10.8.0.0/24 + lab_bridge: it2102 + vpn_routed_cidrs: + - { cidr: 10.21.3.0/24, name: lab } + - { cidr: 10.21.4.0/24, name: kali subnet } + # Comments only our rules carry; used by the final check (the VM-level Terraform rules are not matched). + nt2102_rule_pattern: 'it2102: DNAT OpenVPN|nt2102: VPN clients ->|-> VPN clients \(via nt2102-vpn\)' + + tasks: + - name: Remove the DNAT rules for external port 2102 (current /tcp comment and the old /udp one) + ansible.builtin.iptables: + table: nat + chain: PREROUTING + in_interface: "{{ wan_iface }}" + protocol: tcp + destination_port: "2102" + jump: DNAT + to_destination: "{{ vpn_ip }}:1194" + state: absent + comment: "it2102: DNAT OpenVPN: ext 2102/{{ item }} -> {{ vpn_ip }}:1194" + loop: [tcp, udp] + register: vpn_dnat + + - name: Remove the forwarded VPN client -> subnet accepts + ansible.builtin.iptables: + chain: FORWARD + source: "{{ vpn_client_cidr }}" + destination: "{{ item.cidr }}" + jump: ACCEPT + state: absent + comment: "nt2102: VPN clients -> {{ item.name }} (no SNAT)" + loop: "{{ vpn_routed_cidrs }}" + register: vpn_fwd_in + + - name: Remove the forwarded subnet -> VPN client accepts + ansible.builtin.iptables: + chain: FORWARD + source: "{{ item.cidr }}" + destination: "{{ vpn_client_cidr }}" + jump: ACCEPT + state: absent + comment: "nt2102: {{ item.name }} -> VPN clients (via nt2102-vpn)" + loop: "{{ vpn_routed_cidrs }}" + register: vpn_fwd_out + + - name: Check the return route for VPN clients + ansible.builtin.command: ip route show {{ vpn_client_cidr }} + register: vpn_route + changed_when: false + check_mode: false # read-only, so --check still shows whether the route would be deleted + + - name: Delete the route {{ vpn_client_cidr }} via nt2102-vpn ({{ vpn_ip }}) + ansible.builtin.command: ip route del {{ vpn_client_cidr }} via {{ vpn_ip }} dev {{ lab_bridge }} + when: ("via " ~ vpn_ip ~ " dev " ~ lab_bridge) in vpn_route.stdout + changed_when: true + + # Rewrites /etc/iptables/rules.v4 from the live rules, so a reboot no longer brings ours back. + - name: Save iptables rules persistently + ansible.builtin.command: netfilter-persistent save + when: vpn_dnat.changed or vpn_fwd_in.changed or vpn_fwd_out.changed + changed_when: true + + # Fail loudly if a copy of one of our rules is still there (e.g. a hand-made one with other fields). + # grep exit codes: 0 = a match (fail), 1 = no match, 2 = file missing (nothing to restore, fine). + - name: Check that no NT2102 rule is left in the live rules + ansible.builtin.shell: set -o pipefail; iptables-save | grep -E '{{ nt2102_rule_pattern }}' + args: + executable: /bin/bash + register: live_left + changed_when: false + failed_when: live_left.rc == 0 + when: not ansible_check_mode # in --check nothing was removed, so this would always fail + + - name: Check that no NT2102 rule is left in /etc/iptables/rules.v4 + ansible.builtin.command: grep -E '{{ nt2102_rule_pattern }}' /etc/iptables/rules.v4 + register: saved_left + changed_when: false + failed_when: saved_left.rc == 0 + when: not ansible_check_mode diff --git a/src/ansible/proxmox-firewall.yml b/src/ansible/proxmox-firewall.yml index b6a293e..8c888b5 100644 --- a/src/ansible/proxmox-firewall.yml +++ b/src/ansible/proxmox-firewall.yml @@ -50,7 +50,7 @@ comment: "it2102: DNAT OpenVPN: ext 2102/tcp -> {{ vpn_ip }}:1194" register: vpn_dnat - # Not persistent by choice (user, 2026-11-15): a reboot or an SDN apply (ifreload) drops it, and re-running + # Not persistent: a reboot or an SDN apply (ifreload) drops it, and re-running # this playbook brings it back. `ip route replace` is idempotent; the check keeps changed=0 on a re-run. - name: Check the return route for VPN clients ansible.builtin.command: ip route show {{ vpn_client_cidr }} diff --git a/src/ansible/proxmox.ini b/src/ansible/proxmox.ini index 8d0276f..e072a14 100644 --- a/src/ansible/proxmox.ini +++ b/src/ansible/proxmox.ini @@ -1,11 +1,12 @@ # Proxmox lab (infrastructure/ Terraform): the VMs on the SDN VNet it2102, 10.21.3.0/24. # The workstation reaches the subnet directly over a routed path (home router -> pve-master), so # ansible_host = private_ip. Committed to a public repo. -# Lab-only logins are hardcoded here on purpose (user, 2026-11-06): the VMs are not reachable from the internet. +# Lab-only logins are hardcoded here: the VMs are not reachable from the internet. # Run (Ubuntu FIRST: etwcollect needs Loki to push to): # ansible-playbook -i proxmox.ini ubuntu.yml # ansible-playbook -i proxmox.ini windows.yml -e vulnlab_enabled=true -# One-time on a fresh Windows VM (RDP, admin PowerShell) so WinRM accepts a routed source: README "Proxmox lab". +# One-time on a fresh Windows VM (RDP, admin PowerShell) so WinRM accepts a routed source: +# Get-NetConnectionProfile | Set-NetConnectionProfile -NetworkCategory Private; Enable-PSRemoting -Force [windows] # The inventory name is also the Loki `host` label (etwlab.json). @@ -15,7 +16,7 @@ ws-etw-1 ansible_host=10.21.3.11 private_ip=10.21.3.11 vulnlab_host=false # The collector source is a git clone of repo_url@repo_branch (win_collector role); no inventory var needed. [windows:vars] -# Public by choice (user, 2026-11-06), like Kali's login below. Reachable from the home LAN and over the VPN, not +# Public, like Kali's login below. Reachable from the home LAN and over the VPN, not # from the internet: any home-LAN device can reach WinRM 5985. Do not reuse this password anywhere else. win_user=Administrator win_password=Caohoc@nt2102 @@ -32,14 +33,14 @@ ansible_ssh_common_args='-o StrictHostKeyChecking=accept-new' admin_cidr=192.168.1.0/24 # Lab-only Grafana login (admin / labadmin), same as inventory.local.ini: ufw limits Grafana to admin_cidr. grafana_admin_password=labadmin -# LLM verdict on red windows (DeepSeek). The key is saved once on the trainer: src/live/README.md §5. +# LLM verdict on red windows (DeepSeek). The key is saved once on the trainer (alg2.py --ping prompts for it). live_llm_args='--llm-provider deepseek --llm-reasoning-effort none --llm-debug --llm-max-per-day 30' # The host ocr-live follows until `lab hosts` picks hosts (the DVWA target). Without it, it would flip between hosts. live_loki_host=ws-etw-0 -# SG-Det cut-off: Moderate from this subgraph score (unit default 10 = [PAPER] §7.2.1). 4.5 = [OURS] (user, 2026-11-15): -# the teammate's real react2shell run on ws-etw-1 peaked at 4.72 with a NET node (18:45Z 11-14); re-judge of 24 h: D8. +# SG-Det cut-off: Moderate from this subgraph score (unit default 10 = [PAPER] §7.2.1). 4.5 = [OURS]: +# the real react2shell run on ws-etw-1 peaked at 4.72 with a NET node (18:45Z 11-14); re-judge of 24 h: D8. live_sg_moderate_from=4.5 -# NET rule off (user, 2026-11-15): the teammate's 11-15 react2shell run (winPEAS, sc/schtasks, node -> powershell -enc) +# NET rule off: the 11-15 react2shell run (winPEAS, sc/schtasks, node -> powershell -enc) # scored up to 19.9 but every window was suppressed for lacking an anomalous NET node. Off = paper behaviour; more benign red: D8. live_sg_require_types=none @@ -52,7 +53,7 @@ kali ansible_host=10.21.4.30 private_ip=10.21.4.30 [attacker:vars] # Kali's PUBLIC default account (kali / kali): not a secret on a lab host-only subnet, so hardcoded -# here (user, 2026-11-04). +# here. # Username/password auth (not the it2102-vms key); sshpass must be on the control node. ansible_user=kali ansible_password=kali diff --git a/src/ansible/roles/ubuntu_base/tasks/main.yml b/src/ansible/roles/ubuntu_base/tasks/main.yml index 654c44f..de05825 100644 --- a/src/ansible/roles/ubuntu_base/tasks/main.yml +++ b/src/ansible/roles/ubuntu_base/tasks/main.yml @@ -45,7 +45,7 @@ when: not uv_bin.stat.exists changed_when: true -# ---------- swap (user, 2026-11-07) ---------- +# ---------- swap ---------- - name: Check for the swap file ansible.builtin.stat: path: "{{ swap_file }}" diff --git a/src/ansible/roles/ubuntu_monitoring/tasks/main.yml b/src/ansible/roles/ubuntu_monitoring/tasks/main.yml index 0048e1e..2452d46 100644 --- a/src/ansible/roles/ubuntu_monitoring/tasks/main.yml +++ b/src/ansible/roles/ubuntu_monitoring/tasks/main.yml @@ -2,7 +2,7 @@ # Trainer CPU / memory graphs: node-exporter (whole VM) + cAdvisor (per service, incl. ocr-live.service) -> Prometheus # -> the Grafana the ubuntu_loki role already runs. Run after ubuntu_loki: it needs Docker and Grafana's folders. # -# Own compose project on purpose: the `Restart lokistack` handler restarts Loki too, and a Loki restart can cost live +# Own compose project: the `Restart lokistack` handler restarts Loki too, and a Loki restart can cost live # windows (DEVIATIONS D8). Grafana picks these files up from its existing provisioning mount, so only Grafana restarts. # Host networking like lokistack, but every service binds 127.0.0.1: no ufw rule, nothing reachable off the VM. diff --git a/src/ansible/roles/ubuntu_project/tasks/main.yml b/src/ansible/roles/ubuntu_project/tasks/main.yml index 97870f6..2ec8604 100644 --- a/src/ansible/roles/ubuntu_project/tasks/main.yml +++ b/src/ansible/roles/ubuntu_project/tasks/main.yml @@ -37,7 +37,7 @@ # The Windows capture is always on (win_shipper watchdog) and every live session keeps a raw copy of it # (~2 GB/h under load), so the raw copies are pruned hourly. Only /raw/ goes, once NO file in it # changed for live_raw_keep_hours: the window results (windows/, windows.csv, sessions/history.jsonl) are the -# persistent, range-queryable history and are kept (2026-11-03). replay-* and other folders are never touched; +# persistent, range-queryable history and are kept. replay-* and other folders are never touched; # a session holding a .keep file keeps its raw copy too (touch /.keep). - name: Hourly cleanup of old live raw copies (window results are kept) become: false diff --git a/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 b/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 index 9dae6b3..fe52afb 100644 --- a/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 +++ b/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 @@ -16,7 +16,7 @@ Environment=PYTHONUNBUFFERED=1 # SG-Det cut-off = live_sg_moderate_from (default 10 = [PAPER] §7.2.1; 30 = the old [OURS] live scale). # NET rule = live_sg_require_types (default net = [OURS] D8: a kept subgraph needs an anomalous NET node; none = paper). ExecStart=/usr/local/bin/uv run {{ '--group llm ' if live_llm_args | default('') else '' }}python src/live/live_server.py --bind {{ server_bind }} --port {{ server_port }} --loki-url http://127.0.0.1:{{ loki_port }} --sg-moderate-from {{ live_sg_moderate_from | default(10) }} --sg-require-types {{ live_sg_require_types | default('net') }}{{ ' --loki-default-host ' + live_loki_host if live_loki_host | default('') else '' }}{{ ' ' + live_llm_args if live_llm_args | default('') else '' }} -# 24/7 (2026-11-02): restart on ANY exit, incl. the server's own watchdog (--watchdog-s) after a dead worker +# 24/7: restart on ANY exit, incl. the server's own watchdog (--watchdog-s) after a dead worker # thread or a hung Loki poll. A restart mid-run re-reads the run into a fresh sessions/.r2 folder. Restart=always RestartSec=10 diff --git a/src/ansible/roles/vpn_routing/defaults/main.yml b/src/ansible/roles/vpn_routing/defaults/main.yml index e463951..5660091 100644 --- a/src/ansible/roles/vpn_routing/defaults/main.yml +++ b/src/ansible/roles/vpn_routing/defaults/main.yml @@ -1,5 +1,5 @@ --- -# nt2102-vpn (OpenVPN server, set up by hand on 2026-11-02). This role manages only what VPN clients can reach +# nt2102-vpn (OpenVPN server, set up by hand). This role manages only what VPN clients can reach # and how their traffic is forwarded; OpenVPN itself, the PKI and client certs stay manual. vpn_server_conf: /etc/openvpn/server/server.conf vpn_service: openvpn-server@server diff --git a/src/ansible/roles/win_base/tasks/main.yml b/src/ansible/roles/win_base/tasks/main.yml index 433680e..b6adf1d 100644 --- a/src/ansible/roles/win_base/tasks/main.yml +++ b/src/ansible/roles/win_base/tasks/main.yml @@ -81,7 +81,7 @@ - name: Turn Defender real-time monitoring off # With Tamper Protection ON this is silently ignored. Turn TP off in the Windows Security GUI once - # (see README "Tamper Protection"), then re-run this role. + # (Windows Security > Virus & threat protection > Manage settings), then re-run this role. ansible.windows.win_powershell: script: | Set-MpPreference -DisableRealtimeMonitoring $true diff --git a/src/ansible/roles/win_collector/files/etwctl.ps1 b/src/ansible/roles/win_collector/files/etwctl.ps1 index 2b9a5b3..f99b352 100644 --- a/src/ansible/roles/win_collector/files/etwctl.ps1 +++ b/src/ansible/roles/win_collector/files/etwctl.ps1 @@ -8,7 +8,7 @@ Settings come from C:\ProgramData\etwlab\etwlab.json (written by the win_collector role). The collector is etwcollect (src/etw-python), run by the SYSTEM scheduled task CollectorTask; it pushes the - run's lines to Loki itself (DEVIATIONS D10; it replaced SilkService + Grafana Alloy on 2026-10-26). + run's lines to Loki itself (DEVIATIONS D10). PowerShell notes: Get-ScheduledTask / Start-ScheduledTask read / start a Task Scheduler task (its .State is Ready, Running, ...); `& $exe args` runs a program; $LASTEXITCODE is the diff --git a/src/ansible/roles/win_collector/tasks/main.yml b/src/ansible/roles/win_collector/tasks/main.yml index c94012f..5f0053b 100644 --- a/src/ansible/roles/win_collector/tasks/main.yml +++ b/src/ansible/roles/win_collector/tasks/main.yml @@ -3,7 +3,7 @@ # converter/windowing tool/shipper + etwctl. The Python tools are copied byte-for-byte from src/pipeline and # src/live, so Get-FileHash on the VM (experiment.json tools.*) equals the sha engine.py load_converter computes. -# ---------- 1. Remove the old collector path (SilkETW/SilkService + Grafana Alloy, replaced 2026-10-26) ---------- +# ---------- 1. Remove the old collector path (SilkETW/SilkService + Grafana Alloy) ---------- # Idempotent and cloud-safe: every step is a no-op when the old pieces are not there. - name: Remove the SilkService service ansible.windows.win_service: diff --git a/src/atomic-attack-pack/README.md b/src/atomic-attack-pack/README.md index f2e2066..07e625b 100644 --- a/src/atomic-attack-pack/README.md +++ b/src/atomic-attack-pack/README.md @@ -1,78 +1,32 @@ -# Attack pack — the RCE kill chain +# src/atomic-attack-pack/: RCE kill chain -The demo's ONE attack (CLAUDE §8 end goal): a Kali VM exploits the lab's vulnerable service -(`DVWA`, OS command injection → RCE) and delivers a compact MITRE ATT&CK chain that runs on the Windows -target as a child of the RCE shell. Everything is visible to the SilkETW Kernel-Process/File/Network collector and -self-labelled into `C:\lab-labels\attack-labels.jsonl`. Phase/ATT&CK table: `SCENARIOS.md`. Labels and -their limits: `LABELING.md`. +The demo attack: from a Kali VM, exploit DVWA's OS command injection on `ws-etw-0`, then run an +ATT&CK-mapped post-exploitation chain as a child of the RCE shell, using real signed tools rather than malware. +Lab only: the target subnets cannot reach the home LAN. -## Safety +## Outcome -- Lab only. The target (`ws-etw`) is isolated by the Proxmox SDN firewall rules - (`infrastructure/README.md`), not by unplugging a NIC: `it2102`/`it2102k` only route to each other and - to the internet for provisioning, never to the home LAN. Defender is off on `ws-etw`. `DVWA` is opt-in - (`vulnlab_enabled=true`) and firewalled to the lab subnets only. -- **No snapshot/rollback exists yet** (known gap — nothing in `infrastructure/` automates a Proxmox - snapshot restore). `cleanup-all.ps1` is the only reset today and is best effort. -- Kali keeps its own NAT (for apt) but reaches the target only over the routed lab subnets. +- 3 of 3 live runs turned their window red with an LLM `attack` verdict, with no detection rule written for it. +- High-volume by design (scan ≈ 360 connection attempts, beacon + DB bursts over 180 s), so the attack stands + out on its own, with no detector-side weighting. +- Log clearing (`wevtutil.exe`) is captured but not flagged on its own; it looks normal by its own behaviour. -## Pieces +## Architecture ``` -scenarios/rce-killchain.ps1 the ONE attack: runs on the target (RCE child); scan + REAL tool - download+exec + MySQL enumeration + C2 beacon + persistence + T1070 - anti-forensics (clear event logs, delete tools); custom + labels -tools/launch_exploit.py Kali side: serves the stage (lib, chain, real tool binaries, /beacon) + fires - the DVWA command-injection exploit -lib/attack-lib.ps1 Initialize-AttackLab, Write-AttackLabel, Invoke-LabeledStep/Atomic -tools/win/ real Windows tool binaries staged by Ansible (gitignored; marker fallback) -cleanup-all.ps1 undo the task + tool procs/PSEXESVC/files + RCE shells (snapshot is better) -manifest.json machine-readable technique/indicator map -SCENARIOS.md phase table, topology, alert cut-off -LABELING.md labels.jsonl -> node labels, honesty caveats -tools/build_node_labels.py labels.jsonl + converted graph -> node labels (sketch; columns not fixed yet) +Kali launch_exploit.py ─► DVWA /vulnerabilities/exec/ (command injection) ─► PowerShell cradle on ws-etw-0 + serves stage (lib, chain, tool binaries, /beacon) ◄─────────────────── rce-killchain.ps1 downloads + runs +Chain Discovery → T1046 scan → T1105 tool download + run (PsExec, rclone, nmap, ncat) → MySQL dump + → C2 beacon → T1053.005 scheduled task → T1070 clear logs + delete tools; every step self-labelled ``` -Ansible copies this pack to the Kali VM at `/opt/attack-pack` (`src/ansible/kali.yml` → `kali_attack` -role; Kali is `10.21.4.30` on its own subnet `it2102k`, the target is `http://10.21.3.10:3000`). The -launcher is run directly from `/opt/attack-pack` and auto-detects the attacker IP, so the only required -flag is `--target`. - -## Run during a live session (end-goal path) - -1. **Target VM (`ws-etw`)**, RDP desktop: - ```powershell - C:\scripts\start-live.ps1 -Status # confirm the always-on live capture is recording (etwcollect -> Loki) - ``` - Keep the desktop **idle** (the idle benign baseline); the attack window's own background activity is - the benign noise. (The always-on live task usually already runs; `start-live.ps1 -Rotate` starts a fresh - session for the demo.) -2. **Kali attacker** (pack at `/opt/attack-pack`, Ansible-managed, target `http://10.21.3.10:3000`), - the only required input is the vulnerable web URL: - ```bash - python3 -I /opt/attack-pack/tools/launch_exploit.py --target http://10.21.3.10:3000 --attack-seconds 180 - # DVWA's command-injection sink (/vulnerabilities/exec/, field 'ip', security=low) is the default; - # override only if you changed it: --exploit-path / --exploit-field - # --attack-seconds ([OURS], default 180 = >= 3 min) loops Discovery + the C2 beacon so the attack - # sustains activity across the window instead of a ~10 s blip; 0 = single fast pass. The stage is - # served for attack-seconds + 30 automatically. Persistence (schtask) is created once. - ``` -3. Watch that window in the live UI (trainer `ocr-live`): the RCE subtree should push the window to - **red (≥ Moderate, sg_score ≥ 10, the paper's scale)** while benign windows stay green; `--llm-provider` adds a verdict. - The detector is paper-faithful SG-Det (no per-type weighting; the earlier NET ×2 idea was rolled back). - -Start just after a 5-min window boundary (a 180 s attack fits inside one 5-min window). Whether the chain -clears the cut-off is confirmed here, not tuned (`SCENARIOS.md`, DEVIATIONS D8). - -## Selftests (no VM) - -```bash -python3 -I tools/launch_exploit.py --selftest # stage serves lib+chain+tool, contacts no target -pwsh scenarios/rce-killchain.ps1 -SelfTest # (on the VM) one well-formed label line written -``` +Labels come from injection + indicator/time matching, not analyst ground truth (`LABELING.md`, DEVIATIONS D6). -Offline route (test capture → convert → `tools/build_node_labels.py`) is not runnable yet: the label -script's columns do not match the converter output (`docs/PROGRESS.md` Open items). The live demo does -not need it. +## Key files -Labels come from injection + indicator/time matching, not analyst ground truth (`LABELING.md`, DEVIATIONS D6). +| file | what | +|---|---| +| `scenarios/rce-killchain.ps1` | the chain (runs on the target) | +| `tools/launch_exploit.py` | Kali side: stage server + exploit | +| `lib/attack-lib.ps1` · `cleanup-all.ps1` | labelled-step helpers · best-effort reset | +| `SCENARIOS.md` · `LABELING.md` · `manifest.json` | phase table · label scheme and caveats · technique map | diff --git a/src/atomic-attack-pack/SCENARIOS.md b/src/atomic-attack-pack/SCENARIOS.md index a0d423c..6ea8e8c 100644 --- a/src/atomic-attack-pack/SCENARIOS.md +++ b/src/atomic-attack-pack/SCENARIOS.md @@ -34,7 +34,7 @@ endpoint; phases are separated by port (exploit → :3000, stage/download → :8 | Persistence | Persistence | T1053.005 | `schtasks.exe` creates task `UpdaterSync` running the tool | | Defense evasion | Defense evasion | T1070.001, T1070.004 | `wevtutil.exe cl Security/System/Application` under the RCE shell (process + `.evtx` FILE nodes); `powershell` deletes `C:\Users\Public\tools\` + `downloaded_tool.bin` (anti-forensics). Clearing the event logs does **not** affect collection — `etwcollect` reads live ETW sessions, not `.evtx`. **Observed (2026-11-06):** captured but scores **in-distribution** (not flagged), so it does not enter the kept subgraph or lift the alert — a lone short-lived process is not anomalous by its own per-node features (DEVIATIONS D5/D8); the window reds on the tool/C2/DB nodes | -The chain is deliberately **high-volume** (user, 2026-11-04): the scan alone is ~360 connection attempts, +The chain is **high-volume** by design: the scan alone is ~360 connection attempts, and the beacon + DB bursts repeat for `--attack-seconds` (default 180 ≥ 3 min). That is the point — more real attacker activity = more flagged nodes = a higher subgraph score **without any detector-side weighting** (the earlier NET ×2 idea was rolled back). It also means a large NET/process spike: mind the @@ -51,8 +51,7 @@ artefacts above fall under. ## The alert cut-off (honesty) -A window alerts only if one subgraph holds roughly ≥ 10 anomalous nodes (the paper's Moderate, DEVIATIONS D8; -it was ≥ 30, set on ONE benign window, until 2026-11-03). The kill chain is sized (a Discovery burst of several processes + the download + +A window alerts only if one subgraph holds roughly ≥ 10 anomalous nodes (the paper's Moderate, DEVIATIONS D8). The kill chain is sized (a Discovery burst of several processes + the download + persistence, all rooted at the unseen RCE shell) to clear it, but this is **confirmed on a capture, not tuned to the attack**: if the window scores < 10, widen the chain or justify a lower `--sg-moderate-from` from the benign baseline — do not re-tune the threshold to the attack window (that fits the test). @@ -62,7 +61,7 @@ disclosed in DEVIATIONS D8: `--attack-seconds` (default 180) loops Discovery + t attack sustains ≥ 3 min of activity (more flagged nodes + recurring NET telemetry) instead of a ~10 s blip; and the T1105 phase now **downloads and executes real benign tools** (PsExec/rclone; nmap/ncat best-effort) so their processes + sockets add new unseen nodes. The detector stays paper-faithful SG-Det -(the earlier `--sg-net-weight` NET ×2 idea was **rolled back** 2026-11-04); the Moderate=10 threshold is +(the earlier `--sg-net-weight` NET ×2 idea was **rolled back**); the Moderate=10 threshold is unchanged and the live result is still reported as observed. ## Run diff --git a/src/atomic-attack-pack/manifest.json b/src/atomic-attack-pack/manifest.json index f977990..eb3db3d 100644 --- a/src/atomic-attack-pack/manifest.json +++ b/src/atomic-attack-pack/manifest.json @@ -10,7 +10,7 @@ "stage_endpoints": ["/attack-lib.ps1", "/killchain.ps1", "/tool.bin", "/beacon", "/nmap.exe", "/ncat.exe", "/PsExec64.exe", "/rclone.exe"], "note": "DVWA's command-injection page (/vulnerabilities/exec/, field 'ip', security=low) is a documented, intentional OS-command sink; the launcher logs in (admin/password), sets security low, and injects '127.0.0.1 & '. Override with --exploit-path/--exploit-field if needed." }, - "note": "One scenario, custom steps only (no Atomic Red Team dependency). Realistic, deliberately high-volume post-exploitation (scan + tool download/exec + MySQL enumeration + C2 beacon + persistence + T1070 anti-forensics) so the attack stands out from the idle baseline WITHOUT any detector-side weighting. The T1105 tools are REAL benign signed utilities (Sysinternals PsExec, rclone; nmap/ncat best-effort) staged on Kali and EXECUTED on the target: the signal is the tool's process + sockets (new unseen nodes), not file content. Whether the window reaches the SG-Det cut-off (Moderate, DEVIATIONS D8) is confirmed on a capture, not tuned to the attack. Lab-only: benign tools, read-only DB enumeration, scans of the isolated host-only lab subnets, Defender off, disposable VM; no mimikatz / credential-theft malware.", + "note": "One scenario, custom steps only (no Atomic Red Team dependency). Realistic, high-volume post-exploitation (scan + tool download/exec + MySQL enumeration + C2 beacon + persistence + T1070 anti-forensics) so the attack stands out from the idle baseline WITHOUT any detector-side weighting. The T1105 tools are REAL benign signed utilities (Sysinternals PsExec, rclone; nmap/ncat best-effort) staged on Kali and EXECUTED on the target: the signal is the tool's process + sockets (new unseen nodes), not file content. Whether the window reaches the SG-Det cut-off (Moderate, DEVIATIONS D8) is confirmed on a capture, not tuned to the attack. Lab-only: benign tools, read-only DB enumeration, scans of the isolated host-only lab subnets, Defender off, disposable VM; no mimikatz / credential-theft malware.", "scenarios": [ {"id": "rce-killchain", "file": "scenarios/rce-killchain.ps1", "tactics": ["initial-access","execution","discovery","command-and-control","credential-access","persistence","defense-evasion"], diff --git a/src/atomic-attack-pack/scenarios/rce-killchain.ps1 b/src/atomic-attack-pack/scenarios/rce-killchain.ps1 index 9962659..e7df35a 100755 --- a/src/atomic-attack-pack/scenarios/rce-killchain.ps1 +++ b/src/atomic-attack-pack/scenarios/rce-killchain.ps1 @@ -6,7 +6,7 @@ itself: the Kali attacker (tools/launch_exploit.py) exploits DVWA and delivers this script as the stage. See SCENARIOS.md for the phase/ATT&CK table and README.md for the run recipe. - Realistic post-exploitation chain (user, 2026-11-04 - deliberately high-volume so the attack stands + Realistic post-exploitation chain (high-volume so the attack stands out from the idle baseline on its own, without any detector-side weighting): Initial access / execution ... T1190 + T1059.001 (the delivery; marked only) Discovery .................... T1033 T1082 T1057 T1016 @@ -29,7 +29,7 @@ param( # Where this script fetched its stage from (the Kali attacker). The launcher substitutes these; # defaults keep a manual run on the VM working. ${attacker}:${StagePort} is the T1105/C2 endpoint. - # Env names are neutral on purpose (U_H host, U_P port, U_D duration): Sysmon logs the delivering + # Env names are neutral (U_H host, U_P port, U_D duration): Sysmon logs the delivering # cradle's command line and the LLM reads it decoded; "LAB_*" would leak the lab (DEVIATIONS D14). [string]$Attacker = $(if ($env:U_H) { $env:U_H } else { "10.21.4.30" }), [int] $StagePort = $(if ($env:U_P) { [int]$env:U_P } else { 8080 }), diff --git a/src/atomic-attack-pack/tools/launch_exploit.py b/src/atomic-attack-pack/tools/launch_exploit.py index 1a880be..e5e734b 100755 --- a/src/atomic-attack-pack/tools/launch_exploit.py +++ b/src/atomic-attack-pack/tools/launch_exploit.py @@ -10,7 +10,7 @@ 1. Serves the PowerShell stage over HTTP (this box's lab-subnet IP): /u.ps1 the labeling helpers (../lib/attack-lib.ps1) /s.ps1 the one attack script (../scenarios/rce-killchain.ps1) - Neutral URL paths and env var names on purpose (DEVIATIONS D14): Sysmon records the cradle's command + Neutral URL paths and env var names (DEVIATIONS D14): Sysmon records the cradle's command line, the UI/LLM decode its -enc payload, and lab words such as "attack-lib"/"killchain"/"LAB_" would push the LLM to "attack" for a reason no real intrusion has. /tool.bin a benign marker for the T1105 ingress-transfer step @@ -43,7 +43,7 @@ PACK = Path(__file__).resolve().parent.parent # src/atomic-attack-pack/ LIB = PACK / "lib" / "attack-lib.ps1" SCENARIO = PACK / "scenarios" / "rce-killchain.ps1" -STAGE_LIB, STAGE_SCENARIO = "/u.ps1", "/s.ps1" # served URL paths: neutral on purpose (module docstring, D14) +STAGE_LIB, STAGE_SCENARIO = "/u.ps1", "/s.ps1" # served URL paths: neutral (module docstring, D14) # Real Windows tool binaries are staged here by Ansible (roles/kali_attack) at provision time; this dir is # gitignored and does NOT exist on the control node. When a tool is present we serve its REAL bytes so the # target downloads and EXECUTES the genuine utility (the detector signal is the tool's process + sockets, diff --git a/src/audit-python/README.md b/src/audit-python/README.md index 562ceea..8713b9e 100644 --- a/src/audit-python/README.md +++ b/src/audit-python/README.md @@ -1,60 +1,13 @@ -# auditship: Linux auditd → Loki (ubuntu-etw) +# src/audit-python/: auditd shipper (retired) -The Linux counterpart of the Windows collector's shipper (`src/etw-python`). It runs on the `ubuntu-etw` endpoint -and ships every auditd record to Loki on `ubuntu-trainer`. **Raw logs only:** the OCR-APT pipeline reads -`job="silketw"` (Windows ETW) and has no converter or model for these records (DEVIATIONS D11). +Linux counterpart of the Windows collector: tails `/var/log/audit/audit.log` and pushes every auditd record to +Loki. Retired with the Linux endpoint, which was replaced by a second Windows VM (DEVIATIONS D11). Raw logs only: +the pipeline has no converter or model for auditd records. -``` -kernel audit rules (role linux_auditd: exec, net, file watches; the auditship user excluded) - -> auditd -> /var/log/audit/audit.log one record per line, ENRICHED format - -> auditship run (systemd, user auditship) tail from saved {inode, offset}, follow rotation - -> POST {loki_url}/loki/api/v1/push labels {job="auditd", host="ubuntu-etw"} -``` - -## One record → one Loki entry - -One `curl example.com` produces several records sharing one event serial (`4567`): +## Architecture ``` -type=SYSCALL msg=audit(1762085657.123:4567): arch=c000003e syscall=59 success=yes ... exe="/usr/bin/curl" key="exec"␝ARCH=x86_64 SYSCALL=execve UID="it2102" -type=EXECVE msg=audit(1762085657.123:4567): argc=2 a0="curl" a1="example.com" -``` - -| Line part | Becomes | -|---|---| -| `1762085657.123` (epoch seconds.ms) | entry timestamp `1762085657123000000` ns (event time, not read time) | -| `type=SYSCALL` | structured metadata `type` | -| `key="exec"` (the rule's `-k` tag; SYSCALL records only) | structured metadata `key` | -| the whole line, unchanged (incl. `␝` = `\x1d`, which splits raw fields from resolved names) | entry line | - -Labels stay `{job, host}` (low cardinality); filter in Grafana with e.g. -`{job="auditd", host="ubuntu-etw"} | key="exec"` or `| type="EXECVE"`. - -## Delivery (`tail.py`) - -- `positions.json` = `{"inode", "offset"}`, rewritten after every batch Loki accepted (204). Loki down = the - offset stays and the batch is retried with backoff (1 s → 30 s), so lines are delayed, not lost. -- Rotation: auditd renames `audit.log` → `audit.log.1`. The inode changes under the same path, so we finish the - old file (found by its inode) from the saved offset, then start the new file at 0. -- Batches of ≤ 1 MiB of whole lines; a half-written last line waits. Loki refusing a batch for good (4xx, e.g. - older than the 3-day window) skips it and counts it in `rejected_batches`. -- The Loki client (`LokiClient`, `LokiError`) is imported from `etwcollect.loki` (uv path dependency), so both - collectors share one push contract. - -## Feedback loop (why the auditship user is excluded) - -Each push opens a TCP connection to Loki and rewrites `positions.json`. If the audit rules saw that, every -shipped batch would create new records to ship (the loop SilkService had on Windows, D8/D10). The first -rule in `/etc/audit/rules.d/nt2102.rules` is therefore `-a never,exit -F uid=`. auditd itself is -never audited by the kernel. - -## Commands - -```bash -auditship run --loki-url http://10.21.3.20:3100 --host ubuntu-etw # what the systemd unit runs -auditship status # /var/lib/auditship/status.json + age -auditship selftest # temp log, fake rotation, stub Loki +kernel audit rules (exec, net, file watches; own user excluded) ─► auditd ─► audit.log + ─► auditship (systemd): tail from saved {inode, offset}, follow rotation + ─► Loki /push labels {job="auditd", host}, metadata {type, key}, ts = event time ``` - -`selftest` proves "it runs" (parsing, partial lines, Loki outage, rotation, restart). It says nothing about -detecting anything. diff --git a/src/etw-python/README.md b/src/etw-python/README.md index 8385553..1474eae 100644 --- a/src/etw-python/README.md +++ b/src/etw-python/README.md @@ -1,81 +1,33 @@ -# etw-python: the lab's ETW collector (`etwcollect`) +# src/etw-python/: ETW collector (`etwcollect`) -This replaces SilkETW/SilkService and Grafana Alloy on the Windows VM (DEVIATIONS D10). It records the same -three kernel providers into the same files and pushes them to Loki with the same labels, so nothing on the -trainer changes. It exists because SilkService wrote every event with its own open + write + close, and -those writes fed back into Kernel-File faster than it could drain them (`docs/DEVIATIONS.md` D8, D10). +The lab's own Windows kernel-event collector, replacing SilkETW + Grafana Alloy (DEVIATIONS D10). It records +Kernel-Process, Kernel-File and Kernel-Network, writes SilkETW-format JSON lines and pushes them to Loki itself. +Python stdlib + ctypes only, no third-party packages. -``` -ETW real-time session "etwlab-collector" Kernel-Process 0x50 · Kernel-File 0x380 · Kernel-Network 0x30 - -> callback (one Python thread) drop our own I/O first, decode the payload (cached TDH schema) - -> C:\lab-out\etw\raw\\\ kproc.json · kfile.json · knet.json · dosmap.meta - one SilkETW-format JSON line per event, one batched write per file per second - -> shipper thread whole new lines from saved offsets -> Loki /loki/api/v1/push - {job="silketw", host, split, run, provider} + metadata {event, pid, process}, ts = event time -``` - -stdlib + ctypes only, no third-party packages. - -## Commands - -All commands run elevated on the VM. `etwctl` and the SYSTEM task call them for you. - -| command | what it does | -|---|---| -| `etwcollect run` | capture into the run folder named in `C:\ProgramData\etwlab\state.json` (written by `etwctl start`) until stopped. `--no-push` = files only; `--out-dir DIR` = another folder | -| `etwcollect stop` | stop the ETW session; waits until the collector has flushed, shipped what it can and written `state: stopped` | -| `etwcollect status` | `collector-status.json` (lines, lag, excluded counts, ETW lost-event counters, Loki backlog) + whether the session runs | -| `etwcollect dosmap [--out F]` | this machine's `\device\harddiskvolumeN -> c:` map | -| `etwcollect push-ledger --exp ID --dir \labels` | the 07 workload ledger CSVs -> Loki (`job="workload-ledger"`) | -| `etwcollect selftest` | pure parts on any OS (decode, filters, writer, shipper vs a fake Loki, converter round-trip) | -| `etwcollect selftest --live` | Windows, elevated: a real 15 s session; a child process + a canary file must show up and nothing from our own PID | +## Outcome -Settings come from `C:\ProgramData\etwlab\etwlab.json` (or `$ETWLAB_CONFIG`): `Collectors`, `RawRoot`, -`LokiUrl`, `Host`. It is written by the `win_collector` Ansible role. +- Same files and Loki labels as before, so nothing on the trainer changed. +- Fixes the feedback loop that broke SilkService: its own file writes fed Kernel-File faster than it could drain them. + `etwcollect` drops its own I/O in the ETW callback and batches one write per file per second. +- Plain values (`4096`, dotted IPv4, host-order ports), UTC timestamps and far fewer `N/A` process names. -## Where the code runs - -- Ansible clones the repo on the VM, and the source is `C:\lab\NT2102\src\etw-python`. `uv sync --frozen` - builds the venv on the VM's own disk (`UV_PROJECT_ENVIRONMENT=C:\Tools\etw-python-venv`), separate from - the clone. A code change lands after the next Ansible run (re-clone/fast-forward); on the VM itself, a - change is live after the next `etwctl stop` / `etwctl start`. -- The SYSTEM scheduled task `etwlab-collector` runs `\Scripts\python.exe -m etwcollect run`. - `etwctl start` / `stop` start and stop it. - -On the host (Linux), only the selftest runs: +## Architecture ``` -cd src/etw-python && uv run etwcollect selftest +ETW real-time session Kernel-Process · Kernel-File · Kernel-Network (+ Sysmon EID 1, optional) + ─► callback thread drop own I/O, decode payload (cached TDH schema) + ─► run folder kproc.json · kfile.json · knet.json · dosmap.meta (one batched write per second) + ─► shipper thread new whole lines from saved offsets ─► Loki /push {job, host, split, run, provider} ``` -## Modules (`src/etwcollect/`) - -| file | role | -|---|---| -| `winapi.py` | ctypes declarations of the ETW / TDH / process structs and functions (byte sizes in comments) | -| `session.py` | one real-time session: start (stopping a stale one), enable providers, consume, query, stop | -| `schema.py` | TDH: event type -> names + field list, cached; slow path through TDH for unusual fields | -| `decode.py` | pure Python: payload bytes + field list -> `{name: text}` (plain ints, 0x.. pointers, dotted IPv4, host-order ports) | -| `record.py` | the SilkETW-format line (`EventName` = task or task/opcode, UTC timestamp with 7 digits) | -| `filters.py` | the three exclusion rules (own PID; anything on our own files; network events by payload PID) | -| `procnames.py` | PID -> process name (startup snapshot + ProcessStart), so short-lived processes keep their name | -| `writer.py` | per-file batches, one write + flush per second, whole lines only | -| `loki.py` | push client, file-tail shipper with saved offsets and backoff, dos-map line, ledger push | -| `dosmap.py` | `QueryDosDeviceW` map, device-path conversion, `dosmap.meta` | -| `collector.py` | wires it together: the ETW callback + flush, ship and status threads, clean stop | -| `cli.py`, `__main__.py` | the `etwcollect` command | -| `selftest.py` | offline + `--live` checks | -| `tools/parity.py` | compares a capture with a SilkService capture of the same minutes (migration check) | - -## Differences from SilkETW lines (DEVIATIONS D10) +Runs as the SYSTEM scheduled task `etwlab-collector`, installed by Ansible (`win_collector`). -- `XmlEventData` holds only the payload fields. There is no `FormattedMessage` and none of TraceEvent's - header copies (`MSec`, `PName`, `TID`, header `PID`). -- Values are plain: `4096` not `4,096`, and `23.220.64.154` / `443` instead of SilkETW's signed integers. -- On Kernel-Network, `PID` is the payload owner. SilkETW put it in `_PID` and the converter read the wrong - field (DEVIATIONS D8). -- `TimeStamp` is UTC (`+00:00`) with 7 fractional digits, not the VM's `+07:00`. -- `ProcessName` comes from the startup snapshot plus ProcessStart events, so it is `N/A` far less often. +## Key files (`src/etwcollect/`) -Not verified yet: whether Server 2022's ProcessStart payload carries `ImageName`. If it does not, the -child's name comes from `QueryFullProcessImageNameW`. The parity run settles it. +| file | what | +|---|---| +| `session.py` · `winapi.py` | ETW real-time session over ctypes | +| `schema.py` · `decode.py` · `record.py` | TDH schema cache, payload decode, SilkETW-format line | +| `filters.py` · `procnames.py` · `dosmap.py` | self-exclusion, PID → name, device-path map | +| `writer.py` · `loki.py` | batched file writer, Loki shipper with offsets and backoff | +| `collector.py` · `cli.py` · `selftest.py` | wiring, the `etwcollect` command, offline + live selftests | diff --git a/src/etw-python/pyproject.toml b/src/etw-python/pyproject.toml index 27a6c97..d220c35 100644 --- a/src/etw-python/pyproject.toml +++ b/src/etw-python/pyproject.toml @@ -4,7 +4,7 @@ version = "0.1.0" description = "ETW collector for the OCR-APT lab: Kernel-Process/File/Network -> SilkETW-format JSON lines -> Loki" readme = "README.md" requires-python = ">=3.12" -# No runtime dependencies on purpose: the ETW calls are ctypes, the Loki push is urllib (DEVIATIONS D10). +# No runtime dependencies: the ETW calls are ctypes, the Loki push is urllib (DEVIATIONS D10). dependencies = [] # `etwcollect run | stop | status | dosmap | push-ledger | selftest` (src/etwcollect/cli.py) diff --git a/src/live/README.md b/src/live/README.md index 4b235e3..1764a0f 100644 --- a/src/live/README.md +++ b/src/live/README.md @@ -1,247 +1,41 @@ -# Live demo: VM → Loki → trainer scoring → browser +# src/live/: live detector -``` -VM etwcollect (SYSTEM task) → raw\test\live-\{kfile,knet,kproc}.json (start-live.ps1) - its shipper thread ──push──► Loki :3100 on the trainer (src/etw-python; SilkService + Alloy before 2026-10-26) -trainer live_server.py --loki-url → loki_source.py (poll the newest test run, 1 s) - → engine.py: reorder by event time → etw2nodlink.Graph (same code as training, - src/pipeline/etw2nodlink.py) → 5-min windows → train scaler + train relations → - OCRGCN per type → score > τ → Alg. 1 subgraphs + SG-Det (alert = ≥ 1 subgraph ≥ Moderate - with >= 1 anomalous NET node) - → optional LLM verdict (alg2.py) → sessions//windows// + UI (SSE) -``` - -| file | role | -|---|---| -| `loki_source.py` | follows Loki: newest test run → engine payloads (synthetic offsets, dos map from `etw-meta`) | -| `loki_push.py` | test feed: pushes a recorded run into Loki in the collector's shape (`--shift-to-now --speed N` for live) | -| `etwship.py` | stdlib HTTP shipper: `--replay` on the host (compare_replay), `--print-dos-map` on the VM (etwctl) | -| `engine.py` | ingest, reorder buffer, windows, scoring thread, calls Alg. 1 and the LLM thread | -| `live_server.py` | FastAPI: `/ingest`, `/api/*`, SSE `/api/stream`, UI at `/` | -| `static/index.html` | UI | -| `compare_replay.py` | checks that the live path reproduces the offline pipeline on the training capture | -| `../pipeline/score_window.py` | scorer shared with offline scoring | -| `../pipeline/alg1.py` | Alg. 1 subgraphs + subgraph-score filter; re-judges saved sessions | -| `../pipeline/alg2.py` | LLM verdict on red windows + Alg. 2 attack report; re-judges saved sessions | - -Run everything from the repo root after `uv sync`. Shortcuts: `./selftest.sh`, `./serve.sh [live|local]`, -`./replay.sh [speed]`, `./rejudge.sh [llm-provider]` (`-h` for usage). - -## 1. It runs +Follows each Windows VM's ETW stream in Loki, scores every 5-minute window with that host's OCRGCN model, +turns anomalous nodes into alert subgraphs, asks an LLM for a verdict on red windows, and serves it all in a +web UI with a persistent, range-queryable history. The same server replays a recorded snapshot for the public demo. -`./selftest.sh` → PASS on every step. +## Outcome -## 2. Prerequisite: a valid model - -`src/artifacts/runs/exp01` (current valid run, docs/PROGRESS.md). A retrain on wider benign data -(PROGRESS "Next 3 steps" #1) goes next to it as `exp02`. The server refuses a run whose -`runs_summary.csv` shows `emb_std ≈ 0`. - -## 3. Offline scorer reproduces the training scores - -``` -uv run python src/pipeline/score_window.py --run-dir src/artifacts/runs/exp01 \ - --edges src/out/etw/experiments/20261009T145632Z/SimulatedW10_train_edges.csv \ - --scaler src/artifacts/features/self-dataset/feature_scaler.json -``` -Expect a flag rate per type ≈ `train_flag_rate` in runs_summary.csv; scores equal train_scores.csv. +- Ran 24/7 on the trainer for two weeks on two hosts, with one model per host. +- DVWA kill chain and the real react2shell attack both went red with an LLM `attack` verdict; idle windows stayed + mostly green (a few benign false alarms a day). +- The live path reproduces the offline pipeline on the training capture (`compare_replay.py`). +- Self-healing: watchdog exit + systemd restart, `/healthz`, a restart resumes from Loki. -## 4. Works correctly: replay the training capture (no VM) +## Architecture ``` -./serve.sh local --stride-min 2 --origin-ms 1791557793343 # terminal 1: grid = training w0000, stride 2 -./replay.sh src/out/etw/experiments/20261009T145632Z/raw/train/x-20261009T145632Z # terminal 2: 120x ≈ 10 s -uv run python src/live/compare_replay.py --session src/live/sessions/replay-x-20261009T145632Z \ - --experiment src/out/etw/experiments/20261009T145632Z \ - --features src/artifacts/features/self-dataset/features_model.csv \ - --train-scores src/artifacts/runs/exp01/train_scores.csv +Loki ─► loki_source.py (one per scored VM) ─► engine.py + reorder by event time → provenance graph (same converter as training) → 5-min windows + → train scaler + relations → OCRGCN per node type → anomalous nodes + → Alg. 1 subgraphs + SG-Det level (alg1.py) → red / green + → LLM thread: triage verdict + Alg. 2 report (alg2.py, daily budget) + ─► correlate.py: red window's network nodes → peer VM's process at the other end → both sides to the LLM + ─► repositories (history, cross-host findings, session files) ─► live_server.py (FastAPI + SSE) ─► UI ``` -Expect `ALL MATCH`. Watch at http://127.0.0.1:8000. The dos-map is inferred from the raw paths -(`\device\harddiskvolume4` → `c:` on this VM). Replay speed: 120 works; 0 hangs, 600 times out. -## 5. Live (etwcollect → Loki, the default) +Alert rule: subgraph score = Σ clamped min-max node probability; red at ≥ Moderate (paper scale 10, live 4.5 [OURS], D8). +The LLM verdict is an overlay, never a label or training data (D9). Command lines from Sysmon are shown to +the UI and the LLM only, never used as features (D14). -The trainer runs `ocr-live` (systemd, `src/ansible/roles/ubuntu_project`), which is -`live_server.py ... --loki-url http://127.0.0.1:3100` with the current model (`lab promote `) plus -`live_llm_args` (the LLM flags; set in `inventory.local.ini`, empty = LLM off). +## Key files -**The capture is always on.** The SYSTEM scheduled task `etwlab-live` (win_shipper role) runs -`C:\scripts\start-live.ps1` at boot and every 5 min: it keeps a `test/live-` run capturing, starts a new -run every 6 h, deletes raw `live-*` runs idle for 1 day,. By hand, in an elevated -PowerShell on the VM: -``` -C:\scripts\start-live.ps1 -Status # service, current run, hold, task, last log lines -C:\scripts\start-live.ps1 -Rotate # fresh live run now = a clean session before a demo -C:\scripts\start-live.ps1 -Pause # stop live and keep it stopped; -Resume undoes it -# benign = idle: keep the desktop idle; the always-on capture ships it to Loki, pull an idle range to train -``` -The server follows the newest `split="test"` run, and a new run starts a new session. Window results are kept -forever (the history below); only the raw copy of an old `live-*` session (`/raw/`, ~2 GB/h under load) -is deleted, after 12 idle hours (`live_raw_keep_hours`; a session holding a `.keep` file keeps it). Loki keeps -90 days (`loki_retention`, 72 h until 2026-11-09): pull training captures within that. - -**History: query any time range (2026-11-03, `history.py`).** Every window state (closed, scored, error, LLM -verdict) is appended to `sessions/history.jsonl`, and each scored window's detail to -`windows//detail.json`, so nothing is lost on a restart or a run rotation. The UI's **History** panel -(from / to in lab time, 1 h · 6 h · 24 h · 7 d, alerts only; the URL keeps the range) lists one row per window -start and opens a row in the detail panel. The same from a shell: -``` -curl -s 'http://:8000/api/history?from=2026-11-03T17:00:00Z&to=2026-11-03T18:00:00Z&alert=1' -curl -s 'http://:8000/api/history//' # one window's detail -``` -`from`/`to` take ISO-8601 (no offset = UTC) or epoch ms; default the last 24 h; `replay=1` adds replay sessions. -A row shows the alert, verdict and cut-off **as judged at the time** (`moderate_from`). The first start after the -upgrade backfills older sessions from their `windows.csv` (no LLM report text for those). - -**LLM on the live server.** `ocr-live` has no terminal, so it cannot prompt for the DeepSeek key. Save it -once on the trainer, then let Ansible add the flags: -``` -ssh -i ~/OneDrive/credentials/ssh/it2102-vms/id_rsa it2102@10.21.3.20 -cd ~/NT2102 && uv run --group llm python src/pipeline/alg2.py --ping --llm-provider deepseek # prompts, saves, answers OK -``` -The key lands in `~/.config/nt2102/credentials.json` on the trainer (plain text, mode 600). With -`--llm-debug` in `live_llm_args`, `journalctl -u ocr-live -f` shows every raw LLM response. - -**Replay a live session on the laptop** (to check it by hand): copy `src/live/sessions/live-/` from the -trainer and the model run folder into `src/live/sessions/live-/model/`, then -``` -RUN_DIR=src/live/sessions/live-/model SCALER=<…>/feature_scaler.json EXPERIMENT=<…>/experiment.json \ - ./serve.sh local --llm-provider deepseek --llm-reasoning-effort none --llm-debug # terminal 1 -./replay.sh live- # terminal 2 -``` -and compare `windows.csv` / `llm_verdicts.csv` of `replay-live-` with the live session. -- Clock: newest event time minus `--lateness-s`. After `--loki-idle-s` (default 2 × lateness) with no new - lines, it follows host time, so the last window of a stopped capture still closes (DEVIATIONS D8). -- UI tile "pipeline lag": host time minus the newest event. - -**Running 24/7 (2026-11-02).** What keeps `ocr-live` up unattended: -- `curl http://:8000/healthz` → 200 `{"ok": true}`, or 503 with the reason (an engine thread died, or - no successful Loki poll for 120 s). -- Errors do not end the Loki polling thread: any exception is logged (traceback in `journalctl -u ocr-live`) - and retried with backoff; the UI shows `Loki error: …`. One event the converter cannot handle is skipped - and counted (tile "events skipped"). -- Watchdog (`--watchdog-s 300`): when a worker thread died or a Loki poll hangs for 5 min, the process exits - and systemd (`Restart=always`) starts a fresh one. Loki merely being down does NOT restart it (that would - not fix Loki); it keeps retrying. -- A restart mid-run re-reads the run (up to `--loki-lookback-s`, 1 h) into a **new folder - `sessions/.r2`** (`.r3`, …; `session.json` has `restart_of`), so the first folder's raw copy is never - duplicated. The cleanup cron prunes `.rN` folders like any `live-*` session. -- Catch-up is bounded: at most 20 000 lines per provider per poll, and the clock waits for the provider that - is behind, so a 1-h backlog arrives in slices instead of one multi-GB read (UI: "catching up"). -- The UI tab re-syncs by itself after the server restarts or the session changes (no reload needed). -- **Parameters panel** (top of the UI, 2026-11-15): every scored VM side by side, read from that engine's `/api/status`, so - it shows what scoring uses now. Rows: model run, training hyperparameters (`train_meta.json` args), τ, converter check, - window/stride/lateness, SG-Det cut-off + NET rule, n_seed/max_e/min nodes, LLM provider/model/budget, and the running - code (git sha, branch, uncommitted changes; read at server start). Values that differ from the paper are tagged [OURS]. -- `OOMScoreAdjust=500`: under memory pressure the kernel kills `ocr-live` (it restarts) before Loki/Docker. -- Still open: a ws-etw-0 → Loki push stall longer than `--loki-idle-s` drops that backlog as late (PROGRESS). - -No VM? Feed Loki from a recording (on the trainer): -``` -uv run python src/live/loki_push.py --dir src/out/etw/experiments//raw/train/ \ - --split test --run live-replay1 --shift-to-now --speed 10 -``` - -### Alert rule (Alg. 1 + SG-Det, `src/pipeline/alg1.py`, DEVIATIONS D8) -- Subgraph score = Σ prob over its anomalous nodes; prob = (score − train min) / (train max − train min), clamped to [0, 1]. -- Window is red only if ≥ 1 subgraph is ≥ Moderate = score ≥ 10 ([PAPER] §7.2.1; [AUTHOR CODE] is > 10; until - 2026-11-03 our own live scale was 30). `ocr-live` takes it from Ansible `live_sg_moderate_from` (default 10). - Subgraphs below the cut-off are still listed (dashed buttons in the UI). -- [OURS] NET rule (2026-11-09): a subgraph at or above the cut-off alerts (and goes to the LLM) only if it holds at - least one anomalous NET node. Otherwise it is **suppressed**: the window stays green, the LLM is not called, and the - reason is logged (`journalctl -u ocr-live | grep suppressed`). It is also shown in the UI (timeline, history, subgraph - buttons) and kept in `history.jsonl` (`subgraphs_suppressed`, `suppressed_reason`) and `subgraphs.json` - (`suppressed`, `types_anomalous`). `--sg-require-types none` turns it off (paper behaviour). Why and limits: DEVIATIONS D8. -- Flags: `--n-seed 15 --min-nodes 3 --max-edges 5000 --sg-min-level Moderate --sg-moderate-from 10 [--sg-min-score X] - [--sg-require-types net|file,net,process|none]` (default `net`). -- Try another cut-off on a saved session without the VM: `./rejudge.sh "" --sg-moderate-from 30` - (writes `subgraphs_alg1.{json,csv}` per window). - -### LLM verdict on red windows (`src/pipeline/alg2.py`, DEVIATIONS D9) -- Off by default. `--llm-provider anthropic|openai|ollama|deepseek` (first `uv sync --group llm`; keys from - `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`; Ollama at `http://localhost:11434/v1` unless `--llm-base-url`). - `mock` is a keyword rule for UI tests, not an LLM. -- **Any OpenAI-compatible endpoint** (self-hosted vLLM / LM Studio / OpenRouter / Groq / a proxy): - `--llm-provider openai --llm-base-url http://host:8000/v1 [--llm-model NAME] [--llm-api-key KEY]`. - The key falls back to `$OPENAI_API_KEY`; a keyless endpoint used with `--llm-base-url` gets a harmless - dummy key so the SDK is satisfied. Same flags on `rejudge.sh`/`alg2.py` directly. -- **DeepSeek API** (chosen provider; model `deepseek-flash` = DeepSeek-V4.1-Flash-1017, at - `https://api.deepseek.com`): `--llm-provider deepseek [--llm-reasoning-effort none]`. Get a key at - platform.deepseek.com; usage and cost show at platform.deepseek.com/usage. - - Key: `--llm-api-key` > `$NT2102_DEEPSEEK_API_KEY` > `~/.config/nt2102/credentials.json` > a terminal - prompt (input hidden). Your own unprefixed `DEEPSEEK_API_KEY` is deliberately ignored. - - **The first prompt saves the key to `~/.config/nt2102/credentials.json` in plain text (mode 600, outside - the repo).** Delete its `deepseek` entry (or the file) to forget it or enter a new one. No terminal (for - example a service) → the start fails with a message instead of prompting. - - `--llm-reasoning-effort none|low|high|max`: not sent by default (DeepSeek thinks, effort high, and ignores - temperature). `none` turns thinking off: fastest, and temperature 0 applies, so use it for the live demo. -- **Debug:** `--llm-debug` or `NT2102_LLM_DEBUG=1` (also through `rejudge.sh`) prints every call's raw - response (including DeepSeek's `reasoning_content`) or HTTP error body to stderr and keeps it as `raw` in - `calls.jsonl`. An answer cut at the provider's output limit always prints a warning. -- Runs on its own thread: neutral triage (attack / benign / uncertain), then the paper's Alg. 2 prompts - for attacks. The window stays red; the badge shows `LLM: attack`, `LLM: FP` (struck through), `LLM: ?` - or `LLM: …`. -- UI test: the benign replay `live-20261011T112141Z` has no red window at the default scale; - `./serve.sh local --llm-provider mock --sg-moderate-from 10.0001` makes its 11:25 window red. -- Without the VM: `./rejudge.sh ` (prints the LLM input, no call) or `./rejudge.sh anthropic`. -- An LLM "FP" is not a label and is never used for training. -- **Daily budget** `--llm-max-per-day 10` (default; 0 = no limit): at most 10 red windows investigated per - local calendar day of the trainer. One window = for each of up to `--llm-max-subgraphs` (5) kept subgraphs - 1 triage request (3 if it is judged an attack), plus 9 when ≥ 2 subgraphs are attacks: ≤ 5 requests for a - benign window, ≤ 24 worst case, so 10 windows ≤ 240 requests/day. Later red windows stay red with the badge `LLM: budget` and - `skipped` in `llm_verdicts.csv`. The count lives in `sessions/llm_budget.json` (survives restarts; delete - it to reset today's count). The status panel shows "LLM budget today used / limit". - -A red window is an observation, not a detection result, until the window has labels (DEVIATIONS D6, D8). - -## Outputs per session (`src/live/sessions//`) -- `session.json`: model, scaler, converter sha256, dos_map, parameters. -- `raw/.json`: verbatim; can be replayed or converted into a labelled test split. -- `windows.csv`: one row per window, incl. `subgraphs_kept, max_sg_score, max_level, alert, llm` - (`llm` = pending when written; final verdicts in `llm_verdicts.csv`). -- `windows//`: `edges.csv, node_attrs.csv, node_cmdlines.csv, features_model.csv, scores.csv, subgraphs.json`, and - `llm/` (`sg_doc.txt` = exact LLM input, `triage.json`, `sg_report.md`, `iocs.json`, `calls.jsonl`). -- `node_cmdlines.csv` (DEVIATIONS D14): PROCESS nodes joined to a Sysmon EID 1 record (stream `sysmon`) by PID + start time: - `node, pid, start_utc, image, cmdline, decoded, parent_cmdline, delta_ms` (display copy: `-enc` decoded, secrets redacted, - 400 chars). Investigation-only: shown in the UI and the LLM document, never scored. Empty when the VM has no Sysmon. - Offline for any saved window: `python src/pipeline/cmdlines.py --sysmon raw/sysmon.json --node-attrs windows//node_attrs.csv --out x.csv`. - -## Several Windows hosts - -All Windows VMs push to one Loki, told apart by the `host` label. Each VM has its own model, and `lab hosts` picks which -VMs are scored: - -```bash -lab loop --start --end --split test --benign-split test --host ws-etw-1 --model exp09-ws1 # train one VM -lab promote exp08 --host ws-etw-0 # assign a model to a VM (changes nothing live yet) -lab promote exp09-ws1 --host ws-etw-1 -lab hosts # show assignments -lab hosts ws-etw-0 ws-etw-1 && sudo systemctl restart ocr-live # two-VM mode -lab hosts ws-etw-0 && sudo systemctl restart ocr-live # one-VM mode; assignments are kept -``` - -One `Engine` + one `LokiSource` runs per scored VM, each with its own model, scaler, run rotation and clock. They share -the history and the LLM budget. Session folders are `-`. Per-host scoring and SG-Det are the same code as with one -VM: a selftest checks that a VM's windows are identical either way. Until `lab hosts` is used, `live_loki_host` -(`--loki-default-host`) keeps the server on one VM with the single top-level model. - -`--host` twice still builds a pooled experiment (`merge_experiments()`, D12), but live scoring uses one model per host. -A range that holds several hosts and no `--host` is refused. Lines from before the rename are `--host ws-etw`. - -### Cross-host follow-up (`src/live/correlate.py`, DEVIATIONS D13) - -With two or more VMs scored and `/etc/nt2102-hosts.json` present (Ansible writes it from the inventory), a **red window** on -one VM is followed to the other: every NET node in its kept subgraphs whose IP is another monitored VM is a seed. The raw -network lines give the exact connection (5-tuple), so the other end is found on the peer VM: its socket node, the process -that owns it, and what that process touched, scored by the **peer's own model**. The LLM gets both sides in one document. -Each VM's model cannot do this, because it only sees that VM's graph. - -| Level | Meaning | Effect | -|---|---|---| -| `pending` | a red window's kept subgraph holds a socket on another VM; the peer's windows in [t − 5 min, t + 5 min] are not closed yet | shown | -| `one-sided` | the peer's model scored the nodes around that connection as normal | LLM report of both sides | -| `corroborated` | the peer's model flagged ≥ 1 of them, or one of its kept subgraphs holds them | LLM report again | - -A connection between the VMs with no red window is never shown, and there is no known-traffic list. Nothing here changes a -VM's own windows. Results: `sessions/crosshost.jsonl`, LLM files in `sessions/crosshost//`, API `/api/crosshost`, UI -panel **Cross-host follow-up**. Validated on synthetic windows only. +| file | what | +|---|---| +| `engine.py` | ingest, windows, scoring thread, LLM thread | +| `loki_source.py` · `loki_push.py` · `etwship.py` | Loki input · recorded-run feeder · HTTP replay shipper | +| `correlate.py` | cross-host follow-up (D13): `pending` / `one-sided` / `corroborated` | +| `live_server.py` · `static/index.html` | HTTP API, SSE stream, UI | +| `repository.py` · `history.py` · `file_store.py` | persistence interfaces and file implementations | +| `snapshot.py` · `playback.py` | snapshot build and read-only replay (public demo) | +| `compare_replay.py` | live vs offline equality check | diff --git a/src/live/engine.py b/src/live/engine.py index 8a5e26b..583b485 100644 --- a/src/live/engine.py +++ b/src/live/engine.py @@ -172,7 +172,7 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= self.llm_cfg = {"provider": llm_provider or ("custom" if llm_client else None), "model": getattr(self.llm, "model", None), "max_subgraphs": llm_max_subgraphs, "reasoning_effort": llm_reasoning_effort, "max_per_day": llm_max_per_day} - # [OURS] daily LLM budget (user, 2026-11-02: token spend on a 24/7 server): at most llm_max_per_day red + # [OURS] daily LLM budget (caps token spend on a 24/7 server): at most llm_max_per_day red # windows investigated per local calendar day (each = 1 triage per kept subgraph up to max_subgraphs, 3 for # an attack subgraph, +9 with >= 2 attack subgraphs: <= 24 requests); # 0 = unlimited. Kept by the store (sessions/llm_budget.json) so restarts and new sessions do not reset it. @@ -401,7 +401,7 @@ def _score(self, sid, wid, w_rows, attrs): self.sg["moderate_from"], tuple(self.sg["require_types"])) sg_sum = alg1.summarise(subgraphs) sup_line = alg1.suppression_log(wid, subgraphs) - if sup_line: # the type rule turned a would-be alert into a normal window: say why (user, 2026-11-09) + if sup_line: # the type rule turned a would-be alert into a normal window: say why print(f"[engine]{f' {self.host}' if self.host else ''} {sup_line}", flush=True) nodes["attr"] = nodes["node_uuid"].map(attrs) ms = int((time.time() - t0) * 1000) @@ -625,7 +625,7 @@ def ev(prov, name, pid, pname, ms, **data): streams = {"kproc": [], "kfile": [], "knet": [], "kproc_d14": [], "sysmon": []} vol = r"\Device\HarddiskVolume4" # [OURS] D14: a process started inside window 1 + its Sysmon EID 1 record (header PID = Sysmon's service). - # Its kproc lines go on their own stream, sent on time: the main kproc stream is shipped late on purpose. + # Its kproc lines go on their own stream, sent on time: the main kproc stream is shipped late by design. t300 = base + 390_000 streams["kproc_d14"].append(ev(kp, "ProcessStart/Start", 100, "explorer", t300, ProcessID="300", ParentProcessID="100", ImageName=vol + r"\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")) diff --git a/src/live/loki_push.py b/src/live/loki_push.py index 06e247f..c3ef13e 100644 --- a/src/live/loki_push.py +++ b/src/live/loki_push.py @@ -2,7 +2,7 @@ """loki_push.py - push a recorded SilkETW-format run folder into Loki in the same shape etwcollect pushes. Test feed for the Ubuntu side (pull, build, live) when no Windows VM is running; also a no-VM demo path. -etwcollect on the VM (src/etw-python/src/etwcollect/loki.py; Alloy until 2026-10-26) and this script must agree on: +etwcollect on the VM (src/etw-python/src/etwcollect/loki.py) and this script must agree on: labels job="silketw", host, split, run, provider (= file stem: kproc|kfile|knet) structured metadata event (EventName), pid (ProcessID), process (ProcessName) timestamp the line's TimeStamp (event time, ns) diff --git a/src/live/snapshot.py b/src/live/snapshot.py index 7145283..d35bece 100644 --- a/src/live/snapshot.py +++ b/src/live/snapshot.py @@ -55,7 +55,7 @@ re.compile(r"(?i)(convertto-securestring\s+)(['\"]?)([^\s'\"]+)")] DEFAULT_NOTE = ("Recorded snapshot of the live OCR-APT detector (read-only). Scores, alert levels and LLM verdicts are " "what the live server computed at the time with the model recorded per session; nothing is re-scored " - "here. The 4.5 alert cut-off and NET rule off (since 2026-11-15) were tuned on the 2026-11-15 " + "here. The 4.5 alert cut-off and NET rule off were tuned on the 2026-11-15 " "react2shell run, so that run is in-sample evidence, not an independent test.") diff --git a/src/pipeline/alg1.py b/src/pipeline/alg1.py index df90294..7e810ab 100644 --- a/src/pipeline/alg1.py +++ b/src/pipeline/alg1.py @@ -17,7 +17,7 @@ level = Negligible / Minor / Moderate / Significant / Critical ([PAPER] §7.2.1: Moderate from 10) kept = level >= min_level (default Moderate, [AUTHOR CODE] l.61) Alg. 1 l.22-24 AND [OURS] the subgraph's ANOMALOUS nodes cover every type in require_types - (default: >= 1 anomalous NET node; user, 2026-11-09). A level-kept subgraph that misses a type + (default: >= 1 anomalous NET node). A level-kept subgraph that misses a type stays in the output with kept = False and `suppressed` = the reason (logged, never alerted, never sent to the LLM). --sg-require-types none = paper behaviour. @@ -43,9 +43,9 @@ import pandas as pd LEVELS = ["Negligible", "Minor", "Moderate", "Significant", "Critical"] -MODERATE_FROM = 10.0 # [PAPER] §7.2.1 "between 10 and 100 ... moderate" (user, 2026-11-03); [AUTHOR CODE] l.394 is > 10 +MODERATE_FROM = 10.0 # [PAPER] §7.2.1 "between 10 and 100 ... moderate"; [AUTHOR CODE] l.394 is > 10 TYPE_ORDER = {"net": 1, "process": 2, "file": 3} # [AUTHOR CODE] node_type_order l.674 -# [OURS] (user, 2026-11-09): a kept subgraph must hold >= 1 anomalous NET node. Re-judged on the live history +# [OURS]: a kept subgraph must hold >= 1 anomalous NET node. Re-judged on the live history # 11-05 -> 11-09 (exp08): 5/5 attack windows still alert, false alarms 14 -> 3 (in-sample; DEVIATIONS D8). # 'file,net,process' (the first version) lost the 11-06 00:50Z C2 window (net + process only). REQUIRE_TYPES = ("net",) diff --git a/src/pipeline/alg2.py b/src/pipeline/alg2.py index d0d7dd5..80b10d3 100644 --- a/src/pipeline/alg2.py +++ b/src/pipeline/alg2.py @@ -129,7 +129,7 @@ def display_time(iso_utc: str) -> str: DEFAULT_MODELS = {"openai": "gpt-4o-mini", # [PAPER] §7.5 main model "ollama": "llama3:8b", # [PAPER] §7.5 local model "anthropic": "claude-opus-5-5", - # [OURS] user choice 2026-10-25: DeepSeek API, alias served by DeepSeek-V4.1-Flash-1017 + # [OURS] DeepSeek API, alias served by DeepSeek-V4.1-Flash-1017 "deepseek": "deepseek-flash", "mock": "rule-mock"} DEEPSEEK_BASE_URL = "https://api.deepseek.com" # OpenAI format (api-docs.deepseek.com) @@ -241,7 +241,7 @@ def _resolve_openai_key(api_key: str | None, base_url: str | None) -> str | None # --------------------------------------------------------------------------- saved credentials [OURS] -# Project-prefixed env vars (user, 2026-10-25): a user's own DEEPSEEK_API_KEY etc. (~/.bashrc) are never read. +# Project-prefixed env vars: a user's own DEEPSEEK_API_KEY etc. (~/.bashrc) are never read. DEEPSEEK_ENV = "NT2102_DEEPSEEK_API_KEY" diff --git a/src/pipeline/lab_filters.py b/src/pipeline/lab_filters.py index e38acaf..07ce61f 100644 --- a/src/pipeline/lab_filters.py +++ b/src/pipeline/lab_filters.py @@ -10,7 +10,7 @@ (The watchdog filter, by contrast, lives in etw2nodlink.py and IS hash-covered, because it removes watchdog nodes that DO appear in idle, so it changes the training baseline -- see etw2nodlink.own_tooling_* -and DEVIATIONS D8. Different place, on purpose.) +and DEVIATIONS D8. Hence the different place.) Used by: - src/pipeline/build_experiment.py (training build, before windowing) diff --git a/src/pipeline/lokiclient.py b/src/pipeline/lokiclient.py index b41311f..cd85e22 100644 --- a/src/pipeline/lokiclient.py +++ b/src/pipeline/lokiclient.py @@ -1,7 +1,7 @@ """lokiclient.py - the few Loki HTTP calls the lab needs (stdlib only). Shared by loki_pull.py (training pull), live/loki_source.py (live demo) and live/loki_push.py (test feed). -Label scheme (what etwcollect on the VM pushes, src/etw-python/src/etwcollect/loki.py; Grafana Alloy before 2026-10-26): +Label scheme (what etwcollect on the VM pushes, src/etw-python/src/etwcollect/loki.py): labels (indexed) job="silketw"|"etw-meta"|"workload-ledger", host, split, run, provider (kproc|kfile|knet) structured metadata event (EventName), pid (ProcessID), process (ProcessName) -- filterable, not indexed line the raw SilkETW JSON line, unchanged