From 98006124d1a0998603d66cddfcabe9581cb15c9c Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sun, 25 Oct 2026 13:38:53 +0700 Subject: [PATCH 1/8] Add DeepSeek API as the LLM investigator provider, with debug mode Add --llm-provider deepseek (model deepseek-flash = DeepSeek-V4.1-Flash-1017, https://api.deepseek.com, OpenAI-compatible). A Cloudflare Workers AI attempt for the same model was dropped: the account's Free plan refuses it (403, code 5035) and unlocking it needs a paid plan or AI Gateway credits. The key resolves as --llm-api-key > $NT2102_DEEPSEEK_API_KEY > ~/.config/nt2102/credentials.json > a hidden terminal prompt that saves it there (dir 0700, file 0600, atomic, other sections kept) and says so. The unprefixed DEEPSEEK_API_KEY is deliberately not read. Without a terminal the start fails with a message naming the flag, env var and file. --llm-reasoning-effort none|low|high|max maps to DeepSeek's reasoning_effort, or to thinking disabled for "none" (fastest, temperature 0 applies again). --llm-debug / NT2102_LLM_DEBUG=1 prints each call's raw response (including reasoning_content) or HTTP error body to stderr and keeps it as "raw" in calls.jsonl. A cut answer (finish_reason=length) always warns. A leading block in content is stripped before parsing. Selftests cover key precedence, the prompt/save path and file modes, and, through the openai SDK against an httpx.MockTransport, the request shape, the effort mapping, debug capture and a 401. User-verified real run: the 11:25 updater window of live-20261011T112141Z is judged false_positive. Co-Authored-By: Claude Opus 5.5 --- docs/DEVIATIONS.md | 10 +- docs/PROGRESS.md | 10 +- rejudge.sh | 8 +- src/live/README.md | 15 +- src/live/engine.py | 12 +- src/live/live_server.py | 18 ++- src/pipeline/alg2.py | 303 +++++++++++++++++++++++++++++++++++++--- 7 files changed, 344 insertions(+), 32 deletions(-) diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 2a34e69..b20e497 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -163,7 +163,7 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. cut, keeping lines that touch anomalous nodes first (count recorded). - Left out: Alg. 2 l.16–25 (an LLM judge picks top IOCs, their context is pulled from the graph DB, the report is enriched). - - Provider is pluggable (`--llm-provider anthropic|openai|ollama|mock`). [PAPER] used GPT-4o-mini + - 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 @@ -171,6 +171,14 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. `$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 `alg2.py`. This covers self-hosted (vLLM / LM Studio / Ollama) and hosted (OpenRouter / Groq) servers. + - Model choice (user, 2026-10-25): [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 + reproducible between runs. `--llm-reasoning-effort none` turns thinking off; temperature 0 then applies, but + seed support is undocumented. No output cap is sent (DeepSeek's default is undocumented); a cut answer + (`finish_reason=length`) prints a warning. The key comes from `NT2102_DEEPSEEK_API_KEY` or a prompt saved to + `~/.config/nt2102/credentials.json` (mode 600). - Why: the GNN alone cannot tell unseen-but-benign activity (the 11:25 `updater` window) from an attack; the demo needs a readable report for a real attack. - Impact: the GNN alert is never removed. An LLM `false_positive` shows as a struck-through badge on a diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index c1a7c18..63adabb 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -70,7 +70,11 @@ 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. No real LLM run yet (provider not chosen). + `llm/` files written. Provider chosen (user, 2026-10-25): 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 + point, not a rate (D9). - Attack pack is now ONE attack: the RCE kill chain (`src/atomic-attack-pack/scenarios/rce-killchain.ps1`), delivered from a Kali attacker VM (`tools/launch_exploit.py`; local-only Vagrant box, pack mounted at `/opt/attack-pack`, not Ansible-managed). Kali exploits DVWA (OS command injection) and the RCE shell @@ -136,8 +140,8 @@ OPEN (the real limitation): - Replay equivalence check (`compare_replay.py`); user-confirmed runs of the selftests of score_window.py / engine.py / etwship.py; a benign live run with `06-benign-workload.ps1`. - Test split capture, node labels, test scoring, NODLINK W10 detector baseline. -- LLM: choose a provider (`uv sync --group llm`), re-judge the 11:25 window with - `./rejudge.sh

--sg-moderate-from 10.0001`, then one Atomic scenario live. Alg. 2 l.16–25 +- LLM: DeepSeek on a red window from a real attack (the RCE kill chain live), to see the attack path + (triage → IOCs → report). Alg. 2 l.16–25 not built. - SG-Det cut-off not checked against an attack: our scale (Moderate ≥ 30 ≈ at least 30 anomalous nodes in one subgraph) was set from one benign window; a small Atomic scenario may be filtered out. diff --git a/rejudge.sh b/rejudge.sh index bddbb74..a915d36 100755 --- a/rejudge.sh +++ b/rejudge.sh @@ -3,15 +3,17 @@ # # Usage: ./rejudge.sh [llm-provider] [extra alg1.py flags...] # no provider -> prints the LLM input documents of every red window (alg2.py --serialize-only, no call) -# provider -> anthropic | openai | ollama | mock: writes windows//llm/ (needs: uv sync --group llm) +# provider -> anthropic | openai | ollama | deepseek | mock: writes windows//llm/ (needs: uv sync --group llm) +# deepseek: prompts once for the API key, saved to ~/.config/nt2102/credentials.json # Examples: # ./rejudge.sh replay-live-20261011T112141Z # ./rejudge.sh replay-live-20261011T112141Z anthropic # ./rejudge.sh replay-live-20261011T112141Z "" --sg-min-score 20 # other cut-off, no LLM -# Env: RUN_DIR (default: the current model, `lab current --field run_dir`). +# Env: RUN_DIR (default: the current model, `lab current --field run_dir`); +# NT2102_LLM_DEBUG=1 prints every raw LLM response / HTTP error body (alg2.py --llm-debug). set -euo pipefail cd "$(dirname "$0")" -[[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]] && { sed -n '2,11p' "$0"; exit 0; } +[[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]] && { sed -n '2,13p' "$0"; exit 0; } session=$1 provider=${2:-} diff --git a/src/live/README.md b/src/live/README.md index 45e2100..b818baf 100644 --- a/src/live/README.md +++ b/src/live/README.md @@ -86,13 +86,26 @@ uv run python src/live/loki_push.py --dir src/out/etw/experiments//raw/train (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` (first `uv sync --group llm`; keys from +- 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: …`. diff --git a/src/live/engine.py b/src/live/engine.py index 534cdae..dea33aa 100644 --- a/src/live/engine.py +++ b/src/live/engine.py @@ -131,7 +131,8 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= origin_ms=0, converter_path=DEFAULT_CONVERTER, experiment_json=None, allow_collapsed=False, top_k=20, n_seed=15, min_nodes=3, max_edges=5000, sg_min_level="Moderate", sg_min_score=None, sg_moderate_from=alg1.MODERATE_FROM, llm_provider=None, llm_model=None, llm_base_url=None, - llm_api_key=None, llm_client=None, llm_max_subgraphs=5): + llm_api_key=None, llm_client=None, llm_max_subgraphs=5, llm_reasoning_effort=None, + llm_debug=False): self.conv, self.conv_sha = load_converter(converter_path) self.conv_check = "not checked (no --experiment)" if experiment_json: @@ -156,11 +157,14 @@ def __init__(self, run_dir, scaler_path, sessions_dir, window_min=5, stride_min= "min_level": sg_min_level, "min_score": sg_min_score, "moderate_from": sg_moderate_from} # LLM triage + report after SG-Det (alg2.py); None = off. Own thread: one alert can take tens of - # seconds of LLM calls and must not delay scoring of the next window. - self.llm = llm_client or (alg2.make_client(llm_provider, llm_model, llm_base_url, llm_api_key) + # seconds of LLM calls and must not delay scoring of the next window. Built here, on the main thread + # before the server starts, so a missing-credential prompt (deepseek) reaches the terminal. + self.llm = llm_client or (alg2.make_client(llm_provider, llm_model, llm_base_url, llm_api_key, + llm_reasoning_effort, debug=llm_debug) if llm_provider else None) self.llm_cfg = {"provider": llm_provider or ("custom" if llm_client else None), - "model": getattr(self.llm, "model", None), "max_subgraphs": llm_max_subgraphs} + "model": getattr(self.llm, "model", None), "max_subgraphs": llm_max_subgraphs, + "reasoning_effort": llm_reasoning_effort} self.lock = threading.RLock() self.listeners = [] # callables(event_dict), called from any thread diff --git a/src/live/live_server.py b/src/live/live_server.py index 11501b4..5558351 100644 --- a/src/live/live_server.py +++ b/src/live/live_server.py @@ -16,7 +16,7 @@ The model comes from the current-model pointer (src/artifacts/current.local.json, else current.json; `lab promote ` sets it). --run-dir / --scaler / --experiment override it, e.g. --run-dir src/artifacts/runs/exp01 --scaler src/artifacts/features/self-dataset/feature_scaler.json - add --llm-provider anthropic|openai|ollama|mock for the LLM verdict on red windows (src/live/README.md) + add --llm-provider anthropic|openai|ollama|deepseek|mock for the LLM verdict on red windows (src/live/README.md) """ from __future__ import annotations @@ -36,6 +36,7 @@ sys.path.insert(0, HERE) sys.path.insert(0, os.path.dirname(HERE)) # src/: the `lab` package (current-model pointer) from engine import Engine # noqa: E402 +import alg2 # noqa: E402 (engine put src/pipeline on sys.path; provider list + reasoning efforts) def create_app(engine: Engine, token: str | None, source=None) -> FastAPI: @@ -138,13 +139,21 @@ def main(): g.add_argument("--sg-min-score", type=float, default=None, help="[OURS] numeric cut-off instead of the level (alert if sg_score > X); calibrate on BENIGN sessions") g = ap.add_argument_group("LLM triage + attack report after SG-Det (src/pipeline/alg2.py)") - g.add_argument("--llm-provider", choices=["anthropic", "openai", "ollama", "mock"], default=None, + g.add_argument("--llm-provider", choices=list(alg2.DEFAULT_MODELS), default=None, help="off by default; only red windows are sent; the verdict never turns a red window green") g.add_argument("--llm-model", default=None, help="default per provider, see alg2.DEFAULT_MODELS") g.add_argument("--llm-base-url", default=None, help="OpenAI-compatible endpoint, e.g. http://host:8000/v1 (or a remote Ollama :11434/v1)") g.add_argument("--llm-api-key", default=None, - help="key for an OpenAI-compatible --llm-base-url (else $OPENAI_API_KEY; keyless endpoints use a dummy)") + help="key for an OpenAI-compatible --llm-base-url (else $OPENAI_API_KEY; keyless endpoints use a " + "dummy). deepseek: else $NT2102_DEEPSEEK_API_KEY, else ~/.config/nt2102/credentials.json, " + "else a prompt that saves it there") + g.add_argument("--llm-reasoning-effort", choices=alg2.REASONING_EFFORTS, default=None, + help="deepseek: thinking effort; none = thinking off (fastest, use for the live demo); " + "default: not sent = DeepSeek default (thinking, high)") + g.add_argument("--llm-debug", action="store_true", default=alg2.debug_default(), + help="print each LLM call's raw response / HTTP error body to stderr, keep it in calls.jsonl " + "(default from $NT2102_LLM_DEBUG=1)") g.add_argument("--llm-max-subgraphs", type=int, default=5, help="kept subgraphs investigated per window") a = ap.parse_args() if not (a.run_dir and a.scaler): @@ -170,7 +179,8 @@ def main(): sg_min_level=a.sg_min_level, sg_min_score=a.sg_min_score, sg_moderate_from=a.sg_moderate_from, llm_provider=a.llm_provider, llm_model=a.llm_model, llm_base_url=a.llm_base_url, llm_api_key=a.llm_api_key, - llm_max_subgraphs=a.llm_max_subgraphs) + llm_max_subgraphs=a.llm_max_subgraphs, llm_reasoning_effort=a.llm_reasoning_effort, + llm_debug=a.llm_debug) print(f"[live] model {engine.run_dir} tau={engine.run.tau}") print(f"[live] Alg. 1 {engine.sg} train score range {engine.run.score_range}") print(f"[live] LLM {engine.llm_cfg}") diff --git a/src/pipeline/alg2.py b/src/pipeline/alg2.py index c5e25b4..11522af 100644 --- a/src/pipeline/alg2.py +++ b/src/pipeline/alg2.py @@ -22,6 +22,8 @@ uv run python src/pipeline/alg2.py --selftest uv run python src/pipeline/alg2.py --session-dir src/live/sessions/ --serialize-only # LLM input only uv run --group llm python src/pipeline/alg2.py --session-dir src/live/sessions/ --llm-provider anthropic + uv run --group llm python src/pipeline/alg2.py --session-dir src/live/sessions/ --llm-provider deepseek + (first run prompts for the API key, saved to ~/.config/nt2102/credentials.json; NT2102_LLM_DEBUG=1 = raw) -> /llm/{sg_doc.txt, triage.json, sg_report.md, iocs.json, report_comprehensive.md, calls.jsonl}, one summary row per window """ @@ -118,7 +120,12 @@ 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 + "deepseek": "deepseek-flash", "mock": "rule-mock"} +DEEPSEEK_BASE_URL = "https://api.deepseek.com" # OpenAI format (api-docs.deepseek.com) +# DeepSeek reasoning_effort low|high|max (default: thinking on, high); [OURS] "none" = thinking disabled +REASONING_EFFORTS = ("none", "low", "high", "max") # --------------------------------------------------------------------------- LLM clients @@ -158,22 +165,36 @@ def rule_mock_responder(system, messages): class OpenAICompatible: - """OpenAI chat completions; also Ollama through its OpenAI-compatible /v1 endpoint. - temperature 0 + fixed seed as [PAPER] §7.5 / [AUTHOR CODE] l.135.""" + """OpenAI chat completions; also Ollama and DeepSeek through their OpenAI-compatible endpoints. + temperature 0 + fixed seed as [PAPER] §7.5 / [AUTHOR CODE] l.135 (DeepSeek ignores temperature while + thinking). extra: provider-specific request params (DeepSeek: reasoning_effort or thinking disabled); + http_client: selftest only (httpx.MockTransport, no network).""" - def __init__(self, model, base_url=None, api_key=None): + def __init__(self, model, base_url=None, api_key=None, extra=None, http_client=None): try: import openai except ImportError: raise SystemExit("[alg2] pip package 'openai' missing: uv sync --group llm") self.client = openai.OpenAI(base_url=base_url, api_key=api_key or os.environ.get("OPENAI_API_KEY"), - timeout=600) + timeout=600, http_client=http_client) self.model = model + self.extra = dict(extra or {}) def complete(self, system, messages): r = self.client.chat.completions.create(model=self.model, temperature=0, seed=0, - messages=[{"role": "system", "content": system}, *messages]) - return r.choices[0].message.content or "" + messages=[{"role": "system", "content": system}, *messages], + **self.extra) + self.last_raw = r.model_dump() # --llm-debug: full response incl. reasoning_content, usage + if r.choices[0].finish_reason == "length": # no output cap is sent; never truncate silently + print(f"[alg2] WARNING {self.model}: answer cut at the provider's output limit (finish_reason=length)", + file=sys.stderr) + return strip_think(r.choices[0].message.content or "") + + +def strip_think(text: str) -> str: + """[OURS] drop a leading ... block some reasoning models put in `content`; otherwise the + greedy {...} / [...] parsers below would pick up braces from the reasoning text.""" + return re.sub(r"^\s*.*?\s*", "", text, count=1, flags=re.S) class AnthropicClient: @@ -191,6 +212,7 @@ def __init__(self, model, base_url=None): def complete(self, system, messages): r = self.client.beta.messages.create(model=self.model, max_tokens=16000, system=system, messages=messages, betas=["server-side-fallback-2026-07-01"], fallbacks="default") + self.last_raw = r.model_dump() if r.stop_reason == "refusal": cat = getattr(r.stop_details, "category", None) if r.stop_details else None raise LLMError(f"model refused (category {cat})") @@ -209,13 +231,110 @@ def _resolve_openai_key(api_key: str | None, base_url: str | None) -> str | None return "sk-noauth" if base_url else None +# --------------------------------------------------------------------------- saved credentials [OURS] +# Project-prefixed env vars (user, 2026-10-25): a user's own DEEPSEEK_API_KEY etc. (~/.bashrc) are never read. +DEEPSEEK_ENV = "NT2102_DEEPSEEK_API_KEY" + + +def credentials_path() -> str: + """Per-user file outside the repo (never committed): $XDG_CONFIG_HOME/nt2102/credentials.json.""" + base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config") + return os.path.join(base, "nt2102", "credentials.json") + + +def _read_credentials(path: str) -> dict: + try: + with open(path) as fh: + data = json.load(fh) + except FileNotFoundError: + return {} + except json.JSONDecodeError as e: + raise SystemExit(f"[alg2] {path} is not valid JSON ({e}); fix or delete it") + return data if isinstance(data, dict) else {} + + +def _save_credentials(path: str, section: str, values: dict): + """Merge values into one section; other sections are kept. Dir 0700, file 0600, atomic replace.""" + d = os.path.dirname(path) + os.makedirs(d, mode=0o700, exist_ok=True) + os.chmod(d, 0o700) + data = _read_credentials(path) + data.setdefault(section, {}).update(values) + tmp = path + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as fh: + json.dump(data, fh, indent=1) + os.chmod(tmp, 0o600) # in case a stale .tmp existed with another mode + os.replace(tmp, path) + + +def _tty_prompt(label: str, secret: bool) -> str | None: + """Ask in the terminal; None when not interactive (service, pipe), so the caller can fail clearly.""" + if not (sys.stdin.isatty() and sys.stderr.isatty()): + return None + if secret: + import getpass + return getpass.getpass(f"{label} (input hidden): ") + return input(f"{label}: ") + + +def resolve_secret(section: str, field: str, flag_value: str | None, env: str, label: str, flag_name: str, + prompt=_tty_prompt) -> str: + """One credential: flag > $env > saved file [section][field] > terminal prompt (then saved, mode 600). + Never prints the value.""" + if flag_value or os.environ.get(env): + return flag_value or os.environ[env] + path = credentials_path() + saved = _read_credentials(path).get(section) + if isinstance(saved, dict) and saved.get(field): + print(f"[alg2] using {label} from {path}", file=sys.stderr) + return saved[field] + print(f"[alg2] {label} not found (no {flag_name}, no ${env}, not in {path})", file=sys.stderr) + v = ((prompt(label, True) if prompt else None) or "").strip() + if not v: + raise SystemExit(f"[alg2] {label} missing: pass {flag_name}, export {env}, or run once in a terminal " + f"to be prompted (saved to {path})") + _save_credentials(path, section, {field: v}) + print(f"[alg2] saved {label} to {path} (plain text, mode 600). Delete it from the file to forget it or " + f"re-enter; ${env} and {flag_name} take precedence.", file=sys.stderr) + return v + + +def deepseek_extra(reasoning_effort: str | None) -> dict: + """--llm-reasoning-effort -> DeepSeek request params. None: send nothing (thinking on, high). + 'none': thinking disabled, so temperature 0 applies again ([PAPER] §7.5 setting) and calls are fastest.""" + if not reasoning_effort: + return {} + if reasoning_effort == "none": + return {"extra_body": {"thinking": {"type": "disabled"}}} + return {"reasoning_effort": reasoning_effort} + + def make_client(provider: str, model: str | None = None, base_url: str | None = None, - api_key: str | None = None): + api_key: str | None = None, reasoning_effort: str | None = None, + http_client=None, debug: bool = False): + """reasoning_effort applies to provider 'deepseek' only; http_client is for the selftest; + debug: print every raw provider response / error body to stderr (Recorder).""" + client = _make_client(provider, model, base_url, api_key, reasoning_effort, http_client) + client.debug = debug + return client + + +def debug_default() -> bool: + """--llm-debug default from $NT2102_LLM_DEBUG (1/true/yes), so rejudge.sh / serve.sh need no new flag.""" + return os.environ.get("NT2102_LLM_DEBUG", "").lower() in ("1", "true", "yes") + + +def _make_client(provider, model, base_url, api_key, reasoning_effort, http_client): model = model or DEFAULT_MODELS[provider] if provider == "mock": return MockLLM(model=model) + if provider == "deepseek": + key = resolve_secret("deepseek", "api_key", api_key, DEEPSEEK_ENV, "DeepSeek API key", "--llm-api-key") + return OpenAICompatible(model, base_url or DEEPSEEK_BASE_URL, key, deepseek_extra(reasoning_effort), + http_client) if provider == "openai": # any OpenAI-compatible endpoint (--llm-base-url) - return OpenAICompatible(model, base_url, _resolve_openai_key(api_key, base_url)) + return OpenAICompatible(model, base_url, _resolve_openai_key(api_key, base_url), http_client=http_client) if provider == "ollama": return OpenAICompatible(model, base_url or "http://localhost:11434/v1", api_key=api_key or "ollama") if provider == "anthropic": @@ -224,24 +343,37 @@ def make_client(provider: str, model: str | None = None, base_url: str | None = class Recorder: - """Wraps a client; logs every call (full prompt + response + latency) for calls.jsonl.""" + """Wraps a client; logs every call (full prompt + response + latency) for calls.jsonl. + client.debug (make_client(debug=True), --llm-debug): also print each call's raw provider response (or the + HTTP error body) to stderr and keep it as "raw" in calls.jsonl.""" def __init__(self, client): self.client, self.calls = client, [] + self.debug = getattr(client, "debug", False) def __call__(self, stage, system, messages): t0 = time.time() - err = out = None + err = out = raw = None + self.client.last_raw = None try: out = self.client.complete(system, messages) return out except Exception as e: err = f"{type(e).__name__}: {e}" + resp = getattr(e, "response", None) # openai / anthropic APIStatusError + raw = {"status_code": getattr(resp, "status_code", None), "body": getattr(resp, "text", None)} \ + if resp is not None else None raise finally: - self.calls.append({"stage": stage, "model": getattr(self.client, "model", ""), "system": system, - "messages": messages, "response": out, "error": err, - "ms": int((time.time() - t0) * 1000)}) + rec = {"stage": stage, "model": getattr(self.client, "model", ""), "system": system, + "messages": messages, "response": out, "error": err, "ms": int((time.time() - t0) * 1000)} + if self.debug: + rec["raw"] = raw if err else getattr(self.client, "last_raw", None) + print(f"[alg2 debug] {stage} {rec['model']} {rec['ms']} ms " + f"{'ERROR ' + err if err else 'OK'}\n" + f"{json.dumps(rec['raw'], indent=1, default=str) if rec['raw'] is not None else out}", + file=sys.stderr, flush=True) + self.calls.append(rec) # --------------------------------------------------------------------------- serialization (Alg. 2 l.3) @@ -572,6 +704,70 @@ def selftest(): os.environ["OPENAI_API_KEY"] = _saved_key assert all("amsi" not in ln for ln in serialize(sg, edges, max_lines=2)["lines"]), "anomalous lines first" + # (b3) saved credentials [OURS]: flag > $NT2102_DEEPSEEK_API_KEY > saved file > prompt (then saved, 0600); + # the unprefixed DEEPSEEK_API_KEY is ignored. Temp XDG_CONFIG_HOME: the real user file is never touched. + import contextlib + import io + import stat + env_keys = ["XDG_CONFIG_HOME", DEEPSEEK_ENV, "DEEPSEEK_API_KEY"] + _saved_env = {k: os.environ.pop(k, None) for k in env_keys} + + def no_tty(label, secret): + return None + + def must_not_ask(label, secret): + raise AssertionError(f"prompted for {label}") + + def ds_key(flag=None, prompt=must_not_ask): + return resolve_secret("deepseek", "api_key", flag, DEEPSEEK_ENV, "DeepSeek API key", "--llm-api-key", prompt) + + try: + with tempfile.TemporaryDirectory() as cfg: + os.environ["XDG_CONFIG_HOME"] = cfg + os.environ["DEEPSEEK_API_KEY"] = "user-bashrc-key" # the user's own var: never read + path = credentials_path() + assert path == os.path.join(cfg, "nt2102", "credentials.json"), path + err = io.StringIO() + # nothing set + not interactive -> clear error naming flag, env var and file; nothing written + try: + with contextlib.redirect_stderr(err): + ds_key(prompt=no_tty) + raise AssertionError("expected SystemExit") + except SystemExit as e: + assert path in str(e) and DEEPSEEK_ENV in str(e) and "--llm-api-key" in str(e), e + assert not os.path.exists(path) + # prompt -> returned + saved (file 0600, dir 0700), other sections kept, key never printed + os.makedirs(os.path.dirname(path)) + json.dump({"cloudflare": {"api_token": "old"}}, open(path, "w")) + asked = [] + + def prompt(label, secret): + asked.append((label, secret)) + return " sk-secret " + with contextlib.redirect_stderr(err): + assert ds_key(prompt=prompt) == "sk-secret" + assert asked == [("DeepSeek API key", True)], asked + assert f"saved DeepSeek API key to {path}" in err.getvalue(), err.getvalue() + assert stat.S_IMODE(os.stat(path).st_mode) == 0o600 + assert stat.S_IMODE(os.stat(os.path.dirname(path)).st_mode) == 0o700 + assert json.load(open(path)) == {"cloudflare": {"api_token": "old"}, "deepseek": {"api_key": "sk-secret"}} + # second run reads the file, no prompt; env beats file; flag beats env + with contextlib.redirect_stderr(err): + assert ds_key() == "sk-secret" + assert f"using DeepSeek API key from {path}" in err.getvalue(), err.getvalue() + os.environ[DEEPSEEK_ENV] = "sk-env" + assert ds_key() == "sk-env" and ds_key("sk-flag") == "sk-flag" + assert "sk-secret" not in err.getvalue() and "sk-env" not in err.getvalue() + finally: + for k, v in _saved_env.items(): + os.environ.pop(k, None) + if v is not None: + os.environ[k] = v + assert deepseek_extra(None) == {} and deepseek_extra("low") == {"reasoning_effort": "low"} + assert deepseek_extra("none") == {"extra_body": {"thinking": {"type": "disabled"}}} + assert strip_think('maybe {"x": 1}\n{"v": 1}') == '{"v": 1}' + assert strip_think("plain text") == "plain text" + # (c) IOC parse + hallucination filter assert extract_ioc_list('```python\n["powershell", "10.21.2.1"]\n```') == ["powershell", "10.21.2.1"] assert extract_ioc_list("no list") == [] and extract_ioc_list("[oops") == [] @@ -644,9 +840,76 @@ def boom(s, m): assert r["subgraphs_investigated"] == 0 and r["llm_calls"] == 0 and r["verdict"] == "uncertain" # (k) rule mock runs end to end (UI testing only) assert investigate([sg], edges, win, MockLLM())["verdict"] == "attack" + + # (l) DeepSeek request shape through the real openai SDK, no network (httpx.MockTransport). Proves we send + # what the DeepSeek API docs describe, not that DeepSeek accepts it or that the model triages well. + try: + import httpx + import openai # noqa: F401 + except ImportError: + sdk = "DeepSeek request shape SKIPPED (openai not installed: uv sync --group llm)" + else: + seen, finish = [], {"reason": "stop"} + + def handler(req): + seen.append(req) + content = json.dumps({"verdict": "benign", "confidence": 0.7, "evidence": [doc["lines"][1]], + "attack_tactics": [], "rationale": "test"}) + return httpx.Response(200, json={ + "id": "x", "object": "chat.completion", "created": 0, "model": "m", + "choices": [{"index": 0, "finish_reason": finish["reason"], + "message": {"role": "assistant", "content": content, + "reasoning_content": "thinking about {braces}"}}]}) + hc = httpx.Client(transport=httpx.MockTransport(handler)) + c = make_client("deepseek", api_key="sk-t", reasoning_effort="low", http_client=hc) + r = investigate([sg], edges, win, c) + assert r["verdict"] == "false_positive" and r["model"] == "deepseek-flash", r + req, body = seen[0], json.loads(seen[0].content) + assert str(req.url) == "https://api.deepseek.com/chat/completions", req.url + assert req.headers["authorization"] == "Bearer sk-t" + assert body["model"] == "deepseek-flash" and body["temperature"] == 0 and body["seed"] == 0, body + assert body["reasoning_effort"] == "low" and "thinking" not in body, body + assert body["messages"][0] == {"role": "system", "content": TRIAGE_SYSTEM} + # effort none -> thinking disabled in the body; no effort -> neither key (DeepSeek default) + seen.clear() + make_client("deepseek", api_key="sk-t", reasoning_effort="none", http_client=hc).complete( + "s", [{"role": "user", "content": "u"}]) + body = json.loads(seen[0].content) + assert body["thinking"] == {"type": "disabled"} and "reasoning_effort" not in body, body + seen.clear() + make_client("deepseek", api_key="sk-t", http_client=hc).complete("s", [{"role": "user", "content": "u"}]) + assert set(json.loads(seen[0].content)) == {"model", "temperature", "seed", "messages"} + # the plain openai provider sends exactly what it sent before + seen.clear() + make_client("openai", base_url="http://host:8000/v1", api_key="k", http_client=hc).complete( + "s", [{"role": "user", "content": "u"}]) + assert set(json.loads(seen[0].content)) == {"model", "temperature", "seed", "messages"} + # --llm-debug: raw response (incl. reasoning_content the parser never sees) printed + kept in calls.jsonl + dbg = io.StringIO() + c = make_client("deepseek", api_key="sk-t", http_client=hc, debug=True) + with tempfile.TemporaryDirectory() as d, contextlib.redirect_stderr(dbg): + investigate([sg], edges, win, c, out_dir=d) + call = json.loads(open(f"{d}/calls.jsonl").readline()) + assert call["raw"]["choices"][0]["message"]["reasoning_content"] == "thinking about {braces}", call["raw"] + assert "[alg2 debug] triage" in dbg.getvalue() and "reasoning_content" in dbg.getvalue() + # finish_reason length -> warning on stderr + finish["reason"] = "length" + with contextlib.redirect_stderr(dbg): + make_client("deepseek", api_key="sk-t", http_client=hc).complete("s", [{"role": "user", "content": "u"}]) + assert "finish_reason=length" in dbg.getvalue() + # HTTP error keeps status + body (401 = DeepSeek's bad-key answer shape) + bad = {"error": {"message": "Authentication Fails, Your api key is invalid", "type": "authentication_error"}} + hc401 = httpx.Client(transport=httpx.MockTransport(lambda req: httpx.Response(401, json=bad))) + c = make_client("deepseek", api_key="sk-bad", http_client=hc401, debug=True) + with tempfile.TemporaryDirectory() as d, contextlib.redirect_stderr(dbg): + r = investigate([sg], edges, win, c, out_dir=d) + call = json.loads(open(f"{d}/calls.jsonl").readline()) + assert r["verdict"] == "uncertain" and "AuthenticationError" in r["subgraphs"][0]["triage"]["note"], r + assert call["raw"]["status_code"] == 401 and "invalid" in call["raw"]["body"], call["raw"] + sdk = "DeepSeek request shape + debug raw/HTTP-error capture via openai SDK" print("[SELFTEST OK] NET decode, repo document format + per-minute counts, truncation keeps anomalous lines, " "IOC parse + hallucination filter, evidence check, JSON retry, provider error, window verdict, " - "comprehensive report, output files") + f"comprehensive report, output files, DeepSeek key (flag/env/file/prompt), {sdk}") # --------------------------------------------------------------------------- cli (re-judge saved windows) @@ -682,7 +945,14 @@ def main(): ap.add_argument("--llm-base-url", default=None, help="OpenAI-compatible endpoint, e.g. http://host:8000/v1") ap.add_argument("--llm-api-key", default=None, help="key for the OpenAI-compatible endpoint (else $OPENAI_API_KEY; keyless endpoints with " - "--llm-base-url use a dummy)") + "--llm-base-url use a dummy). deepseek: else $NT2102_DEEPSEEK_API_KEY, else the saved " + "file, else a prompt (saved to ~/.config/nt2102/credentials.json)") + ap.add_argument("--llm-reasoning-effort", choices=REASONING_EFFORTS, default=None, + help="deepseek: thinking effort; none = thinking off (fastest, temperature 0 applies); " + "default: not sent = DeepSeek default (thinking, high)") + ap.add_argument("--llm-debug", action="store_true", default=debug_default(), + help="print each call's raw provider response / HTTP error body to stderr and keep it as " + "'raw' in calls.jsonl (default from $NT2102_LLM_DEBUG=1)") ap.add_argument("--max-lines", type=int, default=400, help="[OURS] document cap per subgraph") ap.add_argument("--max-subgraphs", type=int, default=5, help="[OURS] kept subgraphs investigated per window") a = ap.parse_args() @@ -697,7 +967,8 @@ def main(): if a.session_dir and os.path.exists(os.path.join(a.session_dir, "session.json")): window_min = json.load(open(os.path.join(a.session_dir, "session.json"))).get("window_min", 5.0) wdirs = [a.window_dir] if a.window_dir else sorted(glob.glob(os.path.join(a.session_dir, "windows", "*"))) - client = None if a.serialize_only else make_client(a.llm_provider, a.llm_model, a.llm_base_url, a.llm_api_key) + client = None if a.serialize_only else make_client(a.llm_provider, a.llm_model, a.llm_base_url, a.llm_api_key, + a.llm_reasoning_effort, debug=a.llm_debug) rows = [] for w in wdirs: loaded = load_window(w, a.subgraphs_file, window_min) From ded49ed6616598586948648a5aa4b2aa2114afbc Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sun, 25 Oct 2026 14:03:22 +0700 Subject: [PATCH 2/8] Always-on live capture, LLM on ocr-live, alg2 --ping Live capture (ws-etw): start-live.ps1 becomes a watchdog run by the SYSTEM scheduled task etwlab-live (at boot + every 5 min). One tick keeps a test/live- SilkETW run capturing: starts one when SilkService is stopped, rotates it every 6 h, deletes raw live-* runs idle for 1 day, and leaves SilkService alone while C:\ProgramData\etwlab\live.hold exists or a train / hand-started test capture runs. A fresh run per start is needed because SilkService reads its output folder only at service start, so a plain auto-start would append to the last (possibly training) run. By hand: -Status, -Rotate (clean demo session), -Pause / -Resume. A machine-wide mutex keeps a manual call and a task tick apart. 07-build-train-dataset.ps1 pauses a running live capture for the train capture: it writes the hold (with its PID, so a crashed run's hold is dropped as stale), stops live, and removes the hold in its finally. Trainer: live_llm_args (empty = off; inventory.local.ini sets DeepSeek, thinking off, --llm-debug) is appended to the ocr-live ExecStart, and a non-empty value makes uv sync / uv run include the llm group. The key is never an Ansible variable: it is saved once on the trainer with alg2.py --ping, which sends one tiny prompt (exit 0 = answered) and prompts for a missing key on a terminal. An hourly cron removes live-* sessions with no write for 12 h (each keeps a ~2 GB/h raw copy, measured); a session holding a .keep file is kept. Loki retention 30 d -> 3 d for the same volume reason. Checked: selftests (14/14), ansible --syntax-check, local template renders (ExecStart unchanged when the LLM is off), and a PowerShell 5.1 parse of start-live.ps1 and 07 on ws-etw (0 errors). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 7 +- docs/PROGRESS.md | 46 ++--- src/ansible/README.md | 24 ++- src/ansible/group_vars/all.yml | 16 +- src/ansible/inventory.local.ini | 3 + .../roles/ubuntu_project/tasks/main.yml | 19 +- .../templates/ocr-live.service.j2 | 3 +- src/ansible/roles/win_shipper/tasks/main.yml | 38 +++- .../win_shipper/templates/start-live.ps1.j2 | 186 +++++++++++++++--- src/live/README.md | 37 +++- src/pipeline/alg2.py | 27 ++- src/scripts/07-build-train-dataset.ps1 | 25 ++- 12 files changed, 359 insertions(+), 72 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index a6166a4..dc384f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -114,8 +114,9 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum reproduction. - Current focus: the live detection demo. A valid training run (`runs/exp01`) and the live path (`src/live/`) exist, and Alg. 1 + the subgraph-score filter (SG-Det) decides the window alert. Immediate - steps: wider benign training data + calibration, the replay equivalence check, one Atomic scenario - live, and understanding the trainer (concepts 2–4). + step (user, 2026-10-25): verify the full detection flow with LLM support (DeepSeek, `--llm-provider + deepseek`) live: benign stays green, the DVWA→RCE attack goes red and gets an LLM attack verdict + report. + Then: the browser false positive, the replay equivalence check, understanding the trainer (concepts 2–4). - Data: the user's own Windows 10 audit data (ETW), shaped to match the NODLINK simulated Windows 10 (W10) host format the repo expects. The graph is named `SimulatedW10` because the repo asserts host names. @@ -180,7 +181,7 @@ history of earlier progress) and, if relevant, this section. - VM side (Ansible roles in `src/ansible/roles/`): `win_base`, `win_collector` (SilkETW, `etwctl`, copies `src/pipeline/etw2nodlink.py` / `etwwindow.py` / `src/live/etwship.py`), `win_alloy` - (Alloy → Loki), `win_shipper` (`start-live.ps1`), `win_benign` (`src/scripts/06-benign-workload`, + (Alloy → Loki), `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), `win_benign` (`src/scripts/06-benign-workload`, `07-build-train-dataset`), `win_vulnlab` (XAMPP + DVWA). - Improve loop: `lab` CLI (`src/lab/cli.py`, console script; `source .venv/bin/activate`): `lab loop` = pull + build → features → train into one run folder; `lab promote ` sets the current-model diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 63adabb..0bac418 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,4 +1,4 @@ -# PROGRESS (status as of 2026-10-22) +# PROGRESS (status as of 2026-10-25) Replace lines in place when status changes; no history. "Verified" = checked in code/data. @@ -6,8 +6,9 @@ Replace lines in place when status changes; no history. "Verified" = checked in The "widen benign + calibrate" cycle ran on **1 HOUR** of benign data (not 2): kfile-fixed capture `x-20261022T140932Z` → `exp03` trained + promoted → live DVWA→RCE attack. Work is on branch -**`collect-benign-data-for-1-hour`**. Now: the LLM Attack Investigator (OpenAI-compatible) and the -residual browser false positive. +**`collect-benign-data-for-1-hour`**. **Now (user, 2026-10-25): verify the full detection flow with LLM +support** — live benign stays green, the live DVWA→RCE attack goes red AND the LLM (DeepSeek) judges it an +attack with a report (Next 3 steps). The residual browser false positive stays open. DONE this session (2026-10-22, verified live): - **exp03** trained on the 1-h capture and **PROMOTED** (gate passed: 77-min kfile span, all 6 edge types @@ -25,8 +26,8 @@ OPEN (the real limitation): many per-instance processes are unseen in benign training → the *same* mechanism as the cradle. The fix is benign **variety** (training that covers browsing), **not** more capture time. DEVIATIONS D8, [[live-detector-benign-fp]]. -- A **real LLM run** still needs the user's OpenAI-compatible endpoint URL + key; serialize/mock path - verified without one. +- LLM: DeepSeek works offline-replayed (one benign window → `false_positive`, 2026-10-25) but has never run + inside the live server, and never on an attack window. - `06-benign-workload.ps1` **deadline-overrun bug** (the `while (now < deadline)` loop ran ~74 min for a 60-min target because one scenario call blocked) — deferred, not yet debugged. @@ -194,23 +195,24 @@ Repo hygiene: - `src/out/etw/SimulatedW10_train_edges.csv` (old un-windowed capture) sits next to the experiment folders and is easy to pick by mistake (it caused the first, collapsed exp01 run). -## Next 3 steps (resume the paused cycle — full detail in `~/.claude/plans/i-want-you-to-splendid-naur.md`) - -Pre-flight is already done (trainer on main + Loki ready + Kali selftest ok + kfile fix verified). Start here: - -1. Launch the benign capture on `ws-etw` (VirtualBox window, elevated PS): - `C:\scripts\07-build-train-dataset.ps1 -DurationMinutes 120 -Seed 42` (or 90). ~58 windows at 5-min/2-min. - Note the `x-` run stamp. (Runs in the interactive desktop only — WinRM/session-0 is refused and would - mis-parent apps to powershell.) -2. On the trainer: `lab loop --latest --split train --lookback 1d --model exp03 --seeds 3 --yes`. GATE before - promote: `lab status` shows kfile ≈ full span (fix holds at scale), all 6 edge types non-zero, `emb_std` - ≠ 0 for every type. Then `lab promote exp03` + `sudo systemctl restart ocr-live`. -3. Honest calibrate + attack (both via `vagrant ssh` for the trainer/Kali; the Windows capture is manual): - benign live session first (`start-live.ps1` + `06-benign-workload.ps1 -Seed 7`), record max benign - `sg_score` (`alg1.py --session-dir`); set cut-off from benign only; THEN - `vagrant ssh kali -c 'python3 -I /opt/attack-pack/tools/launch_exploit.py --target http://10.21.2.10:3000'`. - Attack window must reach ≥ cut-off while benign stays green; confirm the kept subgraph is ATTACK indicators - (httpd→cmd→powershell, tool images, attacker :8080), not NAT/powershell noise. Record in DEVIATIONS D8. +## Next 3 steps (verify the full detection flow with LLM support — user, 2026-10-25) + +Goal: one live session where benign windows stay green, the DVWA→RCE attack window goes red, and the LLM +investigator judges it `attack` with ATT&CK tactics + an IOC report in the UI. Model: exp03 (promoted). + +1. LLM on the live server (`ubuntu-trainer`): `uv sync --group llm` in the repo; save the DeepSeek key for the + service user ONCE interactively (`vagrant ssh ubuntu-trainer`, then e.g. `./rejudge.sh deepseek` + → prompt → `~/.config/nt2102/credentials.json`, mode 600; `ocr-live` has no terminal, so it cannot prompt). + Add `--llm-provider deepseek --llm-reasoning-effort none` (+ `--llm-debug` for the first run) to the + `ocr-live` ExecStart via an Ansible var (key never in Ansible/repo; idempotent re-run), restart, and check + journalctl shows `[live] LLM {'provider': 'deepseek', ...}`. +2. Benign live session (`start-live.ps1` + `06-benign-workload.ps1 -Seed 7`): windows stay green; any red + window (e.g. the browser FP) gets an LLM badge — record verdict, latency, calls (`llm_verdicts.csv`). +3. Attack during the live session: `vagrant ssh kali -c 'python3 -I /opt/attack-pack/tools/launch_exploit.py + --target http://10.21.2.10:3000'`. Check (a) window ≥ Moderate with a kept subgraph of attack indicators + (httpd→cmd→powershell, tool images, attacker :8080); (b) triage = `attack` with evidence lines that are in + the document; (c) the report's IOCs survive the hallucination filter. Record in PROGRESS + DEVIATIONS D9 + (one attack = one data point, not a detection rate). Watch item: the first 15-min `07` run (`x-20261021T161810Z`) did not write `stopped_utc` (capture left running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the service on the 2h run. diff --git a/src/ansible/README.md b/src/ansible/README.md index 36091e1..bed7e4f 100644 --- a/src/ansible/README.md +++ b/src/ansible/README.md @@ -131,7 +131,13 @@ ansible-playbook -i inventory.cloud.ini site.yml -e @group_vars/vault.yml --ask- **`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. +and set `repo_branch` to it, or merge it first. One-off, without editing the file: +`ansible-playbook -i inventory.local.ini ubuntu.yml --tags project -e repo_branch=`. + +**LLM on `ocr-live`: `live_llm_args`** (default empty = off; `inventory.local.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. After the Windows run, pin the download hashes the roles print (`silketw_sha256`, `python_embed_sha256` in `group_vars/all.yml`). `alloy_sha256` is already pinned from the release's `SHA256SUMS`. @@ -176,10 +182,16 @@ is down. ```powershell C:\scripts\06-benign-workload.ps1 -SelfTest # once per VM -C:\scripts\start-live.ps1 # window 1: capture test/live-; Alloy ships it -C:\scripts\06-benign-workload.ps1 -DurationMinutes 20 # window 2: benign activity (green windows) +C:\scripts\start-live.ps1 -Rotate # optional: fresh live run = a clean session for the demo +C:\scripts\06-benign-workload.ps1 -DurationMinutes 20 # benign activity (green windows) ``` +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 @@ -210,7 +222,7 @@ windows stay green; the teammate's attack turns its window red. 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). The converter summary lists `alloy` under excluded edges, not as process nodes. -6. `start-live.ps1` + `06`: the live UI shows `session live- (loki, ws-etw)` and windows close. +6. The `etwlab-live` task (or `start-live.ps1 -Rotate`) + `06`: the live UI shows `session live- (loki, ws-etw)` 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). @@ -224,12 +236,12 @@ roles/ win_base OS config: net profile, UTC+7, no-sleep, RDP, folders, Defender win_collector SilkETW + VC++ + embeddable Python + etw2nodlink.py/etwwindow.py/etwship.py/etwctl + SilkService win_alloy Grafana Alloy (native installer, service) + config.alloy -> Loki - win_shipper start-live.ps1 (start/stop a live test capture) + win_shipper start-live.ps1 watchdog + SYSTEM task etwlab-live (always-on live test capture) win_benign 06-benign-workload.ps1 + 07-build-train-dataset.ps1 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_project git clone + uv sync + ocr-live systemd unit (--loki-url) + ubuntu_project git clone + uv sync + ocr-live systemd unit (--loki-url + live_llm_args) + session cleanup cron ``` The converter and windowing tool (`win_collector`) are deployed from `src/pipeline/`, the same files diff --git a/src/ansible/group_vars/all.yml b/src/ansible/group_vars/all.yml index baf460a..64ebb8e 100644 --- a/src/ansible/group_vars/all.yml +++ b/src/ansible/group_vars/all.yml @@ -18,7 +18,8 @@ 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: "720h" # 30 d: how long raw ETW stays queryable (also the max age Loki accepts) +loki_retention: "72h" # 3 d (user, 2026-10-25: always-on capture ~2 GB/h): how long raw ETW stays + # queryable, also the max age Loki accepts. Pull a training capture within 3 days. loki_image: "grafana/loki:3.7.8" grafana_image: "grafana/grafana:13.2.2" loki_stack_dir: "/opt/lokistack" @@ -66,9 +67,22 @@ out_dir: 'C:\lab-out\etw' raw_root: 'C:\lab-out\etw\raw' service_name: "SilkService" +# ---- always-on live capture (win_shipper: C:\scripts\start-live.ps1 run by a SYSTEM scheduled task) ---- +live_task_name: "etwlab-live" # at boot + every live_watchdog_minutes: keep a test/live- run capturing +live_watchdog_minutes: 5 +live_rotate_hours: 6 # a new live run (= a new session in the UI) after this many hours +live_keep_days: 1 # raw test/live-* runs with no write for this long are deleted on the VM + # ---- Ubuntu trainer ------------------------------------------------------------------------------- repo_url: "https://github.com/UITProjects/NT2102.git" repo_branch: "main" repo_dest: "/home/{{ ansible_user | default('vagrant') }}/NT2102" # The model ocr-live loads is NOT set here: it is the repo's pointer src/artifacts/current.json, or # current.local.json on the trainer (`lab promote `). No run_id / experiment_id to keep in sync. +# Extra live_server.py LLM flags for ocr-live; empty = LLM off. Non-empty also installs the `llm` uv group. +# The API key is NEVER set here: save it once on the trainer (alg2.py --ping prompts, src/live/README.md §5). +live_llm_args: "" +# Live sessions (src/live/sessions/live-*) with no write for this many hours are deleted hourly on the trainer +# (each holds a raw copy of the capture, ~2 GB/h measured; replay-* folders and any session holding a .keep +# file are never touched). +live_session_keep_hours: 12 diff --git a/src/ansible/inventory.local.ini b/src/ansible/inventory.local.ini index 560600a..ca8d187 100644 --- a/src/ansible/inventory.local.ini +++ b/src/ansible/inventory.local.ini @@ -24,6 +24,9 @@ ansible_ssh_private_key_file=../.vagrant/machines/ubuntu-trainer/virtualbox/priv ansible_ssh_common_args='-o StrictHostKeyChecking=no' # Grafana: who may open it (the VirtualBox host side of the host-only net) and a lab-only admin password. admin_cidr=10.21.2.0/24 +# LLM verdict on red windows in ocr-live (DeepSeek, thinking off, raw responses in journalctl). The key is +# saved once on the trainer, not here: src/live/README.md §5. Override with -e live_llm_args= to turn it off. +live_llm_args='--llm-provider deepseek --llm-reasoning-effort none --llm-debug' grafana_admin_password=labadmin # The Kali attacker VM is NOT managed by Ansible: it is a local-only Vagrant box that gets the attack diff --git a/src/ansible/roles/ubuntu_project/tasks/main.yml b/src/ansible/roles/ubuntu_project/tasks/main.yml index 3ca6742..f3046d8 100644 --- a/src/ansible/roles/ubuntu_project/tasks/main.yml +++ b/src/ansible/roles/ubuntu_project/tasks/main.yml @@ -13,9 +13,10 @@ # with them the module reports "submodules_changed" on every run notify: restart ocr-live # the running server keeps the old Python code until restarted -- name: uv sync (resolve torch, torch-geometric, fastapi, ...) +- name: uv sync (resolve torch, torch-geometric, fastapi, ...; + the llm group when live_llm_args is set) become: false - ansible.builtin.command: uv sync + # a plain `uv sync` removes packages of groups it was not asked for, so the llm group must be named here + ansible.builtin.command: "uv sync{{ ' --group llm' if live_llm_args else '' }}" args: chdir: "{{ repo_dest }}" register: uv_sync @@ -25,6 +26,20 @@ # current.local.json written by `lab promote` on this host). Each run folder carries its own # experiment.json, so nothing has to be copied from the control node. +# The Windows capture is always on (win_shipper watchdog) and every live session keeps a raw copy of it +# (~2 GB/h), so old sessions are pruned hourly. A session goes only when NO file inside changed for +# live_session_keep_hours (the folder's own mtime does not move while raw/ grows). replay-* and other +# folders are never touched; a session holding a .keep file is kept forever (touch /.keep). +- name: Hourly cleanup of old live sessions + become: false + ansible.builtin.cron: + name: "nt2102 live session cleanup" + special_time: hourly + job: >- + for d in {{ repo_dest }}/src/live/sessions/live-*/; do [ -d "$d" ] && [ ! -e "$d.keep" ] && + [ -z "$(find "$d" -type f -mmin -{{ live_session_keep_hours | int * 60 }} -print -quit)" ] && + rm -rf "$d"; done; true + - name: Install the live-server systemd unit ansible.builtin.template: src: ocr-live.service.j2 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 5ed24d9..e06850a 100644 --- a/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 +++ b/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 @@ -11,7 +11,8 @@ WorkingDirectory={{ repo_dest }} Environment=PYTHONUNBUFFERED=1 # Mirrors serve.sh, but binds {{ server_bind }} (all interfaces) so it listens on the subnet IP. # Model = the repo's current-model pointer (`lab promote `, then `sudo systemctl restart ocr-live`). -ExecStart=/usr/local/bin/uv run python src/live/live_server.py --bind {{ server_bind }} --port {{ server_port }} --loki-url http://127.0.0.1:{{ loki_port }} +# LLM flags = live_llm_args (empty = LLM off); the key comes from ~/.config/nt2102/credentials.json. +ExecStart=/usr/local/bin/uv run {{ '--group llm ' if live_llm_args else '' }}python src/live/live_server.py --bind {{ server_bind }} --port {{ server_port }} --loki-url http://127.0.0.1:{{ loki_port }}{{ ' ' + live_llm_args if live_llm_args else '' }} Restart=on-failure RestartSec=5 diff --git a/src/ansible/roles/win_shipper/tasks/main.yml b/src/ansible/roles/win_shipper/tasks/main.yml index ab06048..4afba60 100644 --- a/src/ansible/roles/win_shipper/tasks/main.yml +++ b/src/ansible/roles/win_shipper/tasks/main.yml @@ -1,9 +1,11 @@ --- -# Deploy start-live.ps1: start/stop a live (test) SilkETW capture. Alloy (win_alloy) ships it to Loki and -# the live server follows Loki, so this script no longer sends anything itself. Run it interactively -# during the demo (elevated PowerShell), alongside the benign workload. +# Always-on live capture. start-live.ps1 is a watchdog: one run = one tick that keeps a test/live- +# SilkETW run capturing (rotated every live_rotate_hours, old raw live runs pruned, paused while a hold file +# exists, e.g. during 07-build-train-dataset.ps1). A SYSTEM scheduled task runs it at boot and every +# live_watchdog_minutes, so nobody has to start the capture by hand. Alloy (win_alloy) ships the lines to +# Loki; the live server follows Loki. -- name: Deploy start-live.ps1 +- name: Deploy start-live.ps1 (watchdog; also -Status / -Rotate / -Pause / -Resume by hand) ansible.windows.win_template: src: start-live.ps1.j2 dest: 'C:\scripts\start-live.ps1' @@ -12,3 +14,31 @@ ansible.windows.win_file: path: 'C:\scripts\ship-live.ps1' state: absent + +# Two triggers, both repeating every live_watchdog_minutes with no end: "boot" (after a reboot) and +# "registration" (starts ticking as soon as Ansible creates or changes the task, no reboot needed). +- name: Register the always-on live capture task + community.windows.win_scheduled_task: + name: "{{ live_task_name }}" + description: "Keeps a live SilkETW capture running (C:\\scripts\\start-live.ps1; managed by Ansible win_shipper)" + actions: + - path: powershell.exe + arguments: -NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\scripts\start-live.ps1 + triggers: + - type: boot + delay: PT1M # let the network and Alloy come up first + repetition: + interval: "PT{{ live_watchdog_minutes }}M" + - type: registration + repetition: + interval: "PT{{ live_watchdog_minutes }}M" + username: SYSTEM + run_level: highest + multiple_instances: 2 # IgnoreNew: a slow tick is never doubled + execution_time_limit: PT15M + allow_demand_start: true + start_when_available: true + disallow_start_if_on_batteries: false + stop_if_going_on_batteries: false + enabled: true + state: present diff --git a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 index 0b41927..e6a540c 100644 --- a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 +++ b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 @@ -2,40 +2,176 @@ <# start-live.ps1 (generated by Ansible: win_shipper role) - Start a live SilkETW capture (split "test", run live-). Nothing is shipped by this script: Grafana - Alloy tails the run folder and pushes every line to Loki ({{ loki_url }}); the live server on the - trainer follows the newest test run in Loki. Conversion, windowing and scoring all run on the trainer. + Keeps a live SilkETW capture (split "test", run live-) ALWAYS running. Nothing is shipped by this + script: Grafana Alloy tails the run folder and pushes every line to Loki ({{ loki_url }}); the live server + on the trainer follows the newest test run in Loki. The capture itself runs inside the SilkService Windows + service; this script only decides WHEN to start a fresh run, because SilkService reads its output folder + once at service start (a plain auto-start would append to the last run, possibly a training run). - Run in an ELEVATED PowerShell during the demo: - C:\scripts\start-live.ps1 # new capture; press Ctrl+C to stop it - C:\scripts\start-live.ps1 -Minutes 30 # stop by itself after 30 minutes + The scheduled task "{{ live_task_name }}" (SYSTEM, at boot + every {{ live_watchdog_minutes }} min) runs it + with no arguments = one watchdog tick: + - a hold file exists ({{ lab_home }}\live.hold) -> do nothing (07-build-train-dataset.ps1 or -Pause) + - a TRAIN capture or a non-live test run is running -> do nothing + - a live-* run older than {{ live_rotate_hours }} h is running -> stop it and start a new live- + - nothing is running -> start a new live- + - delete raw\test\live-* runs with no write for {{ live_keep_days }} days (never raw\train, never the current run) + Each action is one line in {{ lab_home }}\live-watchdog.log. + + By hand (elevated PowerShell): + C:\scripts\start-live.ps1 -Status # service state, current run, hold, last log lines + C:\scripts\start-live.ps1 -Rotate # start a fresh live run now (clean session before a demo) + C:\scripts\start-live.ps1 -Pause # stop the live capture and keep it stopped (hold file) + C:\scripts\start-live.ps1 -Resume # remove the hold; the capture restarts now Live UI: http://{{ trainer_host }}:{{ server_port }}/ Grafana: http://{{ trainer_host }}:{{ grafana_port }}/ - PowerShell notes: try { } finally { } runs the finally block on Ctrl+C too, so the capture is always - stopped; Get-Service reads a service's state; Start-Sleep waits N seconds. + PowerShell notes: Get-Service reads a service's state; a [switch] parameter is a flag that is either given + or not; ConvertFrom-Json / ConvertTo-Json read / write JSON; Add-Content appends a line to a file; a + System.Threading.Mutex is a machine-wide lock, so a manual call and a task tick never act at the same time. #> param( - [int] $Minutes = 0 # 0 = until Ctrl+C + [switch] $Rotate, + [switch] $Pause, + [switch] $Resume, + [switch] $Status ) $ErrorActionPreference = 'Stop' -$LabDir = '{{ lab_home }}' -$Cfg = Get-Content (Join-Path $LabDir 'etwlab.json') -Raw | ConvertFrom-Json -$Etwctl = Join-Path $LabDir 'etwctl.ps1' +$LabDir = '{{ lab_home }}' +$Cfg = Get-Content (Join-Path $LabDir 'etwlab.json') -Raw | ConvertFrom-Json +$Etwctl = Join-Path $LabDir 'etwctl.ps1' +$StateF = Join-Path $LabDir 'state.json' # written by etwctl: split, run, dir, started_utc, stopped_utc +$HoldF = Join-Path $LabDir 'live.hold' # {pid, by, since_utc}; pid 0 = manual hold, never stale +$LogF = Join-Path $LabDir 'live-watchdog.log' +$RotateH = {{ live_rotate_hours }} +$KeepDays = {{ live_keep_days }} + +function Log($msg) { + $line = (Get-Date).ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'") + " $msg" + Add-Content -Path $LogF -Value $line + Write-Host $line +} +function Get-State { if (Test-Path $StateF) { Get-Content $StateF -Raw | ConvertFrom-Json } else { $null } } + +# Hold file: returns its content, or $null. A hold whose writer process is gone (07 crashed) is removed. +function Get-Hold { + if (-not (Test-Path $HoldF)) { return $null } + $h = Get-Content $HoldF -Raw | ConvertFrom-Json + if ($h.pid -ne 0 -and -not (Get-Process -Id $h.pid -ErrorAction SilentlyContinue)) { + Remove-Item $HoldF -Force + Log "removed stale hold (by $($h.by), pid $($h.pid) no longer running)" + return $null + } + return $h +} + +# Run etwctl in a child PowerShell (as the old start-live did); its output goes to the log. +# 'Continue' here: in Windows PowerShell 5.1, 2>&1 on a native program turns its stderr lines into errors, +# which 'Stop' would make fatal. We judge success by the exit code instead. +function Invoke-Etwctl([string[]] $EtwArgs) { + $ErrorActionPreference = 'Continue' + $out = & powershell -NoProfile -ExecutionPolicy Bypass -File $Etwctl @EtwArgs 2>&1 | Out-String + $code = $LASTEXITCODE + Add-Content -Path $LogF -Value ($out.TrimEnd() -split "`r?`n" | ForEach-Object { " $_" }) + return $code +} + +function Start-LiveRun { + $run = 'live-' + (Get-Date).ToUniversalTime().ToString("yyyyMMdd'T'HHmmss'Z'") + $code = Invoke-Etwctl @('start', '-Split', 'test', '-Run', $run) + if ($code -eq 0) { Log "started test/$run" } else { Log "etwctl start test/$run exited $code (see lines above)" } +} -if ((Get-Service Alloy).Status -ne 'Running') { throw "the Alloy service is not running: nothing would reach Loki" } -$svc = Get-Service $Cfg.ServiceName -if ($svc.Status -ne 'Stopped') { throw "$($Cfg.ServiceName) is $($svc.Status). Run 'etwctl stop' first." } +function Test-LiveRunning($svc, $st) { + return ($svc.Status -eq 'Running' -and $st -and $st.split -eq 'test' -and "$($st.run)" -like 'live-*') +} -$run = 'live-' + (Get-Date).ToUniversalTime().ToString("yyyyMMdd'T'HHmmss'Z'") -& powershell -NoProfile -ExecutionPolicy Bypass -File $Etwctl start -Split test -Run $run -if ($LASTEXITCODE -ne 0) { throw "etwctl start failed (exit $LASTEXITCODE)" } +# etwctl writes started_utc with ToString("o"); 5.1's ConvertFrom-Json keeps it a string, 7+ makes a DateTime. +function Get-StartedUtc($st) { + if ($st.started_utc -is [datetime]) { return $st.started_utc.ToUniversalTime() } + return [datetime]::Parse("$($st.started_utc)", [Globalization.CultureInfo]::InvariantCulture, + [Globalization.DateTimeStyles]::RoundtripKind).ToUniversalTime() +} -Write-Host "[start-live] capturing test/$run; Alloy ships it to {{ loki_url }}. Ctrl+C stops the capture." -try { - $until = if ($Minutes -gt 0) { (Get-Date).AddMinutes($Minutes) } else { [datetime]::MaxValue } - while ((Get-Date) -lt $until) { Start-Sleep -Seconds 5 } -} finally { - & powershell -NoProfile -ExecutionPolicy Bypass -File $Etwctl stop - Write-Host "[start-live] stopped. Alloy keeps shipping the last lines for a few seconds." +# Raw live runs with no write for $KeepDays days. Alloy keeps the lines in Loki (its own retention). +function Remove-OldLiveRuns($currentRun) { + $testDir = Join-Path $Cfg.RawRoot 'test' + if (-not (Test-Path $testDir)) { return } + $cut = (Get-Date).ToUniversalTime().AddDays(-$KeepDays) + foreach ($d in Get-ChildItem $testDir -Directory -Filter 'live-*') { + if ($d.Name -eq $currentRun) { continue } + $newest = Get-ChildItem $d.FullName -File -Recurse -ErrorAction SilentlyContinue | + Sort-Object LastWriteTimeUtc -Descending | Select-Object -First 1 + $last = if ($newest) { $newest.LastWriteTimeUtc } else { $d.LastWriteTimeUtc } + if ($last -lt $cut) { + try { Remove-Item $d.FullName -Recurse -Force; Log "deleted raw test/$($d.Name) (last write $($last.ToString('o')))" } + catch { Log "could not delete raw test/$($d.Name): $($_.Exception.Message) (retry next tick)" } + } + } } + +function Show-LiveStatus($svc, $st) { + Write-Host "service : $($svc.Name) = $($svc.Status)" + if ($st) { Write-Host "run : $($st.split)/$($st.run) started $($st.started_utc) stopped $($st.stopped_utc)" } + $h = Get-Hold + Write-Host ("hold : " + $(if ($h) { "yes (by $($h.by) since $($h.since_utc))" } else { "no" })) + $t = Get-ScheduledTask -TaskName '{{ live_task_name }}' -ErrorAction SilentlyContinue + Write-Host ("task : " + $(if ($t) { "{{ live_task_name }} = $($t.State)" } else { "MISSING" })) + Write-Host "alloy : $((Get-Service Alloy).Status)" + if (Test-Path $LogF) { Write-Host "log : last lines of $LogF"; Get-Content $LogF -Tail 8 | ForEach-Object { " $_" } } +} + +# The whole decision, as a function so every early exit is a plain `return` (the mutex is released below). +function Invoke-Main { + $rot = [bool]$Rotate + $svc = Get-Service $Cfg.ServiceName + $st = Get-State + + if ($Status) { Show-LiveStatus $svc $st; return } + + if ($Pause) { + $hold = [ordered]@{ pid = 0; by = 'start-live.ps1 -Pause'; since_utc = (Get-Date).ToUniversalTime().ToString('o') } + Set-Content -Path $HoldF -Value ($hold | ConvertTo-Json -Compress) + if (Test-LiveRunning $svc $st) { [void](Invoke-Etwctl @('stop')); Log "paused: stopped test/$($st.run)" } + else { Log "paused (no live run was running)" } + return + } + + if ($Resume) { + if (Test-Path $HoldF) { Remove-Item $HoldF -Force; Log "resumed: hold removed" } + $rot = $false # continue as a normal tick, which starts a run if none is running + } + + if ((Get-Service Alloy).Status -ne 'Running') { Log "WARNING the Alloy service is not running: nothing reaches Loki" } + + $hold = Get-Hold + if ($hold) { + if ($rot) { Write-Host "[start-live] on hold (by $($hold.by)); run with -Resume first" } + return + } + if ($svc.Status -eq 'Running' -and $st -and -not (Test-LiveRunning $svc $st)) { + if ($rot) { Write-Host "[start-live] $($st.split)/$($st.run) is capturing (not a live run); not touching it" } + return # a training capture or a hand-started test run + } + if ($svc.Status -ne 'Running' -and $svc.Status -ne 'Stopped') { return } # StartPending / StopPending: next tick + + if (Test-LiveRunning $svc $st) { + $age = (Get-Date).ToUniversalTime() - (Get-StartedUtc $st) + if ($rot -or $age.TotalHours -ge $RotateH) { + [void](Invoke-Etwctl @('stop')) + Log ("rotated: stopped test/$($st.run) after {0:N1} h" -f $age.TotalHours) + Start-LiveRun + } + } else { + Start-LiveRun # SilkService is stopped and nothing holds it + } + + $cur = Get-State + Remove-OldLiveRuns $(if ($cur) { "$($cur.run)" } else { '' }) +} + +# One action at a time on this machine (task tick vs a manual call). An "abandoned" mutex (a previous run was +# killed while holding it) is still ours once WaitOne throws AbandonedMutexException. +$mutex = New-Object System.Threading.Mutex($false, 'Global\etwlab-live') +try { $owned = $mutex.WaitOne(0) } catch [System.Threading.AbandonedMutexException] { $owned = $true } +if (-not $owned) { Write-Host "[start-live] another start-live.ps1 is running; try again in a few seconds"; exit 0 } +try { Invoke-Main } finally { $mutex.ReleaseMutex() } diff --git a/src/live/README.md b/src/live/README.md index b818baf..7e9b789 100644 --- a/src/live/README.md +++ b/src/live/README.md @@ -61,12 +61,41 @@ Expect `ALL MATCH`. Watch at http://127.0.0.1:8000. The dos-map is inferred from ## 5. Live (Alloy → Loki, the default) 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 `). On the VM (elevated PowerShell, RDP session): +`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). + +**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, and leaves SilkService alone while a hold exists +(`07-build-train-dataset.ps1` pauses it for a train capture and resumes it after). By hand, in an elevated +PowerShell on the VM: ``` -C:\scripts\start-live.ps1 # shell 1: capture test/live-; Alloy ships it -C:\scripts\06-benign-workload.ps1 # shell 2: benign activity, as in training +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 +C:\scripts\06-benign-workload.ps1 # benign activity, as in training (RDP desktop only; not automatic) ``` -The server follows the newest `split="test"` run, and a new run starts a new session. +The server follows the newest `split="test"` run, and a new run starts a new session. Old `live-*` session +folders on the trainer (each holds a raw copy, ~2 GB/h) are deleted after 12 idle hours (`live_session_keep_hours`; a +session holding a `.keep` file is never deleted). Loki keeps 3 days (`loki_retention`): pull training captures within 3 days. + +**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: +``` +vagrant ssh ubuntu-trainer +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. diff --git a/src/pipeline/alg2.py b/src/pipeline/alg2.py index 11522af..53e7d70 100644 --- a/src/pipeline/alg2.py +++ b/src/pipeline/alg2.py @@ -840,6 +840,10 @@ def boom(s, m): assert r["subgraphs_investigated"] == 0 and r["llm_calls"] == 0 and r["verdict"] == "uncertain" # (k) rule mock runs end to end (UI testing only) assert investigate([sg], edges, win, MockLLM())["verdict"] == "attack" + # (k2) --ping: 0 when the provider answers, 1 (no exception) when it fails + with contextlib.redirect_stdout(io.StringIO()) as out: + assert ping(MockLLM(lambda s, m: "OK")) == 0 and ping(MockLLM(boom)) == 1 + assert "ping OK" in out.getvalue() and "ping FAILED" in out.getvalue(), out.getvalue() # (l) DeepSeek request shape through the real openai SDK, no network (httpx.MockTransport). Proves we send # what the DeepSeek API docs describe, not that DeepSeek accepts it or that the model triages well. @@ -932,6 +936,18 @@ def load_window(wdir: str, sg_file: str, window_min: float): return sgs, edges, win +def ping(client) -> int: + """--ping: one tiny prompt through the Recorder (so --llm-debug shows the raw answer). 0 = answered.""" + call = Recorder(client) + try: + out = call("ping", "Answer with one word.", [{"role": "user", "content": "Say OK."}]) + except Exception as e: + print(f"[alg2] ping FAILED {getattr(client, 'model', '')}: {type(e).__name__}: {e}") + return 1 + print(f"[alg2] ping OK {getattr(client, 'model', '')} {call.calls[-1]['ms']} ms: {out.strip()[:80]!r}") + return 0 + + def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--selftest", action="store_true") @@ -955,11 +971,20 @@ def main(): "'raw' in calls.jsonl (default from $NT2102_LLM_DEBUG=1)") ap.add_argument("--max-lines", type=int, default=400, help="[OURS] document cap per subgraph") ap.add_argument("--max-subgraphs", type=int, default=5, help="[OURS] kept subgraphs investigated per window") + ap.add_argument("--ping", action="store_true", + help="one tiny prompt to --llm-provider and exit (0 = answered): checks the key + endpoint; " + "on a terminal it also prompts for and saves a missing key") a = ap.parse_args() if a.selftest: return selftest() + if a.ping: + if not a.llm_provider: + ap.error("--ping needs --llm-provider") + client = make_client(a.llm_provider, a.llm_model, a.llm_base_url, a.llm_api_key, a.llm_reasoning_effort, + debug=a.llm_debug) + sys.exit(ping(client)) if not (a.window_dir or a.session_dir): - ap.error("one of --window-dir / --session-dir is required (or --selftest)") + ap.error("one of --window-dir / --session-dir is required (or --selftest / --ping)") if not a.serialize_only and not a.llm_provider: ap.error("--llm-provider is required unless --serialize-only") sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) diff --git a/src/scripts/07-build-train-dataset.ps1 b/src/scripts/07-build-train-dataset.ps1 index 3689abf..12921a1 100644 --- a/src/scripts/07-build-train-dataset.ps1 +++ b/src/scripts/07-build-train-dataset.ps1 @@ -5,7 +5,7 @@ (NT2102 / OCR-APT POC, SimulatedW10 ETW lab VM). .DESCRIPTION - 1. preflight interactive desktop session, no capture running, tools present, workload self-test + 1. preflight interactive desktop session, no other capture running (the always-on live capture is paused automatically), tools present, workload self-test (explorer.exe must be the launcher, otherwise benign apps get powershell.exe as parent) 2. capture etwctl start -Split train -Run x- -> settle -> 06-benign-workload.ps1 -> etwctl stop (called from the workload's -BeforeLedger hook, so the ledger write @@ -278,14 +278,22 @@ if ($PostProcess) { return } -# ---------------------------------------------------------------- 1. preflight (nothing is captured yet) +# ---------------------------------------------------------------- 1. preflight (nothing goes into the train capture yet) if ((Get-Process -Id $PID).SessionId -eq 0) { throw 'session 0 (service/WinRM): run this from the RDP or console desktop' } if (-not (Test-Path $WorkloadScript)) { throw "workload script not found: $WorkloadScript" } if (-not (Get-Command $WorkloadScript).Parameters.ContainsKey('BeforeLedger')) { throw "$WorkloadScript has no -BeforeLedger parameter - apply the 2-line patch first" } $svc = Get-Service $Cfg.ServiceName -if ($svc.Status -ne 'Stopped') { throw "$($Cfg.ServiceName) is $($svc.Status): another capture is running ('etwctl stop' first)" } +# The always-on live capture (start-live.ps1 watchdog, test/live-*) is paused below, right before the train +# capture starts. Any other running capture (train, or a hand-started test run) still stops us here. +$StateFile = Join-Path $LabDir 'state.json' +$HoldFile = Join-Path $LabDir 'live.hold' +$cur = if (Test-Path $StateFile) { Get-Content $StateFile -Raw | ConvertFrom-Json } else { $null } +$liveRunning = $svc.Status -eq 'Running' -and $cur -and $cur.split -eq 'test' -and "$($cur.run)" -like 'live-*' +if ($svc.Status -ne 'Stopped' -and -not $liveRunning) { + throw "$($Cfg.ServiceName) is $($svc.Status): another capture is running ('etwctl stop' first)" +} $expected = [math]::Floor(($DurationMinutes - $WindowMinutes) / $StrideMinutes) + 1 if ($expected -lt 1) { throw "-DurationMinutes $DurationMinutes is shorter than one $WindowMinutes-min window" } @@ -332,7 +340,17 @@ $stopCapture = { } }.GetNewClosure() +# Hold file: the start-live.ps1 watchdog (SYSTEM task, every few minutes) leaves SilkService alone while it +# exists. Written BEFORE the live run is stopped, so a watchdog tick cannot restart live in between; removed +# in the finally below, so live resumes within one tick after the train capture. Our $PID lets the watchdog +# drop the hold if this PowerShell dies without running the finally. +$hold = [ordered]@{ pid = $PID; by = '07-build-train-dataset.ps1'; since_utc = (Utc-Now) } +Set-Content -Path $HoldFile -Value ($hold | ConvertTo-Json -Compress) try { + if ((Get-Service $Cfg.ServiceName).Status -ne 'Stopped') { + Log 'pause the always-on live capture (start-live.ps1 resumes it after this capture)' + & $EtwctlPs1 stop | Out-Host + } $rec.capture.started_utc = Utc-Now $Cap.Started = $true # set first: a half-started capture is still stopped $global:LASTEXITCODE = 0 @@ -349,6 +367,7 @@ finally { # also runs on Ctrl+C o & $stopCapture $rec.capture.stopped_utc = $Cap.StoppedUtc Write-Json (Join-Path $exp 'experiment.json') $rec + Remove-Item $HoldFile -Force -ErrorAction SilentlyContinue # live capture resumes at the next watchdog tick } # ---------------------------------------------------------------- 3. collect raw into the experiment From 743a9eef4da03a1c7db3195f80d7f284ebd0465c Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sun, 25 Oct 2026 15:15:12 +0700 Subject: [PATCH 3/8] Fix live_llm_args precedence and replay naming; record the full-flow run live_llm_args had a "" default in group_vars/all.yml, which outranks the inventory's [ubuntu:vars], so the DeepSeek flags in inventory.local.ini were silently ignored (and uv sync removed the llm group again). The default is gone; the template and the uv sync task use live_llm_args | default(''). replay.sh named every replay of a session "replay-raw" (a session's copy is always raw/), so replays of different sessions shared one folder. A session replay is now named replay-. Docs: the first live full-flow run with the LLM (2026-10-25) exposed a collector blocker. SilkService writes Kernel-File events minutes late (about 20-25 % of real-time speed from a fresh run, mostly its own writes plus Alloy's reads), so the live engine drops every file event as late. The Oct 22 live "attack detected" result had zero Read/Write edges and is marked invalid (DEVIATIONS D8 correction). In the rerun no attack node was flagged; the only red window was a benign msedge launch, which the LLM correctly judged a false positive (D9). PROGRESS lists the kfile-lag diagnosis as the next step. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016bXvsQ3vTwv9ULcuM7piSa --- CLAUDE.md | 2 + docs/DEVIATIONS.md | 28 +++++++- docs/PROGRESS.md | 64 +++++++++++-------- replay.sh | 9 ++- src/ansible/group_vars/all.yml | 5 +- .../roles/ubuntu_project/tasks/main.yml | 2 +- .../templates/ocr-live.service.j2 | 2 +- 7 files changed, 78 insertions(+), 34 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index dc384f9..bda3e67 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,6 +116,8 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum (`src/live/`) exist, and Alg. 1 + the subgraph-score filter (SG-Det) decides the window alert. Immediate step (user, 2026-10-25): verify the full detection flow with LLM support (DeepSeek, `--llm-provider deepseek`) live: benign stays green, the DVWA→RCE attack goes red and gets an LLM attack verdict + report. + The first run (2026-10-25) is blocked by the collector: SilkService writes Kernel-File events minutes late, + so live windows have no file events (DEVIATIONS D8 correction). Fix that first, then re-run. Then: the browser false positive, the replay equivalence check, understanding the trainer (concepts 2–4). - Data: the user's own Windows 10 audit data (ETW), shaped to match the NODLINK simulated Windows 10 (W10) host format the repo expects. The graph is named `SimulatedW10` because the repo asserts diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index b20e497..2f0f766 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -136,9 +136,29 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. msedge spawns many short-lived processes, each a fresh node under PID+start-time keying (D4) and so unseen in benign training, tripping the *same* "unfamiliar process+DLL burst" mechanism as the cradle. This is a benign-**variety** gap, not a duration gap — more minutes of the same seeded workload do not - fix it; the fix is benign training that covers browsing. Honest reading: detection works, but the + fix it; the fix is benign training that covers browsing. Reading at the time: detection works, but the attack/benign margin is narrow (56 vs 22 without the browser; 37.76 vs 31 with it) and both sides are the same mechanism, so 30 is not yet a trustworthy clean separator. [[live-detector-benign-fp]] + **Superseded by the correction below.** + - **Correction (2026-10-25, verified): live windows have no file events, so no live result so far is a + valid detection result.** Every window of `live-20261022T155035Z` holds **zero Read/Write edges** + (exp03 training windows: ~14,000 Read + ~500 Write each). Cause, measured on `ws-etw`: SilkService + writes Kernel-File (`kfile`) events far behind real time. From a fresh run it falls behind at once + (event time advances at ~20–25 % of wall time; 9+ min behind after 25 min) with SilkService at ~1 CPU + core, and nearly all recent kfile events are SilkService's own writes to `kfile.json` plus Alloy's reads + of it (a self-feeding loop). Alloy and Loki pass the delay through (both ~real time for kproc/knet), + and the engine drops lines older than the watermark (newest event − 20 s) as late (`late_dropped` + ≈ all kfile lines). ETW reports `Buffers Lost: 0`, yet SilkService memory stays flat (~275 MB), so where + the backlog goes (and whether kfile events are also lost) is open [INFERENCE: lost at the real-time + layer]. Not explained yet: why the Oct 22 1-h training capture kept a full 77-min kfile span. + Rerun 2026-10-25 (`live-20261025T073042Z`, exp03, attack 14:45–14:47 local): the attack's processes + (httpd, cmd, powershell ×3, systeminfo, PING; images whoami/tasklist/ipconfig/net/schtasks) all reached + the graph, but **none was flagged** (closest: the cradle powershell, 0.004 below τ). The window went red + (33.87, Moderate) only because of a benign msedge launch at 14:49. Benign 14:35 / 14:40 stayed green + (12.0 / 21.0). A laptop replay of that session, which receives the kfile lines live dropped, scored the + 14:35 benign window 3.0 instead of 12.0: one data point consistent with "missing file actions push live + features off the training distribution" [INFERENCE], not proof. Until the collector keeps up with kfile + (lag < lateness), live detection is unvalidated. - Limits: shows near-live node scoring + Alg. 1 on our own data. No detection-quality claim until windows are labelled (D6); no claim about Alg. 1 precision; the cut-off (Moderate ≥ 30) is ours, set on one benign window, not the paper's. @@ -171,6 +191,12 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. `$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 `alg2.py`. This covers self-hosted (vLLM / LM Studio / Ollama) and hosted (OpenRouter / Groq) servers. + - First live run (2026-10-25, `ocr-live` with DeepSeek `deepseek-flash`, thinking off, + `live-20261025T073042Z`): the one red window (a benign msedge launch, sg 33.87) → `false_positive` + (confidence 0.9, 1 call, 3.1 s, 8/8 evidence lines found verbatim in the document): correct. A laptop + 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, `--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 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0bac418..ddb8760 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -6,28 +6,44 @@ Replace lines in place when status changes; no history. "Verified" = checked in The "widen benign + calibrate" cycle ran on **1 HOUR** of benign data (not 2): kfile-fixed capture `x-20261022T140932Z` → `exp03` trained + promoted → live DVWA→RCE attack. Work is on branch -**`collect-benign-data-for-1-hour`**. **Now (user, 2026-10-25): verify the full detection flow with LLM -support** — live benign stays green, the live DVWA→RCE attack goes red AND the LLM (DeepSeek) judges it an -attack with a report (Next 3 steps). The residual browser false positive stays open. +**`collect-benign-data-for-1-hour`**. The full flow with LLM support ran live on 2026-10-25 (branch +`make-sure-to-support-llm-investigator`) and exposed a **collector blocker**: SilkService writes Kernel-File +events far behind real time, so the live engine drops every file event as late. **Now: fix the kfile lag**, +then re-run the full flow (Next 3 steps). No live detection result so far is valid (DEVIATIONS D8 correction). DONE this session (2026-10-22, verified live): - **exp03** trained on the 1-h capture and **PROMOTED** (gate passed: 77-min kfile span, all 6 edge types non-zero, `emb_std ≠ 0` per type; Read 517,951 · Send 35,485 · Write 18,308 · Recv 10,109 · Load 4,474 · Start 76). `ocr-live` restarted on exp03. The `0x380` kfile fix held at 1-h scale. -- **Live attack detected** (session `live-20261022T155035Z`): DVWA→RCE kill chain scored **37.76** then - **56.0** (Moderate); kept subgraph = powershell cradle (powershell + .NET assembly loads + RAS/proxy - DLLs). Non-browser benign stayed green (10.0 / 12.45 / 22.0, Minor). DEVIATIONS D8. +- ~~Live attack detected~~ (session `live-20261022T155035Z`, 37.76 / 56.0): **NOT valid** (verified + 2026-10-25): its windows have zero Read/Write edges (training ~14k Read per window). DEVIATIONS D8. - **LLM investigator** (`alg2.py`, paper Alg. 2 l.3–15 incl. the serialize+reduce phase that collapses the DLL-load flood) already implemented; **added OpenAI-compatible support** (`--llm-api-key`, keyless-dummy for a custom `--llm-base-url`) across `alg2.py` / `engine.py` / `live_server.py`; selftest passes. +DONE 2026-10-25 (verified live): +- **Always-on live capture**: SYSTEM task `etwlab-live` runs the `start-live.ps1` watchdog at boot + every + 5 min (rotate 6 h, raw `live-*` kept 1 day, `07` pauses it via a hold file). Verified: ws-etw reboot → + new run by itself; a tick during `-Pause` left it stopped; `-Resume` restarted in 11 s. The `07` hold + path is NOT yet exercised by a real train capture. +- **LLM on `ocr-live`**: DeepSeek, thinking off, `--llm-debug`; key saved once on the trainer + (`alg2.py --ping`, no-TTY ping 0.8 s). Trainer root LV grown 31 → 61 GB; sessions pruned after 12 idle h + (`.keep` on `live-20261022T155035Z`); Loki retention 3 d. +- **Full-flow run** `live-20261025T073042Z` (exp03, attack 14:45–14:47 local): benign 14:35 / 14:40 green; + attack window red (33.87) but ONLY from a benign msedge launch: the attack's processes reached the graph + and none was flagged. LLM judged that red window `false_positive` (0.9): correct. Laptop replay + (`replay-live-20261025T073042Z`, bundle with the model in `src/live/sessions/live-20261025T073042Z/model/`) + reproduces the live windows that were not affected by late kfile lines, and the same LLM verdict. + OPEN (the real limitation): +- **kfile lag (blocker)**: SilkService falls behind on Kernel-File at ~20–25 % of real time from a fresh + run, ~1 CPU core, most events are its own writes + Alloy's reads; the engine drops them as late. + DEVIATIONS D8 correction. - **Browser benign FP**: an Edge-browsing benign window hit **31.0** (Moderate, false alarm). msedge's many per-instance processes are unseen in benign training → the *same* mechanism as the cradle. The fix is benign **variety** (training that covers browsing), **not** more capture time. DEVIATIONS D8, [[live-detector-benign-fp]]. -- LLM: DeepSeek works offline-replayed (one benign window → `false_positive`, 2026-10-25) but has never run - inside the live server, and never on an attack window. +- LLM attack path (triage `attack` → IOCs → report) never run live: no attack subgraph yet. - `06-benign-workload.ps1` **deadline-overrun bug** (the `while (now < deadline)` loop ran ~74 min for a 60-min target because one scenario call blocked) — deferred, not yet debugged. @@ -195,24 +211,20 @@ Repo hygiene: - `src/out/etw/SimulatedW10_train_edges.csv` (old un-windowed capture) sits next to the experiment folders and is easy to pick by mistake (it caused the first, collapsed exp01 run). -## Next 3 steps (verify the full detection flow with LLM support — user, 2026-10-25) - -Goal: one live session where benign windows stay green, the DVWA→RCE attack window goes red, and the LLM -investigator judges it `attack` with ATT&CK tactics + an IOC report in the UI. Model: exp03 (promoted). - -1. LLM on the live server (`ubuntu-trainer`): `uv sync --group llm` in the repo; save the DeepSeek key for the - service user ONCE interactively (`vagrant ssh ubuntu-trainer`, then e.g. `./rejudge.sh deepseek` - → prompt → `~/.config/nt2102/credentials.json`, mode 600; `ocr-live` has no terminal, so it cannot prompt). - Add `--llm-provider deepseek --llm-reasoning-effort none` (+ `--llm-debug` for the first run) to the - `ocr-live` ExecStart via an Ansible var (key never in Ansible/repo; idempotent re-run), restart, and check - journalctl shows `[live] LLM {'provider': 'deepseek', ...}`. -2. Benign live session (`start-live.ps1` + `06-benign-workload.ps1 -Seed 7`): windows stay green; any red - window (e.g. the browser FP) gets an LLM badge — record verdict, latency, calls (`llm_verdicts.csv`). -3. Attack during the live session: `vagrant ssh kali -c 'python3 -I /opt/attack-pack/tools/launch_exploit.py - --target http://10.21.2.10:3000'`. Check (a) window ≥ Moderate with a kept subgraph of attack indicators - (httpd→cmd→powershell, tool images, attacker :8080); (b) triage = `attack` with evidence lines that are in - the document; (c) the report's IOCs survive the hallucination filter. Record in PROGRESS + DEVIATIONS D9 - (one attack = one data point, not a detection rate). +## Next 3 steps (fix the kfile lag, then re-run the full flow — 2026-10-25) + +1. Diagnose the SilkService kfile lag on `ws-etw` (time-boxed A/B): + - stop Alloy for ~2 min: does SilkService catch up? + - count SilkService Write events per output line (self-amplification); + - check whether the exp03 training kfile also thinned out over time (Read per window across the 37 windows); + - read the real-time "events lost" counter. + Then propose a fix (e.g. keep the collector's own I/O out of the Kernel-File stream, or another consumer). +2. Re-run the full flow once kfile keeps up (Loki kfile lag < 20 s, `late_dropped` ≈ 0). Check: + - benign stays green; + - the attack's own nodes are flagged; + - LLM triage `attack` + IOC report. + Replay it on the laptop as in 2026-10-25. +3. Browser FP (benign variety in training) once live data is complete. Watch item: the first 15-min `07` run (`x-20261021T161810Z`) did not write `stopped_utc` (capture left running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the service on the 2h run. diff --git a/replay.sh b/replay.sh index 9eb5e2e..4ad5ef8 100755 --- a/replay.sh +++ b/replay.sh @@ -6,15 +6,18 @@ # raw-dir any folder of SilkETW *.json, e.g. # src/out/etw/experiments/20261009T145632Z/raw/train/x-20261009T145632Z # speed default 120 (0 hangs, 600 makes POSTs too large and the shipper times out) -# Env: PORT (default 8000). The replay is saved as a new session named replay-. +# Env: PORT (default 8000). The replay is saved as a new session named replay- (or +# replay- for a raw-dir). set -euo pipefail cd "$(dirname "$0")" -[[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]] && { sed -n '2,9p' "$0"; exit 0; } +[[ $# -lt 1 || "$1" == "-h" || "$1" == "--help" ]] && { sed -n '2,10p' "$0"; exit 0; } src=$1 speed=${2:-120} PORT=${PORT:-8000} +name=() if [[ -d "src/live/sessions/$src/raw" ]]; then + name=(--session "replay-$src") # a session's copy is always called raw/: name the replay after the session src="src/live/sessions/$src/raw" elif [[ ! -d "$src" ]]; then echo "[replay] no session src/live/sessions/$src and no folder $src" >&2 @@ -24,4 +27,4 @@ if ! curl -sf "http://127.0.0.1:$PORT/api/status" >/dev/null; then echo "[replay] no live server on 127.0.0.1:$PORT. Start one first: ./serve.sh local" >&2 exit 1 fi -exec uv run python src/live/etwship.py --server "http://127.0.0.1:$PORT" --speed "$speed" --replay "$src" +exec uv run python src/live/etwship.py --server "http://127.0.0.1:$PORT" --speed "$speed" --replay "$src" "${name[@]}" diff --git a/src/ansible/group_vars/all.yml b/src/ansible/group_vars/all.yml index 64ebb8e..9b722d9 100644 --- a/src/ansible/group_vars/all.yml +++ b/src/ansible/group_vars/all.yml @@ -79,9 +79,10 @@ repo_branch: "main" repo_dest: "/home/{{ ansible_user | default('vagrant') }}/NT2102" # The model ocr-live loads is NOT set here: it is the repo's pointer src/artifacts/current.json, or # current.local.json on the trainer (`lab promote `). No run_id / experiment_id to keep in sync. -# Extra live_server.py LLM flags for ocr-live; empty = LLM off. Non-empty also installs the `llm` uv group. +# 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). -live_llm_args: "" # Live sessions (src/live/sessions/live-*) with no write for this many hours are deleted hourly on the trainer # (each holds a raw copy of the capture, ~2 GB/h measured; replay-* folders and any session holding a .keep # file are never touched). diff --git a/src/ansible/roles/ubuntu_project/tasks/main.yml b/src/ansible/roles/ubuntu_project/tasks/main.yml index f3046d8..8d64f6d 100644 --- a/src/ansible/roles/ubuntu_project/tasks/main.yml +++ b/src/ansible/roles/ubuntu_project/tasks/main.yml @@ -16,7 +16,7 @@ - name: uv sync (resolve torch, torch-geometric, fastapi, ...; + the llm group when live_llm_args is set) become: false # a plain `uv sync` removes packages of groups it was not asked for, so the llm group must be named here - ansible.builtin.command: "uv sync{{ ' --group llm' if live_llm_args else '' }}" + ansible.builtin.command: "uv sync{{ ' --group llm' if live_llm_args | default('') else '' }}" args: chdir: "{{ repo_dest }}" register: uv_sync 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 e06850a..e750a35 100644 --- a/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 +++ b/src/ansible/roles/ubuntu_project/templates/ocr-live.service.j2 @@ -12,7 +12,7 @@ Environment=PYTHONUNBUFFERED=1 # Mirrors serve.sh, but binds {{ server_bind }} (all interfaces) so it listens on the subnet IP. # Model = the repo's current-model pointer (`lab promote `, then `sudo systemctl restart ocr-live`). # LLM flags = live_llm_args (empty = LLM off); the key comes from ~/.config/nt2102/credentials.json. -ExecStart=/usr/local/bin/uv run {{ '--group llm ' if live_llm_args else '' }}python src/live/live_server.py --bind {{ server_bind }} --port {{ server_port }} --loki-url http://127.0.0.1:{{ loki_port }}{{ ' ' + live_llm_args if live_llm_args else '' }} +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 }}{{ ' ' + live_llm_args if live_llm_args | default('') else '' }} Restart=on-failure RestartSec=5 From 5a51ee536b76a979f818a11648cae40bb243a0f9 Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Mon, 26 Oct 2026 23:40:47 +0700 Subject: [PATCH 4/8] Add etwcollect, our own Python ETW collector that also ships to Loki SilkService (SilkETW v0.8) writes every event with File.AppendAllText, so each line it writes adds Kernel-File events of its own; together with Alloy's reads this loop left live windows without file events. Replace it with src/etw-python (uv project, stdlib + ctypes): one real-time ETW session, TDH-decoded payloads, the collector's own I/O dropped before formatting, one batched write per file per second, and a shipper that pushes the run files to Loki with Alloy's labels. - Vagrant mounts src/etw-python at C:\etw-python locally; cloud clones the repo. - win_collector installs uv, builds the venv, registers the SYSTEM task etwlab-collector; etwctl/start-live/07 drive it (collector=python), Alloy is stopped and disabled. SilkService stays installed only until removal. - Converter: network events take the owner from the payload PID (_PID); 77 % of knet events had a different header PID. - Verified on ws-etw: live selftest, 20 s parity with SilkService (100 % of events matched, no field mismatch), live path late_dropped = 0. - Docs: CLAUDE.md, DEVIATIONS D8/D10, PROGRESS, docs/notes/silkservice-kfile-lag.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VCx5NxSphANRKqvrtUUw3W --- .gitignore | 3 + CLAUDE.md | 31 +- docs/DEVIATIONS.md | 41 +- docs/PROGRESS.md | 55 +-- docs/notes/silkservice-kfile-lag.md | 229 ++++++++++ selftest.sh | 9 + src/README.md | 9 +- src/Vagrantfile | 11 +- src/ansible/README.md | 45 +- src/ansible/group_vars/all.yml | 21 + src/ansible/inventory.local.ini | 4 + src/ansible/roles/win_alloy/handlers/main.yml | 1 + src/ansible/roles/win_alloy/tasks/main.yml | 9 +- .../roles/win_collector/files/etwctl.ps1 | 262 +++++++----- .../roles/win_collector/tasks/main.yml | 110 ++++- .../win_collector/templates/etwlab.json.j2 | 7 + src/ansible/roles/win_shipper/tasks/main.yml | 2 +- .../win_shipper/templates/start-live.ps1.j2 | 32 +- src/ansible/verify-windows.yml | 39 +- src/etw-python/.python-version | 1 + src/etw-python/README.md | 82 ++++ src/etw-python/pyproject.toml | 22 + src/etw-python/src/etwcollect/__init__.py | 10 + src/etw-python/src/etwcollect/__main__.py | 6 + src/etw-python/src/etwcollect/cli.py | 157 +++++++ src/etw-python/src/etwcollect/collector.py | 253 +++++++++++ src/etw-python/src/etwcollect/decode.py | 191 +++++++++ src/etw-python/src/etwcollect/dosmap.py | 43 ++ src/etw-python/src/etwcollect/filters.py | 98 +++++ src/etw-python/src/etwcollect/loki.py | 277 ++++++++++++ src/etw-python/src/etwcollect/procnames.py | 86 ++++ src/etw-python/src/etwcollect/providers.py | 35 ++ src/etw-python/src/etwcollect/record.py | 66 +++ src/etw-python/src/etwcollect/schema.py | 138 ++++++ src/etw-python/src/etwcollect/selftest.py | 395 ++++++++++++++++++ src/etw-python/src/etwcollect/session.py | 111 +++++ src/etw-python/src/etwcollect/winapi.py | 236 +++++++++++ src/etw-python/src/etwcollect/writer.py | 52 +++ src/etw-python/tools/parity.py | 180 ++++++++ src/etw-python/uv.lock | 8 + src/pipeline/etw2nodlink.py | 17 +- src/scripts/07-build-train-dataset.ps1 | 41 +- 42 files changed, 3222 insertions(+), 203 deletions(-) create mode 100644 docs/notes/silkservice-kfile-lag.md create mode 100644 src/etw-python/.python-version create mode 100644 src/etw-python/README.md create mode 100644 src/etw-python/pyproject.toml create mode 100644 src/etw-python/src/etwcollect/__init__.py create mode 100644 src/etw-python/src/etwcollect/__main__.py create mode 100644 src/etw-python/src/etwcollect/cli.py create mode 100644 src/etw-python/src/etwcollect/collector.py create mode 100644 src/etw-python/src/etwcollect/decode.py create mode 100644 src/etw-python/src/etwcollect/dosmap.py create mode 100644 src/etw-python/src/etwcollect/filters.py create mode 100644 src/etw-python/src/etwcollect/loki.py create mode 100644 src/etw-python/src/etwcollect/procnames.py create mode 100644 src/etw-python/src/etwcollect/providers.py create mode 100644 src/etw-python/src/etwcollect/record.py create mode 100644 src/etw-python/src/etwcollect/schema.py create mode 100644 src/etw-python/src/etwcollect/selftest.py create mode 100644 src/etw-python/src/etwcollect/session.py create mode 100644 src/etw-python/src/etwcollect/winapi.py create mode 100644 src/etw-python/src/etwcollect/writer.py create mode 100644 src/etw-python/tools/parity.py create mode 100644 src/etw-python/uv.lock diff --git a/.gitignore b/.gitignore index 5f8c74b..892abfa 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,6 @@ __pycache__/ # per-machine current-model pointer written by `lab promote` (overrides src/artifacts/current.json) /src/artifacts/current.local.json + +# etw-python collector (uv project): its own venv when run on the host +/src/etw-python/.venv/ diff --git a/CLAUDE.md b/CLAUDE.md index bda3e67..87d2855 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,8 +116,11 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum (`src/live/`) exist, and Alg. 1 + the subgraph-score filter (SG-Det) decides the window alert. Immediate step (user, 2026-10-25): verify the full detection flow with LLM support (DeepSeek, `--llm-provider deepseek`) live: benign stays green, the DVWA→RCE attack goes red and gets an LLM attack verdict + report. - The first run (2026-10-25) is blocked by the collector: SilkService writes Kernel-File events minutes late, - so live windows have no file events (DEVIATIONS D8 correction). Fix that first, then re-run. + The first run (2026-10-25) is blocked by the collector: SilkService writes Kernel-File events minutes late + (its own per-event file writes feed back into Kernel-File), so live windows have no file events (DEVIATIONS + D8 correction, `docs/notes/silkservice-kfile-lag.md`). Fix (user, 2026-10-26): replace SilkService AND + Alloy with our own Python ETW collector `src/etw-python` (it pushes to Loki itself); once verified, remove + both completely (D10). Then capture benign data with it, train exp04, re-run. Then: the browser false positive, the replay equivalence check, understanding the trainer (concepts 2–4). - Data: the user's own Windows 10 audit data (ETW), shaped to match the NODLINK simulated Windows 10 (W10) host format the repo expects. The graph is named `SimulatedW10` because the repo asserts @@ -141,16 +144,20 @@ history of earlier progress) and, if relevant, this section. - Environment: Python deps are managed with uv (`pyproject.toml` + `uv.lock`), not containers. Docker is used only on the Ubuntu trainer for Loki + Grafana (installed by Ansible). No RDF / GraphDB (user, 2026-10-17): edges stay CSV and Alg. 1 runs in memory. -- Log transport (user, 2026-10-17): Grafana Alloy (native on the Windows VM) ships raw SilkETW lines, - unchanged, to Loki (Docker, host network) on the Ubuntu trainer. Labels: job, host, split, run, provider; - event/pid/process as structured metadata. Training pulls from Loki by run or time range +- Log transport (user, 2026-10-26, superseding the 2026-10-17 Alloy decision): our collector + (`src/etw-python`, `etwcollect`) pushes its SilkETW-format JSON lines to Loki (Docker, host network) on + the Ubuntu trainer itself, from its own run files with saved offsets; Grafana Alloy is removed once the + collector is verified. Labels unchanged: job (`silketw`, it names the line format), host, split, run, + provider; event/pid/process as structured metadata. Training pulls from Loki by run or time range (`loki_pull.py`); the live server follows Loki (`--loki-url`). All conversion, windowing and scoring run on the trainer with the training converter code, scaler and relation list; the live clock is event time (newest event − lateness), with a host-clock fallback when idle (DEVIATIONS D8). The HTTP shipper (`etwship.py`) remains for replay only. - Collection lab: three VMs provisioned by Ansible (`src/ansible/`, cloud-portable via inventory): Windows - Server 2022 `ws-etw` (SilkETW/SilkService on Kernel-Process, Kernel-File, Kernel-Network + Alloy + the - DVWA vulnlab on XAMPP, no training), Ubuntu `ubuntu-trainer` (Loki + Grafana, training, live server), and + Server 2022 `ws-etw` (own Python ETW collector `etwcollect` on Kernel-Process, Kernel-File, + Kernel-Network, pushing to Loki, + the DVWA vulnlab on XAMPP, no training; user, 2026-10-26: replaces + SilkETW/SilkService v0.8, whose per-event file writes feed back into Kernel-File and which has no exclude + filter), Ubuntu `ubuntu-trainer` (Loki + Grafana, training, live server), and Kali `kali` (attacker: exploits DVWA + delivers the RCE kill chain, same host-only subnet; LOCAL LAB ONLY and NOT Ansible-managed — it mounts `src/atomic-attack-pack` via a Vagrant synced folder). The Vagrantfile only @@ -181,9 +188,11 @@ history of earlier progress) and, if relevant, this section. ### Pipeline map (where each stage lives) -- VM side (Ansible roles in `src/ansible/roles/`): `win_base`, `win_collector` (SilkETW, `etwctl`, - copies `src/pipeline/etw2nodlink.py` / `etwwindow.py` / `src/live/etwship.py`), `win_alloy` - (Alloy → Loki), `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), `win_benign` (`src/scripts/06-benign-workload`, +- VM side (Ansible roles in `src/ansible/roles/`): `win_base`, `win_collector` (uv + `src/etw-python` + collector as SYSTEM task `etwlab-collector`, `etwctl`, copies `src/pipeline/etw2nodlink.py` / + `etwwindow.py` / `src/live/etwship.py`; the collector source is the Vagrant mount `C:\etw-python` locally + and a git clone on cloud; SilkETW and `win_alloy` stay installed only until the collector is verified), + `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), `win_benign` (`src/scripts/06-benign-workload`, `07-build-train-dataset`), `win_vulnlab` (XAMPP + DVWA). - Improve loop: `lab` CLI (`src/lab/cli.py`, console script; `source .venv/bin/activate`): `lab loop` = pull + build → features → train into one run folder; `lab promote ` sets the current-model @@ -226,6 +235,8 @@ Full entries (what / why / impact / claims limited) live in `docs/DEVIATIONS.md` - Windowed, near-live detection instead of the paper's offline whole-log prediction. - Own scripted Windows ETW data instead of NODLINK/DARPA datasets; benign activity is scripted. +- Own Python ETW collector (`src/etw-python`) instead of SilkETW: SilkETW-format lines with plain values, + self/collector I/O excluded in the callback, pushes to Loki itself (D10). - Feature extraction: all 15 columns kept; idle scaler fit on train only; RDF skipped; per-window nodes give correlated rows. - Graph storage: no RDF/GraphDB; edges stay CSV and Alg. 1 runs in memory per window. diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 2f0f766..a7c62da 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -12,7 +12,8 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. - Limits: no claim about whole-log detection quality. ## D2. Own scripted Windows ETW data -- What: [PAPER] NODLINK / DARPA TC3 / OpTC. [OURS] SilkETW Kernel-Process/File/Network on a W10 VM, +- What: [PAPER] NODLINK / DARPA TC3 / OpTC. [OURS] ETW Kernel-Process/File/Network on a Windows VM (SilkETW + until 2026-10-26, then our own collector, D10), converted to the NODLINK SimulatedW10 schema; benign activity from a seeded scripted workload (`src/scripts/06-benign-workload.ps1`), plus background OS activity. - Why: own end-to-end pipeline for the live demo; dataset small enough to inspect. @@ -159,6 +160,16 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. 14:35 benign window 3.0 instead of 12.0: one data point consistent with "missing file actions push live features off the training distribution" [INFERENCE], not proof. Until the collector keeps up with kfile (lag < lateness), live detection is unvalidated. + - **Cause found (2026-10-26, SilkService source):** SilkService writes every event with + `File.AppendAllText` (open + write + close per line), so each line adds ≥ 1 Create + ≥ 1 Write of its + own to Kernel-File; Alloy's reads add more. In `live-20261025T073042Z`, 224k of the first 300k kfile + lines are SilkService's and 45k Alloy's. Fix: our own collector (D10). + - **NET attribution bug (verified 2026-10-26, `live-20261025T073042Z/raw/knet.json`):** in 77 % of knet + events (14,826 / 19,212) the header PID differs from the payload PID (header = Idle 0, System, + SilkService; payload = msedge, …). SilkETW stores the payload owner as `XmlEventData._PID` and the header + copy as `PID`; `etw2nodlink._net()` reads `pid`, so most NET edges of every capture so far (exp01–exp03 + included) hang off the wrong process. D10 data writes the payload PID as `PID`; the converter will + prefer `_pid` so old captures are fixed on re-conversion. - Limits: shows near-live node scoring + Alg. 1 on our own data. No detection-quality claim until windows are labelled (D6); no claim about Alg. 1 precision; the cut-off (Moderate ≥ 30) is ours, set on one benign window, not the paper's. @@ -215,3 +226,31 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. not fed back into training: log text (paths, process names) is attacker-controlled, so prompt injection is possible, and [PAPER] §3 assumes training logs free of attack traces. No claim about report quality vs the paper's Table 5. + +## 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 + 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; + - SilkETW's JSON line shape (top-level keys, `EventName` = task or task/opcode, payload in + `XmlEventData` under manifest names), but plain values: ints without thousands separators, IPv4 dotted, + ports in host order, UTC timestamps; no `FormattedMessage` and no TraceEvent header copies (`MSec`, + `PName`, `TID`, header `PID`) inside `XmlEventData`; + - exclusion **before** formatting, counted: events of its own PID; Read/Write on file objects whose + Create named a path under the raw output root (any process, incl. System lazy writes); knet events + whose payload PID is excluded. During the switch also Alloy's PID; + - one batched write per provider per second instead of one file open per event; + - it pushes its own files to Loki (saved offsets, retry), with the labels/metadata/timestamps Alloy used, + plus the dos-map line and the 07 workload ledger. Alloy is removed once this is verified. +- Why: SilkService's per-event writes feed back into Kernel-File faster than it can drain them, and it has + no exclude filter (keep-only, one value) and no batching (`docs/notes/silkservice-kfile-lag.md`); live + windows had no file events (D8 correction). Own code is also fully explainable. +- Impact: raw lines differ in formatting from earlier captures, and process names of short-lived + processes are real instead of `N/A`, so earlier experiments (exp01–exp03) are not comparable; a new + benign capture + retrain (exp04) is required. The converter output contract is unchanged. Excluded events + are gone from the raw data (counts in `collector-status.json`); an attacker binary named like the + collector's or Alloy's process is not affected (PID-based, not name-based, except Alloy during the switch). +- Limits: collector correctness is shown only by the parity check against SilkService and the lag/lossless + checks (PROGRESS); no claim that it captures every kernel event (`EventsLost` is reported, not prevented). diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index ddb8760..a163b28 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,4 +1,4 @@ -# PROGRESS (status as of 2026-10-25) +# PROGRESS (status as of 2026-10-26) Replace lines in place when status changes; no history. "Verified" = checked in code/data. @@ -8,8 +8,11 @@ The "widen benign + calibrate" cycle ran on **1 HOUR** of benign data (not 2): k `x-20261022T140932Z` → `exp03` trained + promoted → live DVWA→RCE attack. Work is on branch **`collect-benign-data-for-1-hour`**. The full flow with LLM support ran live on 2026-10-25 (branch `make-sure-to-support-llm-investigator`) and exposed a **collector blocker**: SilkService writes Kernel-File -events far behind real time, so the live engine drops every file event as late. **Now: fix the kfile lag**, -then re-run the full flow (Next 3 steps). No live detection result so far is valid (DEVIATIONS D8 correction). +events far behind real time, so the live engine drops every file event as late. Cause found 2026-10-26: its +per-event file writes feed back into Kernel-File (`docs/notes/silkservice-kfile-lag.md`). **Now (user, +2026-10-26): build our own Python collector `src/etw-python` that also pushes to Loki, verify it, then remove +SilkService and Alloy completely** (DEVIATIONS D10, plan in Next 3 steps). No live detection result so far is +valid (DEVIATIONS D8 correction). DONE this session (2026-10-22, verified live): - **exp03** trained on the 1-h capture and **PROMOTED** (gate passed: 77-min kfile span, all 6 edge types @@ -36,9 +39,13 @@ DONE 2026-10-25 (verified live): reproduces the live windows that were not affected by late kfile lines, and the same LLM verdict. OPEN (the real limitation): -- **kfile lag (blocker)**: SilkService falls behind on Kernel-File at ~20–25 % of real time from a fresh - run, ~1 CPU core, most events are its own writes + Alloy's reads; the engine drops them as late. - DEVIATIONS D8 correction. +- **kfile lag (blocker)**: SilkService falls behind on Kernel-File from a fresh run (9+ min behind after + 25 min; the "~20–25 % of real time" figure does not fit that, re-measure), ~1 CPU core; cause verified in + its source: `File.AppendAllText` per event → ≥ 2 Kernel-File events of its own per line (224k of 300k kfile + lines are SilkService's, 45k Alloy's). Fix in progress: own collector (D10). +- **NET attribution bug** (verified 2026-10-26): 77 % of knet events have header PID ≠ payload PID; + `etw2nodlink._net()` uses the header copy (`XmlEventData.PID`), not the owner (`_PID`). Every capture so + far, exp03 included, has mostly wrong NET edges. Converter fix (prefer `_pid`) is part of the D10 work. - **Browser benign FP**: an Edge-browsing benign window hit **31.0** (Moderate, false alarm). msedge's many per-instance processes are unseen in benign training → the *same* mechanism as the cradle. The fix is benign **variety** (training that covers browsing), **not** more capture time. DEVIATIONS D8, @@ -141,10 +148,9 @@ OPEN (the real limitation): ## Not done -- 2h (or 90-min) benign train capture (07) on `ws-etw`, pulled from Loki, retrain into `exp03`, promote, - calibrate, attack-test. NOT run yet; this is the paused cycle (see Current focus + Next 3 steps). The - kfile-truncation blocker that made earlier captures FILE-starved is now fixed (see Done 2026-10-21). - Still gate on `lab status` per-provider coverage (kfile ≈ full span) before trusting any new capture. +- Benign train capture (07) with the NEW collector (D10), pulled from Loki, train `exp04`, promote, + calibrate, attack-test. Blocked on the collector. Gate on `lab status` per-provider coverage (kfile ≈ full + span) and Read/Write per window before trusting it. - Run the RCE kill chain end to end against DVWA. DVWA provisioning is verified on `ws-etw` (`ansible-playbook -i inventory.local.ini windows.yml -e vulnlab_enabled=true` serves DVWA on :3000, @@ -211,20 +217,21 @@ Repo hygiene: - `src/out/etw/SimulatedW10_train_edges.csv` (old un-windowed capture) sits next to the experiment folders and is easy to pick by mistake (it caused the first, collapsed exp01 run). -## Next 3 steps (fix the kfile lag, then re-run the full flow — 2026-10-25) - -1. Diagnose the SilkService kfile lag on `ws-etw` (time-boxed A/B): - - stop Alloy for ~2 min: does SilkService catch up? - - count SilkService Write events per output line (self-amplification); - - check whether the exp03 training kfile also thinned out over time (Read per window across the 37 windows); - - read the real-time "events lost" counter. - Then propose a fix (e.g. keep the collector's own I/O out of the Kernel-File stream, or another consumer). -2. Re-run the full flow once kfile keeps up (Loki kfile lag < 20 s, `late_dropped` ≈ 0). Check: - - benign stays green; - - the attack's own nodes are flagged; - - LLM triage `attack` + IOC report. - Replay it on the laptop as in 2026-10-25. -3. Browser FP (benign variety in training) once live data is complete. +## Next 3 steps (own collector, then re-run the full flow — 2026-10-26) + +1. Build `src/etw-python` (`etwcollect`, uv, stdlib + ctypes): ETW session + TDH decode, self-exclusion, + batched writer, Loki shipper (replaces Alloy), ledger push; Linux `selftest`. Ansible: uv, mount + `C:\etw-python` locally / clone on cloud, SYSTEM task `etwlab-collector`, `etwctl` switch. +2. Verify on `ws-etw` with SilkService + Alloy still installed: + - `etwcollect selftest --live`; + - parity vs SilkService (3 min side by side, `tools/parity.py`); + - ≥ 30 min alone with the benign workload: Loki kfile lag < 20 s, `EventsLost` 0, CPU well under a core, + Loki counts = file lines, backlog recovers after a Loki outage; + - a 5-min build: all 6 edge types, Read/Write per window in the exp03 range; live `late_dropped` ≈ 0. + Then remove SilkService and Alloy completely (Ansible cleanup, docs, deliverables) + the converter + `_pid` fix. +3. 07 benign capture with the new collector → `exp04` → promote → full flow (benign green, attack nodes + flagged, LLM `attack` + report; laptop replay). Browser FP (benign variety) after that. Watch item: the first 15-min `07` run (`x-20261021T161810Z`) did not write `stopped_utc` (capture left running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the service on the 2h run. diff --git a/docs/notes/silkservice-kfile-lag.md b/docs/notes/silkservice-kfile-lag.md new file mode 100644 index 0000000..002399a --- /dev/null +++ b/docs/notes/silkservice-kfile-lag.md @@ -0,0 +1,229 @@ +# Live windows have no file events: the SilkService kfile lag + +Status as of 2026-10-26: cause found in the code. **Decision (user, 2026-10-26): replace SilkService and +Alloy with our own Python collector `src/etw-python`** (see "Decision" below, DEVIATIONS D10); not built yet. Measurements are from `ws-etw` on +2026-10-25 (DEVIATIONS D8 correction, PROGRESS "OPEN"). This note explains why the events go missing. +Fix options are at the end. + +Tags: [OURS] what this project does · [INFERENCE] a guess · **SilkService code** = mandiant/SilkETW tag +`v0.8` (the version we deploy, `src/ansible/group_vars/all.yml:48`), file `SilkService/ETWCollector.cs` +(identical on `master` @ 093f57201525). + +``` +Windows activity ──► ETW Kernel-File ──► SilkService ──► kfile.json ──► Alloy ──► Loki ──► loki_source ──► engine + (1 core, the (drops lines older + bottleneck) than watermark) +``` + +## Symptom + +- Every live window of `live-20261022T155035Z` has **zero Read and Write edges**. The exp03 training + windows have about 14,000 Read and 500 Write edges each. +- The live engine's `late_dropped` counter ≈ every kfile line. +- So the Oct 22 "attack detected" result is not valid, and the Oct 25 rerun missed the attack (D8). + +There are two separate parts. Part 1 is how the engine drops the lines. Part 2 is why they are late. + +## Part 1: why the engine drops late lines (`src/live/engine.py`) + +Variables: + +| piece | type | meaning | +|---|---|---| +| `S` | `dict` | the current session's state | +| `t` | `int` | one event's timestamp, epoch milliseconds | +| `clock_ms` | `int` | newest event time seen from *any* provider (kproc, kfile, knet) | +| `self.lateness_ms` | `int` | 20,000 (20 s, `--lateness-s`) | +| `wm` | `int` | watermark = `clock_ms − lateness_ms` | +| `S["released_wm"]` | `int \| None` | the watermark the engine has already processed up to | +| `S["heap"]` | `list[tuple]` | min-heap of waiting events, ordered by `(t, stream, offset)` | + +Flow: + +1. Each new line is first written to the session's raw copy (`engine.py:256-259`). This happens even for + lines that are dropped later, which is why a laptop replay can recover them. +2. If `t < S["released_wm"]`, the line is counted in `late_dropped` and discarded (`engine.py:267-269`). + Otherwise it goes into the heap. +3. When the clock moves, `_advance` pops every event with `t < wm` in time order, feeds it to the + converter and sets `released_wm = wm` (`engine.py:246, 274-286`). +4. A window `[start, end)` closes and is scored once `end ≤ wm` (`engine.py:295`). + +**Why a late event can't simply be inserted:** the converter (`etw2nodlink.Graph`) is stateful and +order-dependent. It keys processes by PID + start time, and it maps a file object to a path from the +earlier Create event. Once later events have been processed, an older one can't be slotted in behind them. +So the drop is **per event**, even while the event's window is still open. + +Two examples: + +- **Lag of 1 minute** (early in a run). + - At 14:47:30 a kproc event stamped 14:47:30 arrives, so `wm` = 14:47:10. + - A kfile line stamped 14:46:30 arrives at the same moment. + - 14:46:30 < 14:47:10, so it is dropped, although its window [14:45, 14:50) is not scored yet. +- **Lag of 9 minutes** (25 minutes into a run). + - At 14:50:20 kproc pushes `wm` to 14:50:00. The window [14:45, 14:50) is scored with zero Read/Write edges. + - The kfile lines arriving now are stamped around 14:41, far below `wm`, so they are dropped. + - Their window [14:40, 14:45) was scored minutes earlier. + +kproc and knet keep up with real time, so they set the clock. Any kfile delay above 20 s means a drop. +Offline (`build_experiment.py`) sorts the whole capture after the fact, so lateness never matters there, +and the problem only shows up live. + +## Part 2: why kfile is late (the collector) + +### Measured (2026-10-25) + +- From a fresh run, Kernel-File event time falls behind wall time at once (9+ minutes behind after + 25 minutes). kproc and knet stay near real time. +- SilkService uses about 1 CPU core. Its memory stays flat at ~275 MB. +- Loki's kfile lag equals the lag in `kfile.json` on disk, so Alloy and Loki add nothing. +- Nearly all recent kfile events are SilkService's own writes to `kfile.json` plus Alloy's reads of it. +- The figures disagree: "event time advances at ~20–25 % of wall time" would mean ~19 minutes behind + after 25 minutes, not 9+. Re-measure. + +### Mechanism (verified in SilkService code) + +For each event, the callback (`ETWCollector.cs:219`) does all of the following on **one thread**: + +1. Builds a record. It may also call `Process.GetProcessById` when the process name is empty + (`ETWCollector.cs:274`). +2. Parses the event's XML (`data.ToString()` → `XmlTextReader`). +3. Serializes the record to JSON (`ETWCollector.cs:315`). +4. Writes it like this (`ETWCollector.cs:117`): + +```csharp +// JSONData: string = one event as JSON; Path: string = \kfile.json (from etwctl.ps1:60) +File.AppendAllText(Path, (JSONData + Environment.NewLine)); +``` + +`File.AppendAllText` **opens, writes and closes** the file on every call. There is no long-lived +buffered writer. Our Kernel-File keywords `0x380` = Create (0x80) + Read (0x100) + Write (0x200) +(`etwlab.json.j2:15`). So every line SilkService writes produces new events of its own: +- ≥ 1 Create (the open); +- ≥ 1 Write. + +These come from SilkService itself, and they go back into SilkService's own queue. + +Alloy tails `kfile.json`. Every read it does is a Read event, which SilkService turns into another line. +That line means another Create + Write, and Alloy reads it in turn. + +``` +1 real file event ──► SilkService writes 1 line ──► 1 Create + 1 Write (by SilkService) ──► 2 more lines ──► 4 ──► 8 … + │ + └──► Alloy reads the line ──► 1 Read (by alloy) ──► 1 more line ──► … +``` + +Two examples of the growth: + +- **A program does 100 file operations.** + - SilkService writes 100 lines, which creates about 200 self-events. + - Writing those creates about 400, then 800, and so on. + - Nothing limits this except CPU. SilkService has one callback thread, so it stays at about 1 core and + the queue keeps growing. This fits the measurements (lag from the first minute, 1 core, mostly + self-events). +- **kproc, by contrast.** Writing `kproc.json` produces Kernel-*File* events, not Kernel-*Process* events. + So kproc has no loop and stays near real time. knet is the same. + +### Why the current exclusions don't help + +- [OURS] The converter already drops edges from `silkservice` and `alloy` (`etw2nodlink.py:25`, + `EXCLUDE_IMAGES`). That runs on the trainer, after SilkService has already received, serialized and + written each event, so the loop has already happened. The filter has to run **inside the collector, + before the write**. +- SilkService's own filter can only *keep* one value (`ETWCollector.cs:222-240`). With + `FilterOption=ProcessName` and value `X`, any event whose name is not `X` is dropped. There is no + "everything except SilkService and Alloy" option. + +### All SilkService options checked (`h_SilkUtility.cs`, `h_SilkParameters.cs`) + +| option | values | can it exclude SilkService / Alloy? | +|---|---|---| +| `CollectorType` | Kernel, User | no | +| `ProviderName`, `UserKeywords` / `KernelKeywords` | provider + categories | no: categories, not processes | +| `OutputType` + `Path` | file, url, eventlog | no | +| `FilterOption` + `FilterValue` | EventName, ProcessID, ProcessName, Opcode | no: keep-only, one value | +| `YaraScan` + `YaraOptions` | rule folder; None, All, Matches | indirectly (below) | + +- **`url` output** (`ETWCollector.cs:128-155`): one synchronous HTTP POST per event (10 s timeout), body = + that event's JSON, no batching, no auth headers, no retry (a failed POST drops the event). It would move + the loop to Kernel-Network (each POST = SilkService Send + Recv events), be slower per event, lose events + while the endpoint is down, and Loki's push API cannot take a bare event. +- **Yara as an exclude filter** [INFERENCE, untested]: with `YaraOptions=Matches` only events matching a + rule are written (`ETWCollector.cs:97`); a rule matching JSON that does *not* contain + `"ProcessName":"SilkService"` / `"alloy` would break the loop with config only, but every event is still + serialized + scanned, kept events get re-parsed with a `YaraMatch` field added, and the per-line open + stays. +- SilkETW is Mandiant's, Apache-2.0, last release v0.8 (2019-09), repo archived (last commit 2023-06): no + upstream fix will come. + +### A second problem in the same data: network events point at the wrong process + +Verified on `live-20261025T073042Z/raw/knet.json`: in **77 %** of the Kernel-Network events (14,826 of +19,212) the event header's PID is not the payload's PID. The header PID is the thread that happened to run +when the packet was processed (Idle 0 in 10,441 events, System, even SilkService); the payload PID is the +owning process (e.g. msedge). TraceEvent writes the payload field as `_PID` and its header copy as `PID`, and +`etw2nodlink._net()` reads `pid`, so most NET edges in every capture so far (exp03 included) hang off the +wrong process. The new collector writes the payload PID as `PID`; the converter will prefer `_pid` for old +captures (DEVIATIONS D8). + +### Still open + +- **Late or lost?** ETW reports `Buffers Lost: 0`, yet memory stays flat while the lag grows. A growing + backlog should use memory somewhere. [INFERENCE] Some events may be lost at the real-time layer, not + just delayed. +- **Is the training data affected?** The Oct 22 1-hour training capture kept a full 77-minute kfile + span. That hasn't been explained, and it hasn't been checked whether its kfile thinned out over time + (Read edges per window across its 37 windows). +- **How much is the open/close cost, and how much the self-events?** [INFERENCE] Both add to the load. + The fix below removes both. + +## Ideas considered and rejected + +- **Pull each window from Loki after it ends** instead of following Loki every 1 s. Live already pulls + (`LokiSource.run_forever`, poll 1 s). Pulling later only waits longer for the same late data: + - the wait must equal the kfile lag; + - the lag grows the whole time SilkService runs (rotation every 6 h); + - lost events never arrive. + + It also hides the problem, because no `late_dropped` counter would show it. +- **Raise `--lateness-s`** (for example 900). This needs no code and is a useful test: if the windows + then get about training-level Read/Write counts, the events are late, not lost. But it isn't a fix, + because the lag keeps growing. +- **Remove the HTTP shipper** (`etwship.py`). Live doesn't use it. Only replay and `compare_replay.py` + do, so removing it changes nothing about this issue. + +## Decision (user, 2026-10-26) + +Option 2 below, in **Python** (stdlib + ctypes, uv-managed) at `src/etw-python`, and it also replaces +Alloy: the collector pushes its own run files to Loki with the same labels. SilkService and Alloy are removed +completely once the collector passes the checks at the end of this note plus a parity run against +SilkService. Design and plan: DEVIATIONS D10, PROGRESS "Next 3 steps", `src/etw-python/README.md`. + +## Fix options (as considered before the decision) + +1. **Patch SilkService**. It is open-source C#, and the change is about 10 lines: + - In the callback, before building the record, drop events whose `ProcessID` is SilkService's own PID + (`Process.GetCurrentProcess().Id`), or whose process name is `alloy`. This breaks the loop. + - Replace the per-event `AppendAllText` with one `StreamWriter` that stays open and flushes about + every 1 s. Even unfiltered, that turns one open + write per line into a few writes per second. + + The JSON format stays the same, and the converter already drops these edges. So [INFERENCE] the graph + content shouldn't change, and exp03 stays usable. + + Cost: we have to build SilkService (.NET Framework, on Windows), and the `win_collector` role ships + our build instead of the v0.8 zip. This goes in DEVIATIONS. +2. **Our own small ETW consumer** (C# with TraceEvent, or krabsetw). Full control, but more work, and + its output must match SilkETW's JSON field names for the converter. +3. **SilkService `eventlog` output.** This avoids the per-line file opens. But the Event Log service + still writes `.evtx` files, Alloy would need a different source, and the raw line format changes. It + isn't verified to break the loop. + +Excluding Alloy by name means an attacker binary named `alloy.exe` goes unseen. The converter already +does this today, so it isn't new, but it belongs in DEVIATIONS. + +## How to check a fix + +1. Start a fresh run and compare the newest kfile `TimeStamp` in Loki with wall time. It should be + < 20 s behind and stay there for ≥ 30 minutes. +2. Check that `late_dropped` in `/api/status` stays ≈ 0. +3. Check that each live window's Read/Write counts are in the range of the exp03 training windows. +4. Check that SilkService's CPU is well below 1 core. diff --git a/selftest.sh b/selftest.sh index eaae445..fff664c 100755 --- a/selftest.sh +++ b/selftest.sh @@ -38,5 +38,14 @@ for i in "${!steps[@]}"; do failed=1 fi done +# The ETW collector is its own uv project (src/etw-python), so it runs in its own environment. +log="$log_dir/etwcollect.log" +if (cd src/etw-python && UV_LINK_MODE=copy uv run etwcollect selftest) >"$log" 2>&1; then + echo "PASS src/etw-python: etwcollect selftest" +else + echo "FAIL src/etw-python: etwcollect selftest (last lines below, full log: $log)" + tail -n 15 "$log" | sed 's/^/ /' + failed=1 +fi [[ $failed -eq 0 ]] && rm -rf "$log_dir" exit $failed diff --git a/src/README.md b/src/README.md index 315451a..9f38b26 100644 --- a/src/README.md +++ b/src/README.md @@ -3,7 +3,8 @@ 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. -- **Windows Server lab VM** (`ws-etw`): records kernel activity with ETW (SilkETW); Grafana Alloy ships it to Loki. +- **Windows Server lab VM** (`ws-etw`): 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. @@ -57,7 +58,8 @@ trained model is never overwritten. | folder | kind | runs where | in git | |---|---|---|---| | `Vagrantfile`, `setup-virtualbox.sh` | builds the two bare lab VMs (Windows collector + Ubuntu trainer) | host | yes | -| `ansible/` | provisions both VMs (Windows: SilkETW, Alloy, vulnlab; Ubuntu: Loki/Grafana, repo, `ocr-live`); cloud-portable via inventory | control node | yes | +| `etw-python/` | the ETW collector `etwcollect` (uv project, stdlib + ctypes): ETW -> SilkETW-format lines -> Loki; mounted at `C:\etw-python` locally, cloned on cloud | VM | yes | +| `ansible/` | provisions both VMs (Windows: etw-python collector, vulnlab, SilkETW + Alloy until verified; Ubuntu: Loki/Grafana, repo, `ocr-live`); 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) | @@ -103,13 +105,14 @@ src/ ├── Vagrantfile the two bare VMs: ws-etw (Windows Server 2022, 10.21.2.10, 3D off) and │ ubuntu-trainer (Ubuntu 24.04, 10.21.2.20); no provisioners (Ansible does that) ├── setup-virtualbox.sh one-time host prep: allow 10.21.2.0/24 in VirtualBox, warn about KVM +├── 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 JSON -> edges (the converter; Ansible copies it to the VM too) +│ ├── 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 diff --git a/src/Vagrantfile b/src/Vagrantfile index 2f2979f..b696859 100644 --- a/src/Vagrantfile +++ b/src/Vagrantfile @@ -40,8 +40,10 @@ KALI_NAME = "kali" ISOLATED = ENV.fetch("LAB_ISOLATED", "0") == "1" Vagrant.configure("2") do |config| - # Never expose the whole project dir to a VM; Ubuntu gets the repo via git clone. The one narrow - # exception is the Kali attacker below, which mounts ONLY src/atomic-attack-pack (its own tooling). + # Never expose the whole project dir to a VM; Ubuntu gets the repo via git clone. Two narrow exceptions, + # LOCAL LAB ONLY: the Kali attacker mounts ONLY src/atomic-attack-pack (its own tooling), and ws-etw mounts + # ONLY src/etw-python (the ETW collector) for quick edit-and-test. On cloud, Ansible clones the repo instead + # (etwpy_mode=clone, the default in group_vars/all.yml; inventory.local.ini sets etwpy_mode=mount). config.vm.synced_folder ".", "/vagrant", disabled: true # ------------------------------------------------------------------ Windows Server 2022 collector VM @@ -58,6 +60,11 @@ Vagrant.configure("2") do |config| # Host-only NIC. Vagrant creates/reuses a vboxnetN whose host IP is 10.21.2.1. win.vm.network "private_network", ip: WIN_IP, netmask: "255.255.255.0" + # The collector source (src/etw-python) appears at C:\etw-python (VirtualBox shared folder; Vagrant links + # the path to \\vboxsvr\...). Edits on the host are live in the VM: `etwctl stop` + `etwctl start` picks + # them up. Its venv lives on the VM's own disk (C:\Tools\etw-python-venv), never in this share. + win.vm.synced_folder "etw-python", "C:/etw-python" + if ISOLATED # NAT is unplugged, so the NAT port-forward is dead: reach WinRM over the host-only IP. win.winrm.host = WIN_IP diff --git a/src/ansible/README.md b/src/ansible/README.md index bed7e4f..11cad71 100644 --- a/src/ansible/README.md +++ b/src/ansible/README.md @@ -4,7 +4,7 @@ Provisions the lab the Vagrantfile builds (or any two cloud VMs in one subnet): | host (group) | address | role | |---|---|---| -| `ws-etw` (`windows`) | 10.21.2.10 | SilkETW collector, **Grafana Alloy** (ships raw ETW to Loki), benign workload, DVWA vulnlab (optional, `-e vulnlab_enabled=true`). No training. | +| `ws-etw` (`windows`) | 10.21.2.10 | ETW collector **`etwcollect`** (`src/etw-python`, SYSTEM task `etwlab-collector`; it also pushes to Loki), benign workload, DVWA vulnlab (optional, `-e vulnlab_enabled=true`). No training. | | `ubuntu-trainer` (`ubuntu`) | 10.21.2.20 | **Loki + Grafana** (Docker, host network), repo + `uv sync`, training, `live_server.py` (systemd `ocr-live`, follows Loki). | > The lab also has a **Kali attacker VM** (`10.21.2.30`), but it is **not provisioned by Ansible** — it @@ -12,13 +12,15 @@ Provisions the lab the Vagrantfile builds (or any two cloud VMs in one subnet): > folder (`src/Vagrantfile`), and runs the exploit launcher directly. See that pack's `README.md`. ``` -SilkService -> C:\lab-out\etw\raw\\\{kproc,kfile,knet}.json - -> Alloy (Windows service) -> Loki :3100 on the trainer <- Grafana :3000 (browse / LogQL) +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 ``` -Loki keeps every SilkETW line exactly as written. Alloy only adds labels next to it: +Until `etwcollect` was verified (2026-10-26, DEVIATIONS D10) SilkService wrote the files and Grafana Alloy +shipped them; `collector: silketw` in `group_vars/all.yml` still selects that path until both are removed. +The Loki contract did not change: Loki keeps every line exactly as written, with these labels next to it: | kind | keys | use | |---|---|---| @@ -122,7 +124,7 @@ vagrant up # from src/, builds both bare VMs ansible ubuntu -m ping ansible windows -m ansible.windows.win_ping # use win_ping on Windows, NOT ping ansible-playbook site.yml --limit ubuntu # Loki + Grafana + repo + ocr-live -ansible-playbook site.yml --limit windows # SilkETW + Alloy + scripts (+ vulnlab with -e vulnlab_enabled=true) +ansible-playbook site.yml --limit windows # etwcollect (uv) + scripts (+ vulnlab with -e vulnlab_enabled=true) # cloud (the vault supplies the Windows + Grafana creds): ansible-playbook -i inventory.cloud.ini site.yml -e @group_vars/vault.yml --ask-vault-pass @@ -140,18 +142,24 @@ on the trainer (`alg2.py --ping`, `src/live/README.md` §5) BEFORE the flags are at start (no terminal to prompt). `-e live_llm_args=` turns the LLM off for one run. After the Windows run, pin the download hashes the roles print (`silketw_sha256`, `python_embed_sha256` in -`group_vars/all.yml`). `alloy_sha256` is already pinned from the release's `SHA256SUMS`. +`group_vars/all.yml`). `alloy_sha256` and `uv_sha256` are already pinned from the releases' checksum files. + +**Collector source (`etwpy_mode`).** Local lab: `inventory.local.ini` sets `etwpy_mode=mount`, and +`src/Vagrantfile` shares `src/etw-python` as `C:\etw-python` (needs `vagrant reload ws-etw` once). A host +edit is live after `etwctl stop; etwctl start`; re-run `--tags collector` only when `pyproject.toml` / +`uv.lock` change. Cloud: the default `clone` git-clones `repo_url@repo_branch` to `C:\lab\NT2102`. Either way +`uv sync --frozen` builds the venv at `C:\Tools\etw-python-venv` (never in the share). ## Rebuild training data (from scratch, through Loki) ```powershell # on ws-etw, elevated PowerShell in the RDP desktop session (not WinRM): C:\scripts\06-benign-workload.ps1 -SelfTest # once per VM -C:\scripts\07-build-train-dataset.ps1 # 20-min benign capture, run x-; Alloy ships it live +C:\scripts\07-build-train-dataset.ps1 # 20-min benign capture, run x-; shipped to Loki live ``` -`07` still converts on the VM. That copy is now a cross-check; the training source is Loki. After the -stop, `07` waits `-ShipWaitSeconds` (default 15) so Alloy can push the last lines, then **copies** the raw -files into the experiment folder. It used to move them; copying leaves the files Alloy tails in place. +`07` still converts on the VM. That copy is now a cross-check; the training source is Loki. `etwctl stop` +waits until `etwcollect` has pushed its last lines, `07` then pushes the workload ledger +(`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): @@ -211,17 +219,15 @@ windows stay green; the teammate's attack turns its window red. - `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. `Get-Service Alloy` shows Running. +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"}` shows lines labelled with `split`, `run` and `provider`, - and the line details show `event`, `pid` and `process`. If `split`/`run` are missing, Alloy's - `filename` regex did not match the Windows path form: check `stage.regex` in `config.alloy`. -4. A raw `TimeStamp` ends in `+07:00`, and the Loki time of a line equals its `TimeStamp`. The first - checks the zone; the second shows the timestamp stage works. + 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). The converter summary - lists `alloy` under excluded edges, not as process nodes. + 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)` 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). @@ -234,8 +240,9 @@ inventory.local.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_collector SilkETW + VC++ + embeddable Python + etw2nodlink.py/etwwindow.py/etwship.py/etwctl + SilkService - win_alloy Grafana Alloy (native installer, service) + config.alloy -> Loki + win_collector uv + etw-python venv + SYSTEM task etwlab-collector + embeddable Python + etw2nodlink.py/ + etwwindow.py/etwship.py/etwctl (+ SilkETW/SilkService until etwcollect is verified) + win_alloy Grafana Alloy: stopped + disabled unless collector=silketw (removed after verification) win_shipper start-live.ps1 watchdog + SYSTEM task etwlab-live (always-on live test capture) win_benign 06-benign-workload.ps1 + 07-build-train-dataset.ps1 win_vulnlab XAMPP (Apache + PHP + MariaDB) + DVWA, served on vulnlab_port (opt-in: vulnlab_enabled) diff --git a/src/ansible/group_vars/all.yml b/src/ansible/group_vars/all.yml index 9b722d9..c4a6e04 100644 --- a/src/ansible/group_vars/all.yml +++ b/src/ansible/group_vars/all.yml @@ -54,6 +54,11 @@ python_embed_version: "3.12.7" python_embed_url: "https://www.python.org/ftp/python/{{ python_embed_version }}/python-{{ python_embed_version }}-embed-amd64.zip" python_embed_sha256: "sha256:0d57bb6cb078b74d23dbfe91f77d6780d45bed328911609f1f7ee2ba1606bf44" +# uv (Windows): builds the etw-python collector's venv and downloads its CPython (uv-managed, not the embed zip). +uv_version: "0.9.3" +uv_url: "https://github.com/astral-sh/uv/releases/download/{{ uv_version }}/uv-x86_64-pc-windows-msvc.zip" +uv_sha256: "sha256:9f7595313b44e57dcaeef63fe4f3de9a0cf4f92a53302b429341f457f70ca3b9" # release .sha256 file + alloy_version: "1.20.1" alloy_url: "https://github.com/grafana/alloy/releases/download/v{{ alloy_version }}/alloy-installer-windows-amd64.exe" alloy_sha256: "sha256:23fcfe3755f02e8a6a83f27149851322ab2b66d584e76d239d9c031f50d3a8f0" # release SHA256SUMS @@ -67,6 +72,22 @@ out_dir: 'C:\lab-out\etw' raw_root: 'C:\lab-out\etw\raw' service_name: "SilkService" +# ---- ETW collector: our own Python collector (src/etw-python, DEVIATIONS D10) -------------------------- +# collector: which collector etwctl drives. "python" = etwcollect (also pushes to Loki itself, so Alloy is +# stopped and disabled); "silketw" = the old SilkService + Alloy path, kept ONLY until etwcollect is verified +# (parity run, PROGRESS), then both are removed. +collector: "python" +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: etwpy_mode = clone (cloud default: git clone repo_url@repo_branch to +# etwpy_clone_dir) or mount (local Vagrant lab: src/Vagrantfile mounts src/etw-python at etwpy_src). etwpy_mode +# and etwpy_src are deliberately NOT defined here (this file outranks the inventory's [windows:vars]); the +# win_collector role reads them with | default(clone, \src\etw-python). +etwpy_clone_dir: 'C:\lab\NT2102' +uv_dir: 'C:\Tools\uv' # uv.exe, its cache and the CPython it downloads +etwpy_venv: 'C:\Tools\etw-python-venv' # on the VM's own disk: never inside the VirtualBox share +etwpy_python: "{{ etwpy_venv }}\\Scripts\\python.exe" + # ---- always-on live capture (win_shipper: C:\scripts\start-live.ps1 run by a SYSTEM scheduled task) ---- live_task_name: "etwlab-live" # at boot + every live_watchdog_minutes: keep a test/live- run capturing live_watchdog_minutes: 5 diff --git a/src/ansible/inventory.local.ini b/src/ansible/inventory.local.ini index ca8d187..0fe9118 100644 --- a/src/ansible/inventory.local.ini +++ b/src/ansible/inventory.local.ini @@ -12,6 +12,10 @@ ws-etw ansible_host=10.21.2.10 private_ip=10.21.2.10 # (passed with -e @group_vars/vault.yml --ask-vault-pass). win_user=vagrant win_password=vagrant +# The ETW collector source is the Vagrant mount of src/etw-python (src/Vagrantfile), not a git clone, so a +# host edit is live in the VM after `etwctl stop; etwctl start`. Cloud keeps the default (clone). +etwpy_mode=mount +etwpy_src='C:\etw-python' [ubuntu] ubuntu-trainer ansible_host=10.21.2.20 private_ip=10.21.2.20 diff --git a/src/ansible/roles/win_alloy/handlers/main.yml b/src/ansible/roles/win_alloy/handlers/main.yml index 0f67ee0..d26c69b 100644 --- a/src/ansible/roles/win_alloy/handlers/main.yml +++ b/src/ansible/roles/win_alloy/handlers/main.yml @@ -3,3 +3,4 @@ ansible.windows.win_service: name: Alloy state: restarted + when: collector == 'silketw' diff --git a/src/ansible/roles/win_alloy/tasks/main.yml b/src/ansible/roles/win_alloy/tasks/main.yml index a2dcc47..7794311 100644 --- a/src/ansible/roles/win_alloy/tasks/main.yml +++ b/src/ansible/roles/win_alloy/tasks/main.yml @@ -45,11 +45,14 @@ "C:\Program Files\GrafanaLabs\Alloy\alloy-windows-amd64.exe" fmt "C:\Program Files\GrafanaLabs\Alloy\config.alloy" changed_when: false -- name: Alloy service automatic and running +# collector=python (default): etwcollect pushes to Loki itself, so Alloy is stopped AND disabled (a reboot must not +# bring it back to double-ship). collector=silketw: the old path, Alloy automatic and running. This whole role +# is removed once etwcollect is verified (DEVIATIONS D10). +- name: Alloy service (running only for collector=silketw) ansible.windows.win_service: name: Alloy - start_mode: auto - state: started + start_mode: "{{ 'auto' if collector == 'silketw' else 'disabled' }}" + state: "{{ 'started' if collector == 'silketw' else 'stopped' }}" - name: Restart now if the config changed (so the check below sees the new pipeline) ansible.builtin.meta: flush_handlers diff --git a/src/ansible/roles/win_collector/files/etwctl.ps1 b/src/ansible/roles/win_collector/files/etwctl.ps1 index 3ecb68b..6527721 100644 --- a/src/ansible/roles/win_collector/files/etwctl.ps1 +++ b/src/ansible/roles/win_collector/files/etwctl.ps1 @@ -1,105 +1,157 @@ -<# - etwctl - start/stop SilkService captures and convert them to OCR-APT CSVs. - etwctl start -Split train|test [-Run ] new capture run (never appends to an old one) - etwctl stop stop the collector - etwctl status service state + current run file sizes - etwctl convert -Split train|test raw\\*\*.json -> __*.csv - Settings come from C:\ProgramData\etwlab\etwlab.json (written by the win_collector role). -#> -param( - [Parameter(Mandatory = $true, Position = 0)][ValidateSet("start", "stop", "status", "convert")][string]$Command, - [ValidateSet("train", "test")][string]$Split, - [string]$Run -) -$ErrorActionPreference = "Stop" -$Home_ = "C:\ProgramData\etwlab" -$Cfg = Get-Content "$Home_\etwlab.json" -Raw | ConvertFrom-Json -$State = "$Home_\state.json" -$Utf8 = New-Object System.Text.UTF8Encoding($false) # UTF-8 without BOM - -function Get-State { if (Test-Path $State) { Get-Content $State -Raw | ConvertFrom-Json } else { $null } } -function Set-State($obj) { [IO.File]::WriteAllText($State, ($obj | ConvertTo-Json), $Utf8) } - -function Show-Status { - $svc = Get-Service $Cfg.ServiceName - $st = Get-State - Write-Host "service : $($svc.Name) = $($svc.Status)" - if ($st) { - Write-Host "run : $($st.split)/$($st.run) started $($st.started_utc) stopped $($st.stopped_utc)" - Get-ChildItem $st.dir -Filter *.json -ErrorAction SilentlyContinue | - ForEach-Object { "{0,-12} {1,10:N0} KB" -f $_.Name, ($_.Length / 1KB) } | Write-Host - } -} - -switch ($Command) { - "start" { - if (-not $Split) { throw "start needs -Split train or -Split test" } - $svc = Get-Service $Cfg.ServiceName - if ($svc.Status -ne "Stopped") { throw "collector is $($svc.Status). Run 'etwctl stop' first." } - if (-not $Run) { $Run = (Get-Date).ToUniversalTime().ToString("yyyyMMdd'T'HHmmss'Z'") } - $dir = Join-Path $Cfg.RawRoot "$Split\$Run" - if (Test-Path $dir) { throw "run folder already exists: $dir (choose another -Run)" } - New-Item -ItemType Directory -Force -Path $dir | Out-Null - - # dosmap.meta: \Device\HarddiskVolumeN -> C: for THIS machine, one JSON line. Alloy ships it to Loki - # (job="etw-meta") so the converter on the Ubuntu trainer maps paths like it would here. Not *.json, - # so the converter never reads it as events. (etwship.py prints the map; -Compress = one line.) - $dmap = (& $Cfg.Python "$Home_\etwship.py" --print-dos-map | Out-String) | ConvertFrom-Json | ConvertTo-Json -Compress - [IO.File]::WriteAllText((Join-Path $dir "dosmap.meta"), "$dmap`n", $Utf8) - - # SilkService reads SilkServiceConfig.xml from its own folder, once, at service start. - $sb = New-Object System.Text.StringBuilder - [void]$sb.AppendLine("") - foreach ($c in $Cfg.Collectors) { - [void]$sb.AppendLine(" ") - [void]$sb.AppendLine(" $($c.Guid)") - [void]$sb.AppendLine(" user") - [void]$sb.AppendLine(" $($c.Provider)") - [void]$sb.AppendLine(" $($c.Keywords)") - [void]$sb.AppendLine(" file") - [void]$sb.AppendLine(" $dir\$($c.Stem).json") - [void]$sb.AppendLine(" ") - } - [void]$sb.AppendLine("") - [IO.File]::WriteAllText((Join-Path $Cfg.SilkServiceDir "SilkServiceConfig.xml"), $sb.ToString(), $Utf8) - - Set-State ([ordered]@{ split = $Split; run = $Run; dir = $dir; - started_utc = (Get-Date).ToUniversalTime().ToString("o"); stopped_utc = $null }) - Start-Service $Cfg.ServiceName - - # Canary: a process start + image loads + file reads we know must show up. - Start-Sleep -Seconds 5 - & cmd.exe /c "whoami > nul" - $deadline = (Get-Date).AddSeconds(40) - $need = $Cfg.Collectors | Where-Object { $_.Required } | ForEach-Object { "$dir\$($_.Stem).json" } - do { - Start-Sleep -Seconds 2 - $missing = @($need | Where-Object { -not ((Test-Path $_) -and (Get-Item $_).Length -gt 0) }) - } while ($missing.Count -gt 0 -and (Get-Date) -lt $deadline) - if ($missing.Count -gt 0) { - Write-Warning "no events yet in: $($missing -join ', ')" - Write-Warning "check the service log in $($Cfg.SilkServiceDir) and the Application event log" - exit 1 - } - Write-Host "[etwctl] capturing $Split/$Run -> $dir" - Show-Status - } - "stop" { - Stop-Service $Cfg.ServiceName -ErrorAction SilentlyContinue - $st = Get-State - if ($st -and -not $st.stopped_utc) { - $st.stopped_utc = (Get-Date).ToUniversalTime().ToString("o"); Set-State $st - } - Show-Status - } - "status" { Show-Status } - "convert" { - if (-not $Split) { throw "convert needs -Split train or -Split test" } - $st = Get-State - if ((Get-Service $Cfg.ServiceName).Status -ne "Stopped" -and $st -and $st.split -eq $Split) { - throw "a $Split capture is still running; 'etwctl stop' first (files are still being written)" - } - & $Cfg.Python $Cfg.Converter --raw-root $Cfg.RawRoot --split $Split --graph $Cfg.Graph --out $Cfg.OutDir - if ($LASTEXITCODE -ne 0) { throw "converter exited with $LASTEXITCODE (see $($Cfg.OutDir)\$($Cfg.Graph)_$($Split)_summary.json)" } - } -} +<# + etwctl - start/stop ETW captures and convert them to OCR-APT CSVs. + etwctl start -Split train|test [-Run ] new capture run (never appends to an old one) + etwctl stop stop the collector (python: flush + ship to Loki first) + etwctl status collector state + current run (+ lag, exclusions, Loki backlog) + etwctl running exit code 0 = a capture is running, 1 = not (for scripts) + etwctl convert -Split train|test raw\\*\*.json -> __*.csv + Settings come from C:\ProgramData\etwlab\etwlab.json (written by the win_collector role). + + Collector (etwlab.json "Collector"): "python" = etwcollect (src/etw-python), run by the SYSTEM scheduled task + CollectorTask, pushes to Loki itself (DEVIATIONS D10). "silketw" = the old SilkService Windows service, kept + only until etwcollect is verified. + + PowerShell notes: Get-ScheduledTask / Start-ScheduledTask read / start a Task Scheduler task (its .State is + Ready, Running, ...); Get-Service reads a Windows service; `& $exe args` runs a program; $LASTEXITCODE is the + exit code of the last program; ConvertFrom-Json turns JSON text into an object with properties. +#> +param( + [Parameter(Mandatory = $true, Position = 0)][ValidateSet("start", "stop", "status", "running", "convert")][string]$Command, + [ValidateSet("train", "test")][string]$Split, + [string]$Run +) +$ErrorActionPreference = "Stop" +$Home_ = "C:\ProgramData\etwlab" +$Cfg = Get-Content "$Home_\etwlab.json" -Raw | ConvertFrom-Json +$State = "$Home_\state.json" +$Status = "$Home_\collector-status.json" +$Utf8 = New-Object System.Text.UTF8Encoding($false) # UTF-8 without BOM +$Py = ("$($Cfg.Collector)" -ne "silketw") # [bool]: anything but "silketw" = etwcollect + +function Get-State { if (Test-Path $State) { Get-Content $State -Raw | ConvertFrom-Json } else { $null } } +function Set-State($obj) { [IO.File]::WriteAllText($State, ($obj | ConvertTo-Json), $Utf8) } + +function Test-CollectorRunning { + if ($Py) { return ((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State -eq "Running") } + return ((Get-Service $Cfg.ServiceName).Status -ne "Stopped") +} + +function Show-Status { + $st = Get-State + if ($Py) { + Write-Host "collector: task $($Cfg.CollectorTask) = $((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State)" + } else { + $svc = Get-Service $Cfg.ServiceName + Write-Host "service : $($svc.Name) = $($svc.Status)" + } + if ($st) { + Write-Host "run : $($st.split)/$($st.run) started $($st.started_utc) stopped $($st.stopped_utc)" + Get-ChildItem $st.dir -Filter *.json -ErrorAction SilentlyContinue | + ForEach-Object { "{0,-12} {1,10:N0} KB" -f $_.Name, ($_.Length / 1KB) } | Write-Host + } + if ($Py -and (Test-Path $Status)) { + $c = Get-Content $Status -Raw | ConvertFrom-Json + Write-Host "status : $($c.state) (pid $($c.pid), updated $($c.updated_utc))" + foreach ($p in $c.providers.PSObject.Properties) { # one line per provider: kproc, kfile, knet + Write-Host (" {0,-6} lines {1,9} newest {2} lag {3} s" -f $p.Name, $p.Value.lines, + $p.Value.newest_event_utc, $p.Value.lag_s) + } + Write-Host " excluded: $($c.excluded | ConvertTo-Json -Compress)" + if ($c.etw) { Write-Host " ETW lost: events $($c.etw.events_lost) realtime buffers $($c.etw.realtime_buffers_lost)" } + if ($c.ship) { Write-Host " Loki: pushed $($c.ship.pushed_lines) backlog $($c.ship.backlog_bytes | ConvertTo-Json -Compress) last error $($c.ship.last_error)" } + if ($c.last_error) { Write-Host " last error: $($c.last_error)" } + } +} + +switch ($Command) { + "start" { + if (-not $Split) { throw "start needs -Split train or -Split test" } + if (Test-CollectorRunning) { throw "a capture is already running. Run 'etwctl stop' first." } + if (-not $Run) { $Run = (Get-Date).ToUniversalTime().ToString("yyyyMMdd'T'HHmmss'Z'") } + $dir = Join-Path $Cfg.RawRoot "$Split\$Run" + if (Test-Path $dir) { throw "run folder already exists: $dir (choose another -Run)" } + New-Item -ItemType Directory -Force -Path $dir | Out-Null + + # dosmap.meta: \Device\HarddiskVolumeN -> C: for THIS machine, one JSON line. It goes to Loki + # (job="etw-meta") so the converter on the Ubuntu trainer maps paths like it would here. Not *.json, + # so the converter never reads it as events. (etwship.py prints the map; -Compress = one line.) + $dmap = (& $Cfg.Python "$Home_\etwship.py" --print-dos-map | Out-String) | ConvertFrom-Json | ConvertTo-Json -Compress + [IO.File]::WriteAllText((Join-Path $dir "dosmap.meta"), "$dmap`n", $Utf8) + + Set-State ([ordered]@{ split = $Split; run = $Run; dir = $dir; + started_utc = (Get-Date).ToUniversalTime().ToString("o"); stopped_utc = $null }) + if ($Py) { + # The task runs `python -m etwcollect run`, which reads the run folder from state.json (written above). + Start-ScheduledTask -TaskName $Cfg.CollectorTask + } else { + # SilkService reads SilkServiceConfig.xml from its own folder, once, at service start. + $sb = New-Object System.Text.StringBuilder + [void]$sb.AppendLine("") + foreach ($c in $Cfg.Collectors) { + [void]$sb.AppendLine(" ") + [void]$sb.AppendLine(" $($c.Guid)") + [void]$sb.AppendLine(" user") + [void]$sb.AppendLine(" $($c.Provider)") + [void]$sb.AppendLine(" $($c.Keywords)") + [void]$sb.AppendLine(" file") + [void]$sb.AppendLine(" $dir\$($c.Stem).json") + [void]$sb.AppendLine(" ") + } + [void]$sb.AppendLine("") + [IO.File]::WriteAllText((Join-Path $Cfg.SilkServiceDir "SilkServiceConfig.xml"), $sb.ToString(), $Utf8) + Start-Service $Cfg.ServiceName + } + + # Canary: a process start + image loads + file reads we know must show up. + Start-Sleep -Seconds 5 + & cmd.exe /c "whoami > nul" + $deadline = (Get-Date).AddSeconds(40) + $need = $Cfg.Collectors | Where-Object { $_.Required } | ForEach-Object { "$dir\$($_.Stem).json" } + do { + Start-Sleep -Seconds 2 + $missing = @($need | Where-Object { -not ((Test-Path $_) -and (Get-Item $_).Length -gt 0) }) + } while ($missing.Count -gt 0 -and (Get-Date) -lt $deadline) + if ($missing.Count -gt 0) { + Write-Warning "no events yet in: $($missing -join ', ')" + if ($Py) { Write-Warning "check $Status (last_error) and: & '$($Cfg.EtwPython)' -m etwcollect status" } + else { Write-Warning "check the service log in $($Cfg.SilkServiceDir) and the Application event log" } + exit 1 + } + Write-Host "[etwctl] capturing $Split/$Run -> $dir" + Show-Status + } + "stop" { + if ($Py) { + if (Test-CollectorRunning) { + # etwcollect stop: stops the ETW session; the collector then writes its last lines, ships them + # to Loki (bounded) and exits. It waits for that itself (--wait). + & $Cfg.EtwPython -m etwcollect stop --wait 120 | Out-Host + $deadline = (Get-Date).AddSeconds(30) + while ((Test-CollectorRunning) -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 1 } + if (Test-CollectorRunning) { + # Last resort: kills the process (no final flush); the next start ships what is on disk. + Write-Warning "collector task still running after stop; ending it with Stop-ScheduledTask" + Stop-ScheduledTask -TaskName $Cfg.CollectorTask + } + } + } else { + Stop-Service $Cfg.ServiceName -ErrorAction SilentlyContinue + } + $st = Get-State + if ($st -and -not $st.stopped_utc) { + $st.stopped_utc = (Get-Date).ToUniversalTime().ToString("o"); Set-State $st + } + Show-Status + } + "status" { Show-Status } + "running" { if (Test-CollectorRunning) { exit 0 } else { exit 1 } } + "convert" { + if (-not $Split) { throw "convert needs -Split train or -Split test" } + $st = Get-State + if ((Test-CollectorRunning) -and $st -and $st.split -eq $Split) { + throw "a $Split capture is still running; 'etwctl stop' first (files are still being written)" + } + & $Cfg.Python $Cfg.Converter --raw-root $Cfg.RawRoot --split $Split --graph $Cfg.Graph --out $Cfg.OutDir + if ($LASTEXITCODE -ne 0) { throw "converter exited with $LASTEXITCODE (see $($Cfg.OutDir)\$($Cfg.Graph)_$($Split)_summary.json)" } + } +} diff --git a/src/ansible/roles/win_collector/tasks/main.yml b/src/ansible/roles/win_collector/tasks/main.yml index a62471f..46ac1b1 100644 --- a/src/ansible/roles/win_collector/tasks/main.yml +++ b/src/ansible/roles/win_collector/tasks/main.yml @@ -1,5 +1,5 @@ --- -# Collector install: SilkETW, converter, etwctl, SilkService. +# Collector install: etw-python collector (etwcollect) + converter + etwctl; SilkETW/SilkService until verified. # Installs SilkETW/SilkService, embeddable Python, deploys the converter/windowing tool/shipper/etwctl, # registers the service. 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. @@ -119,7 +119,113 @@ ansible.windows.win_command: '"{{ python_exe }}" "{{ lab_home }}\etwwindow.py" --selftest' changed_when: false -# ---------- 5. SilkService Windows service ---------- +# ---------- 5. etw-python collector (src/etw-python, DEVIATIONS D10) ---------- +# Source: mount (local lab: src/Vagrantfile shares src/etw-python as C:\etw-python, inventory.local.ini sets +# etwpy_mode=mount) or clone (cloud default: git clone of repo_url@repo_branch). uv builds the venv on the VM's +# own disk and downloads its own CPython 3.12 (.python-version); the embeddable Python above stays for the +# converter/windowing/shipper scripts. +- name: Resolve the collector source (mount or clone) + ansible.builtin.set_fact: + etwpy_mode_r: "{{ etwpy_mode | default('clone') }}" + etwpy_src_r: "{{ etwpy_src | default(etwpy_clone_dir ~ '\\src\\etw-python') }}" + uv_exe: "{{ uv_dir }}\\{{ uv_version }}\\uv.exe" + +- name: Install git (clone mode) + chocolatey.chocolatey.win_chocolatey: + name: git + state: present + when: etwpy_mode_r == 'clone' + +- name: Clone or fast-forward the repo (clone mode) + ansible.windows.win_shell: | + $ErrorActionPreference = 'Continue' + $d = '{{ etwpy_clone_dir }}' + if (-not (Test-Path "$d\.git")) { + git clone --branch '{{ repo_branch }}' '{{ repo_url }}' $d 2>&1 | Out-Null + if ($LASTEXITCODE) { throw "git clone failed ($LASTEXITCODE)" } + 'cloned' + } else { + $before = git -C $d rev-parse HEAD + git -C $d fetch origin '{{ repo_branch }}' 2>&1 | Out-Null + git -C $d checkout -B '{{ repo_branch }}' 'origin/{{ repo_branch }}' 2>&1 | Out-Null + if ($LASTEXITCODE) { throw "git checkout failed ($LASTEXITCODE)" } + if ((git -C $d rev-parse HEAD) -ne $before) { 'updated' } else { 'unchanged' } + } + register: etwpy_git + changed_when: "'unchanged' not in etwpy_git.stdout" + when: etwpy_mode_r == 'clone' + +- name: Collector source present ({{ etwpy_src_r }}) + ansible.windows.win_stat: + path: "{{ etwpy_src_r }}\\pyproject.toml" + register: etwpy_pp + +- name: Fail if the collector source is missing + ansible.builtin.assert: + that: etwpy_pp.stat.exists + fail_msg: >- + {{ etwpy_src_r }}\pyproject.toml not found. mount mode: `vagrant reload ws-etw` so src/Vagrantfile mounts + src/etw-python at C:\etw-python; clone mode: check repo_url / repo_branch. + +- name: Download uv {{ uv_version }} + ansible.windows.win_get_url: + url: "{{ uv_url }}" + dest: "{{ tools_dir }}\\uv-{{ uv_version }}.zip" + checksum: "{{ uv_sha256 | regex_replace('^sha256:', '') or omit }}" + checksum_algorithm: sha256 + force: false # version-pinned URL: keep the existing file (idempotent) + +- name: Extract uv + community.windows.win_unzip: + src: "{{ tools_dir }}\\uv-{{ uv_version }}.zip" + dest: "{{ uv_dir }}\\{{ uv_version }}" + creates: "{{ uv_exe }}" + +# UV_PROJECT_ENVIRONMENT puts the venv outside the source: a venv inside the VirtualBox share would break +# (no symlinks there) and would clash with a host .venv. --frozen = install exactly uv.lock, never rewrite it. +- name: Build the collector venv (uv sync; the first run downloads CPython 3.12) + ansible.windows.win_command: '"{{ uv_exe }}" sync --frozen --project "{{ etwpy_src_r }}"' + environment: + UV_PROJECT_ENVIRONMENT: "{{ etwpy_venv }}" + UV_PYTHON_INSTALL_DIR: "{{ uv_dir }}\\python" + UV_CACHE_DIR: "{{ uv_dir }}\\cache" + UV_LINK_MODE: copy + UV_PYTHON_PREFERENCE: only-managed + register: etwpy_sync + changed_when: >- + 'Installed' in etwpy_sync.stderr or 'Uninstalled' in etwpy_sync.stderr + or 'Creating virtual environment' in etwpy_sync.stderr + +- name: Collector selftest (pure parts + converter round-trip; proves it runs, not that it captures) + ansible.windows.win_command: '"{{ etwpy_python }}" -m etwcollect selftest' + environment: + ETW2NODLINK: "{{ lab_home }}\\etw2nodlink.py" + changed_when: false + +# No trigger: `etwctl start` starts it, `etwctl stop` stops it (etwcollect stop -> the process exits by itself). +# A reboot must not resume into an old run folder, so nothing starts it at boot (start-live.ps1 starts a new +# live run instead). Restart on failure covers a crash during a run. +- name: Register the collector task (SYSTEM, started by etwctl) + community.windows.win_scheduled_task: + name: "{{ collector_task }}" + description: "etwcollect: ETW -> raw run files -> Loki (started/stopped by etwctl; managed by Ansible win_collector)" + actions: + - path: "{{ etwpy_python }}" + arguments: -m etwcollect run + working_directory: "{{ lab_home }}" + username: SYSTEM + run_level: highest + multiple_instances: 2 # IgnoreNew: never two collectors + execution_time_limit: PT0S # no time limit + restart_count: 3 + restart_interval: PT1M + allow_demand_start: true + disallow_start_if_on_batteries: false + stop_if_going_on_batteries: false + enabled: true + state: present + +# ---------- 6. SilkService Windows service (kept only until etwcollect is verified; collector=silketw) ---------- - name: Register the SilkService collector (startup = Manual) ansible.windows.win_service: name: "{{ service_name }}" diff --git a/src/ansible/roles/win_collector/templates/etwlab.json.j2 b/src/ansible/roles/win_collector/templates/etwlab.json.j2 index 2719e8f..d89bd4f 100644 --- a/src/ansible/roles/win_collector/templates/etwlab.json.j2 +++ b/src/ansible/roles/win_collector/templates/etwlab.json.j2 @@ -8,6 +8,13 @@ "Graph": graph_name, "Python": python_exe, "Converter": lab_home ~ "\\etw2nodlink.py", + "Collector": collector, + "CollectorTask": collector_task, + "CollectorSession": collector_session, + "EtwPython": etwpy_python, + "EtwPySrc": etwpy_src | default(etwpy_clone_dir ~ "\\src\\etw-python"), + "LokiUrl": loki_url, + "Host": inventory_hostname, "Collectors": [ {"Stem": "kproc", "Required": true, "Guid": "6f1a2c10-0b7e-4c1d-9a51-3e1f00000001", "Provider": "Microsoft-Windows-Kernel-Process", "Keywords": "0x50"}, diff --git a/src/ansible/roles/win_shipper/tasks/main.yml b/src/ansible/roles/win_shipper/tasks/main.yml index 4afba60..2c51dca 100644 --- a/src/ansible/roles/win_shipper/tasks/main.yml +++ b/src/ansible/roles/win_shipper/tasks/main.yml @@ -20,7 +20,7 @@ - name: Register the always-on live capture task community.windows.win_scheduled_task: name: "{{ live_task_name }}" - description: "Keeps a live SilkETW capture running (C:\\scripts\\start-live.ps1; managed by Ansible win_shipper)" + description: "Keeps a live ETW capture running (C:\\scripts\\start-live.ps1; managed by Ansible win_shipper)" actions: - path: powershell.exe arguments: -NoProfile -NonInteractive -ExecutionPolicy Bypass -File C:\scripts\start-live.ps1 diff --git a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 index e6a540c..3d5fcf7 100644 --- a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 +++ b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 @@ -2,10 +2,11 @@ <# start-live.ps1 (generated by Ansible: win_shipper role) - Keeps a live SilkETW capture (split "test", run live-) ALWAYS running. Nothing is shipped by this - script: Grafana Alloy tails the run folder and pushes every line to Loki ({{ loki_url }}); the live server - on the trainer follows the newest test run in Loki. The capture itself runs inside the SilkService Windows - service; this script only decides WHEN to start a fresh run, because SilkService reads its output folder + Keeps a live ETW capture (split "test", run live-) ALWAYS running. Nothing is shipped by this + script: the collector (etwcollect, the SYSTEM task {{ collector_task }}; or SilkService + Alloy while + collector=silketw) pushes every line to Loki ({{ loki_url }}); the live server on the trainer follows the + newest test run in Loki. This script only decides WHEN to start a fresh run, because the collector reads its + output folder once at service start (a plain auto-start would append to the last run, possibly a training run). The scheduled task "{{ live_task_name }}" (SYSTEM, at boot + every {{ live_watchdog_minutes }} min) runs it @@ -24,7 +25,7 @@ C:\scripts\start-live.ps1 -Resume # remove the hold; the capture restarts now Live UI: http://{{ trainer_host }}:{{ server_port }}/ Grafana: http://{{ trainer_host }}:{{ grafana_port }}/ - PowerShell notes: Get-Service reads a service's state; a [switch] parameter is a flag that is either given + PowerShell notes: Get-Service reads a service's state, Get-ScheduledTask a task's state; a [switch] parameter is a flag that is either given or not; ConvertFrom-Json / ConvertTo-Json read / write JSON; Add-Content appends a line to a file; a System.Threading.Mutex is a machine-wide lock, so a manual call and a task tick never act at the same time. #> @@ -81,6 +82,15 @@ function Start-LiveRun { if ($code -eq 0) { Log "started test/$run" } else { Log "etwctl start test/$run exited $code (see lines above)" } } +# The collector's state as {Name, Status} with Status Running | Stopped | StartPending (the shape of a +# Get-Service result), so the decisions below read the same for etwcollect (a scheduled task) and SilkService. +function Get-Collector { + if ($Cfg.Collector -eq 'silketw') { $s = Get-Service $Cfg.ServiceName; return [pscustomobject]@{ Name = $s.Name; Status = "$($s.Status)" } } + $t = Get-ScheduledTask -TaskName $Cfg.CollectorTask + $status = switch ("$($t.State)") { 'Running' { 'Running' } 'Queued' { 'StartPending' } default { 'Stopped' } } + return [pscustomobject]@{ Name = "task $($Cfg.CollectorTask)"; Status = $status } +} + function Test-LiveRunning($svc, $st) { return ($svc.Status -eq 'Running' -and $st -and $st.split -eq 'test' -and "$($st.run)" -like 'live-*') } @@ -92,7 +102,7 @@ function Get-StartedUtc($st) { [Globalization.DateTimeStyles]::RoundtripKind).ToUniversalTime() } -# Raw live runs with no write for $KeepDays days. Alloy keeps the lines in Loki (its own retention). +# Raw live runs with no write for $KeepDays days. Loki keeps the lines (its own retention). function Remove-OldLiveRuns($currentRun) { $testDir = Join-Path $Cfg.RawRoot 'test' if (-not (Test-Path $testDir)) { return } @@ -110,20 +120,20 @@ function Remove-OldLiveRuns($currentRun) { } function Show-LiveStatus($svc, $st) { - Write-Host "service : $($svc.Name) = $($svc.Status)" + Write-Host "collector: $($svc.Name) = $($svc.Status)" if ($st) { Write-Host "run : $($st.split)/$($st.run) started $($st.started_utc) stopped $($st.stopped_utc)" } $h = Get-Hold Write-Host ("hold : " + $(if ($h) { "yes (by $($h.by) since $($h.since_utc))" } else { "no" })) $t = Get-ScheduledTask -TaskName '{{ live_task_name }}' -ErrorAction SilentlyContinue Write-Host ("task : " + $(if ($t) { "{{ live_task_name }} = $($t.State)" } else { "MISSING" })) - Write-Host "alloy : $((Get-Service Alloy).Status)" + if ($Cfg.Collector -eq 'silketw') { Write-Host "alloy : $((Get-Service Alloy).Status)" } if (Test-Path $LogF) { Write-Host "log : last lines of $LogF"; Get-Content $LogF -Tail 8 | ForEach-Object { " $_" } } } # The whole decision, as a function so every early exit is a plain `return` (the mutex is released below). function Invoke-Main { $rot = [bool]$Rotate - $svc = Get-Service $Cfg.ServiceName + $svc = Get-Collector $st = Get-State if ($Status) { Show-LiveStatus $svc $st; return } @@ -141,7 +151,7 @@ function Invoke-Main { $rot = $false # continue as a normal tick, which starts a run if none is running } - if ((Get-Service Alloy).Status -ne 'Running') { Log "WARNING the Alloy service is not running: nothing reaches Loki" } + if ($Cfg.Collector -eq 'silketw' -and (Get-Service Alloy).Status -ne 'Running') { Log "WARNING the Alloy service is not running: nothing reaches Loki" } $hold = Get-Hold if ($hold) { @@ -162,7 +172,7 @@ function Invoke-Main { Start-LiveRun } } else { - Start-LiveRun # SilkService is stopped and nothing holds it + Start-LiveRun # the collector is stopped and nothing holds it } $cur = Get-State diff --git a/src/ansible/verify-windows.yml b/src/ansible/verify-windows.yml index 8faae73..2ed7387 100644 --- a/src/ansible/verify-windows.yml +++ b/src/ansible/verify-windows.yml @@ -34,22 +34,53 @@ fail_msg: "A collector file is missing — run role win_collector" success_msg: "Converter, windowing, shipper, etwctl and embeddable Python all present" + - name: etw-python collector present (win_collector) + ansible.windows.win_stat: + path: "{{ item }}" + loop: + - "{{ uv_dir }}\\{{ uv_version }}\\uv.exe" + - "{{ etwpy_python }}" + - "{{ etwpy_src | default(etwpy_clone_dir ~ '\\src\\etw-python') }}\\pyproject.toml" + register: etwpy_files + - ansible.builtin.assert: + that: etwpy_files.results | map(attribute='stat.exists') | min + fail_msg: "uv, the collector venv or its source is missing — run role win_collector (mount mode: vagrant reload ws-etw)" + success_msg: "uv, collector venv and source present" + + - name: Collector task registered (win_collector) + ansible.windows.win_powershell: + script: | + $Ansible.Changed = $false + $t = Get-ScheduledTask -TaskName '{{ collector_task }}' -ErrorAction SilentlyContinue + if ($t) { "$($t.State)|$($t.Principal.UserId)|$($t.Actions[0].Execute)" } else { 'missing' } + register: coll_task + - ansible.builtin.assert: + that: coll_task.output[0] != 'missing' + fail_msg: "task {{ collector_task }} not registered — run role win_collector" + success_msg: "task {{ collector_task }}: {{ coll_task.output[0] }}" + + - name: Collector selftest (proves it runs; not that it captures) + ansible.windows.win_command: '"{{ etwpy_python }}" -m etwcollect selftest' + environment: + ETW2NODLINK: "{{ lab_home }}\\etw2nodlink.py" + changed_when: false + - name: Converter selftest (proves it runs) ansible.windows.win_command: >- "{{ tools_dir }}\python-embed\{{ python_embed_version }}\python.exe" "{{ lab_home }}\etw2nodlink.py" --selftest changed_when: false # ---------- win_alloy ---------- - - name: Alloy service running (win_alloy) + - name: Alloy service state (win_alloy; running only for collector=silketw) ansible.windows.win_service_info: name: Alloy register: alloy_svc - ansible.builtin.assert: that: - alloy_svc.services | length == 1 - - alloy_svc.services[0].state == 'started' - fail_msg: "Alloy not running — run role win_alloy" - success_msg: "Alloy service running" + - alloy_svc.services[0].state == ('started' if collector == 'silketw' else 'stopped') + fail_msg: "Alloy is {{ alloy_svc.services[0].state | default('missing') }}, expected {{ 'started' if collector == 'silketw' else 'stopped (etwcollect pushes to Loki itself)' }} — run role win_alloy" + success_msg: "Alloy {{ alloy_svc.services[0].state }} (collector={{ collector }})" - name: Alloy config present (win_alloy) ansible.windows.win_stat: diff --git a/src/etw-python/.python-version b/src/etw-python/.python-version new file mode 100644 index 0000000..e4fba21 --- /dev/null +++ b/src/etw-python/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/src/etw-python/README.md b/src/etw-python/README.md new file mode 100644 index 0000000..9485e7a --- /dev/null +++ b/src/etw-python/README.md @@ -0,0 +1,82 @@ +# etw-python: the lab's 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/notes/silkservice-kfile-lag.md`). + +``` +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 | + +Settings come from `C:\ProgramData\etwlab\etwlab.json` (or `$ETWLAB_CONFIG`): `Collectors`, `RawRoot`, +`LokiUrl`, `Host`. It is written by the `win_collector` Ansible role. + +## Where the code runs + +- **Local lab:** the Vagrant box mounts this folder at `C:\etw-python`. Ansible runs + `uv sync --frozen` with the venv on the VM's own disk (`UV_PROJECT_ENVIRONMENT=C:\Tools\etw-python-venv`). + A venv on the VirtualBox share would break and would also clash with a host `.venv`. A code change on + the host is live after the next `etwctl stop` / `etwctl start`. +- **Cloud:** Ansible clones the repo, and the source is `C:\lab\NT2102\src\etw-python`. +- 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: + +``` +cd src/etw-python && uv run etwcollect selftest +``` + +## 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) + +- `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. + +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. diff --git a/src/etw-python/pyproject.toml b/src/etw-python/pyproject.toml new file mode 100644 index 0000000..27a6c97 --- /dev/null +++ b/src/etw-python/pyproject.toml @@ -0,0 +1,22 @@ +[project] +name = "etwcollect" +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). +dependencies = [] + +# `etwcollect run | stop | status | dosmap | push-ledger | selftest` (src/etwcollect/cli.py) +[project.scripts] +etwcollect = "etwcollect.cli:main" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/etwcollect"] + +[tool.uv] +package = true diff --git a/src/etw-python/src/etwcollect/__init__.py b/src/etw-python/src/etwcollect/__init__.py new file mode 100644 index 0000000..1ca447b --- /dev/null +++ b/src/etw-python/src/etwcollect/__init__.py @@ -0,0 +1,10 @@ +"""etwcollect - the lab's ETW collector (replaces SilkETW/SilkService + Grafana Alloy, DEVIATIONS D10). + + ETW real-time session (Kernel-Process, Kernel-File, Kernel-Network) + -> callback: exclude our own I/O, decode the payload (TDH schema, cached), one SilkETW-format JSON line + -> raw_root\\\\\\{kproc,kfile,knet}.json (batched: one write per file per second) + -> shipper thread: tail those files from saved offsets -> Loki push API (same labels Alloy used) + +Module map: README.md. +""" +__version__ = "0.1.0" diff --git a/src/etw-python/src/etwcollect/__main__.py b/src/etw-python/src/etwcollect/__main__.py new file mode 100644 index 0000000..352d0c8 --- /dev/null +++ b/src/etw-python/src/etwcollect/__main__.py @@ -0,0 +1,6 @@ +"""`python -m etwcollect ...` = the `etwcollect` console script (the SYSTEM task calls it this way).""" +import sys + +from .cli import main + +sys.exit(main()) diff --git a/src/etw-python/src/etwcollect/cli.py b/src/etw-python/src/etwcollect/cli.py new file mode 100644 index 0000000..328c3ea --- /dev/null +++ b/src/etw-python/src/etwcollect/cli.py @@ -0,0 +1,157 @@ +"""cli.py - `etwcollect ` (console script from pyproject.toml). + + etwcollect run [--state FILE | --out-dir DIR] [--no-push] capture until stopped (the SYSTEM task runs this) + etwcollect stop [--wait 60] stop the session; waits until the collector exited + etwcollect status collector-status.json + live ETW counters + etwcollect dosmap [--out FILE] this machine's \\device\\... -> c: map (JSON) + etwcollect push-ledger --exp ID --dir DIR 07's workload ledger CSVs -> Loki + etwcollect selftest [--live] pure parts (any OS); --live: a real 15 s session + +Settings come from etwlab.json (default C:\\ProgramData\\etwlab\\etwlab.json, or $ETWLAB_CONFIG), written by +the win_collector Ansible role: Collectors (Stem, Provider, Keywords), RawRoot, LokiUrl, Host. The run folder +comes from state.json next to it, written by `etwctl start`. +""" +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +DEFAULT_HOME = r"C:\ProgramData\etwlab" + + +def load_config(path: str | None) -> tuple[dict, str]: + path = path or os.environ.get("ETWLAB_CONFIG") or os.path.join(DEFAULT_HOME, "etwlab.json") + with open(path, encoding="utf-8-sig") as fh: + return json.load(fh), os.path.dirname(os.path.abspath(path)) + + +def cmd_run(a) -> int: + from .collector import Config, Collector + from .providers import Provider + cfg, home = load_config(a.config) + if a.out_dir: + out_dir = os.path.abspath(a.out_dir) + else: + with open(a.state or os.path.join(home, "state.json"), encoding="utf-8-sig") as fh: + st = json.load(fh) + out_dir = st["dir"] + run = os.path.basename(out_dir.rstrip("\\/")) + split = os.path.basename(os.path.dirname(out_dir.rstrip("\\/"))) + providers = [Provider.from_config(c) for c in cfg["Collectors"]] + c = Config(out_dir=out_dir, split=split, run=run, providers=providers, raw_root=cfg["RawRoot"], + status_path=a.status or os.path.join(home, "collector-status.json"), + positions_path=os.path.join(home, "ship-positions.json"), + host=cfg.get("Host", "ws-etw"), loki_url=cfg.get("LokiUrl"), push=not a.no_push, + session=a.session, exclude_images=tuple(a.exclude_image), drain_s=a.drain_s) + return Collector(c).run() + + +def _read_status(home: str) -> dict | None: + try: + with open(os.path.join(home, "collector-status.json"), encoding="utf-8") as fh: + return json.load(fh) + except (OSError, ValueError): + return None + + +def cmd_stop(a) -> int: + from .session import RealtimeSession + _, home = load_config(a.config) + before = _read_status(home) + counters = RealtimeSession.stop_by_name(a.session) + if counters is None: + print(f"[etwcollect] no session {a.session!r} running") + return 0 + print(f"[etwcollect] stopped session {a.session!r}: {json.dumps(counters)}") + deadline = time.monotonic() + a.wait + while time.monotonic() < deadline: # the collector flushes and drains to Loki, then writes "stopped" + st = _read_status(home) + if st and st.get("state") == "stopped" and (before is None or st.get("updated_utc") != before.get("updated_utc")): + print(f"[etwcollect] collector finished: {st.get('run')} lines " + + ", ".join(f"{k}={v.get('lines')}" for k, v in st.get("providers", {}).items())) + return 0 + time.sleep(1) + print(f"[etwcollect] collector did not report 'stopped' within {a.wait:.0f} s", file=sys.stderr) + return 1 + + +def cmd_status(a) -> int: + from .session import RealtimeSession + _, home = load_config(a.config) + st = _read_status(home) + live = RealtimeSession(a.session).query() if os.name == "nt" else None + print(json.dumps({"status": st, "session_running": live is not None, "etw": live}, indent=1)) + return 0 if live is not None else 3 + + +def cmd_dosmap(a) -> int: + from . import dosmap + m = dosmap.dos_device_map() + if a.out: + dosmap.write_meta(a.out, m) + else: + print(json.dumps(m, indent=1)) + return 0 + + +def cmd_push_ledger(a) -> int: + from .loki import LokiClient, LokiError, push_ledger + cfg, _ = load_config(a.config) + url, host = a.loki_url or cfg.get("LokiUrl"), a.host or cfg.get("Host", "ws-etw") + if not url: + print("[etwcollect] no LokiUrl in etwlab.json and no --loki-url", file=sys.stderr) + return 2 + for attempt in range(6): + try: + n = push_ledger(LokiClient(url), host, a.exp, a.dir) + print(f"[etwcollect] ledger: {n} rows -> {url} (job=workload-ledger, exp={a.exp})") + return 0 + except LokiError as e: + if not e.retryable or attempt == 5: + print(f"[etwcollect] ledger push failed: {e} (re-run: etwcollect push-ledger --exp {a.exp} " + f"--dir {a.dir})", file=sys.stderr) + return 1 + time.sleep(2 ** attempt) + return 1 + + +def cmd_selftest(a) -> int: + from . import selftest + return selftest.live() if a.live else selftest.offline() + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="etwcollect", description=__doc__.split("\n")[0]) + ap.add_argument("--config", help="etwlab.json (default $ETWLAB_CONFIG or C:\\ProgramData\\etwlab\\etwlab.json)") + ap.add_argument("--session", default="etwlab-collector", help="ETW session name") + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("run", help="capture until `etwcollect stop`") + r.add_argument("--state", help="state.json from `etwctl start` (default: next to etwlab.json)") + r.add_argument("--out-dir", help="write here instead of the run folder in state.json") + r.add_argument("--status", help="status file (default: collector-status.json next to etwlab.json)") + r.add_argument("--no-push", action="store_true", help="files only, nothing to Loki") + r.add_argument("--exclude-image", action="append", default=["alloy"], + help="also drop the I/O of processes whose image starts with this (default: alloy)") + r.add_argument("--drain-s", type=float, default=30.0, help="seconds to finish shipping after a stop") + s = sub.add_parser("stop") + s.add_argument("--wait", type=float, default=60.0) + sub.add_parser("status") + d = sub.add_parser("dosmap") + d.add_argument("--out") + lg = sub.add_parser("push-ledger") + lg.add_argument("--exp", required=True, help="experiment id (07's folder name, run x-)") + lg.add_argument("--dir", required=True, help=r"\labels") + lg.add_argument("--loki-url") + lg.add_argument("--host") + t = sub.add_parser("selftest") + t.add_argument("--live", action="store_true", help="Windows, elevated: a real 15 s ETW session") + a = ap.parse_args(argv) + return {"run": cmd_run, "stop": cmd_stop, "status": cmd_status, "dosmap": cmd_dosmap, + "push-ledger": cmd_push_ledger, "selftest": cmd_selftest}[a.cmd](a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/etw-python/src/etwcollect/collector.py b/src/etw-python/src/etwcollect/collector.py new file mode 100644 index 0000000..86cadd7 --- /dev/null +++ b/src/etw-python/src/etwcollect/collector.py @@ -0,0 +1,253 @@ +"""collector.py - the running collector: ETW callback + writer, shipper and status threads. + + thread "etw" session.consume(): Windows calls _on_event() for every event, one at a time + thread "flush" writer.flush() every second (whole lines, one write per file) + thread "ship" shipper.step() every second: new whole lines -> Loki (skipped with --no-push) + thread "status" collector-status.json every 5 s (counters, lag, ETW lost-event counters, backlog) + main thread waits; `etwcollect stop` (another process) stops the session -> "etw" returns -> + final flush, shipper drains what is left (bounded), status "stopped", exit + +_on_event() per event (cheap first, so excluded events cost little): + 1. which provider? (header GUID) unknown -> count, return + 2. kproc from an excluded PID? drop before decoding (rule a) + 3. schema (cached) + decode the payload + 4. kfile rules (a)+(b) / knet rule (c) drop our own I/O + 5. ProcessStart -> remember the child's name (and exclude it if it is Alloy, during the switch) + 6. build the SilkETW-format line, hand it to the writer +""" +from __future__ import annotations + +import ctypes +import json +import os +import threading +import time +from collections import Counter +from dataclasses import dataclass, field + +from . import dosmap, record +from .decode import DecodeError, FILETIME_UNIX +from .filters import Excluder +from .loki import LokiClient, Shipper, utc_now_iso +from .procnames import ProcNames, query_image +from .providers import Provider +from .writer import LineWriter + +SESSION = "etwlab-collector" + + +@dataclass +class Config: + out_dir: str # raw_root\\ + split: str + run: str + providers: list[Provider] + raw_root: str + status_path: str + positions_path: str + host: str = "ws-etw" + loki_url: str | None = None # None or push=False: write files only + push: bool = True + session: str = SESSION + exclude_images: tuple = ("alloy",) + drain_s: float = 30.0 + extra_own_paths: tuple = field(default_factory=tuple) + + +def _int(v) -> int | None: + try: + return int(v) + except (TypeError, ValueError): + return None + + +def _now_filetime() -> int: + return time.time_ns() // 100 + FILETIME_UNIX + + +class Collector: + def __init__(self, cfg: Config, log=print): + from . import winapi as w # Windows only from here on + from .schema import Schemas + from .session import RealtimeSession + self.w, self.cfg, self.log = w, cfg, log + self.own_pid = os.getpid() + self.by_guid = {p.guid_le: p for p in cfg.providers} + self.dmap = dosmap.dos_device_map() + own_paths = [dosmap.to_device(cfg.raw_root, self.dmap).rstrip("\\") + "\\", + dosmap.to_device(cfg.out_dir, self.dmap).rstrip("\\") + "\\", + dosmap.to_device(cfg.status_path, self.dmap), + dosmap.to_device(cfg.positions_path, self.dmap), + # ETW's own spill file for this real-time session (System writes it): ETW plumbing, not activity + dosmap.to_device(os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "LogFiles", + "WMI", "RtBackup", f"EtwRT{cfg.session}.etl"), self.dmap), + *(dosmap.to_device(p, self.dmap) for p in cfg.extra_own_paths)] + self.ex = Excluder({self.own_pid}, cfg.exclude_images, own_paths) + self.names = ProcNames() + self.schemas = Schemas({p.guid_le: p.name for p in cfg.providers}) + self.writer = LineWriter(cfg.out_dir, [p.stem for p in cfg.providers]) + self.client = LokiClient(cfg.loki_url) if (cfg.push and cfg.loki_url) else None + self.shipper = Shipper(self.client, cfg.positions_path, cfg.host, log=log) if self.client else None + self.session = RealtimeSession(cfg.session) + self.stats = {p.stem: Counter() for p in cfg.providers} + self.newest = {p.stem: 0 for p in cfg.providers} # newest event FILETIME written, per provider + self.other = 0 + self.decode_errors = 0 + self.slow_events = 0 + self.callback_errors = 0 + self.last_error = None + self.state = "starting" + self.started_utc = utc_now_iso() + self.etw_rc = None + self._stop = threading.Event() + + # ---------------------------------------------------------------- per event (ETW thread) + def _callback(self, rp) -> None: + try: + self._on_event(rp) + except Exception as e: # never let an exception cross back into Windows + self.callback_errors += 1 + self.last_error = f"{type(e).__name__}: {e}" + + def _on_event(self, rp) -> None: + r = rp.contents + h = r.EventHeader + prov = self.by_guid.get(bytes(h.ProviderId)) + if prov is None: # e.g. the session's own EventTrace header event + self.other += 1 + return + stem, pid = prov.stem, h.ProcessId + st = self.stats[stem] + st["events"] += 1 + plan = self.schemas.get(rp) # cached: a dict lookup after the first event of a type + start = stem == "kproc" and plan.event_name.startswith("ProcessStart") + # A ProcessStart is logged in the PARENT's context, so one we excluded (a child we spawned) is still + # decoded first: the PID -> name map must learn the child either way. + if stem == "kproc" and not start and self.ex.header(stem, pid): + return + ptr = 4 if h.Flags & self.w.EVENT_HEADER_FLAG_32_BIT_HEADER else 8 + n = r.UserDataLength + data = ctypes.string_at(r.UserData, n) if n else b"" + try: + props, slow = plan.decode(rp, data, ptr) + except DecodeError as e: + self.decode_errors += 1 + self.last_error = f"decode {plan.provider_name}/{plan.event_name}: {e}" + props, slow = {}, False + self.slow_events += slow + if stem == "kfile": + if self.ex.kfile(plan.event_name, pid, props): + return + elif stem == "knet": + if self.ex.knet(props): + return + elif start: + child = _int(props.get("ProcessID")) + if child is not None: + name = self.names.set(child, props.get("ImageName", "")) or self.names.set(child, query_image(child)) + self.ex.note_process(child, name) + if self.ex.header(stem, pid): + return + hdr = {"ts": h.TimeStamp, "tid": h.ThreadId, "pid": pid, "pname": self.names.get(pid), "ptr": ptr, "len": n} + self.writer.add(stem, record.line(record.build(plan, hdr, props))) + st["written"] += 1 + if h.TimeStamp > self.newest[stem]: + self.newest[stem] = h.TimeStamp + + # ---------------------------------------------------------------- helper threads + def _every(self, seconds: float, fn) -> None: + while not self._stop.wait(seconds): + try: + fn() + except Exception as e: # a full disk or a bad status write must not kill capture + self.last_error = f"{fn.__name__}: {type(e).__name__}: {e}" + self.log(f"[collector] {self.last_error}") + + def _ship(self) -> None: + self.shipper.push_meta(self.cfg.split, self.cfg.run, self.dmap) + self.shipper.step() + + def status(self) -> dict: + now = _now_filetime() + provs = {} + for p in self.cfg.providers: + nf = self.newest[p.stem] + provs[p.stem] = {**self.stats[p.stem], "lines": self.writer.lines[p.stem], "bytes": self.writer.bytes[p.stem], + "newest_event_utc": record.filetime_iso(nf) if nf else None, + "lag_s": round((now - nf) / 1e7, 1) if nf else None} + ship = None + if self.shipper: + ship = {"loki": self.cfg.loki_url, "pushed_lines": self.shipper.pushed_lines, + "bad_lines": self.shipper.bad_lines, "rejected_batches": self.shipper.rejected, + "last_push_ns": self.shipper.last_push_ns, "last_error": self.shipper.last_error, + "backlog_bytes": {os.path.basename(k): v for k, v in self.shipper.backlog().items()}} + return {"state": self.state, "pid": self.own_pid, "session": self.cfg.session, "split": self.cfg.split, + "run": self.cfg.run, "dir": self.cfg.out_dir, "started_utc": self.started_utc, + "updated_utc": utc_now_iso(), "providers": provs, "excluded": dict(self.ex.counts), + "excluded_pids": sorted(self.ex.pids), "other_events": self.other, + "decode_errors": self.decode_errors, "slow_events": self.slow_events, + "schemas": len(self.schemas.cache), "no_schema": self.schemas.no_schema, + "callback_errors": self.callback_errors, "last_error": self.last_error, "etw_rc": self.etw_rc, + "etw": self.session.query() if self.state == "running" else None, "ship": ship} + + def write_status(self) -> None: + tmp = self.cfg.status_path + ".tmp" + with open(tmp, "w", encoding="utf-8") as fh: + json.dump(self.status(), fh, indent=1) + os.replace(tmp, self.cfg.status_path) + + # ---------------------------------------------------------------- lifecycle + def run(self) -> int: + for pid, name in self.names.snapshot(): + self.ex.note_process(pid, name) + meta = os.path.join(self.cfg.out_dir, "dosmap.meta") + if not os.path.exists(meta): + dosmap.write_meta(meta, self.dmap) + if self.session.start(): + self.log(f"[collector] stopped a stale session {self.cfg.session!r} first") + for p in self.cfg.providers: + self.session.enable(p.guid, p.keywords) + if self.shipper: + for p in self.cfg.providers: + self.shipper.track(self.writer.paths[p.stem]) + self.state = "running" + self.log(f"[collector] pid {self.own_pid} capturing {self.cfg.split}/{self.cfg.run} -> {self.cfg.out_dir}" + f" ({', '.join(p.stem for p in self.cfg.providers)}; push={'on' if self.shipper else 'off'})") + threads = [threading.Thread(target=self._every, args=(1.0, self.writer.flush), name="flush", daemon=True), + threading.Thread(target=self._every, args=(5.0, self.write_status), name="status", daemon=True)] + if self.shipper: + threads.append(threading.Thread(target=self._every, args=(1.0, self._ship), name="ship", daemon=True)) + for t in threads: + t.start() + etw = threading.Thread(target=self._consume, name="etw", daemon=True) + etw.start() + try: + while etw.is_alive(): + etw.join(0.5) + except KeyboardInterrupt: # console run: Ctrl+C = stop + self.session.stop() + etw.join(10) + self.state = "draining" + self._stop.set() + for t in threads: + t.join(5) + self.writer.close() + ok = True + if self.shipper: + self.shipper.push_meta(self.cfg.split, self.cfg.run, self.dmap) + self.shipper.close_run(self.cfg.out_dir) + ok = self.shipper.drain(self.cfg.drain_s) + if not ok: + self.log(f"[collector] Loki backlog left after {self.cfg.drain_s:.0f} s; shipped at the next start") + self.state = "stopped" + self.write_status() + self.log(f"[collector] stopped (ETW status {self.etw_rc}); lines " + + ", ".join(f"{s}={self.writer.lines[s]}" for s in self.writer.lines)) + return 0 + + def _consume(self) -> None: + try: + self.etw_rc = self.session.consume(self._callback) + except OSError as e: + self.last_error = str(e) + self.log(f"[collector] consumer failed: {e}") diff --git a/src/etw-python/src/etwcollect/decode.py b/src/etw-python/src/etwcollect/decode.py new file mode 100644 index 0000000..7c1f59a --- /dev/null +++ b/src/etw-python/src/etwcollect/decode.py @@ -0,0 +1,191 @@ +"""decode.py - raw ETW payload bytes (EVENT_RECORD.UserData) -> {property name: string}. Pure Python. + +An ETW event carries its fields as one packed byte string, in the order the provider's manifest declares +them. The manifest (read once per event type through TDH, schema.py) gives each field a name and an "in-type" +(how it is stored: UINT32, POINTER, UNICODESTRING, ...). schema.py turns that into a list of Prop; this module +walks the bytes with that list. Nothing here calls Windows, so the selftest runs it on Linux. + + data: bytes = b'\\x00\\x38\\x01\\x13\\x02\\xcd\\xff\\xff' + 'C:\\x.txt\\0' (UTF-16) + ... + props: list[Prop] = [Prop("FileObject", IN_POINTER), Prop("FileName", IN_UNICODESTRING), ...] + decode(props, data, ptr_size=8) -> {"FileObject": "0xffffcd0213013800", "FileName": "C:\\x.txt", ...} + +Values are written plainly (D10): decimal ints without thousands separators, pointers and hex ints as 0x.., +IPv4 dotted, ports in host order. SilkETW (via TraceEvent) wrote "4,888" and signed ints for addresses. +""" +from __future__ import annotations + +import ipaddress +import struct +import uuid +from dataclasses import dataclass +from datetime import datetime, timezone + +# TDH_INTYPE (tdh.h): how a field is stored in the payload. +IN_NULL, IN_UNICODESTRING, IN_ANSISTRING = 0, 1, 2 +IN_INT8, IN_UINT8, IN_INT16, IN_UINT16, IN_INT32, IN_UINT32, IN_INT64, IN_UINT64 = range(3, 11) +IN_FLOAT, IN_DOUBLE, IN_BOOLEAN, IN_BINARY, IN_GUID, IN_POINTER = range(11, 17) +IN_FILETIME, IN_SYSTEMTIME, IN_SID, IN_HEXINT32, IN_HEXINT64 = range(17, 22) +IN_UNICODECHAR, IN_ANSICHAR, IN_SIZET = 22, 23, 24 + +# TDH_OUTTYPE values we care about: how the manifest wants a field shown. +OUT_HEXINT8, OUT_HEXINT16, OUT_HEXINT32, OUT_HEXINT64 = 16, 17, 18, 19 +OUT_PORT, OUT_IPV4, OUT_IPV6 = 22, 23, 24 + +# in-type -> (struct format, byte size). "<" = little-endian, the byte order of every x86/x64 Windows field. +FIXED: dict[int, tuple[str, int]] = { + IN_INT8: (" 1970-01-01 in 100 ns ticks + + +class DecodeError(ValueError): + pass + + +@dataclass(frozen=True) +class Prop: + """One top-level payload field, as schema.py read it from the manifest.""" + name: str + intype: int + fmt: str | None = None # None | "hex" | "port" | "ipv4" | "ipv6" + length: int | None = None # fixed byte length (BINARY only) + length_index: int | None = None # BINARY: index of the earlier field that holds its byte length + + +def filetime_iso(ft: int) -> str: + """FILETIME (100 ns ticks since 1601, UTC) -> '2026-10-25T07:30:47.8891166+00:00' (SilkETW's 7 digits). + ft = 134_373_870_478_891_166 -> '2026-10-25T07:30:47.8891166+00:00' + ft = 0 -> '0' (a 'not set' FILETIME field)""" + if ft <= 0: + return "0" + sec, frac = divmod(ft - FILETIME_UNIX, 10_000_000) # whole seconds since 1970, 100 ns remainder + dt = datetime.fromtimestamp(sec, tz=timezone.utc) + return f"{dt:%Y-%m-%dT%H:%M:%S}.{frac:07d}+00:00" + + +def filetime_ns(ft: int) -> int: + """FILETIME -> Unix epoch nanoseconds (Loki entry timestamps).""" + return (ft - FILETIME_UNIX) * 100 + + +def _wcs_end(data: bytes, off: int) -> int: + """Byte offset of the UTF-16 NUL terminator at or after off (len(data) when unterminated). The NUL must + start on an even distance from off: b'A\\x00\\x00\\x01' has a 0x0000 pair at 1, but that is not a char.""" + i = off + while True: + j = data.find(b"\x00\x00", i) + if j < 0: + return len(data) + if (j - off) % 2 == 0: + return j + i = j + 1 + + +def _sid(b: bytes) -> str: + """Binary SID -> 'S-1-5-18'. Layout: revision u8, sub-authority count u8, authority 6 bytes big-endian, + then count x u32 little-endian.""" + rev, n = b[0], b[1] + auth = int.from_bytes(b[2:8], "big") + subs = struct.unpack_from("<%dI" % n, b, 8) + return "S-%d-%d" % (rev, auth) + "".join("-%d" % s for s in subs) + + +def _systemtime(b: bytes) -> str: + y, mo, _dow, d, h, mi, s, ms = struct.unpack("<8H", b) + return f"{y:04d}-{mo:02d}-{d:02d}T{h:02d}:{mi:02d}:{s:02d}.{ms:03d}" + + +def format_int(v: int, fmt: str | None, size: int) -> str: + if fmt == "hex": + return "0x%x" % (v & ((1 << (8 * size)) - 1)) + return str(v) + + +def read_one(p: Prop, data: bytes, off: int, ptr_size: int, nums: list) -> tuple[str, int, int | None]: + """Decode prop p at data[off:]. Returns (text, next offset, int value or None). nums = int values of the + props decoded so far (a BINARY field's length lives in an earlier field).""" + t = p.intype + if t in FIXED: + f, n = FIXED[t] + if off + n > len(data): + raise DecodeError(f"{p.name}: needs {n} bytes at {off}, payload has {len(data)}") + if p.fmt == "port" and n == 2: # stored in network byte order (big-endian) + v = struct.unpack_from(">H", data, off)[0] + return str(v), off + n, v + if p.fmt == "ipv4" and n == 4: # in_addr: the 4 bytes ARE a.b.c.d in order + return ".".join(str(x) for x in data[off:off + 4]), off + n, None + v = struct.unpack_from(f, data, off)[0] + if t == IN_BOOLEAN: + return ("True" if v else "False"), off + n, v + if t == IN_FILETIME: + return filetime_iso(v), off + n, v + if t in (IN_FLOAT, IN_DOUBLE): + return repr(v), off + n, None + hexed = "hex" if t in (IN_HEXINT32, IN_HEXINT64) else p.fmt + return format_int(v, hexed, n), off + n, v + if t in (IN_POINTER, IN_SIZET): + if off + ptr_size > len(data): + raise DecodeError(f"{p.name}: pointer at {off} past payload end {len(data)}") + v = int.from_bytes(data[off:off + ptr_size], "little") + return "0x%x" % v, off + ptr_size, v + if t == IN_UNICODESTRING: + end = _wcs_end(data, off) + s = data[off:end].decode("utf-16-le", errors="replace") + return s, min(end + 2, len(data)), None + if t == IN_ANSISTRING: + end = data.find(b"\x00", off) + end = len(data) if end < 0 else end + return data[off:end].decode("cp1252", errors="replace"), min(end + 1, len(data)), None + if t == IN_GUID: + if off + 16 > len(data): + raise DecodeError(f"{p.name}: GUID past payload end") + return str(uuid.UUID(bytes_le=data[off:off + 16])), off + 16, None + if t == IN_SYSTEMTIME: + if off + 16 > len(data): + raise DecodeError(f"{p.name}: SYSTEMTIME past payload end") + return _systemtime(data[off:off + 16]), off + 16, None + if t == IN_SID: + if off + 8 > len(data): + raise DecodeError(f"{p.name}: SID header past payload end") + n = 8 + 4 * data[off + 1] + return _sid(data[off:off + n]), off + n, None + if t == IN_BINARY: + n = p.length if p.length is not None else (nums[p.length_index] if p.length_index is not None else None) + if n is None: + raise DecodeError(f"{p.name}: BINARY without a length") + raw = data[off:off + n] + if p.fmt == "ipv6" and n == 16: + return str(ipaddress.IPv6Address(raw)), off + n, None + if p.fmt == "ipv4" and n == 4: + return ".".join(str(x) for x in raw), off + n, None + return "0x" + raw.hex(), off + n, None + raise DecodeError(f"{p.name}: unsupported in-type {t}") + + +def decode(props: list[Prop], data: bytes, ptr_size: int = 8) -> dict[str, str]: + """Walk data with props. A payload that ends early (an older event version without the trailing + fields) stops cleanly; a field cut in half raises DecodeError.""" + out: dict[str, str] = {} + nums: list = [] + off = 0 + for p in props: + if off >= len(data): + break + text, off, num = read_one(p, data, off, ptr_size, nums) + out[p.name] = text + nums.append(num) + return out + + +def decode_value(p: Prop, raw: bytes, ptr_size: int = 8) -> str: + """One field whose exact bytes TDH already cut out (the slow path in schema.py).""" + if p.intype == IN_BINARY: + p = Prop(p.name, p.intype, p.fmt, len(raw)) + return read_one(p, raw, 0, ptr_size, [])[0] diff --git a/src/etw-python/src/etwcollect/dosmap.py b/src/etw-python/src/etwcollect/dosmap.py new file mode 100644 index 0000000..c43cc3b --- /dev/null +++ b/src/etw-python/src/etwcollect/dosmap.py @@ -0,0 +1,43 @@ +"""dosmap.py - NT device names <-> drive letters ('\\device\\harddiskvolume4' <-> 'c:'). + +Kernel-File and Kernel-Process report paths in NT device form (\\Device\\HarddiskVolume4\\Windows\\...). The +converter on the trainer needs this machine's mapping to turn them into C:\\Windows\\..., so every run carries +it: dosmap.meta in the run folder and one job="etw-meta" line in Loki (same JSON as +`etwship.py --print-dos-map`, which this replaces in etwctl). + + {"\\\\device\\\\harddiskvolume4": "c:"} (JSON-escaped backslashes) +""" +from __future__ import annotations + +import ctypes +import json +import os + + +def dos_device_map() -> dict[str, str]: + """QueryDosDeviceW('C:') -> '\\Device\\HarddiskVolume4' for every drive letter; longest device first so a + prefix match never picks \\device\\harddiskvolume1 for \\device\\harddiskvolume12. Empty off Windows.""" + m: dict[str, str] = {} + if os.name != "nt": + return m + from . import winapi as w + buf = ctypes.create_unicode_buffer(1024) + for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ": + if w.QueryDosDeviceW(c + ":", buf, 1024): + m[buf.value.lower()] = c.lower() + ":" + return dict(sorted(m.items(), key=lambda kv: -len(kv[0]))) + + +def to_device(path: str, dmap: dict[str, str]) -> str: + """'C:\\lab-out\\etw\\raw' -> '\\device\\harddiskvolume4\\lab-out\\etw\\raw' (lower case), the form Kernel-File + reports. Unchanged when the drive is not in the map.""" + p = os.path.normpath(path).lower() if os.name == "nt" else path.lower() + for dev, drive in dmap.items(): + if p.startswith(drive): + return dev + p[len(drive):] + return p + + +def write_meta(path: str, dmap: dict[str, str]) -> None: + with open(path, "w", encoding="utf-8", newline="\n") as fh: + fh.write(json.dumps(dmap, separators=(",", ":")) + "\n") diff --git a/src/etw-python/src/etwcollect/filters.py b/src/etw-python/src/etwcollect/filters.py new file mode 100644 index 0000000..80f201e --- /dev/null +++ b/src/etw-python/src/etwcollect/filters.py @@ -0,0 +1,98 @@ +"""filters.py - drop the collector's own I/O BEFORE it becomes a line (the fix for the SilkService loop). + +Why: every line we write is itself a Kernel-File Write; every read of our files (the shipper, formerly Alloy) +is a Kernel-File Read. Written out, those become more lines -> more events (docs/notes/silkservice-kfile-lag.md). +Three rules, each counted (Excluder.counts -> collector-status.json): + + (a) self_pid the event's header PID is ours (or, during the switch, Alloy's). kproc / kfile. + (b) own_file a Kernel-File event on one of OUR files, whoever issued it: a Create whose FileName is under + the raw output root, or a Read/Write on a FileObject / FileKey learned from such a Create. + This also catches System (PID 4) lazy-writer flushes of our files, which (a) cannot. + (c) net_pid a Kernel-Network event whose PAYLOAD PID is excluded. The header PID of network events is + whatever thread ran (Idle, System, any process: 77 % mismatch measured), so it is not used. + +FileObject = the kernel address of one open handle's file object; FileKey = the address of the file's stream +control block, shared by every handle to the same file. Both arrive as hex strings ("0xffffcd02..."). +A FileObject address is reused after a close; a new Create on that address always comes first, so a Create +for a path outside our root forgets it again. +""" +from __future__ import annotations + +from collections import Counter + + +def image_base(path: str) -> str: + """'\\Device\\HarddiskVolume4\\Windows\\System32\\msedge.exe' -> 'msedge' (SilkETW's ProcessName shape).""" + b = path.replace("/", "\\").rsplit("\\", 1)[-1] + return b[:-4] if b.lower().endswith(".exe") else b + + +class Excluder: + def __init__(self, own_pids: set[int], image_prefixes=(), own_paths=()): + self.own: set[int] = set(own_pids) # never dropped from the excluded set + self.pids: set[int] = set(own_pids) # own + PIDs of excluded images (alloy*) + self.image_prefixes = tuple(p.lower() for p in image_prefixes) + # own_paths: NT device paths, lower-case. A folder ends with '\\' (prefix match); a file does not. + self.own_paths = tuple(p.lower() for p in own_paths) + self.fobj: set[str] = set() # FileObjects of our files + self.fkey: set[str] = set() # FileKeys of our files + self.counts: Counter = Counter() # "kfile.own_file" -> n + + # ---------------------------------------------------------------- process names + def note_process(self, pid: int, name: str) -> None: + """A process started (or was found at startup) with this image name.""" + if pid in self.own: + return + if self.image_prefixes and name.lower().startswith(self.image_prefixes): + self.pids.add(pid) + else: + self.pids.discard(pid) # the PID was reused by another image + + def ours(self, filename: str) -> bool: + f = filename.lower() + return any(f.startswith(p) if p.endswith("\\") else f == p for p in self.own_paths) + + # ---------------------------------------------------------------- rules + def header(self, stem: str, pid: int) -> bool: + """Rule (a) for kproc, checked before any decoding.""" + if pid in self.pids: + self.counts[stem + ".self_pid"] += 1 + return True + return False + + def kfile(self, event: str, pid: int, d: dict[str, str]) -> bool: + """Rules (a) + (b) for one decoded Kernel-File event. True = drop it.""" + fo = d.get("FileObject", "").lower() + fk = d.get("FileKey", "").lower() + if event.startswith("Create"): # Create / CreateNewFile carry the path + if self.ours(d.get("FileName", "")): + if fo: + self.fobj.add(fo) + self.counts["kfile.own_file"] += 1 + return True + self.fobj.discard(fo) # address reused for another file + elif (fo and fo in self.fobj) or (fk and fk in self.fkey): + if fo in self.fobj and fk: + self.fkey.add(fk) # learn the file's key from a handle we know + self.counts["kfile.own_file"] += 1 + return True + if pid in self.pids: + self.counts["kfile.self_pid"] += 1 + return True + return False + + def knet(self, d: dict[str, str]) -> bool: + """Rule (c): the owner is the payload PID.""" + try: + owner = int(d.get("PID", "")) + except ValueError: + return False + if owner in self.pids: + self.counts["knet.net_pid"] += 1 + return True + return False + + def reset_files(self) -> None: + """New run folder: file objects of the old run mean nothing any more.""" + self.fobj.clear() + self.fkey.clear() diff --git a/src/etw-python/src/etwcollect/loki.py b/src/etw-python/src/etwcollect/loki.py new file mode 100644 index 0000000..04218ac --- /dev/null +++ b/src/etw-python/src/etwcollect/loki.py @@ -0,0 +1,277 @@ +"""loki.py - push our run files to Loki on the trainer (replaces Grafana Alloy, DEVIATIONS D10). + +Loki contract = what Alloy produced (src/ansible/roles/win_alloy/templates/config.alloy.j2), so the trainer +side (lokiclient.py, loki_pull.py, loki_source.py) is unchanged: + + events labels {job="silketw", host, split, run, provider} provider = file stem (kproc|kfile|knet) + structured metadata {event, pid, process} (filterable, not indexed) + entry timestamp = the line's own TimeStamp (event time), line = the file line unchanged + dos map labels {job="etw-meta", host, split, run} one JSON line per run (dosmap.meta) + ledger labels {job="workload-ledger", host, exp} one entry per CSV row, ts = its "utc" column + +Delivery works like Alloy's file tail: the shipper reads each tracked file from a saved byte offset +(positions file), pushes whole lines in batches, and only moves the offset after Loki said 204. A Loki +outage or a collector restart therefore delays lines but does not lose them (Loki accepts entries up to +reject_old_samples_max_age = the 3-day retention). Re-sending a batch Loki partly took is harmless: Loki +drops entries identical to ones it has (same stream, timestamp and line). + +Push body (POST /loki/api/v1/push, gzip JSON): + {"streams": [{"stream": {"job": "silketw", ..., "provider": "kfile"}, + "values": [["1761377445872583100", "", {"event": "Create", "pid": "420", "process": "x"}]]}]} +""" +from __future__ import annotations + +import glob +import gzip +import json +import os +import re +import time +import urllib.error +import urllib.request +from datetime import datetime, timezone + +NS = 1_000_000_000 +MAX_BATCH = 1 << 20 # 1 MiB of line bytes per push (Alloy: batch_size 1MiB) +_TS = re.compile(r"^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d+))?\s*(Z|[+-]\d\d:\d\d)?$") + + +class LokiError(OSError): + def __init__(self, code: int, msg: str): + super().__init__(f"Loki push HTTP {code}: {msg}") + self.code = code + # 429 = rate limited, 5xx = Loki trouble, 0 = no connection: try again later. Other 4xx = Loki + # refuses these lines (e.g. older than the retention): retrying would stall the file forever. + self.retryable = code == 0 or code == 429 or code >= 500 + + +def ts_ns(s: str) -> int: + """'2026-10-25T07:30:45.8725831+00:00' -> 1761377445872583100. Accepts 0-9 fractional digits, Z or an + offset ('...+07:00' = 7 h ahead of UTC, so the same instant has a smaller UTC hour).""" + m = _TS.match(str(s).strip()) + if not m: + raise ValueError(f"not an ISO timestamp: {s!r}") + off = m.group(3) or "+00:00" + base = datetime.fromisoformat(m.group(1) + ("+00:00" if off == "Z" else off)) + frac = (m.group(2) or "0")[:9].ljust(9, "0") + return int(base.timestamp()) * NS + int(frac) + + +class LokiClient: + def __init__(self, url: str, timeout: float = 15.0): + self.url = url.rstrip("/") + self.timeout = timeout + + def push(self, streams: list[dict]) -> int: + body = gzip.compress(json.dumps({"streams": streams}, ensure_ascii=False).encode("utf-8")) + req = urllib.request.Request(self.url + "/loki/api/v1/push", data=body, method="POST", + headers={"Content-Type": "application/json", "Content-Encoding": "gzip"}) + try: + with urllib.request.urlopen(req, timeout=self.timeout) as r: + return r.status + except urllib.error.HTTPError as e: + raise LokiError(e.code, e.read()[:300].decode(errors="replace")) from None + except (urllib.error.URLError, OSError) as e: + raise LokiError(0, str(e)) from None + + +def labels_for(path: str, host: str) -> dict[str, str]: + """raw_root\\\\\\.json -> the Loki stream labels Alloy derived from the same path.""" + p = os.path.normpath(path) + run_dir, fn = os.path.split(p) + split_dir, run = os.path.split(run_dir) + split = os.path.basename(split_dir) + return {"job": "silketw", "host": host, "split": split, "run": run, "provider": os.path.splitext(fn)[0]} + + +def entry(line: bytes, now_ns: int) -> tuple[list, bool]: + """One file line -> [ts_ns, line, metadata]. A line that does not parse keeps the read time (Alloy's + action_on_failure = skip); the converter counts such lines as bad on the trainer.""" + text = line.decode("utf-8", errors="replace").rstrip("\r\n") + try: + ev = json.loads(text) + return [str(ts_ns(ev["TimeStamp"])), text, {"event": str(ev.get("EventName", "")), + "pid": str(ev.get("ProcessID", "")), + "process": str(ev.get("ProcessName", ""))}], True + except (ValueError, KeyError, TypeError): + return [str(now_ns), text], False + + +class Shipper: + """Tails tracked files from saved offsets and pushes whole lines. Positions file: + {"files": {"C:\\\\...\\\\kfile.json": {"offset": 123, "labels": {...}, "closed": false}}, + "meta": {"test/live-20261026T080000Z": true}} + Not thread-safe: one thread calls step(); track()/close_run() are called from the same collector.""" + + def __init__(self, client: LokiClient | None, positions_path: str, host: str, max_batch: int = MAX_BATCH, + now_ns=time.time_ns, log=print): + self.client, self.pos_path, self.host = client, positions_path, host + self.max_batch, self.now_ns, self.log = max_batch, now_ns, log + self.state = {"files": {}, "meta": {}} + if os.path.exists(positions_path): + try: + with open(positions_path, encoding="utf-8") as fh: + self.state = json.load(fh) + except (OSError, ValueError): + self.log(f"[ship] positions file unreadable, starting from offset 0: {positions_path}") + self.state.setdefault("files", {}) + self.state.setdefault("meta", {}) + self.pushed_lines = 0 + self.bad_lines = 0 + self.rejected = 0 + self.last_push_ns = None + self.last_error = None + self.backoff_until = 0.0 + self.backoff = 1.0 + + # ---------------------------------------------------------------- bookkeeping + def _save(self) -> None: + tmp = self.pos_path + ".tmp" + with open(tmp, "w", encoding="utf-8") as fh: + json.dump(self.state, fh, indent=1) + os.replace(tmp, self.pos_path) + + def track(self, path: str) -> None: + if path not in self.state["files"]: + self.state["files"][path] = {"offset": 0, "labels": labels_for(path, self.host), "closed": False} + self._save() + + def close_run(self, run_dir: str) -> None: + """The collector stopped writing this run: once shipped to the end, its entries are forgotten.""" + for p, f in self.state["files"].items(): + if os.path.dirname(os.path.normpath(p)) == os.path.normpath(run_dir): + f["closed"] = True + self._save() + + def backlog(self) -> dict[str, int]: + """Unshipped bytes per tracked file (for collector-status.json).""" + out = {} + for p, f in self.state["files"].items(): + try: + out[p] = max(0, os.path.getsize(p) - f["offset"]) + except OSError: + out[p] = 0 + return out + + # ---------------------------------------------------------------- pushing + def _push(self, streams: list[dict]) -> bool: + """True = Loki has the lines (or refused them for good); False = try again later.""" + if self.client is None: + return False + try: + self.client.push(streams) + self.last_push_ns, self.last_error, self.backoff = self.now_ns(), None, 1.0 + return True + except LokiError as e: + self.last_error = str(e) + if not e.retryable: + self.rejected += 1 + self.log(f"[ship] Loki refused a batch, skipping it: {e}") + return True + self.backoff_until = time.monotonic() + self.backoff + self.backoff = min(self.backoff * 2, 30.0) + return False + + def push_meta(self, split: str, run: str, dmap: dict) -> bool: + key = f"{split}/{run}" + if self.state["meta"].get(key): + return True + line = json.dumps(dmap, separators=(",", ":")) + ok = self._push([{"stream": {"job": "etw-meta", "host": self.host, "split": split, "run": run}, + "values": [[str(self.now_ns()), line]]}]) + if ok: + self.state["meta"][key] = True + self._save() + return ok + + def step(self) -> int: + """Ship at most one batch per tracked file. Returns the number of lines Loki accepted.""" + if time.monotonic() < self.backoff_until: + return 0 + sent = 0 + for path in list(self.state["files"]): + f = self.state["files"][path] + try: + size = os.path.getsize(path) + except OSError: # run folder deleted (live runs are pruned after a day) + del self.state["files"][path] + self._save() + continue + if f["offset"] >= size: + if f["closed"]: + del self.state["files"][path] + self._save() + continue + with open(path, "rb") as fh: + fh.seek(f["offset"]) + chunk = fh.read(self.max_batch) + cut = chunk.rfind(b"\n") + 1 # whole lines only; a partial last line waits + if cut == 0: + if len(chunk) == self.max_batch: # one line longer than a batch: ship it alone + cut = len(chunk) + elif f["closed"]: # a crashed run left half a line: never completes + f["offset"] = size + self.bad_lines += 1 + self._save() + continue + else: + continue + now = self.now_ns() + values = [] + for raw in chunk[:cut].splitlines(keepends=True): + if not raw.strip(): + continue + v, ok = entry(raw, now) + values.append(v) + self.bad_lines += not ok + refused = self.rejected + if values and not self._push([{"stream": f["labels"], "values": values}]): + return sent # Loki down: keep the offset, retry after backoff + f["offset"] += cut + self._save() + if self.rejected == refused: # a refused batch is skipped, not counted as shipped + sent += len(values) + self.pushed_lines += len(values) + return sent + + def drain(self, timeout_s: float) -> bool: + """Ship until every tracked file is at its end, or the timeout passes. True = nothing left.""" + deadline = time.monotonic() + timeout_s + while time.monotonic() < deadline: + if not any(self.backlog().values()): + return True + if self.step() == 0: + time.sleep(0.5) + return not any(self.backlog().values()) + + +# --------------------------------------------------------------------------- the 07 workload ledger +_LEDGER_TS = re.compile(r'^"(\d{4}-[^"]+)"') + + +def push_ledger(client: LokiClient, host: str, exp: str, labels_dir: str, now_ns=time.time_ns) -> int: + """\\labels\\*.csv -> {job="workload-ledger", host, exp}. Each row's timestamp is its first column + ("utc"); the header row has none and gets the push time (loki_pull.py puts it back on top).""" + values = [] + for p in sorted(glob.glob(os.path.join(labels_dir, "*.csv"))): + with open(p, encoding="utf-8-sig") as fh: + for row in fh: + row = row.rstrip("\r\n") + if not row: + continue + m = _LEDGER_TS.match(row) + t = now_ns() + if m: + try: + t = ts_ns(m.group(1)) + except ValueError: + pass + values.append([str(t), row]) + labels = {"job": "workload-ledger", "host": host, "exp": exp} + for i in range(0, len(values), 5000): + client.push([{"stream": labels, "values": values[i:i + 5000]}]) + return len(values) + + +def utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat() diff --git a/src/etw-python/src/etwcollect/procnames.py b/src/etw-python/src/etwcollect/procnames.py new file mode 100644 index 0000000..c972c48 --- /dev/null +++ b/src/etw-python/src/etwcollect/procnames.py @@ -0,0 +1,86 @@ +"""procnames.py - PID -> process name ('msedge', SilkETW's ProcessName: image file name without '.exe'). + +ETW event headers carry only a PID. SilkETW asked .NET for the name when it wrote the line, so a process that +had already exited got 'N/A' (9,487 of 17k kproc lines on 2026-10-25). Here the map is filled + 1. at startup from a process snapshot (CreateToolhelp32Snapshot: every running process, its exe name), + 2. on every Kernel-Process ProcessStart event, from its ImageName field (or, if missing, by asking Windows + while the new process is still alive: QueryFullProcessImageNameW), +so short-lived processes such as `whoami` keep their real name. A PID is overwritten when it is reused. +""" +from __future__ import annotations + +import ctypes +import os + +from .filters import image_base + + +class ProcNames: + def __init__(self): + self.names: dict[int, str] = {0: "Idle", 4: "System"} + self.misses: set[int] = set() # PIDs we already failed to look up (dead): no retry + + def set(self, pid: int, image: str) -> str: + name = image_base(image) if image else "" + if name: + self.names[pid] = name + self.misses.discard(pid) + return name + + def get(self, pid: int) -> str: + n = self.names.get(pid) + if n is not None: + return n + if pid in self.misses: + return "N/A" + n = query_image(pid) + if n: + self.names[pid] = image_base(n) + return self.names[pid] + self.misses.add(pid) + return "N/A" + + def snapshot(self) -> list[tuple[int, str]]: + """Fill from the running processes. Returns [(pid, name)] so the Excluder can see them too.""" + found = [] + for pid, exe in snapshot(): + if pid in (0, 4): + continue + found.append((pid, self.set(pid, exe))) + return found + + +def snapshot() -> list[tuple[int, str]]: + if os.name != "nt": + return [] + from . import winapi as w + h = w.CreateToolhelp32Snapshot(w.TH32CS_SNAPPROCESS, 0) + if not h or h == w.INVALID_HANDLE_VALUE: + return [] + out = [] + try: + e = w.PROCESSENTRY32W() + e.dwSize = ctypes.sizeof(e) + ok = w.Process32FirstW(h, ctypes.byref(e)) + while ok: + out.append((int(e.th32ProcessID), e.szExeFile)) + ok = w.Process32NextW(h, ctypes.byref(e)) + finally: + w.CloseHandle(h) + return out + + +def query_image(pid: int) -> str: + """Full image path of a live process ('C:\\Windows\\System32\\whoami.exe'), '' when it is gone.""" + if os.name != "nt" or pid <= 4: + return "" + from . import winapi as w + h = w.OpenProcess(w.PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if not h: + return "" + try: + buf = ctypes.create_unicode_buffer(1024) + n = ctypes.c_ulong(1024) + return buf.value if w.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(n)) else "" + finally: + w.CloseHandle(h) diff --git a/src/etw-python/src/etwcollect/providers.py b/src/etw-python/src/etwcollect/providers.py new file mode 100644 index 0000000..5c46de2 --- /dev/null +++ b/src/etw-python/src/etwcollect/providers.py @@ -0,0 +1,35 @@ +"""providers.py - the three kernel ETW providers the lab records, by name. + +etwlab.json (written by Ansible, src/ansible/roles/win_collector/templates/etwlab.json.j2) names providers +and keywords; ETW needs the provider GUID. The GUIDs are the ones SilkETW wrote into every line's +`ProviderGuid` (checked on src/live/sessions/live-20261025T073042Z/raw/*.json). +""" +import uuid + +GUIDS: dict[str, uuid.UUID] = { + "Microsoft-Windows-Kernel-Process": uuid.UUID("22fb2cd6-0e7b-422b-a0c7-2fad1fd0e716"), + "Microsoft-Windows-Kernel-File": uuid.UUID("edd08927-9cc4-4e65-b970-c2560fb5c289"), + "Microsoft-Windows-Kernel-Network": uuid.UUID("7dd42a49-5329-4832-8dfd-43d979153a88"), +} + +NETWORK = "Microsoft-Windows-Kernel-Network" + + +class Provider: + """One collector entry of etwlab.json: {"Stem": "kfile", "Provider": "...Kernel-File", "Keywords": "0x380"}.""" + + def __init__(self, stem: str, name: str, keywords: int | str, required: bool = True): + self.stem = stem # file stem and Loki `provider` label: kproc | kfile | knet + self.name = name + self.keywords = int(keywords, 16) if isinstance(keywords, str) else int(keywords) + self.required = required + if name not in GUIDS: + raise ValueError(f"unknown provider {name!r} (known: {', '.join(GUIDS)})") + self.guid: uuid.UUID = GUIDS[name] + # EVENT_HEADER.ProviderId is a Windows GUID struct: the first three fields are little-endian, which + # is exactly uuid.bytes_le. bytes(header.ProviderId) == self.guid_le identifies the provider per event. + self.guid_le: bytes = self.guid.bytes_le + + @classmethod + def from_config(cls, c: dict) -> "Provider": + return cls(c["Stem"], c["Provider"], c.get("Keywords", "0xffffffffffffffff"), c.get("Required", True)) diff --git a/src/etw-python/src/etwcollect/record.py b/src/etw-python/src/etwcollect/record.py new file mode 100644 index 0000000..baba751 --- /dev/null +++ b/src/etw-python/src/etwcollect/record.py @@ -0,0 +1,66 @@ +"""record.py - one decoded event -> one SilkETW-format JSON line. + +The converter (src/pipeline/etw2nodlink.py), the Loki labels and every notebook read SilkETW's line shape, so +we keep its top-level keys and their order: + + {"ProviderGuid":"edd08927-...","YaraMatch":[],"ProviderName":"Microsoft-Windows-Kernel-File", + "EventName":"Create","Opcode":0,"OpcodeName":"Info","TimeStamp":"2026-10-25T07:30:45.8725831+00:00", + "ThreadID":4888,"ProcessID":420,"ProcessName":"explorer","PointerSize":8,"EventDataLength":188, + "XmlEventData":{"FileObject":"0xffffcd0213013800","FileName":"\\Device\\HarddiskVolume4\\...",...}} + +Differences from SilkETW (DEVIATIONS D10): XmlEventData holds only the payload fields (no FormattedMessage, +no TraceEvent copies of the header such as MSec/PName/TID/PID), values are plain (see decode.py), and the +timestamp is UTC (+00:00) instead of the VM's local offset. Every consumer converts it to epoch ms anyway. +""" +from __future__ import annotations + +import json + +from .decode import filetime_iso + + +def ident(s: str | None) -> str: + """TraceEvent's names drop the spaces of the manifest strings: 'Data sent.' -> 'Datasent.'.""" + return "".join(s.split()) if s else "" + + +def event_name(task: str, opcode_name: str, opcode: int, event_id: int) -> str: + """TraceEvent's EventName rule, which the converter's classify() was written against: + task 'Create', opcode 0 -> 'Create' + task 'ProcessStart', opcode 1 'Start' -> 'ProcessStart/Start' + task 'KERNEL_NETWORK_TASK_TCPIP', opcode 10 'Data sent.' -> 'KERNEL_NETWORK_TASK_TCPIP/Datasent.'""" + task, op = ident(task), ident(opcode_name) + if not task: + return f"EventID({event_id})" + if opcode == 0: + return task + return f"{task}/{op or opcode}" + + +def opcode_label(opcode_name: str, opcode: int) -> str: + return ident(opcode_name) or ("Info" if opcode == 0 else str(opcode)) + + +def build(meta, header: dict, props: dict[str, str]) -> dict: + """meta: schema.EventPlan (provider_guid, provider_name, event_name, opcode, opcode_name). + header: {"ts": FILETIME int, "tid": int, "pid": int, "pname": str, "ptr": 4|8, "len": UserDataLength}.""" + return { + "ProviderGuid": meta.provider_guid, + "YaraMatch": [], + "ProviderName": meta.provider_name, + "EventName": meta.event_name, + "Opcode": meta.opcode, + "OpcodeName": meta.opcode_name, + "TimeStamp": filetime_iso(header["ts"]), + "ThreadID": header["tid"], + "ProcessID": header["pid"], + "ProcessName": header["pname"], + "PointerSize": header["ptr"], + "EventDataLength": header["len"], + "XmlEventData": props, + } + + +def line(rec: dict) -> bytes: + """Compact JSON (no spaces, like SilkETW), UTF-8, one line + '\\n'.""" + return json.dumps(rec, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n" diff --git a/src/etw-python/src/etwcollect/schema.py b/src/etw-python/src/etwcollect/schema.py new file mode 100644 index 0000000..734eade --- /dev/null +++ b/src/etw-python/src/etwcollect/schema.py @@ -0,0 +1,138 @@ +"""schema.py - what each event type's payload looks like, asked from Windows (TDH) once and cached. + +TDH ("Trace Data Helper", tdh.dll) reads the provider's manifest and returns a TRACE_EVENT_INFO for an event: +provider name, task name ('Create'), opcode name ('Info'), and the list of payload fields with their in-types. +That call is slow-ish, but all events of one type (provider, event id, version) share it, so it runs once per +type (a few dozen types in total) and is cached as an EventPlan. + +Fast path: every top-level field is a simple scalar/string -> EventPlan.props (decode.Prop list), and each event +is decoded in pure Python from its bytes. Slow path (structs, arrays, counted strings): ask TDH for each field's +bytes per event (TdhGetPropertySize + TdhGetProperty). None of our 3 providers is expected to need it; the +counter `slow_events` in collector-status.json shows it if they do. + +TRACE_EVENT_INFO buffer layout ([n B] = bytes): + [112 B] header (offsets of the name strings, PropertyCount, TopLevelPropertyCount, ...) + [24 B x PropertyCount] EVENT_PROPERTY_INFO (Flags, NameOffset, InType, OutType, Count, Length) + [...] UTF-16 strings; every *Offset above is a byte offset from the start of the buffer +""" +from __future__ import annotations + +import ctypes +import uuid +from dataclasses import dataclass, field + +from . import decode as dc +from . import winapi as w +from .providers import NETWORK +from .record import event_name, opcode_label + +IPV4_NAMES, PORT_NAMES = {"daddr", "saddr"}, {"dport", "sport"} + + +@dataclass +class EventPlan: + provider_guid: str + provider_name: str + event_name: str + opcode: int + opcode_name: str + props: list | None # decode.Prop list (fast path) or None (slow path) + slow: list = field(default_factory=list) # [(Prop, PROPERTY_DATA_DESCRIPTOR)] for the slow path + buf: object = None # keeps the TRACE_EVENT_INFO buffer alive (names point into it) + + def decode(self, rec_ptr, data: bytes, ptr_size: int) -> tuple[dict[str, str], bool]: + """-> (fields, used_slow_path).""" + if self.props is not None: + return dc.decode(self.props, data, ptr_size), False + out = {} + for p, pdd in self.slow: + size = ctypes.c_ulong(0) + if w.TdhGetPropertySize(rec_ptr, 0, None, 1, ctypes.byref(pdd), ctypes.byref(size)) != 0: + continue + raw = ctypes.create_string_buffer(max(size.value, 1)) + if w.TdhGetProperty(rec_ptr, 0, None, 1, ctypes.byref(pdd), size.value, raw) != 0: + continue + try: + out[p.name] = dc.decode_value(p, raw.raw[:size.value], ptr_size) + except (dc.DecodeError, ValueError, IndexError): + out[p.name] = "0x" + raw.raw[:size.value].hex() + return out, True + + +def _fmt(provider_name: str, name: str, intype: int, outtype: int) -> str | None: + if outtype in (dc.OUT_HEXINT8, dc.OUT_HEXINT16, dc.OUT_HEXINT32, dc.OUT_HEXINT64): + return "hex" + net = provider_name == NETWORK + if outtype == dc.OUT_IPV4 or (net and name in IPV4_NAMES and intype in (dc.IN_UINT32, dc.IN_INT32)): + return "ipv4" + if outtype == dc.OUT_IPV6 or (net and name in IPV4_NAMES and intype == dc.IN_BINARY): + return "ipv6" + if outtype == dc.OUT_PORT or (net and name in PORT_NAMES and intype in (dc.IN_UINT16, dc.IN_INT16)): + return "port" + return None + + +class Schemas: + def __init__(self, provider_names: dict[bytes, str]): + self.cache: dict[tuple, EventPlan] = {} + self.provider_names = provider_names # guid_le -> name (fallback when TDH has no schema) + self.no_schema = 0 + + def get(self, rec_ptr) -> EventPlan: + h = rec_ptr.contents.EventHeader + d = h.EventDescriptor + key = (bytes(h.ProviderId), d.Id, d.Version, d.Opcode, d.Task) + plan = self.cache.get(key) + if plan is None: + plan = self.cache[key] = self._build(rec_ptr) + return plan + + def _build(self, rec_ptr) -> EventPlan: + h = rec_ptr.contents.EventHeader + d = h.EventDescriptor + guid_le = bytes(h.ProviderId) + gstr = str(uuid.UUID(bytes_le=guid_le)) + size = ctypes.c_ulong(0) + rc = w.TdhGetEventInformation(rec_ptr, 0, None, None, ctypes.byref(size)) + if rc == w.ERROR_INSUFFICIENT_BUFFER: + buf = ctypes.create_string_buffer(size.value) + rc = w.TdhGetEventInformation(rec_ptr, 0, None, buf, ctypes.byref(size)) + if rc != 0: # no manifest for this event: header only, empty payload + self.no_schema += 1 + return EventPlan(gstr, self.provider_names.get(guid_le, gstr), f"EventID({d.Id})", d.Opcode, + opcode_label("", d.Opcode), []) + base = ctypes.addressof(buf) + tei = w.TRACE_EVENT_INFO.from_buffer(buf) + + def s(off: int) -> str: + return ctypes.wstring_at(base + off).strip() if off else "" + + pname = s(tei.ProviderNameOffset) or self.provider_names.get(guid_le, gstr) + task, opname = s(tei.TaskNameOffset), s(tei.OpcodeNameOffset) + arr = base + ctypes.sizeof(w.TRACE_EVENT_INFO) + props, slow, fast = [], [], True + for i in range(tei.TopLevelPropertyCount): + epi = w.EVENT_PROPERTY_INFO.from_address(arr + i * ctypes.sizeof(w.EVENT_PROPERTY_INFO)) + name = s(epi.NameOffset) + fl = epi.Flags + p = dc.Prop(name, epi.InType, _fmt(pname, name, epi.InType, epi.OutType)) + pdd = w.PROPERTY_DATA_DESCRIPTOR(base + epi.NameOffset, 0xFFFFFFFF, 0) + if fl & w.PropertyStruct: + fast = False # struct: slow path, field kept as one hex blob + slow.append((dc.Prop(name, dc.IN_BINARY), pdd)) + continue + slow.append((p, pdd)) + if fl & w.PropertyParamCount or epi.Count > 1 or epi.InType not in dc.SUPPORTED: + fast = False + elif epi.InType in (dc.IN_UNICODESTRING, dc.IN_ANSISTRING) and (fl & w.PropertyParamLength or epi.Length): + fast = False # counted strings: let TDH cut them + elif epi.InType == dc.IN_BINARY: + if fl & w.PropertyParamLength: + p = dc.Prop(name, epi.InType, p.fmt, length_index=epi.Length) + elif epi.Length: + p = dc.Prop(name, epi.InType, p.fmt, length=epi.Length) + else: + fast = False + props.append(p) + return EventPlan(gstr, pname, event_name(task, opname, d.Opcode, d.Id), d.Opcode, + opcode_label(opname, d.Opcode), props if fast else None, slow, buf) diff --git a/src/etw-python/src/etwcollect/selftest.py b/src/etw-python/src/etwcollect/selftest.py new file mode 100644 index 0000000..6b600ba --- /dev/null +++ b/src/etw-python/src/etwcollect/selftest.py @@ -0,0 +1,395 @@ +"""selftest.py - `etwcollect selftest` (any OS) and `etwcollect selftest --live` (Windows, elevated). + +A selftest proves "it runs", never "it captures everything" (CLAUDE.md §6). What each part checks: + offline decode of a synthetic payload (every in-type we use, IPv4/port, length-prefixed binary, early end); + EventName rule + timestamp; exclusion rules (a)-(c); whole-line batching; the Loki shipper against a + fake Loki (labels, metadata, event-time timestamps, resume from offsets, retry, refusal, meta line, + ledger); our lines through the real converter (etw2nodlink.py) when it can be found. + --live struct sizes vs the C headers; a real 15 s ETW session: a child process + a canary file must show + up, nothing from our own PID may be written, the converter turns the capture into edges. +""" +from __future__ import annotations + +import gzip +import importlib.util +import json +import os +import struct +import subprocess +import sys +import tempfile +import threading +import time +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +from . import decode as dc +from . import record +from .filters import Excluder, image_base +from .loki import LokiClient, Shipper, push_ledger, ts_ns +from .writer import LineWriter + +KP, KF, KN = ("Microsoft-Windows-Kernel-" + x for x in ("Process", "File", "Network")) + + +def check(cond, what: str) -> None: + if not cond: + raise AssertionError(what) + print(f" ok {what}") + + +# --------------------------------------------------------------------------- fake Loki +class FakeLoki: + """POST /loki/api/v1/push only. fail_next = n -> the next n pushes answer `code`.""" + + def __init__(self): + self.entries, self.fail_next, self.code = [], 0, 500 + fake = self + + class H(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + raw = self.rfile.read(int(self.headers["Content-Length"])) + if fake.fail_next > 0: + fake.fail_next -= 1 + self.send_response(fake.code) + self.send_header("Content-Length", "4") + self.end_headers() + self.wfile.write(b"nope") + return + if self.headers.get("Content-Encoding") == "gzip": + raw = gzip.decompress(raw) + for s in json.loads(raw)["streams"]: + for v in s["values"]: + fake.entries.append((int(v[0]), s["stream"], v[1], v[2] if len(v) > 2 else {})) + self.send_response(204) + self.end_headers() + + self.srv = ThreadingHTTPServer(("127.0.0.1", 0), H) + self.url = f"http://127.0.0.1:{self.srv.server_port}" + threading.Thread(target=self.srv.serve_forever, daemon=True).start() + + def close(self): + self.srv.shutdown() + + +class _Plan: # stands in for schema.EventPlan + def __init__(self, prov, name, opcode=0, opname="Info"): + self.provider_guid = {KP: "22fb2cd6-0e7b-422b-a0c7-2fad1fd0e716", KF: "edd08927-9cc4-4e65-b970-c2560fb5c289", + KN: "7dd42a49-5329-4832-8dfd-43d979153a88"}[prov] + self.provider_name, self.event_name, self.opcode, self.opcode_name = prov, name, opcode, opname + + +def _ft(sec_from_base: float) -> int: + """FILETIME for 2026-10-26T08:00:00Z + sec.""" + return dc.FILETIME_UNIX + int((1_793_001_600 + sec_from_base) * 10_000_000) + + +def _line(prov, name, pid, pname, sec, props, opcode=0, opname="Info") -> bytes: + hdr = {"ts": _ft(sec), "tid": 1, "pid": pid, "pname": pname, "ptr": 8, "len": 0} + return record.line(record.build(_Plan(prov, name, opcode, opname), hdr, props)) + + +# --------------------------------------------------------------------------- offline parts +def t_decode(): + print("decode") + sid = bytes([1, 1, 0, 0, 0, 0, 0, 5]) + struct.pack("H", 443) + + struct.pack(" task name") + check(record.event_name("ProcessStart", "Start", 1, 1) == "ProcessStart/Start", "task/opcode") + check(record.event_name("KERNEL_NETWORK_TASK_TCPIP", "Data sent.", 10, 10) == "KERNEL_NETWORK_TASK_TCPIP/Datasent.", + "spaces dropped like TraceEvent") + check(record.event_name("", "", 0, 77) == "EventID(77)", "no task -> EventID(n)") + ev = json.loads(_line(KF, "Create", 420, "explorer", 1.5, {"FileObject": "0xaa"})) + check(list(ev) == ["ProviderGuid", "YaraMatch", "ProviderName", "EventName", "Opcode", "OpcodeName", "TimeStamp", + "ThreadID", "ProcessID", "ProcessName", "PointerSize", "EventDataLength", "XmlEventData"], + "SilkETW key order") + check(ev["TimeStamp"] == "2026-10-26T08:00:01.5000000+00:00" and ts_ns(ev["TimeStamp"]) == (1_793_001_601_500_000_000), + "timestamp 7 digits, UTC, round-trips to ns") + check(ts_ns("2026-10-26T15:00:00.1234567+07:00") == 1_793_001_600_123_456_700, "+07:00 offset handled") + check(image_base("\\Device\\HarddiskVolume4\\Windows\\System32\\msedge.exe") == "msedge", "image name without .exe") + + +def t_filters(): + print("filters") + own = r"\device\harddiskvolume4\lab-out\etw\raw" + "\\" + ex = Excluder({999}, ("alloy",), [own, r"\device\harddiskvolume4\programdata\etwlab\collector-status.json"]) + check(ex.header("kproc", 999) and not ex.header("kproc", 4), "(a) own PID dropped before decode") + ours = r"\Device\HarddiskVolume4\lab-out\etw\raw\test\live-1\kfile.json" + check(ex.kfile("Create", 999, {"FileObject": "0xA1", "FileName": ours}), "(b) our own Create dropped, handle learned") + check(ex.kfile("Write", 999, {"FileObject": "0xa1", "FileKey": "0xK1"}), "(b) our Write dropped, file key learned") + check(ex.kfile("Write", 4, {"FileObject": "0xB2", "FileKey": "0xk1"}), "(b) System lazy write of our file dropped (key)") + check(not ex.kfile("Create", 77, {"FileObject": "0xa1", "FileName": r"\Device\HarddiskVolume4\tmp\x.txt"}), + "a reused file object for another file is kept ...") + check(not ex.kfile("Read", 77, {"FileObject": "0xa1", "FileKey": "0xk9"}), "... and forgotten") + check(ex.kfile("Read", 5, {"FileObject": "0xc3", + "FileName": r"\device\harddiskvolume4\programdata\etwlab\collector-status.json"}) is False + and ex.kfile("Create", 5, {"FileObject": "0xc3", + "FileName": r"\device\harddiskvolume4\programdata\etwlab\collector-status.json"}), + "exact own file matched, its folder is not") + ex.note_process(420, "alloy-windows-amd64") + check(ex.knet({"PID": "420"}) and ex.knet({"PID": "999"}) and not ex.knet({"PID": "7172"}), "(c) payload PID decides") + ex.note_process(420, "notepad") + check(not ex.knet({"PID": "420"}), "a reused PID of another image is no longer excluded") + check(ex.counts["kfile.own_file"] == 4 and ex.counts["knet.net_pid"] == 2, "counters") + + +def t_writer(tmp): + print("writer") + w = LineWriter(os.path.join(tmp, "w"), ["kfile"]) + w.add("kfile", b'{"a":1}\n') + w.add("kfile", b'{"a":2}\n') + check(os.path.getsize(w.paths["kfile"]) == 0, "nothing on disk before the 1 s flush") + check(w.flush() == 2 and open(w.paths["kfile"], "rb").read() == b'{"a":1}\n{"a":2}\n', "one write, whole lines") + w.close() + + +def t_shipper(tmp): + print("shipper (fake Loki)") + fake = FakeLoki() + try: + run = os.path.join(tmp, "raw", "test", "live-1") + os.makedirs(run) + p = os.path.join(run, "kfile.json") + a = _line(KF, "Create", 420, "explorer", 1, {"FileObject": "0xaa"}) + b = _line(KF, "Write", 420, "explorer", 2, {"FileObject": "0xaa"}) + c = _line(KF, "Read", 7, "N/A", 3, {"FileObject": "0xbb"}) + with open(p, "wb") as fh: + fh.write(a + b + c[:20]) # third line half written + pos = os.path.join(tmp, "pos.json") + sh = Shipper(LokiClient(fake.url), pos, "ws-etw", log=lambda *_: None) + sh.track(p) + check(sh.step() == 2 and len(fake.entries) == 2, "whole lines shipped, the half line waits") + t, lab, line, meta = fake.entries[0] + check(lab == {"job": "silketw", "host": "ws-etw", "split": "test", "run": "live-1", "provider": "kfile"}, + "labels = Alloy's (job, host, split, run, provider)") + check(meta == {"event": "Create", "pid": "420", "process": "explorer"} and line == a.decode().rstrip("\n"), + "structured metadata + unchanged line") + check(t == 1_793_001_601 * 1_000_000_000, "entry timestamp = event time") + with open(p, "ab") as fh: + fh.write(c[20:]) + fake.fail_next, fake.code = 1, 503 + check(sh.step() == 0 and len(fake.entries) == 2, "Loki 503: offset kept") + sh.backoff_until = 0 + check(sh.step() == 1 and len(fake.entries) == 3, "retried after backoff") + sh2 = Shipper(LokiClient(fake.url), pos, "ws-etw", log=lambda *_: None) + check(sh2.step() == 0 and len(fake.entries) == 3, "restart resumes from the saved offset: no duplicates") + check(sh2.push_meta("test", "live-1", {"\\device\\harddiskvolume4": "c:"}) and + sh2.push_meta("test", "live-1", {}) and len(fake.entries) == 4 and fake.entries[3][1]["job"] == "etw-meta", + "dos-map line pushed once per run") + with open(p, "ab") as fh: + fh.write(b"not json\n") + fake.fail_next, fake.code = 1, 400 + check(sh2.step() == 0 and sh2.rejected == 1 and not any(sh2.backlog().values()), "Loki 400: batch skipped, no stall") + sh2.close_run(run) + check(sh2.drain(2) and sh2.step() == 0 and not sh2.state["files"], "closed run forgotten once shipped") + led = os.path.join(tmp, "labels") + os.makedirs(led) + with open(os.path.join(led, "ledger.csv"), "w", encoding="utf-8") as fh: + fh.write('"utc","scenario","action","target"\n"2026-10-26T08:00:05.0000000Z","notes","edit","x.txt"\n') + n0 = len(fake.entries) + check(push_ledger(LokiClient(fake.url), "ws-etw", "20261026T080000Z", led) == 2 + and fake.entries[n0 + 1][0] == 1_793_001_605 * 1_000_000_000 + and fake.entries[n0][1] == {"job": "workload-ledger", "host": "ws-etw", "exp": "20261026T080000Z"}, + "ledger rows pushed with their utc time") + finally: + fake.close() + + +def _find_converter() -> str | None: + here = os.path.dirname(os.path.abspath(__file__)) + for c in (os.environ.get("ETW2NODLINK"), + os.path.join(here, "..", "..", "..", "pipeline", "etw2nodlink.py"), # repo: src/pipeline + r"C:\ProgramData\etwlab\etw2nodlink.py"): # the VM copy (Ansible) + if c and os.path.exists(c): + return os.path.abspath(c) + return None + + +def _load_converter(path): + spec = importlib.util.spec_from_file_location("etw2nodlink", path) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def t_converter(tmp): + print("converter round-trip") + path = _find_converter() + if not path: + print(" skip etw2nodlink.py not found (set ETW2NODLINK=path)") + return + conv = _load_converter(path) + run = os.path.join(tmp, "conv", "raw", "train", "r1") + os.makedirs(run) + dev = "\\Device\\HarddiskVolume2" + lines = { + "kproc.json": [_line(KP, "ProcessStart/Start", 100, "explorer", 0, {"ProcessID": "4321", "ParentProcessID": "100", + "ImageName": dev + "\\Windows\\System32\\cmd.exe"}, 1, "Start"), + _line(KP, "ImageLoad", 4321, "cmd", 0.1, {"ProcessID": "4321", + "ImageName": dev + "\\Windows\\System32\\ntdll.dll"})], + "kfile.json": [_line(KF, "Create", 4321, "cmd", 1, {"FileObject": "0xaa", "FileName": dev + "\\tmp\\x.txt"}), + _line(KF, "Write", 4321, "cmd", 1.5, {"FileObject": "0xaa", "FileKey": "0xbb", "IOSize": "4096"})], + "knet.json": [_line(KN, "KERNEL_NETWORK_TASK_TCPIP/Datasent.", 0, "Idle", 3, {"PID": "4321", + "daddr": "93.184.216.34", "dport": "443", "size": "100"}, 10, "Datasent.")], + } + for fn, ls in lines.items(): + with open(os.path.join(run, fn), "wb") as fh: + fh.write(b"".join(ls)) + s = conv.convert(os.path.join(tmp, "conv", "raw"), "train", "SelfTest", os.path.join(tmp, "conv", "out"), + {"\\device\\harddiskvolume2": "c:"}) + check(s["edges"] == {"Start": 1, "Load": 1, "Write": 1, "Send": 1}, f"converter edges {s['edges']}") + with open(os.path.join(tmp, "conv", "out", "SelfTest_train_edges.csv"), encoding="utf-8") as fh: + send = [r for r in fh if ",Send," in r][0] + check(send.startswith("p4321_"), "Send edge hangs off the payload PID's process (not Idle)") + + +def offline() -> int: + with tempfile.TemporaryDirectory() as tmp: + try: + t_decode() + t_record() + t_filters() + t_writer(tmp) + t_shipper(tmp) + t_converter(tmp) + except AssertionError as e: + print(f" FAIL {e}") + print("[SELFTEST FAILED]") + return 1 + print("[SELFTEST OK] decode, record, filters, writer, shipper, converter round-trip") + return 0 + + +# --------------------------------------------------------------------------- live (Windows) +def live() -> int: + if os.name != "nt": + print("--live needs Windows (and an elevated shell)") + return 2 + import ctypes + from . import winapi as w + from .collector import Collector, Config + from .providers import Provider + from .session import RealtimeSession + rc = offline() + if rc: + return rc + print("live") + try: + sizes = {"EVENT_TRACE_PROPERTIES": (w.EVENT_TRACE_PROPERTIES, 120), "EVENT_RECORD": (w.EVENT_RECORD, 112), + "EVENT_TRACE_LOGFILEW": (w.EVENT_TRACE_LOGFILEW, 448), "TRACE_EVENT_INFO": (w.TRACE_EVENT_INFO, 112), + "EVENT_PROPERTY_INFO": (w.EVENT_PROPERTY_INFO, 24)} + for n, (t, size) in sizes.items(): + check(ctypes.sizeof(t) == size, f"sizeof({n}) == {size} (x64 C headers)") + root = tempfile.mkdtemp(prefix="etwcollect-") + out = os.path.join(root, "raw", "test", "selftest-live") + provs = [Provider("kproc", KP, "0x50"), Provider("kfile", KF, "0x380"), Provider("knet", KN, "0x30")] + cfg = Config(out_dir=out, split="test", run="selftest-live", providers=provs, raw_root=os.path.join(root, "raw"), + status_path=os.path.join(root, "status.json"), positions_path=os.path.join(root, "pos.json"), + push=False, session="etwlab-selftest") + col = Collector(cfg, log=lambda m: print(" " + m)) + th = threading.Thread(target=col.run, daemon=True) + th.start() + t0 = time.monotonic() + while col.state != "running" and th.is_alive() and time.monotonic() - t0 < 20: + time.sleep(0.2) + check(col.state == "running", "session started") + time.sleep(2) + child = subprocess.Popen(["cmd.exe", "/c", "whoami"], stdout=subprocess.DEVNULL) + child.wait() + # network: a child process (our own traffic is excluded) asks Loki on the trainer, if etwlab.json names it + url = None + try: + with open(r"C:\ProgramData\etwlab\etwlab.json", encoding="utf-8-sig") as fh: + url = json.load(fh).get("LokiUrl") + except (OSError, ValueError): + pass + net = subprocess.Popen(["curl.exe", "-s", "-m", "5", url + "/ready"], stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL) if url else None + if net: + net.wait() + # the canary file is written and read by a CHILD: our own file I/O is excluded by design (rule a) + canary = os.path.join(tempfile.gettempdir(), f"etwcollect-canary-{os.getpid()}.txt") + subprocess.run(["cmd.exe", "/c", f"echo canary> {canary} & type {canary}"], stdout=subprocess.DEVNULL) # TEMP: no spaces + time.sleep(8) + RealtimeSession.stop_by_name("etwlab-selftest") + th.join(60) + check(col.state == "stopped", "collector stopped and flushed") + + def lines(stem): + with open(os.path.join(out, stem + ".json"), encoding="utf-8") as fh: + return [json.loads(x) for x in fh if x.strip()] + kp, kf, kn = lines("kproc"), lines("kfile"), lines("knet") + print(f" lines kproc={len(kp)} kfile={len(kf)} knet={len(kn)} excluded={dict(col.ex.counts)} " + f"schemas={len(col.schemas.cache)} slow={col.slow_events} decode_errors={col.decode_errors} " + f"callback_errors={col.callback_errors} last_error={col.last_error}") + check(any(e["EventName"].startswith("ProcessStart") and e["XmlEventData"].get("ParentProcessID") == str(child.pid) + and e["XmlEventData"].get("ImageName", "").lower().endswith("whoami.exe") for e in kp), + f"ProcessStart of whoami.exe under our cmd.exe (pid {child.pid})") + check(col.names.get(child.pid) == "cmd", "cmd.exe named although its ProcessStart came from our own PID") + if net: + check(any(e["XmlEventData"].get("PID") == str(net.pid) for e in kn), + f"Kernel-Network events owned by curl.exe (pid {net.pid}, payload PID)") + sample = next(e for e in kn if e["XmlEventData"].get("PID") == str(net.pid)) + print(f" knet sample: {sample['EventName']} {sample['XmlEventData']}") + else: + print(" skip no LokiUrl in etwlab.json: Kernel-Network not exercised") + cname = os.path.basename(canary).lower() + check(any(e["EventName"].startswith("Create") and e["XmlEventData"].get("FileName", "").lower().endswith(cname) + for e in kf), "Create of the canary file") + check(any(e["EventName"] in ("Write", "Read") for e in kf), "file Read/Write events") + own = os.getpid() + check(not any(e["ProcessID"] == own for e in kp + kf), "nothing from our own PID was written") + check(col.ex.counts.get("kfile.self_pid", 0) + col.ex.counts.get("kfile.own_file", 0) > 0, + "our own file I/O was seen and dropped") + check(col.callback_errors == 0, "no callback errors") + conv = _find_converter() + if conv: + s = _load_converter(conv).convert(os.path.join(root, "raw"), "test", "SelfTestLive", os.path.join(root, "out"), + col.dmap) + print(f" converter: edges {s['edges']} unresolved {s['unresolved']} unmapped_top " + f"{dict(list(s['unmapped_top'].items())[:5])}") + check(s["edges"].get("Start", 0) >= 1 and s["edges"].get("Load", 0) >= 1, "converter: Start + Load edges") + print(f" capture kept in {root}") + os.remove(canary) + except AssertionError as e: + print(f" FAIL {e}") + print("[SELFTEST --live FAILED]") + return 1 + print("[SELFTEST --live OK] real session, child + canary seen, own I/O excluded") + return 0 + + +if __name__ == "__main__": + sys.exit(live() if "--live" in sys.argv else offline()) diff --git a/src/etw-python/src/etwcollect/session.py b/src/etw-python/src/etwcollect/session.py new file mode 100644 index 0000000..8810abf --- /dev/null +++ b/src/etw-python/src/etwcollect/session.py @@ -0,0 +1,111 @@ +"""session.py - one real-time ETW session: start it, enable the providers, consume events, query, stop. + +ETW in four calls (all in advapi32.dll): + StartTraceW(name, props) create a session = a set of kernel buffers events are written into + EnableTraceEx2(session, guid) tell a provider (e.g. Kernel-File) to write into it, filtered by keywords + OpenTraceW + ProcessTrace attach a consumer: ProcessTrace calls our callback once per event and + blocks until the session is stopped + ControlTraceW(name, STOP) from any process: stop the session; ProcessTrace then returns + +A session is named and outlives the process that started it: if the collector crashes, the session keeps +buffering. start() therefore stops an old session of the same name first. + +Buffers: BufferSize 256 KB x up to 512 buffers = up to 128 MB of kernel memory to absorb bursts while the +Python callback is busy. If they are all full, ETW drops events and counts them (EventsLost / +RealTimeBuffersLost, see query()); SilkService lost time instead of events because it fell behind itself. +""" +from __future__ import annotations + +import ctypes + +from . import winapi as w + + +class RealtimeSession: + def __init__(self, name: str, buffer_kb: int = 256, min_buffers: int = 64, max_buffers: int = 512, + flush_s: int = 1): + self.name = name + self.buffer_kb, self.min_buffers, self.max_buffers, self.flush_s = buffer_kb, min_buffers, max_buffers, flush_s + self.handle = w.TRACEHANDLE(0) + self.trace = w.TRACEHANDLE(w.INVALID_PROCESSTRACE_HANDLE) + self._cb = None # the ctypes callback object: must stay referenced while consuming + + def _props(self) -> tuple[ctypes.Array, "ctypes._Pointer"]: + """EVENT_TRACE_PROPERTIES followed by room for the session name, in one buffer (the API wants that).""" + size = ctypes.sizeof(w.EVENT_TRACE_PROPERTIES) + 2 * (len(self.name) + 1) + 2048 + buf = ctypes.create_string_buffer(size) + p = ctypes.cast(buf, w.PPROPS) + p.contents.Wnode.BufferSize = size + p.contents.Wnode.Flags = w.WNODE_FLAG_TRACED_GUID + p.contents.LoggerNameOffset = ctypes.sizeof(w.EVENT_TRACE_PROPERTIES) + return buf, p + + @staticmethod + def stop_by_name(name: str) -> dict | None: + """Stop a session by name from any process. Returns its final counters, None if it was not running.""" + s = RealtimeSession(name) + buf, p = s._props() + rc = w.ControlTraceW(0, name, p, w.EVENT_TRACE_CONTROL_STOP) + if rc == w.ERROR_WMI_INSTANCE_NOT_FOUND: + return None + w.check(rc, f"ControlTraceW(STOP {name})") + return s._counters(p) + + def start(self) -> bool: + """Create the session. Returns True if an old session of the same name had to be stopped first.""" + stale = False + for attempt in range(2): + buf, p = self._props() + p.contents.Wnode.ClientContext = 1 # timestamps from QPC, delivered as FILETIME + p.contents.LogFileMode = w.EVENT_TRACE_REAL_TIME_MODE + p.contents.BufferSize = self.buffer_kb + p.contents.MinimumBuffers = self.min_buffers + p.contents.MaximumBuffers = self.max_buffers + p.contents.FlushTimer = self.flush_s + rc = w.StartTraceW(ctypes.byref(self.handle), self.name, p) + if rc == w.ERROR_ALREADY_EXISTS and attempt == 0: + self.stop_by_name(self.name) + stale = True + continue + w.check(rc, f"StartTraceW({self.name})") + return stale + return stale + + def enable(self, guid, keywords: int, level: int = w.TRACE_LEVEL_VERBOSE) -> None: + g = w.GUID.from_uuid(guid) + rc = w.EnableTraceEx2(self.handle, ctypes.byref(g), w.EVENT_CONTROL_CODE_ENABLE_PROVIDER, level, + keywords, 0, 0, None) + w.check(rc, f"EnableTraceEx2({guid}, keywords={keywords:#x})") + + def consume(self, callback) -> int: + """Blocks: callback(POINTER(EVENT_RECORD)) runs on THIS thread for every event until the session + stops. Returns ProcessTrace's status (0 or ERROR_CANCELLED after a normal stop).""" + lf = w.EVENT_TRACE_LOGFILEW() + lf.LoggerName = self.name + lf.ProcessTraceMode = w.PROCESS_TRACE_MODE_REAL_TIME | w.PROCESS_TRACE_MODE_EVENT_RECORD + self._cb = w.EVENT_RECORD_CALLBACK(callback) + lf.EventRecordCallback = self._cb + self.trace = w.TRACEHANDLE(w.OpenTraceW(ctypes.byref(lf))) + if self.trace.value == w.INVALID_PROCESSTRACE_HANDLE: + raise OSError(ctypes.get_last_error(), f"OpenTraceW({self.name}) failed") + try: + return w.ProcessTrace(ctypes.byref(self.trace), 1, None, None) + finally: + w.CloseTrace(self.trace) + + @staticmethod + def _counters(p) -> dict: + c = p.contents + return {"events_lost": int(c.EventsLost), "realtime_buffers_lost": int(c.RealTimeBuffersLost), + "log_buffers_lost": int(c.LogBuffersLost), "buffers_written": int(c.BuffersWritten), + "buffers": int(c.NumberOfBuffers), "free_buffers": int(c.FreeBuffers)} + + def query(self) -> dict | None: + buf, p = self._props() + rc = w.ControlTraceW(0, self.name, p, w.EVENT_TRACE_CONTROL_QUERY) + if rc != 0: + return None + return self._counters(p) + + def stop(self) -> dict | None: + return self.stop_by_name(self.name) diff --git a/src/etw-python/src/etwcollect/winapi.py b/src/etw-python/src/etwcollect/winapi.py new file mode 100644 index 0000000..f714b14 --- /dev/null +++ b/src/etw-python/src/etwcollect/winapi.py @@ -0,0 +1,236 @@ +"""winapi.py - the ctypes declarations for the Windows ETW / TDH / process APIs we call. Windows only. + +ctypes lets Python call C functions in Windows DLLs directly. A C struct is declared as a ctypes.Structure +whose _fields_ list the members IN ORDER with their C types; ctypes then lays them out in memory exactly like +the C compiler would (same sizes, same alignment padding), so a pointer to it can be passed to Windows. +Byte sizes are given in the comments ([n B]) because the layout must match the C headers exactly +(evntrace.h, evntcons.h, tdh.h, tlhelp32.h). + +Java analogy: like JNA's Structure classes. Nothing here runs any logic; session.py / schema.py / +procnames.py use these declarations. +""" +from __future__ import annotations + +import ctypes +from ctypes import wintypes + +ULONG, USHORT, UCHAR = ctypes.c_ulong, ctypes.c_ushort, ctypes.c_ubyte +ULONG64 = LONGLONG = ctypes.c_uint64 +TRACEHANDLE = ctypes.c_uint64 + +# ---------------------------------------------------------------- constants (evntrace.h / evntcons.h) +WNODE_FLAG_TRACED_GUID = 0x00020000 +EVENT_TRACE_REAL_TIME_MODE = 0x00000100 +EVENT_TRACE_CONTROL_QUERY, EVENT_TRACE_CONTROL_STOP, EVENT_TRACE_CONTROL_FLUSH = 0, 1, 3 +EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1 +TRACE_LEVEL_VERBOSE = 5 +PROCESS_TRACE_MODE_REAL_TIME = 0x00000100 +PROCESS_TRACE_MODE_EVENT_RECORD = 0x10000000 +INVALID_PROCESSTRACE_HANDLE = 0xFFFFFFFFFFFFFFFF +EVENT_HEADER_FLAG_32_BIT_HEADER = 0x0020 +EVENT_HEADER_FLAG_64_BIT_HEADER = 0x0040 + +ERROR_SUCCESS = 0 +ERROR_INSUFFICIENT_BUFFER = 122 +ERROR_ALREADY_EXISTS = 183 +ERROR_CANCELLED = 1223 +ERROR_WMI_INSTANCE_NOT_FOUND = 4201 + +# tdh.h PROPERTY_FLAGS +PropertyStruct, PropertyParamLength, PropertyParamCount = 0x1, 0x2, 0x4 +PropertyParamFixedLength, PropertyParamFixedCount = 0x10, 0x20 + + +class GUID(ctypes.Structure): # [16 B] + _fields_ = [("Data1", ULONG), ("Data2", USHORT), ("Data3", USHORT), ("Data4", UCHAR * 8)] + + @classmethod + def from_uuid(cls, u) -> "GUID": + return cls.from_buffer_copy(u.bytes_le) + + +class WNODE_HEADER(ctypes.Structure): # [48 B] + _fields_ = [("BufferSize", ULONG), ("ProviderId", ULONG), ("HistoricalContext", ULONG64), + ("TimeStamp", LONGLONG), ("Guid", GUID), ("ClientContext", ULONG), ("Flags", ULONG)] + + +class EVENT_TRACE_PROPERTIES(ctypes.Structure): # [120 B], the session name follows it in the same buffer + _fields_ = [("Wnode", WNODE_HEADER), ("BufferSize", ULONG), ("MinimumBuffers", ULONG), + ("MaximumBuffers", ULONG), ("MaximumFileSize", ULONG), ("LogFileMode", ULONG), + ("FlushTimer", ULONG), ("EnableFlags", ULONG), ("AgeLimit", ctypes.c_long), + ("NumberOfBuffers", ULONG), ("FreeBuffers", ULONG), ("EventsLost", ULONG), + ("BuffersWritten", ULONG), ("LogBuffersLost", ULONG), ("RealTimeBuffersLost", ULONG), + ("LoggerThreadId", wintypes.HANDLE), ("LogFileNameOffset", ULONG), ("LoggerNameOffset", ULONG)] + + +class EVENT_DESCRIPTOR(ctypes.Structure): # [16 B] + _fields_ = [("Id", USHORT), ("Version", UCHAR), ("Channel", UCHAR), ("Level", UCHAR), + ("Opcode", UCHAR), ("Task", USHORT), ("Keyword", ULONG64)] + + +class EVENT_HEADER(ctypes.Structure): # [80 B] + _fields_ = [("Size", USHORT), ("HeaderType", USHORT), ("Flags", USHORT), ("EventProperty", USHORT), + ("ThreadId", ULONG), ("ProcessId", ULONG), ("TimeStamp", LONGLONG), ("ProviderId", GUID), + ("EventDescriptor", EVENT_DESCRIPTOR), ("ProcessorTime", ULONG64), ("ActivityId", GUID)] + + +class ETW_BUFFER_CONTEXT(ctypes.Structure): # [4 B] + _fields_ = [("ProcessorNumber", UCHAR), ("Alignment", UCHAR), ("LoggerId", USHORT)] + + +class EVENT_RECORD(ctypes.Structure): # [112 B] what the callback receives (a pointer to it) + _fields_ = [("EventHeader", EVENT_HEADER), ("BufferContext", ETW_BUFFER_CONTEXT), + ("ExtendedDataCount", USHORT), ("UserDataLength", USHORT), ("ExtendedData", ctypes.c_void_p), + ("UserData", ctypes.c_void_p), ("UserContext", ctypes.c_void_p)] + + +EVENT_RECORD_CALLBACK = ctypes.WINFUNCTYPE(None, ctypes.POINTER(EVENT_RECORD)) + + +class EVENT_TRACE_HEADER(ctypes.Structure): # [48 B] (legacy, only sized here: part of EVENT_TRACE) + _fields_ = [("Size", USHORT), ("FieldTypeFlags", USHORT), ("Version", ULONG), ("ThreadId", ULONG), + ("ProcessId", ULONG), ("TimeStamp", LONGLONG), ("Guid", GUID), ("ProcessorTime", ULONG64)] + + +class EVENT_TRACE(ctypes.Structure): + _fields_ = [("Header", EVENT_TRACE_HEADER), ("InstanceId", ULONG), ("ParentInstanceId", ULONG), + ("ParentGuid", GUID), ("MofData", ctypes.c_void_p), ("MofLength", ULONG), + ("ClientContext", ULONG)] + + +class SYSTEMTIME(ctypes.Structure): # [16 B] + _fields_ = [(n, wintypes.WORD) for n in ("wYear", "wMonth", "wDayOfWeek", "wDay", "wHour", "wMinute", + "wSecond", "wMilliseconds")] + + +class TIME_ZONE_INFORMATION(ctypes.Structure): # [172 B] + _fields_ = [("Bias", ctypes.c_long), ("StandardName", wintypes.WCHAR * 32), ("StandardDate", SYSTEMTIME), + ("StandardBias", ctypes.c_long), ("DaylightName", wintypes.WCHAR * 32), + ("DaylightDate", SYSTEMTIME), ("DaylightBias", ctypes.c_long)] + + +class TRACE_LOGFILE_HEADER(ctypes.Structure): + _fields_ = [("BufferSize", ULONG), ("Version", ULONG), ("ProviderVersion", ULONG), + ("NumberOfProcessors", ULONG), ("EndTime", LONGLONG), ("TimerResolution", ULONG), + ("MaximumFileSize", ULONG), ("LogFileMode", ULONG), ("BuffersWritten", ULONG), + ("LogInstanceGuid", GUID), ("LoggerName", ctypes.c_void_p), ("LogFileName", ctypes.c_void_p), + ("TimeZone", TIME_ZONE_INFORMATION), ("BootTime", LONGLONG), ("PerfFreq", LONGLONG), + ("StartTime", LONGLONG), ("ReservedFlags", ULONG), ("BuffersLost", ULONG)] + + +class EVENT_TRACE_LOGFILEW(ctypes.Structure): # what OpenTraceW gets: which session, which callback + _fields_ = [("LogFileName", wintypes.LPWSTR), ("LoggerName", wintypes.LPWSTR), + ("CurrentTime", LONGLONG), ("BuffersRead", ULONG), ("ProcessTraceMode", ULONG), + ("CurrentEvent", EVENT_TRACE), ("LogfileHeader", TRACE_LOGFILE_HEADER), + ("BufferCallback", ctypes.c_void_p), ("BufferSize", ULONG), ("Filled", ULONG), + ("EventsLost", ULONG), ("EventRecordCallback", EVENT_RECORD_CALLBACK), + ("IsKernelTrace", ULONG), ("Context", ctypes.c_void_p)] + + +# ---------------------------------------------------------------- TDH (tdh.h): the event's schema +class TRACE_EVENT_INFO(ctypes.Structure): # [112 B] + EVENT_PROPERTY_INFO[PropertyCount] + strings + _fields_ = [("ProviderGuid", GUID), ("EventGuid", GUID), ("EventDescriptor", EVENT_DESCRIPTOR), + ("DecodingSource", ctypes.c_int), ("ProviderNameOffset", ULONG), ("LevelNameOffset", ULONG), + ("ChannelNameOffset", ULONG), ("KeywordsNameOffset", ULONG), ("TaskNameOffset", ULONG), + ("OpcodeNameOffset", ULONG), ("EventMessageOffset", ULONG), ("ProviderMessageOffset", ULONG), + ("BinaryXMLOffset", ULONG), ("BinaryXMLSize", ULONG), ("EventNameOffset", ULONG), + ("EventAttributesOffset", ULONG), ("PropertyCount", ULONG), ("TopLevelPropertyCount", ULONG), + ("Flags", ULONG)] + + +class EVENT_PROPERTY_INFO(ctypes.Structure): # [24 B] one field of the payload + _fields_ = [("Flags", ctypes.c_int), ("NameOffset", ULONG), + ("InType", USHORT), ("OutType", USHORT), ("MapNameOffset", ULONG), # (union: non-struct view) + ("Count", USHORT), ("Length", USHORT), ("Reserved", ULONG)] + + +class PROPERTY_DATA_DESCRIPTOR(ctypes.Structure): # [16 B] "give me property " for TdhGetProperty + _fields_ = [("PropertyName", ULONG64), ("ArrayIndex", ULONG), ("Reserved", ULONG)] + + +# ---------------------------------------------------------------- processes (tlhelp32.h) +TH32CS_SNAPPROCESS = 0x2 +PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + + +class PROCESSENTRY32W(ctypes.Structure): + _fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD), ("th32ProcessID", wintypes.DWORD), + ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", wintypes.DWORD), + ("cntThreads", wintypes.DWORD), ("th32ParentProcessID", wintypes.DWORD), + ("pcPriClassBase", ctypes.c_long), ("dwFlags", wintypes.DWORD), ("szExeFile", wintypes.WCHAR * 260)] + + +# ---------------------------------------------------------------- function prototypes +advapi32 = ctypes.WinDLL("advapi32", use_last_error=True) +tdh = ctypes.WinDLL("tdh", use_last_error=True) +kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + +PPROPS = ctypes.POINTER(EVENT_TRACE_PROPERTIES) + +StartTraceW = advapi32.StartTraceW +StartTraceW.argtypes = [ctypes.POINTER(TRACEHANDLE), wintypes.LPCWSTR, PPROPS] +StartTraceW.restype = ULONG + +ControlTraceW = advapi32.ControlTraceW +ControlTraceW.argtypes = [TRACEHANDLE, wintypes.LPCWSTR, PPROPS, ULONG] +ControlTraceW.restype = ULONG + +EnableTraceEx2 = advapi32.EnableTraceEx2 +EnableTraceEx2.argtypes = [TRACEHANDLE, ctypes.POINTER(GUID), ULONG, UCHAR, ULONG64, ULONG64, ULONG, ctypes.c_void_p] +EnableTraceEx2.restype = ULONG + +OpenTraceW = advapi32.OpenTraceW +OpenTraceW.argtypes = [ctypes.POINTER(EVENT_TRACE_LOGFILEW)] +OpenTraceW.restype = TRACEHANDLE + +ProcessTrace = advapi32.ProcessTrace +ProcessTrace.argtypes = [ctypes.POINTER(TRACEHANDLE), ULONG, ctypes.c_void_p, ctypes.c_void_p] +ProcessTrace.restype = ULONG + +CloseTrace = advapi32.CloseTrace +CloseTrace.argtypes = [TRACEHANDLE] +CloseTrace.restype = ULONG + +TdhGetEventInformation = tdh.TdhGetEventInformation +TdhGetEventInformation.argtypes = [ctypes.POINTER(EVENT_RECORD), ULONG, ctypes.c_void_p, ctypes.c_void_p, + ctypes.POINTER(ULONG)] +TdhGetEventInformation.restype = ULONG + +TdhGetPropertySize = tdh.TdhGetPropertySize +TdhGetPropertySize.argtypes = [ctypes.POINTER(EVENT_RECORD), ULONG, ctypes.c_void_p, ULONG, + ctypes.POINTER(PROPERTY_DATA_DESCRIPTOR), ctypes.POINTER(ULONG)] +TdhGetPropertySize.restype = ULONG + +TdhGetProperty = tdh.TdhGetProperty +TdhGetProperty.argtypes = [ctypes.POINTER(EVENT_RECORD), ULONG, ctypes.c_void_p, ULONG, + ctypes.POINTER(PROPERTY_DATA_DESCRIPTOR), ULONG, ctypes.c_void_p] +TdhGetProperty.restype = ULONG + +CreateToolhelp32Snapshot = kernel32.CreateToolhelp32Snapshot +CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD] +CreateToolhelp32Snapshot.restype = wintypes.HANDLE +Process32FirstW = kernel32.Process32FirstW +Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)] +Process32FirstW.restype = wintypes.BOOL +Process32NextW = kernel32.Process32NextW +Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)] +Process32NextW.restype = wintypes.BOOL +OpenProcess = kernel32.OpenProcess +OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] +OpenProcess.restype = wintypes.HANDLE +QueryFullProcessImageNameW = kernel32.QueryFullProcessImageNameW +QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)] +QueryFullProcessImageNameW.restype = wintypes.BOOL +CloseHandle = kernel32.CloseHandle +CloseHandle.argtypes = [wintypes.HANDLE] +CloseHandle.restype = wintypes.BOOL +QueryDosDeviceW = kernel32.QueryDosDeviceW +QueryDosDeviceW.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD] +QueryDosDeviceW.restype = wintypes.DWORD + +INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value + + +def check(code: int, what: str) -> None: + if code != ERROR_SUCCESS: + raise OSError(code, f"{what} failed: {ctypes.FormatError(code).strip()} ({code})") diff --git a/src/etw-python/src/etwcollect/writer.py b/src/etw-python/src/etwcollect/writer.py new file mode 100644 index 0000000..a90fe24 --- /dev/null +++ b/src/etw-python/src/etwcollect/writer.py @@ -0,0 +1,52 @@ +"""writer.py - batched line writer: one write + flush per provider file per second. + +SilkService opened, wrote and closed its file for every single event (File.AppendAllText), so every event +cost a Create + Write of its own. Here the ETW callback only appends bytes to a list (cheap, in memory); a +timer thread calls flush() once a second, which writes the whole batch with one write() and flush(). +Each batch ends on a full line, so a reader (the shipper) never sees half a line. + + w = LineWriter(r"C:\\lab-out\\etw\\raw\\test\\live-20261026T080000Z", ["kproc", "kfile", "knet"]) + w.add("kfile", b'{"ProviderName":...}\\n') # from the ETW callback thread + w.flush() # from the timer thread: kfile.json grows by whole lines +""" +from __future__ import annotations + +import os +import threading + + +class LineWriter: + def __init__(self, out_dir: str, stems: list[str]): + os.makedirs(out_dir, exist_ok=True) + self.dir = out_dir + self.paths = {s: os.path.join(out_dir, s + ".json") for s in stems} + # "ab": binary append; the file is opened ONCE for the whole run. + self.fh = {s: open(p, "ab") for s, p in self.paths.items()} + self.pending: dict[str, list[bytes]] = {s: [] for s in stems} + self.lines = {s: 0 for s in stems} # lines written so far + self.bytes = {s: 0 for s in stems} + self.lock = threading.Lock() + + def add(self, stem: str, line: bytes) -> None: + with self.lock: + self.pending[stem].append(line) + + def flush(self) -> int: + with self.lock: # swap the lists out, write without holding the lock + batches, self.pending = self.pending, {s: [] for s in self.pending} + n = 0 + for stem, lines in batches.items(): + if not lines: + continue + blob = b"".join(lines) + self.fh[stem].write(blob) + self.fh[stem].flush() + self.lines[stem] += len(lines) + self.bytes[stem] += len(blob) + n += len(lines) + return n + + def close(self) -> None: + self.flush() + for fh in self.fh.values(): + fh.close() diff --git a/src/etw-python/tools/parity.py b/src/etw-python/tools/parity.py new file mode 100644 index 0000000..a68f8fe --- /dev/null +++ b/src/etw-python/tools/parity.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""parity.py - compare an etwcollect capture with a SilkService capture of the SAME minutes (migration check). + +Both collectors can record at the same time: ETW lets several sessions enable one provider. Run SilkService +(etwctl, Collector=silketw) and `etwcollect run --no-push --out-dir C:\\lab-out\\etw\\parity\\test\\p1` together +for a few minutes, stop both, then: + + python tools/parity.py --silk C:\\lab-out\\etw\\raw\\test\\ --ours C:\\lab-out\\etw\\parity\\test\\p1 + +Events are paired per (provider, ThreadID) in time order, within --tol-ms: both sessions see the same events +in the same order per thread, but TraceEvent derives its timestamps its own way (sub-ms differences), so an +exact timestamp key does not match. For matched events it compares the fields the converter reads, +after undoing SilkETW's formatting: + "4,096" -> 4096 · daddr "-1,707,025,385" (little-endian int32) -> 23.220.64.154 · + dport "-17,663" (network-order u16 read as int16) -> 443 · knet owner PID: SilkETW `_PID` vs ours `PID`. +Unmatched events are grouped by process name: SilkService's own events (and Alloy's) are expected on the +SilkETW side only, ours should hold nothing SilkETW lacks except the window edges. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import struct +import sys +from collections import Counter, defaultdict + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "src")) +from etwcollect.loki import ts_ns # noqa: E402 + +FIELDS = {"kproc": ["ProcessID", "ParentProcessID", "ImageName"], + "kfile": ["FileObject", "FileKey", "FileName", "IOSize"], + "knet": ["PID", "daddr", "dport", "size"]} + + +def num(v): + s = str(v).replace(",", "").strip() + try: + return int(s, 16) if s.lower().startswith("0x") else int(s) + except ValueError: + return s.lower() + + +def silk_norm(stem: str, d: dict) -> dict: + out = {} + for f in FIELDS[stem]: + src = "_PID" if (stem == "knet" and f == "PID") else f + v = d.get(src) + if v is None: + continue + if stem == "knet" and f == "daddr" and re.fullmatch(r"-?[\d,]+", str(v)): + v = ".".join(str(b) for b in struct.pack("H", struct.pack(" dict: + return {f: (num(d[f]) if f not in ("daddr", "FileName", "ImageName") else str(d[f]).lower()) + for f in FIELDS[stem] if f in d} + + +def first_ts(path: str) -> int | None: + with open(path, encoding="utf-8-sig", errors="replace") as fh: + for line in fh: + try: + return ts_ns(json.loads(line)["TimeStamp"]) + except (ValueError, KeyError): + continue + return None + + +def load(path: str, lo: int, hi: int) -> list[dict]: + """Events with lo <= ts <= hi only (streamed: captures can be hundreds of MB).""" + out = [] + with open(path, encoding="utf-8-sig", errors="replace") as fh: + for line in fh: + try: + e = json.loads(line) + if lo <= ts_ns(e["TimeStamp"]) <= hi: + x = e.get("XmlEventData") or {} + keep = set(FIELDS["kproc"] + FIELDS["kfile"] + FIELDS["knet"] + ["_PID"]) + out.append({k: e.get(k) for k in ("ThreadID", "TimeStamp", "EventName", "ProcessID", "ProcessName")} + | {"XmlEventData": {k: v for k, v in x.items() if k in keep}}) + except (ValueError, KeyError): + pass + return out + + +def compare(silk_dir: str, ours_dir: str, seconds: float = 60, skip: float = 5, tol_ms: float = 5) -> dict: + report = {} + for stem in ("kproc", "kfile", "knet"): + sp, op = os.path.join(silk_dir, stem + ".json"), os.path.join(ours_dir, stem + ".json") + if not (os.path.exists(sp) and os.path.exists(op)): + report[stem] = {"missing": [p for p in (sp, op) if not os.path.exists(p)]} + continue + f1, f2 = first_ts(sp), first_ts(op) + if f1 is None or f2 is None: + report[stem] = {"empty": [p for p, f in ((sp, f1), (op, f2)) if f is None]} + continue + lo = max(f1, f2) + int(skip * 1e9) # both running, past the start-up + hi = lo + int(seconds * 1e9) + silk, ours = load(sp, lo, hi), load(op, lo, hi) + tol = int(tol_ms * 1e6) + threads = defaultdict(lambda: ([], [])) + for e in silk: + threads[int(e.get("ThreadID", 0))][0].append(e) + for e in ours: + threads[int(e.get("ThreadID", 0))][1].append(e) + pairs, silk_only, used = [], Counter(), set() + offsets = [] + for a_list, b_list in threads.values(): + a_list.sort(key=lambda e: ts_ns(e["TimeStamp"])) + b_list.sort(key=lambda e: ts_ns(e["TimeStamp"])) + i = j = 0 + while i < len(a_list) and j < len(b_list): + ta, tb = ts_ns(a_list[i]["TimeStamp"]), ts_ns(b_list[j]["TimeStamp"]) + if abs(ta - tb) <= tol: + pairs.append((a_list[i], b_list[j])) + offsets.append(tb - ta) + used.add(id(b_list[j])) + i, j = i + 1, j + 1 + elif ta < tb: + silk_only[a_list[i].get("ProcessName", "?")] += 1 + i += 1 + else: + j += 1 + for e in a_list[i:]: + silk_only[e.get("ProcessName", "?")] += 1 + matched, mism, names, pname = 0, Counter(), Counter(), Counter() + examples = defaultdict(list) + for e, o in pairs: + matched += 1 + if e.get("EventName") != o.get("EventName"): + names[(e.get("EventName"), o.get("EventName"))] += 1 + if e.get("ProcessID") != o.get("ProcessID"): + mism["header ProcessID"] += 1 + if e.get("ProcessName") != o.get("ProcessName") and e.get("ProcessName") != "N/A": + pname[(e.get("ProcessName"), o.get("ProcessName"))] += 1 + a, b = silk_norm(stem, e.get("XmlEventData") or {}), ours_norm(stem, o.get("XmlEventData") or {}) + for f in FIELDS[stem]: + if f in a and a.get(f) != b.get(f): + mism[f] += 1 + if len(examples[f]) < 3: + examples[f].append({"silk": a.get(f), "ours": b.get(f), "event": e.get("EventName")}) + ours_only = Counter(o.get("ProcessName", "?") for o in ours if id(o) not in used) + offsets.sort() + report[stem] = {"window_utc": [lo, hi], "silk": len(silk), "ours": len(ours), "matched": matched, + "ts_offset_us_median": round(offsets[len(offsets) // 2] / 1000, 1) if offsets else None, + "matched_of_ours": round(matched / len(ours), 4) if ours else None, + "field_mismatch": dict(mism), "examples": dict(examples), + "event_name_diff": {f"{k[0]} | {k[1]}": v for k, v in names.most_common(10)}, + "process_name_diff": {f"{k[0]} | {k[1]}": v for k, v in pname.most_common(10)}, + "silk_only_by_process": dict(silk_only.most_common(10)), + "ours_only_by_process": dict(ours_only.most_common(10))} + return report + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("--silk", required=True, help="SilkService run folder (kproc/kfile/knet.json)") + ap.add_argument("--ours", required=True, help="etwcollect run folder") + ap.add_argument("--json", help="also write the report here") + ap.add_argument("--seconds", type=float, default=60, help="compare this many seconds of event time") + ap.add_argument("--skip", type=float, default=5, help="start this many seconds after both began") + ap.add_argument("--tol-ms", type=float, default=5, help="max timestamp difference of a pair") + a = ap.parse_args() + rep = compare(a.silk, a.ours, a.seconds, a.skip, a.tol_ms) + text = json.dumps(rep, indent=1, default=str) + print(text) + if a.json: + with open(a.json, "w", encoding="utf-8") as fh: + fh.write(text) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/etw-python/uv.lock b/src/etw-python/uv.lock new file mode 100644 index 0000000..d2c51c5 --- /dev/null +++ b/src/etw-python/uv.lock @@ -0,0 +1,8 @@ +version = 1 +revision = 3 +requires-python = ">=3.12" + +[[package]] +name = "etwcollect" +version = "0.1.0" +source = { editable = "." } diff --git a/src/pipeline/etw2nodlink.py b/src/pipeline/etw2nodlink.py index be9ceb4..a3e0f69 100644 --- a/src/pipeline/etw2nodlink.py +++ b/src/pipeline/etw2nodlink.py @@ -238,7 +238,10 @@ def on_write(self, t, d, hpid, hname): self._file_io(t, d, hpid, hname, "Write") def _net(self, t, d, hpid, hname, etype): - pid = first(num(d.get("pid")), hpid) + # The owner is the PAYLOAD PID. The header PID of a network event is whatever thread ran (Idle, System, + # any process: 77 % mismatch on 2026-10-25). SilkETW wrote the payload field as `_PID` and a header copy + # as `PID`; etwcollect writes the payload field as `PID` (DEVIATIONS D8, D10). + pid = first(num(d.get("_pid")), num(d.get("pid")), hpid) daddr, dport = d.get("daddr"), num(d.get("dport")) proc = self.proc(pid, hname if pid == hpid else "") if proc is None or not daddr: @@ -323,7 +326,10 @@ def ev(prov, name, pid, pname, ts, **data): ev(kf, "Read", 888, "alloy", "2026-10-07T10:00:02.3000000Z", FileObject="0xDD")], "knet.json": [ ev(kn, "KERNEL_NETWORK_TASK_TCPIP/Datasent.", 4, "System", "2026-10-07T10:00:03.0000000Z", - PID="4321", daddr="93.184.216.34", dport="443", size="100")], + PID="4321", daddr="93.184.216.34", dport="443", size="100"), + # SilkETW's shape: header PID = Idle, `PID` = its header copy, `_PID` = the real owner + ev(kn, "KERNEL_NETWORK_TASK_TCPIP/Datareceived.", 0, "Idle", "2026-10-07T10:00:03.5000000Z", + PID="0", _PID="4,321", daddr="-1,707,025,385", dport="-17,663", size="64")], } with tempfile.TemporaryDirectory() as tmp: run = os.path.join(tmp, "raw", "train", "run1") @@ -338,9 +344,12 @@ def ev(prov, name, pid, pname, ts, **data): with open(os.path.join(tmp, "out", "SelfTest_train_node_attrs.csv"), encoding="utf-8") as fh: attrs = fh.read() # excluded: SilkService's Write + Alloy's Read; the dos map turns \device\harddiskvolume2 into c: - ok = (s["edges"] == {"Start": 1, "Load": 1, "Write": 1, "Send": 1} and s["excluded"] == {"Write": 1, "Read": 1} + recv = [r for r in rows if r[4] == "Recv"] + ok = (s["edges"] == {"Start": 1, "Load": 1, "Write": 1, "Send": 1, "Recv": 1} + and s["excluded"] == {"Write": 1, "Read": 1} and "c:\\windows\\system32\\ntdll.dll" in attrs - and sum(s["unmapped_top"].values()) == 1 and rows[0] == EDGE_HEADER and len(rows) == 5) + and len(recv) == 1 and recv[0][0].startswith("p4321_") # owner from _PID, not Idle's header PID + and sum(s["unmapped_top"].values()) == 1 and rows[0] == EDGE_HEADER and len(rows) == 6) print("selftest", "OK" if ok else "FAILED", json.dumps(s["edges"])) return 0 if ok else 1 diff --git a/src/scripts/07-build-train-dataset.ps1 b/src/scripts/07-build-train-dataset.ps1 index 12921a1..bb7f1de 100644 --- a/src/scripts/07-build-train-dataset.ps1 +++ b/src/scripts/07-build-train-dataset.ps1 @@ -10,7 +10,7 @@ 2. capture etwctl start -Split train -Run x- -> settle -> 06-benign-workload.ps1 -> etwctl stop (called from the workload's -BeforeLedger hook, so the ledger write happens AFTER the capture and is not in the data) - 3. collect copy the run's raw JSON into \raw\train\x-\ (Alloy has shipped it to Loki) + 3. collect copy the run's raw JSON into \raw\train\x-\ (the collector has shipped it to Loki) 4. convert etw2nodlink.py on \raw only -> \converted\ (un-windowed, + _summary.json) 5. window etwwindow.py -> \ SimulatedW10_train_edges.csv pooled windows, node IDs prefixed w0007_ <- host: encode_to_features.py @@ -28,7 +28,7 @@ .NOTES Run in an ELEVATED PowerShell inside the VM's RDP/console desktop (not vagrant powershell / WinRM). - Elevation is needed for SilkService; the workload still starts apps through explorer.exe, so they run + Elevation is needed for the ETW collector; the workload still starts apps through explorer.exe, so they run un-elevated with explorer as parent, like a real user. Needs etwwindow.py, installed by the win_collector Ansible role. #> @@ -40,7 +40,7 @@ param( [ValidateRange(1, 120)] [int] $StrideMinutes = 2, [ValidateRange(10, 3600)] [int] $MaxGapSeconds = 120, [ValidateRange(0, 600)] [int] $SettleSeconds = 30, # idle capture before the workload starts - [ValidateRange(0, 600)] [int] $ShipWaitSeconds = 15, # after the stop: let Alloy push the tail to Loki + [ValidateRange(0, 600)] [int] $ShipWaitSeconds = 15, # after the stop: let the tail reach Loki [switch] $IncludeUserPowerShell, [switch] $AllowFallbackLauncher, # accept powershell.exe as app parent (not advised) [switch] $KeepWorkDir, # default: empty Documents\work so every run starts equal @@ -257,7 +257,7 @@ function Complete-Experiment([string]$Exp, [System.Collections.IDictionary]$Reco Write-Json (Join-Path $Exp 'experiment.json') $Record if ($rc -ne 0) { throw "contract check FAILED - see $Exp\check.json (files kept for inspection)" } Log ("done {0} windows, {1} edges, {2} node copies -> {3}" -f $t.windows, $t.edges_out, $t.node_window_copies, $Exp) - Log "next on the trainer: lab loop (Alloy has shipped this capture to Loki)" + Log "next on the trainer: lab loop (the collector has shipped this capture to Loki)" } if ($PostProcess) { @@ -284,15 +284,17 @@ if (-not (Test-Path $WorkloadScript)) { throw "workload script not found: $Workl if (-not (Get-Command $WorkloadScript).Parameters.ContainsKey('BeforeLedger')) { throw "$WorkloadScript has no -BeforeLedger parameter - apply the 2-line patch first" } -$svc = Get-Service $Cfg.ServiceName +# `etwctl running` exits 0 while a capture runs (etwcollect task or SilkService, whichever etwlab.json names). +& $EtwctlPs1 running | Out-Null +$capturing = ($LASTEXITCODE -eq 0) # The always-on live capture (start-live.ps1 watchdog, test/live-*) is paused below, right before the train # capture starts. Any other running capture (train, or a hand-started test run) still stops us here. $StateFile = Join-Path $LabDir 'state.json' $HoldFile = Join-Path $LabDir 'live.hold' $cur = if (Test-Path $StateFile) { Get-Content $StateFile -Raw | ConvertFrom-Json } else { $null } -$liveRunning = $svc.Status -eq 'Running' -and $cur -and $cur.split -eq 'test' -and "$($cur.run)" -like 'live-*' -if ($svc.Status -ne 'Stopped' -and -not $liveRunning) { - throw "$($Cfg.ServiceName) is $($svc.Status): another capture is running ('etwctl stop' first)" +$liveRunning = $capturing -and $cur -and $cur.split -eq 'test' -and "$($cur.run)" -like 'live-*' +if ($capturing -and -not $liveRunning) { + throw "another capture is running ($($cur.split)/$($cur.run)): 'etwctl stop' first" } $expected = [math]::Floor(($DurationMinutes - $WindowMinutes) / $StrideMinutes) + 1 if ($expected -lt 1) { throw "-DurationMinutes $DurationMinutes is shorter than one $WindowMinutes-min window" } @@ -340,14 +342,15 @@ $stopCapture = { } }.GetNewClosure() -# Hold file: the start-live.ps1 watchdog (SYSTEM task, every few minutes) leaves SilkService alone while it +# Hold file: the start-live.ps1 watchdog (SYSTEM task, every few minutes) leaves the collector alone while it # exists. Written BEFORE the live run is stopped, so a watchdog tick cannot restart live in between; removed # in the finally below, so live resumes within one tick after the train capture. Our $PID lets the watchdog # drop the hold if this PowerShell dies without running the finally. $hold = [ordered]@{ pid = $PID; by = '07-build-train-dataset.ps1'; since_utc = (Utc-Now) } Set-Content -Path $HoldFile -Value ($hold | ConvertTo-Json -Compress) try { - if ((Get-Service $Cfg.ServiceName).Status -ne 'Stopped') { + & $EtwctlPs1 running | Out-Null + if ($LASTEXITCODE -eq 0) { Log 'pause the always-on live capture (start-live.ps1 resumes it after this capture)' & $EtwctlPs1 stop | Out-Host } @@ -370,16 +373,26 @@ finally { # also runs on Ctrl+C o Remove-Item $HoldFile -Force -ErrorAction SilentlyContinue # live capture resumes at the next watchdog tick } +# ---------------------------------------------------------------- 2b. workload ledger -> Loki (etwcollect) +# The ledger is written AFTER the capture stopped (-BeforeLedger), so the collector cannot ship it; Alloy used +# to tail labels\*.csv. loki_pull.py on the trainer finds it as {job="workload-ledger", exp=}. +if ("$($Cfg.Collector)" -ne 'silketw') { + Log "ledger $(Join-Path $exp 'labels') -> Loki" + & $Cfg.EtwPython -m etwcollect push-ledger --exp $stamp --dir (Join-Path $exp 'labels') | Out-Host + if ($LASTEXITCODE) { Write-Warning "ledger push failed; re-run: & '$($Cfg.EtwPython)' -m etwcollect push-ledger --exp $stamp --dir '$(Join-Path $exp 'labels')'" } +} + # ---------------------------------------------------------------- 3. collect raw into the experiment $src = Join-Path $Cfg.RawRoot "$Split\$run" $dst = Join-Path $exp "raw\$Split\$run" if (-not (Test-Path $src)) { throw "raw run folder not found: $src" } Log "collect $src -> $dst" -# COPY, not move: Grafana Alloy tails $src and ships it to Loki (the training source on the trainer); it -# needs a few seconds after the stop for the last lines, and moving files it holds open would fail. -Log "wait ${ShipWaitSeconds}s for Alloy to ship the last lines to Loki" +# COPY, not move: the collector's shipper (or Alloy with collector=silketw) reads $src to ship it to Loki (the +# training source on the trainer); etwctl stop already waited for etwcollect's final push, Alloy needs a few +# seconds after the stop, and moving files that are still open would fail. +Log "wait ${ShipWaitSeconds}s for the last lines to reach Loki" Start-Sleep -Seconds $ShipWaitSeconds -# robocopy /E = cp -r (keep the source for Alloy); exit codes 0-7 mean success +# robocopy /E = cp -r (keep the source for the shipper); exit codes 0-7 mean success Invoke-Native 'robocopy.exe' @($src, $dst, '/E', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') -Ok (0..7) | Out-Null $rec.capture.raw = $dst Write-Json (Join-Path $exp 'experiment.json') $rec From 51284881fdfb44488a6eb025f7f4205e4d433980 Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Tue, 27 Oct 2026 07:35:13 +0700 Subject: [PATCH 5/8] Remove SilkService and Alloy after verifying etwcollect on ws-etw etwcollect (src/etw-python) passed on ws-etw: live selftest, 20 s parity with SilkService (kproc 620/620, kfile 88,612/88,612, knet 26/26, 0 field mismatches), a 32-min lag test (kfile within +-4 s, EventsLost 0, ~10 % of a core) and a Loki outage drain (Loki counts == file lines). So the win_alloy role goes, win_collector uninstalls SilkService/SilkETW and Alloy, etwctl/start-live/07 use the collector task, verify-windows asserts both are gone, and the docs (CLAUDE.md, DEVIATIONS D10, PROGRESS, READMEs, report, slides) describe the new collector. CLAUDE.md section 8 lists the next steps: benign capture with 07, exp04, then the DVWA->RCE full flow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VCx5NxSphANRKqvrtUUw3W --- CLAUDE.md | 21 ++- README.md | 6 +- docs/DEVIATIONS.md | 27 +++- docs/PROGRESS.md | 72 ++++++---- docs/notes/silkservice-kfile-lag.md | 18 ++- latex/contents.tex | 8 +- presentation/slides.md | 4 +- src/README.md | 2 +- src/ansible/README.md | 22 ++- src/ansible/group_vars/all.yml | 20 +-- src/ansible/roles/win_alloy/handlers/main.yml | 6 - src/ansible/roles/win_alloy/tasks/main.yml | 80 ----------- .../roles/win_alloy/templates/config.alloy.j2 | 128 ------------------ .../roles/win_collector/files/etwctl.ps1 | 70 +++------- .../roles/win_collector/tasks/main.yml | 111 ++++++--------- .../win_collector/templates/etwlab.json.j2 | 3 - .../win_shipper/templates/start-live.ps1.j2 | 11 +- src/ansible/verify-windows.yml | 33 +---- src/ansible/windows.yml | 9 +- src/etw-python/src/etwcollect/cli.py | 4 +- src/etw-python/src/etwcollect/collector.py | 6 +- src/etw-python/src/etwcollect/filters.py | 2 +- src/live/README.md | 10 +- src/live/loki_push.py | 4 +- src/live/loki_source.py | 4 +- src/pipeline/etw2nodlink.py | 5 +- src/pipeline/loki_pull.py | 6 +- src/pipeline/lokiclient.py | 2 +- src/scripts/07-build-train-dataset.ps1 | 15 +- 29 files changed, 213 insertions(+), 496 deletions(-) delete mode 100644 src/ansible/roles/win_alloy/handlers/main.yml delete mode 100644 src/ansible/roles/win_alloy/tasks/main.yml delete mode 100644 src/ansible/roles/win_alloy/templates/config.alloy.j2 diff --git a/CLAUDE.md b/CLAUDE.md index 87d2855..cd15fc1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -118,10 +118,18 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum deepseek`) live: benign stays green, the DVWA→RCE attack goes red and gets an LLM attack verdict + report. The first run (2026-10-25) is blocked by the collector: SilkService writes Kernel-File events minutes late (its own per-event file writes feed back into Kernel-File), so live windows have no file events (DEVIATIONS - D8 correction, `docs/notes/silkservice-kfile-lag.md`). Fix (user, 2026-10-26): replace SilkService AND - Alloy with our own Python ETW collector `src/etw-python` (it pushes to Loki itself); once verified, remove - both completely (D10). Then capture benign data with it, train exp04, re-run. - Then: the browser false positive, the replay equivalence check, understanding the trainer (concepts 2–4). + D8 correction, `docs/notes/silkservice-kfile-lag.md`). Fixed (user, 2026-10-26): our own Python ETW collector + `src/etw-python` (`etwcollect`, pushes to Loki itself) replaced SilkService AND Alloy, verified on `ws-etw` and + both removed (D10, PROGRESS). exp03 does not match the new data (other collector, fixed NET owners), so + live windows are red until a new model exists; that is not a detection result. +- Next step (user, 2026-10-27), in order; details and gates in PROGRESS "Next 3 steps": + 1. Benign train capture with etwcollect: `07-build-train-dataset.ps1` from the RDP desktop, browsing + included (browser FP). First real use of `etwctl` by 07 and of `etwcollect push-ledger`: check the + ledger reaches Loki. Gate on `lab status` coverage and Read/Write per window. + 2. `lab loop` → `exp04` → `lab promote exp04`; `ocr-live` restarts on it; benign live windows stay green. + 3. Full flow: DVWA→RCE from Kali during a live session → attack window red, LLM triage `attack` + report + (DeepSeek); laptop replay. + Then: the replay equivalence check, understanding the trainer (concepts 2–4). - Data: the user's own Windows 10 audit data (ETW), shaped to match the NODLINK simulated Windows 10 (W10) host format the repo expects. The graph is named `SimulatedW10` because the repo asserts host names. @@ -146,8 +154,7 @@ history of earlier progress) and, if relevant, this section. 2026-10-17): edges stay CSV and Alg. 1 runs in memory. - Log transport (user, 2026-10-26, superseding the 2026-10-17 Alloy decision): our collector (`src/etw-python`, `etwcollect`) pushes its SilkETW-format JSON lines to Loki (Docker, host network) on - the Ubuntu trainer itself, from its own run files with saved offsets; Grafana Alloy is removed once the - collector is verified. Labels unchanged: job (`silketw`, it names the line format), host, split, run, + the Ubuntu trainer itself, from its own run files with saved offsets (Grafana Alloy removed 2026-10-26). Labels unchanged: job (`silketw`, it names the line format), host, split, run, provider; event/pid/process as structured metadata. Training pulls from Loki by run or time range (`loki_pull.py`); the live server follows Loki (`--loki-url`). All conversion, windowing and scoring run on the trainer with the training converter code, scaler and relation list; the live clock is event time @@ -191,7 +198,7 @@ history of earlier progress) and, if relevant, this section. - VM side (Ansible roles in `src/ansible/roles/`): `win_base`, `win_collector` (uv + `src/etw-python` collector as SYSTEM task `etwlab-collector`, `etwctl`, copies `src/pipeline/etw2nodlink.py` / `etwwindow.py` / `src/live/etwship.py`; the collector source is the Vagrant mount `C:\etw-python` locally - and a git clone on cloud; SilkETW and `win_alloy` stay installed only until the collector is verified), + and a git clone on cloud; it also removes the old SilkETW/SilkService and Grafana Alloy), `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), `win_benign` (`src/scripts/06-benign-workload`, `07-build-train-dataset`), `win_vulnlab` (XAMPP + DVWA). - Improve loop: `lab` CLI (`src/lab/cli.py`, console script; `source .venv/bin/activate`): `lab loop` diff --git a/README.md b/README.md index d05ade0..c3dc56f 100644 --- a/README.md +++ b/README.md @@ -30,14 +30,14 @@ ACM CCS 2025), built as a live demo. **Not a full reproduction** of the paper. S ```mermaid flowchart LR - subgraph VM["Windows 10 VM · 10.21.2.10"] - A["SilkETW
kernel events"] --> B["shipper"] + subgraph VM["Windows Server VM · 10.21.2.10"] + A["etwcollect
kernel events (ETW)"] --> B["shipper
(push to Loki)"] end subgraph H["Linux host · 10.21.2.1:8000"] C["graph +
5-min windows"] --> D["OCRGCN
node scores"] --> E["Alg. 1 subgraphs
+ score filter"] --> F["alert in web UI"] E -.-> G["LLM verdict + report
(optional)"] -.-> F end - B -- "HTTP" --> C + B -- "HTTP · Loki" --> C ``` ## Quick start (no VM needed) diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index a7c62da..00fbc60 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -240,17 +240,32 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. `PName`, `TID`, header `PID`) inside `XmlEventData`; - exclusion **before** formatting, counted: events of its own PID; Read/Write on file objects whose Create named a path under the raw output root (any process, incl. System lazy writes); knet events - whose payload PID is excluded. During the switch also Alloy's PID; + whose payload PID is excluded; Read/Write on ETW's own real-time spill file for the session (System writes it); - one batched write per provider per second instead of one file open per event; - it pushes its own files to Loki (saved offsets, retry), with the labels/metadata/timestamps Alloy used, - plus the dos-map line and the 07 workload ledger. Alloy is removed once this is verified. + plus the dos-map line and the 07 workload ledger. SilkService and Alloy were removed from `ws-etw` the + same day, after the checks below (`win_collector` uninstalls them). + - Verified on `ws-etw` (2026-10-26): + - parity: SilkService and etwcollect side by side, 20 s window: kproc 620/620, kfile 88,612/88,612 (the 76 + SilkETW-only lines are our own process), knet 26/26 events matched, 0 field mismatches after undoing + SilkETW's formatting (`tools/parity.py`); our timestamps are 0.13–0.18 ms earlier than TraceEvent's; + - 32-min live run with generated activity (~1,300 kfile events/s): kfile lag within ±4 s throughout + (negative values = ETW timestamps a few seconds ahead of the system clock), `EventsLost` 0, collector CPU + ~9–11 % of one core; Loki stopped for 2 min mid-run: 69 MB backlog, shipped within ~7 min of the + restart; Loki per-provider counts = file line counts exactly (2,629,621 lines); the live engine got + ~374k Read edges per 5-min window (SilkService runs: 0). - Why: SilkService's per-event writes feed back into Kernel-File faster than it can drain them, and it has no exclude filter (keep-only, one value) and no batching (`docs/notes/silkservice-kfile-lag.md`); live windows had no file events (D8 correction). Own code is also fully explainable. - Impact: raw lines differ in formatting from earlier captures, and process names of short-lived processes are real instead of `N/A`, so earlier experiments (exp01–exp03) are not comparable; a new benign capture + retrain (exp04) is required. The converter output contract is unchanged. Excluded events - are gone from the raw data (counts in `collector-status.json`); an attacker binary named like the - collector's or Alloy's process is not affected (PID-based, not name-based, except Alloy during the switch). -- Limits: collector correctness is shown only by the parity check against SilkService and the lag/lossless - checks (PROGRESS); no claim that it captures every kernel event (`EventsLost` is reported, not prevented). + are gone from the raw data (counts in `collector-status.json`); exclusion is by PID and by our own file + paths, not by name, so a binary named like the collector is still recorded. Anything written under the raw + output root (`C:\lab-out\etw\raw`) by any process is dropped: an attacker hiding files there is invisible. + Fields the manifest marks as hex (IOSize, ByteOffset, CreateOptions) are written as `0x..`. Live: a Loki + outage longer than the engine's idle fallback makes the backlog arrive after its windows closed (dropped as + late, D8); the files and Loki still hold every line. +- Limits: collector correctness is shown by the parity check against SilkService (one 20 s window) and the + lag/lossless checks on one 32-min run with generated (not workload) activity; no claim that it captures + every kernel event (`EventsLost` is reported, not prevented). diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index a163b28..d5a2686 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -8,11 +8,12 @@ The "widen benign + calibrate" cycle ran on **1 HOUR** of benign data (not 2): k `x-20261022T140932Z` → `exp03` trained + promoted → live DVWA→RCE attack. Work is on branch **`collect-benign-data-for-1-hour`**. The full flow with LLM support ran live on 2026-10-25 (branch `make-sure-to-support-llm-investigator`) and exposed a **collector blocker**: SilkService writes Kernel-File -events far behind real time, so the live engine drops every file event as late. Cause found 2026-10-26: its -per-event file writes feed back into Kernel-File (`docs/notes/silkservice-kfile-lag.md`). **Now (user, -2026-10-26): build our own Python collector `src/etw-python` that also pushes to Loki, verify it, then remove -SilkService and Alloy completely** (DEVIATIONS D10, plan in Next 3 steps). No live detection result so far is -valid (DEVIATIONS D8 correction). +events far behind real time, so the live engine drops every file event as late. Cause: its per-event file +writes feed back into Kernel-File (`docs/notes/silkservice-kfile-lag.md`). **Fixed 2026-10-26: our own Python +collector `src/etw-python` (`etwcollect`, pushes to Loki itself) is verified on `ws-etw`, and SilkService + +Alloy are removed** (DEVIATIONS D10, Done below). The always-on live capture now runs on it. **Now:** a benign +train capture with the new collector (07, from the RDP desktop) → `exp04` → full flow (Next 3 steps). No live +detection result so far is valid (DEVIATIONS D8 correction); exp03 does not match the new data (D10). DONE this session (2026-10-22, verified live): - **exp03** trained on the 1-h capture and **PROMOTED** (gate passed: 77-min kfile span, all 6 edge types @@ -39,13 +40,14 @@ DONE 2026-10-25 (verified live): reproduces the live windows that were not affected by late kfile lines, and the same LLM verdict. OPEN (the real limitation): -- **kfile lag (blocker)**: SilkService falls behind on Kernel-File from a fresh run (9+ min behind after - 25 min; the "~20–25 % of real time" figure does not fit that, re-measure), ~1 CPU core; cause verified in - its source: `File.AppendAllText` per event → ≥ 2 Kernel-File events of its own per line (224k of 300k kfile - lines are SilkService's, 45k Alloy's). Fix in progress: own collector (D10). -- **NET attribution bug** (verified 2026-10-26): 77 % of knet events have header PID ≠ payload PID; - `etw2nodlink._net()` uses the header copy (`XmlEventData.PID`), not the owner (`_PID`). Every capture so - far, exp03 included, has mostly wrong NET edges. Converter fix (prefer `_pid`) is part of the D10 work. +- **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 outages: after a Loki outage 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 + clock (status compares against wall time). Harmless for windows; not investigated further. - **Browser benign FP**: an Edge-browsing benign window hit **31.0** (Moderate, false alarm). msedge's many per-instance processes are unseen in benign training → the *same* mechanism as the cradle. The fix is benign **variety** (training that covers browsing), **not** more capture time. DEVIATIONS D8, @@ -56,6 +58,24 @@ OPEN (the real limitation): ## Done +- **Own ETW collector `etwcollect`** (`src/etw-python`, 2026-10-26, verified on `ws-etw`, DEVIATIONS D10): + stdlib + ctypes, one real-time session (Kernel-Process 0x50 / File 0x380 / Network 0x30), TDH decode, own + I/O dropped in the callback, 1 s batched writes, Loki shipper with saved offsets (replaces Alloy), ledger push + for 07. SYSTEM task `etwlab-collector` started/stopped by `etwctl`; local source = Vagrant mount `C:\etw-python`, + cloud = git clone. Checks: + - `etwcollect selftest` (any OS) + `selftest --live` on ws-etw (struct sizes, child process + canary file + + curl network event captured, nothing from our PID written, converter gives Start/Load/Read/Write/Send/Recv); + - parity vs SilkService side by side (20 s): 100 % of events matched for kproc 620, kfile 88,612, knet 26, 0 + field mismatches; SilkETW-only = our own 76 events; + - 32-min live run (~1,300 kfile ev/s generated activity): kfile lag within ±4 s, `EventsLost` 0, CPU ~10 % + of a core; Loki down 2 min → 69 MB backlog shipped within ~7 min; Loki counts = file lines (2,629,621); + live engine `late_dropped` 0 outside the outage, ~374k Read edges per window; + - Ansible: SilkService + Alloy uninstalled, `win_alloy` role deleted, 2nd `windows.yml` run `changed=0`, + `verify-windows.yml` passes (DVWA too). Repo-wide `./selftest.sh` 15/15. +- **NET attribution fix** (2026-10-26): 77 % of knet events have header PID ≠ payload PID; the converter now + takes the owner from `_PID` (SilkETW) / `PID` (etwcollect), selftest case added. Old captures are fixed on + re-conversion; models trained before (exp01–exp03) used the wrong owners. + - Windows 10 ETW lab VM + collector + converter, end to end (Ansible, `src/ansible/`) + `src/scripts/06, 07`. - Benign train dataset, experiment `20261009T145632Z` (verified, `src/out/etw/experiments/20261009T145632Z/`): 20-min capture, workload seed 42, launch mode explorer-com; 8 windows (5 min / 2 min stride); @@ -149,7 +169,7 @@ OPEN (the real limitation): ## Not done - Benign train capture (07) with the NEW collector (D10), pulled from Loki, train `exp04`, promote, - calibrate, attack-test. Blocked on the collector. Gate on `lab status` per-provider coverage (kfile ≈ full + calibrate, attack-test (Next 3 steps; the collector is ready). Gate on `lab status` per-provider coverage (kfile ≈ full span) and Read/Write per window before trusting it. - Run the RCE kill chain end to end against DVWA. DVWA provisioning is verified on `ws-etw` @@ -217,21 +237,15 @@ Repo hygiene: - `src/out/etw/SimulatedW10_train_edges.csv` (old un-windowed capture) sits next to the experiment folders and is easy to pick by mistake (it caused the first, collapsed exp01 run). -## Next 3 steps (own collector, then re-run the full flow — 2026-10-26) - -1. Build `src/etw-python` (`etwcollect`, uv, stdlib + ctypes): ETW session + TDH decode, self-exclusion, - batched writer, Loki shipper (replaces Alloy), ledger push; Linux `selftest`. Ansible: uv, mount - `C:\etw-python` locally / clone on cloud, SYSTEM task `etwlab-collector`, `etwctl` switch. -2. Verify on `ws-etw` with SilkService + Alloy still installed: - - `etwcollect selftest --live`; - - parity vs SilkService (3 min side by side, `tools/parity.py`); - - ≥ 30 min alone with the benign workload: Loki kfile lag < 20 s, `EventsLost` 0, CPU well under a core, - Loki counts = file lines, backlog recovers after a Loki outage; - - a 5-min build: all 6 edge types, Read/Write per window in the exp03 range; live `late_dropped` ≈ 0. - Then remove SilkService and Alloy completely (Ansible cleanup, docs, deliverables) + the converter - `_pid` fix. -3. 07 benign capture with the new collector → `exp04` → promote → full flow (benign green, attack nodes - flagged, LLM `attack` + report; laptop replay). Browser FP (benign variety) after that. +## Next 3 steps (new collector in place — 2026-10-26) + +1. Benign train capture with etwcollect: `07-build-train-dataset.ps1` from the RDP desktop (the first real use + of `etwctl` start/stop by 07 and of `etwcollect push-ledger`; check the ledger reaches Loki). Gate on + `lab status` coverage and Read/Write per window. Include browsing in the workload (browser FP). +2. `lab loop` → `exp04` → `lab promote exp04`; `ocr-live` restarts on it. Benign live windows should be green. +3. Full flow: DVWA→RCE from Kali during a live session: attack nodes flagged, LLM triage `attack` + report; + laptop replay as on 2026-10-25. Watch item: the first 15-min `07` run (`x-20261021T161810Z`) did not write `stopped_utc` (capture left -running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the service on the 2h run. +running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the collector task +(`etwctl running` exits 1 afterwards) on the 2h run. diff --git a/docs/notes/silkservice-kfile-lag.md b/docs/notes/silkservice-kfile-lag.md index 002399a..f7f7530 100644 --- a/docs/notes/silkservice-kfile-lag.md +++ b/docs/notes/silkservice-kfile-lag.md @@ -1,9 +1,8 @@ # Live windows have no file events: the SilkService kfile lag -Status as of 2026-10-26: cause found in the code. **Decision (user, 2026-10-26): replace SilkService and -Alloy with our own Python collector `src/etw-python`** (see "Decision" below, DEVIATIONS D10); not built yet. Measurements are from `ws-etw` on -2026-10-25 (DEVIATIONS D8 correction, PROGRESS "OPEN"). This note explains why the events go missing. -Fix options are at the end. +Status as of 2026-10-26: **resolved.** Our own Python collector `src/etw-python` (`etwcollect`) replaced +SilkService and Alloy, was verified on `ws-etw` and both were removed (DEVIATIONS D10; results in "Outcome" +at the end). Measurements of the problem are from `ws-etw` on 2026-10-25 (DEVIATIONS D8 correction). Tags: [OURS] what this project does · [INFERENCE] a guess · **SilkService code** = mandiant/SilkETW tag `v0.8` (the version we deploy, `src/ansible/group_vars/all.yml:48`), file `SilkService/ETWCollector.cs` @@ -227,3 +226,14 @@ does this today, so it isn't new, but it belongs in DEVIATIONS. 2. Check that `late_dropped` in `/api/status` stays ≈ 0. 3. Check that each live window's Read/Write counts are in the range of the exp03 training windows. 4. Check that SilkService's CPU is well below 1 core. + +## Outcome (2026-10-26, verified on `ws-etw`) + +- Parity with SilkService (both recording the same 20 s): every event matched (kproc 620, kfile 88,612, knet 26), + 0 field mismatches; the only SilkETW-only events were the collector's own. +- 32-minute live run at ~1,300 kfile events/s: kfile lag within ±4 s the whole time, `EventsLost` 0, collector + ~10 % of one core (SilkService: 1 core and minutes behind). Loki stopped for 2 minutes: the backlog was + shipped within ~7 minutes, and Loki's counts equal the file line counts exactly. +- The live engine received ~374k Read edges per 5-minute window, where SilkService runs gave 0. +- Remaining effect: a Loki outage longer than the live engine's idle fallback still makes the live windows of + the outage thin (late lines dropped, D8); the files and Loki are complete. diff --git a/latex/contents.tex b/latex/contents.tex index f7368a1..68f3959 100644 --- a/latex/contents.tex +++ b/latex/contents.tex @@ -556,7 +556,7 @@ \subsection{Hạ tầng lab và pipeline} \toprule \textbf{Máy} & \textbf{Hệ điều hành} & \textbf{Vai trò} \\ \midrule -\texttt{ws-etw} & Windows Server 2022 & Thu thập kernel log bằng SilkETW \cite{silketw} (Kernel-Process, Kernel-File, Kernel-Network); Grafana Alloy đẩy nguyên văn từng dòng log về Loki; benign workload có seed; dịch vụ web chưa vá làm mục tiêu tấn công. Không huấn luyện. \\ +\texttt{ws-etw} & Windows Server 2022 & Thu thập kernel log bằng collector Python tự viết \texttt{etwcollect} (Kernel-Process, Kernel-File, Kernel-Network) và tự đẩy nguyên văn từng dòng log về Loki; collector này thay SilkETW \cite{silketw} + Grafana Alloy, vì SilkETW ghi mỗi event bằng một lần mở file riêng nên tự sinh thêm Kernel-File event của chính nó (vòng lặp làm log file đến trễ nhiều phút); benign workload có seed; dịch vụ web chưa vá làm mục tiêu tấn công. Không huấn luyện. \\ \texttt{ubuntu-trainer} & Ubuntu 24.04 & Loki + Grafana \cite{grafana_loki}; chuyển đổi, cắt window, trích feature, huấn luyện; máy chủ demo trực tiếp (FastAPI + giao diện web). \\ \bottomrule \end{tabularx} @@ -568,8 +568,8 @@ \subsection{Hạ tầng lab và pipeline} \centering \begin{tikzpicture}[node distance=0.8cm and 0.9cm] % máy Windows: thu thập - \node[prep] (etw) at (0,0) {SilkETW\\ \scriptsize kernel log (process, file, mạng)}; - \node[prep] (alloy) at (0,-1.8) {Grafana Alloy\\ \scriptsize gửi nguyên văn từng dòng}; + \node[prep] (etw) at (0,0) {etwcollect (Python)\\ \scriptsize kernel log (process, file, mạng)}; + \node[prep] (alloy) at (0,-1.8) {Shipper của etwcollect\\ \scriptsize gửi nguyên văn từng dòng}; % máy Ubuntu: xử lý, phát hiện, hiển thị \node[prep] (loki) at (3.6,0) {Loki\\ \scriptsize kho log}; \node[prep] (s1) at (7.0,0) {Chuyển sang đồ thị + cắt window 5 phút}; @@ -648,7 +648,7 @@ \subsection{Dữ liệu và benign workload} \tagpaper{} OCR-APT được đánh giá trên các bộ dữ liệu công bố. \tagours{} Đồ án dùng dữ liệu tự thu thập vì mục tiêu là demo trực tiếp trên một máy thật: \begin{itemize} - \item \textbf{Thu thập:} SilkETW ghi ba kernel provider (process, file, mạng) dưới dạng JSON. Alloy đẩy nguyên văn từng dòng về Loki, gắn nhãn theo lần chạy và provider, nên dữ liệu huấn luyện có thể kéo lại theo lần chạy hoặc khoảng thời gian. + \item \textbf{Thu thập:} \texttt{etwcollect} (collector Python tự viết) ghi ba kernel provider (process, file, mạng) dưới dạng JSON theo định dạng dòng của SilkETW, bỏ I/O của chính nó trước khi ghi, và tự đẩy nguyên văn từng dòng về Loki, gắn nhãn theo lần chạy và provider, nên dữ liệu huấn luyện có thể kéo lại theo lần chạy hoặc khoảng thời gian. \item \textbf{Chuyển đổi:} một bộ chuyển đổi đưa sự kiện ETW về đúng lược đồ NODLINK Windows 10 mà mã gốc yêu cầu (3 loại node, 6 loại edge, mốc thời gian epoch mili-giây). Đồ thị được đặt tên \texttt{SimulatedW10} vì mã gốc kiểm tra tên host. \item \textbf{Định danh node:} process được khoá bằng PID + thời điểm khởi động, vì Windows tái sử dụng PID và nếu chỉ dùng PID thì hai process khác nhau sẽ bị gộp, làm sai thống kê thời gian nghỉ. File và luồng mạng được khoá bằng băm của đường dẫn / IP:cổng, nên định danh ổn định giữa huấn luyện và kiểm thử. \item \textbf{Benign workload:} một bộ sinh hoạt động có seed (mở trình duyệt, soạn thảo, truy cập mạng, \ldots). Ứng dụng được khởi chạy qua \texttt{explorer} (Shell COM) thay vì PowerShell, để mô hình không học ``PowerShell là cha bình thường của mọi thứ'', vì công cụ tấn công thường đi qua PowerShell. diff --git a/presentation/slides.md b/presentation/slides.md index 09fe17f..1d795d9 100644 --- a/presentation/slides.md +++ b/presentation/slides.md @@ -489,7 +489,7 @@ $$s_i = \|\mathbf{z}_i - \mathbf{c}\|_2^2 - R^2$$

-
ws-etw · Windows Server 2022: SilkETW (ghi ETW ra JSON; Kernel-Process, -File, -Network) + Grafana Alloy (agent thu log) gửi nguyên văn từng dòng; benign workload có seed; dịch vụ web chưa vá. Không huấn luyện.
+
ws-etw · Windows Server 2022: etwcollect (collector Python tự viết: ghi ETW ra JSON; Kernel-Process, -File, -Network) tự gửi nguyên văn từng dòng về Loki; benign workload có seed; dịch vụ web chưa vá. Không huấn luyện.
ubuntu-trainer · Ubuntu 24.04: Loki (kho lưu log) + Grafana (dashboard); chuyển đổi, cắt window, feature, huấn luyện; máy chủ demo (FastAPI + web UI). Cả hai máy dựng bằng Ansible, chuyển lên cloud được.
@@ -656,7 +656,7 @@ transition: fade
```powershell -# ws-etw (PowerShell quyền admin): bắt đầu một lần thu thập live; Alloy tự gửi về Loki +# ws-etw (PowerShell quyền admin): bắt đầu một lần thu thập live; etwcollect tự gửi về Loki C:\scripts\start-live.ps1 -Minutes 30 # Song song: benign workload (khởi chạy ứng dụng qua explorer) diff --git a/src/README.md b/src/README.md index 9f38b26..ed6d4a1 100644 --- a/src/README.md +++ b/src/README.md @@ -59,7 +59,7 @@ trained model is never overwritten. |---|---|---|---| | `Vagrantfile`, `setup-virtualbox.sh` | builds the two bare lab VMs (Windows collector + Ubuntu trainer) | host | yes | | `etw-python/` | the ETW collector `etwcollect` (uv project, stdlib + ctypes): ETW -> SilkETW-format lines -> Loki; mounted at `C:\etw-python` locally, cloned on cloud | VM | yes | -| `ansible/` | provisions both VMs (Windows: etw-python collector, vulnlab, SilkETW + Alloy until verified; Ubuntu: Loki/Grafana, repo, `ocr-live`); cloud-portable via inventory | control node | yes | +| `ansible/` | provisions both VMs (Windows: etw-python collector, vulnlab; Ubuntu: Loki/Grafana, repo, `ocr-live`); 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) | diff --git a/src/ansible/README.md b/src/ansible/README.md index 11cad71..def0c17 100644 --- a/src/ansible/README.md +++ b/src/ansible/README.md @@ -18,9 +18,8 @@ etwcollect (SYSTEM task) -> C:\lab-out\etw\raw\\\{kproc,kfile,knet}. live: live_server.py --loki-url (loki_source.py) -> windows -> UI :8000 ``` -Until `etwcollect` was verified (2026-10-26, DEVIATIONS D10) SilkService wrote the files and Grafana Alloy -shipped them; `collector: silketw` in `group_vars/all.yml` still selects that path until both are removed. -The Loki contract did not change: Loki keeps every line exactly as written, with these labels next to it: +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 | |---|---|---| @@ -64,13 +63,13 @@ sum by (provider) (count_over_time({job="silketw", run="live-20261017T040000Z"}[ > 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-17) +## Status (2026-10-26) | level | state | |---|---| -| it runs (static) | `--syntax-check` passes for every playbook; `alloy fmt` (v1.20.1) accepts the rendered `config.alloy`; 14/14 `./selftest.sh` steps pass | +| 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 | **not run yet**: `win_alloy` and the `etwctl` dos-map change are untested on `ws-etw`. Use the checklist below | +| Windows side | verified on `ws-etw` (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) @@ -78,7 +77,7 @@ sum by (provider) (count_over_time({job="silketw", run="live-20261017T040000Z"}[ 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 (Alloy → Loki). +- `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 @@ -119,7 +118,7 @@ continues. ## Run ```bash -# local lab (default inventory.local.ini, no vault needed). Ubuntu FIRST: Alloy needs Loki to push to. +# local lab (default inventory.local.ini, no vault needed). Ubuntu FIRST: etwcollect needs Loki to push to. vagrant up # from src/, builds both bare VMs ansible ubuntu -m ping ansible windows -m ansible.windows.win_ping # use win_ping on Windows, NOT ping @@ -141,8 +140,8 @@ Non-empty also makes `uv sync` install the `llm` group. The API key is never an 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. -After the Windows run, pin the download hashes the roles print (`silketw_sha256`, `python_embed_sha256` in -`group_vars/all.yml`). `alloy_sha256` and `uv_sha256` are already pinned from the releases' checksum files. +`python_embed_sha256` and `uv_sha256` in `group_vars/all.yml` are pinned (the latter from the release's +checksum file). **Collector source (`etwpy_mode`).** Local lab: `inventory.local.ini` sets `etwpy_mode=mount`, and `src/Vagrantfile` shares `src/etw-python` as `C:\etw-python` (needs `vagrant reload ws-etw` once). A host @@ -241,8 +240,7 @@ 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_collector uv + etw-python venv + SYSTEM task etwlab-collector + embeddable Python + etw2nodlink.py/ - etwwindow.py/etwship.py/etwctl (+ SilkETW/SilkService until etwcollect is verified) - win_alloy Grafana Alloy: stopped + disabled unless collector=silketw (removed after verification) + 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_benign 06-benign-workload.ps1 + 07-build-train-dataset.ps1 win_vulnlab XAMPP (Apache + PHP + MariaDB) + DVWA, served on vulnlab_port (opt-in: vulnlab_enabled) diff --git a/src/ansible/group_vars/all.yml b/src/ansible/group_vars/all.yml index c4a6e04..04c8a14 100644 --- a/src/ansible/group_vars/all.yml +++ b/src/ansible/group_vars/all.yml @@ -13,8 +13,8 @@ server_port: 8000 # The Ubuntu server binds all interfaces so it listens on the subnet IP whatever it is. server_bind: "0.0.0.0" -# ---- log pipeline: Alloy (Windows, native) -> Loki + Grafana (Docker, host network, on the trainer) -- -# Alloy pushes to loki_url; the live server and loki_pull.py read Loki on the trainer itself (127.0.0.1). +# ---- log pipeline: etwcollect (Windows) -> Loki + Grafana (Docker, host network, on the trainer) ------- +# etwcollect pushes to loki_url; the live server and loki_pull.py read Loki on the trainer itself (127.0.0.1). 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 }}" @@ -27,7 +27,7 @@ loki_stack_dir: "/opt/lokistack" # (local inventory for the lab; vault for cloud). Loki itself only accepts the Windows host's private_ip. # ---- lab clock ------------------------------------------------------------------------------------ -# Both VMs run on UTC+7. Safe for the pipeline: SilkETW writes the offset into every TimeStamp +# Both VMs run on UTC+7. Safe for the pipeline: every TimeStamp carries its offset (etwcollect writes UTC) # (e.g. "...+07:00"), labels/ledger/window IDs use UTC explicitly, so epoch ms do not depend on the zone. tz_windows: "SE Asia Standard Time" # Windows ID: (UTC+07:00) Bangkok, Hanoi, Jakarta tz_linux: "Asia/Ho_Chi_Minh" # IANA name, UTC+7, no DST @@ -45,11 +45,6 @@ dvwa_db_password: "p@ssw0rd" # lab-only DB password on a host-only network; DVWA # gets the attack pack via a synced-folder mount (src/Vagrantfile). No attacker vars here. # ---- pinned tool versions ------------------------------------------------------------------------- -silketw_tag: "v0.8" -# v0.8 release asset. Pin the sha256 after the first download (printed by the role) to make it immutable. -silketw_url: "https://github.com/mandiant/SilkETW/releases/download/v0.8/SilkETW_SilkService_v8.zip" -silketw_sha256: "sha256:6c612c406844c72cde51bcd0660ca6bb704656549043cb5a8b8bbba5fe3d8dc3" - python_embed_version: "3.12.7" python_embed_url: "https://www.python.org/ftp/python/{{ python_embed_version }}/python-{{ python_embed_version }}-embed-amd64.zip" python_embed_sha256: "sha256:0d57bb6cb078b74d23dbfe91f77d6780d45bed328911609f1f7ee2ba1606bf44" @@ -59,24 +54,15 @@ uv_version: "0.9.3" uv_url: "https://github.com/astral-sh/uv/releases/download/{{ uv_version }}/uv-x86_64-pc-windows-msvc.zip" uv_sha256: "sha256:9f7595313b44e57dcaeef63fe4f3de9a0cf4f92a53302b429341f457f70ca3b9" # release .sha256 file -alloy_version: "1.20.1" -alloy_url: "https://github.com/grafana/alloy/releases/download/v{{ alloy_version }}/alloy-installer-windows-amd64.exe" -alloy_sha256: "sha256:23fcfe3755f02e8a6a83f27149851322ab2b66d584e76d239d9c031f50d3a8f0" # release SHA256SUMS # ---- Windows lab paths ---------------------------------------------------------------------------- graph_name: "SimulatedW10" # the repo asserts the host name against a fixed list; keep this name tools_dir: 'C:\Tools' lab_home: 'C:\ProgramData\etwlab' -silketw_dir: 'C:\Tools\SilkETW' out_dir: 'C:\lab-out\etw' raw_root: 'C:\lab-out\etw\raw' -service_name: "SilkService" # ---- ETW collector: our own Python collector (src/etw-python, DEVIATIONS D10) -------------------------- -# collector: which collector etwctl drives. "python" = etwcollect (also pushes to Loki itself, so Alloy is -# stopped and disabled); "silketw" = the old SilkService + Alloy path, kept ONLY until etwcollect is verified -# (parity run, PROGRESS), then both are removed. -collector: "python" 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: etwpy_mode = clone (cloud default: git clone repo_url@repo_branch to diff --git a/src/ansible/roles/win_alloy/handlers/main.yml b/src/ansible/roles/win_alloy/handlers/main.yml deleted file mode 100644 index d26c69b..0000000 --- a/src/ansible/roles/win_alloy/handlers/main.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -- name: Restart Alloy - ansible.windows.win_service: - name: Alloy - state: restarted - when: collector == 'silketw' diff --git a/src/ansible/roles/win_alloy/tasks/main.yml b/src/ansible/roles/win_alloy/tasks/main.yml deleted file mode 100644 index 7794311..0000000 --- a/src/ansible/roles/win_alloy/tasks/main.yml +++ /dev/null @@ -1,80 +0,0 @@ ---- -# Grafana Alloy, native Windows install (no Docker on the VM): tails SilkETW's raw files and pushes every -# line to Loki on the trainer ({{ loki_url }}). Replaces the HTTP shipper as the data path. -# Installer: the release's alloy-installer-windows-amd64.exe, silent (/S). It registers the "Alloy" service -# (LocalSystem, automatic) with the config at C:\Program Files\GrafanaLabs\Alloy\config.alloy. - -- name: Download Alloy {{ alloy_version }} - ansible.windows.win_get_url: - url: "{{ alloy_url }}" - dest: "{{ tools_dir }}\\alloy-installer-{{ alloy_version }}.exe" - checksum: "{{ alloy_sha256 | regex_replace('^sha256:', '') or omit }}" - checksum_algorithm: sha256 - force: false # version-pinned URL: do not re-download each run (idempotent) - -- name: Installed Alloy version - ansible.windows.win_powershell: - script: | - $Ansible.Changed = $false - $exe = Join-Path $env:ProgramFiles 'GrafanaLabs\Alloy\alloy-windows-amd64.exe' - if (Test-Path $exe) { (& $exe --version | Out-String).Trim() } else { '' } - register: alloy_installed - changed_when: false - -- name: Install Alloy silently (only when missing or another version) - ansible.windows.win_command: >- - "{{ tools_dir }}\alloy-installer-{{ alloy_version }}.exe" /S /DISABLEREPORTING=yes - when: alloy_version not in (alloy_installed.output | join(' ')) - -- name: Defender exclusion for Alloy (it reads every raw line; do not scan it) - ansible.windows.win_powershell: - script: | - Add-MpPreference -ExclusionPath "$env:ProgramFiles\GrafanaLabs\Alloy","$env:ProgramData\GrafanaLabs\Alloy" - $Ansible.Changed = $false - failed_when: false - -- name: Alloy config (SilkETW + dos map + ledger -> Loki) - ansible.windows.win_template: - src: config.alloy.j2 - dest: 'C:\Program Files\GrafanaLabs\Alloy\config.alloy' - newline_sequence: "\n" - notify: Restart Alloy - -- name: Validate the config with Alloy itself - ansible.windows.win_command: >- - "C:\Program Files\GrafanaLabs\Alloy\alloy-windows-amd64.exe" fmt "C:\Program Files\GrafanaLabs\Alloy\config.alloy" - changed_when: false - -# collector=python (default): etwcollect pushes to Loki itself, so Alloy is stopped AND disabled (a reboot must not -# bring it back to double-ship). collector=silketw: the old path, Alloy automatic and running. This whole role -# is removed once etwcollect is verified (DEVIATIONS D10). -- name: Alloy service (running only for collector=silketw) - ansible.windows.win_service: - name: Alloy - start_mode: "{{ 'auto' if collector == 'silketw' else 'disabled' }}" - state: "{{ 'started' if collector == 'silketw' else 'stopped' }}" - -- name: Restart now if the config changed (so the check below sees the new pipeline) - ansible.builtin.meta: flush_handlers - -# Loki is Alloy's push target but NOT required to provision the collector — this is a soft check only -# (failed_when: false). Keep it FAST: a short per-request timeout + few retries so an off/aborted trainer -# (or one still replaying its WAL right after boot) degrades to a quick warning in ~15s, not ~4 minutes of -# win_uri connection timeouts. Logs still ship once the trainer is up; this task does not gate anything. -- name: Loki reachable from this VM (Alloy's push target) - ansible.windows.win_uri: - url: "{{ loki_url }}/ready" - return_content: true - timeout: 4 # cap each attempt; an unreachable host otherwise hangs on the default 30s - register: loki_from_vm - until: loki_from_vm.status_code == 200 - retries: 3 # brief tolerance for a just-booted Loki; not a hard wait (it is only a warning) - delay: 2 - failed_when: false - -- name: Report Loki reachability - ansible.builtin.debug: - msg: >- - {{ 'Loki ready at ' ~ loki_url if (loki_from_vm.status_code | default(0)) == 200 else - 'WARNING: Loki not reachable at ' ~ loki_url ~ ' - the Ubuntu trainer is likely off; start it with ' - ~ '`vagrant up ubuntu-trainer` (or provision it: site.yml --limit ubuntu). Collector still installs fine.' }} diff --git a/src/ansible/roles/win_alloy/templates/config.alloy.j2 b/src/ansible/roles/win_alloy/templates/config.alloy.j2 deleted file mode 100644 index 7f63655..0000000 --- a/src/ansible/roles/win_alloy/templates/config.alloy.j2 +++ /dev/null @@ -1,128 +0,0 @@ -// Generated by Ansible (win_alloy role). Grafana Alloy: ship raw SilkETW lines to Loki on the trainer. -// -// {{ raw_root }}\\\.json (SilkService, one JSON event per line; etwctl start) -// -> labels job="silketw", host, split, run, provider (few values: one stream per raw file) -// -> metadata event, pid, process (filterable, NOT indexed: pid would explode streams) -// -> timestamp the event's own TimeStamp (VM clock), not the time Alloy read it -// -> line unchanged: Loki holds exactly what SilkETW wrote -// + dosmap.meta per run (job="etw-meta") and the benign-workload ledger CSVs (job="workload-ledger"). -// The same label scheme is documented in src/pipeline/lokiclient.py and produced by src/live/loki_push.py. -// Alloy's own file reads show up in Kernel-File; the converter drops edges of image "alloy" (like silkservice). - -// ---------------------------------------------------------------- SilkETW events -local.file_match "silketw" { - path_targets = [{ - "__path__" = "{{ raw_root | replace('\\', '/') }}/*/*/*.json", - "job" = "silketw", - "host" = "{{ inventory_hostname }}", - }] - sync_period = "2s" // a new run folder is picked up within 2 s of etwctl start -} - -loki.source.file "silketw" { - targets = local.file_match.silketw.targets - forward_to = [loki.process.silketw.receiver] - tail_from_end = false // new files are read from the start; positions survive restarts -} - -loki.process "silketw" { - stage.regex { - source = "filename" - expression = `[\\/](?Ptrain|test)[\\/](?P[^\\/]+)[\\/](?P[A-Za-z0-9_-]+)\.json$` - } - stage.labels { - values = { split = "", run = "", provider = "" } - } - stage.json { - expressions = { ts = "TimeStamp", event = "EventName", pid = "ProcessID", process = "ProcessName" } - } - stage.timestamp { - source = "ts" - format = "RFC3339Nano" // accepts SilkETW's 6-7 fractional digits and the +07:00 offset - action_on_failure = "skip" // keep the read time; the converter counts such lines as bad - } - stage.structured_metadata { - values = { event = "", pid = "", process = "" } - } - stage.label_drop { - values = ["filename"] - } - forward_to = [loki.write.trainer.receiver] -} - -// ---------------------------------------------------------------- dos map per run (etwctl start) -local.file_match "etwmeta" { - path_targets = [{ - "__path__" = "{{ raw_root | replace('\\', '/') }}/*/*/dosmap.meta", - "job" = "etw-meta", - "host" = "{{ inventory_hostname }}", - }] - sync_period = "2s" -} - -loki.source.file "etwmeta" { - targets = local.file_match.etwmeta.targets - forward_to = [loki.process.etwmeta.receiver] - tail_from_end = false -} - -loki.process "etwmeta" { - stage.regex { - source = "filename" - expression = `[\\/](?Ptrain|test)[\\/](?P[^\\/]+)[\\/]dosmap\.meta$` - } - stage.labels { - values = { split = "", run = "" } - } - stage.label_drop { - values = ["filename"] - } - forward_to = [loki.write.trainer.receiver] -} - -// ---------------------------------------------------------------- benign workload ledger (06 via 07) -local.file_match "ledger" { - path_targets = [{ - "__path__" = "{{ out_dir | replace('\\', '/') }}/experiments/*/labels/*.csv", - "job" = "workload-ledger", - "host" = "{{ inventory_hostname }}", - }] - sync_period = "10s" -} - -loki.source.file "ledger" { - targets = local.file_match.ledger.targets - forward_to = [loki.process.ledger.receiver] - tail_from_end = false -} - -loki.process "ledger" { - stage.regex { - source = "filename" - expression = `[\\/]experiments[\\/](?P[^\\/]+)[\\/]labels[\\/]` - } - stage.labels { - values = { exp = "" } - } - stage.regex { - expression = `^"(?P\d{4}-[^"]+)"` // first CSV column = action time (UTC); header line has none - } - stage.timestamp { - source = "utc" - format = "RFC3339Nano" - action_on_failure = "skip" - } - stage.label_drop { - values = ["filename"] - } - forward_to = [loki.write.trainer.receiver] -} - -// ---------------------------------------------------------------- push -loki.write "trainer" { - endpoint { - url = "{{ loki_url }}/loki/api/v1/push" - batch_wait = "1s" - batch_size = "1MiB" - } -} diff --git a/src/ansible/roles/win_collector/files/etwctl.ps1 b/src/ansible/roles/win_collector/files/etwctl.ps1 index 6527721..2b9a5b3 100644 --- a/src/ansible/roles/win_collector/files/etwctl.ps1 +++ b/src/ansible/roles/win_collector/files/etwctl.ps1 @@ -7,12 +7,11 @@ etwctl convert -Split train|test raw\\*\*.json -> __*.csv Settings come from C:\ProgramData\etwlab\etwlab.json (written by the win_collector role). - Collector (etwlab.json "Collector"): "python" = etwcollect (src/etw-python), run by the SYSTEM scheduled task - CollectorTask, pushes to Loki itself (DEVIATIONS D10). "silketw" = the old SilkService Windows service, kept - only until etwcollect is verified. + 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). PowerShell notes: Get-ScheduledTask / Start-ScheduledTask read / start a Task Scheduler task (its .State is - Ready, Running, ...); Get-Service reads a Windows service; `& $exe args` runs a program; $LASTEXITCODE is the + Ready, Running, ...); `& $exe args` runs a program; $LASTEXITCODE is the exit code of the last program; ConvertFrom-Json turns JSON text into an object with properties. #> param( @@ -26,30 +25,21 @@ $Cfg = Get-Content "$Home_\etwlab.json" -Raw | ConvertFrom-Json $State = "$Home_\state.json" $Status = "$Home_\collector-status.json" $Utf8 = New-Object System.Text.UTF8Encoding($false) # UTF-8 without BOM -$Py = ("$($Cfg.Collector)" -ne "silketw") # [bool]: anything but "silketw" = etwcollect function Get-State { if (Test-Path $State) { Get-Content $State -Raw | ConvertFrom-Json } else { $null } } function Set-State($obj) { [IO.File]::WriteAllText($State, ($obj | ConvertTo-Json), $Utf8) } -function Test-CollectorRunning { - if ($Py) { return ((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State -eq "Running") } - return ((Get-Service $Cfg.ServiceName).Status -ne "Stopped") -} +function Test-CollectorRunning { return ((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State -eq "Running") } function Show-Status { $st = Get-State - if ($Py) { - Write-Host "collector: task $($Cfg.CollectorTask) = $((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State)" - } else { - $svc = Get-Service $Cfg.ServiceName - Write-Host "service : $($svc.Name) = $($svc.Status)" - } + Write-Host "collector: task $($Cfg.CollectorTask) = $((Get-ScheduledTask -TaskName $Cfg.CollectorTask).State)" if ($st) { Write-Host "run : $($st.split)/$($st.run) started $($st.started_utc) stopped $($st.stopped_utc)" Get-ChildItem $st.dir -Filter *.json -ErrorAction SilentlyContinue | ForEach-Object { "{0,-12} {1,10:N0} KB" -f $_.Name, ($_.Length / 1KB) } | Write-Host } - if ($Py -and (Test-Path $Status)) { + if (Test-Path $Status) { $c = Get-Content $Status -Raw | ConvertFrom-Json Write-Host "status : $($c.state) (pid $($c.pid), updated $($c.updated_utc))" foreach ($p in $c.providers.PSObject.Properties) { # one line per provider: kproc, kfile, knet @@ -80,27 +70,8 @@ switch ($Command) { Set-State ([ordered]@{ split = $Split; run = $Run; dir = $dir; started_utc = (Get-Date).ToUniversalTime().ToString("o"); stopped_utc = $null }) - if ($Py) { - # The task runs `python -m etwcollect run`, which reads the run folder from state.json (written above). - Start-ScheduledTask -TaskName $Cfg.CollectorTask - } else { - # SilkService reads SilkServiceConfig.xml from its own folder, once, at service start. - $sb = New-Object System.Text.StringBuilder - [void]$sb.AppendLine("") - foreach ($c in $Cfg.Collectors) { - [void]$sb.AppendLine(" ") - [void]$sb.AppendLine(" $($c.Guid)") - [void]$sb.AppendLine(" user") - [void]$sb.AppendLine(" $($c.Provider)") - [void]$sb.AppendLine(" $($c.Keywords)") - [void]$sb.AppendLine(" file") - [void]$sb.AppendLine(" $dir\$($c.Stem).json") - [void]$sb.AppendLine(" ") - } - [void]$sb.AppendLine("") - [IO.File]::WriteAllText((Join-Path $Cfg.SilkServiceDir "SilkServiceConfig.xml"), $sb.ToString(), $Utf8) - Start-Service $Cfg.ServiceName - } + # The task runs `python -m etwcollect run`, which reads the run folder from state.json (written above). + Start-ScheduledTask -TaskName $Cfg.CollectorTask # Canary: a process start + image loads + file reads we know must show up. Start-Sleep -Seconds 5 @@ -113,29 +84,24 @@ switch ($Command) { } while ($missing.Count -gt 0 -and (Get-Date) -lt $deadline) if ($missing.Count -gt 0) { Write-Warning "no events yet in: $($missing -join ', ')" - if ($Py) { Write-Warning "check $Status (last_error) and: & '$($Cfg.EtwPython)' -m etwcollect status" } - else { Write-Warning "check the service log in $($Cfg.SilkServiceDir) and the Application event log" } + Write-Warning "check $Status (last_error) and: & '$($Cfg.EtwPython)' -m etwcollect status" exit 1 } Write-Host "[etwctl] capturing $Split/$Run -> $dir" Show-Status } "stop" { - if ($Py) { + if (Test-CollectorRunning) { + # etwcollect stop: stops the ETW session; the collector then writes its last lines, ships them + # to Loki (bounded) and exits. It waits for that itself (--wait). + & $Cfg.EtwPython -m etwcollect stop --wait 120 | Out-Host + $deadline = (Get-Date).AddSeconds(30) + while ((Test-CollectorRunning) -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 1 } if (Test-CollectorRunning) { - # etwcollect stop: stops the ETW session; the collector then writes its last lines, ships them - # to Loki (bounded) and exits. It waits for that itself (--wait). - & $Cfg.EtwPython -m etwcollect stop --wait 120 | Out-Host - $deadline = (Get-Date).AddSeconds(30) - while ((Test-CollectorRunning) -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 1 } - if (Test-CollectorRunning) { - # Last resort: kills the process (no final flush); the next start ships what is on disk. - Write-Warning "collector task still running after stop; ending it with Stop-ScheduledTask" - Stop-ScheduledTask -TaskName $Cfg.CollectorTask - } + # Last resort: kills the process (no final flush); the next start ships what is on disk. + Write-Warning "collector task still running after stop; ending it with Stop-ScheduledTask" + Stop-ScheduledTask -TaskName $Cfg.CollectorTask } - } else { - Stop-Service $Cfg.ServiceName -ErrorAction SilentlyContinue } $st = Get-State if ($st -and -not $st.stopped_utc) { diff --git a/src/ansible/roles/win_collector/tasks/main.yml b/src/ansible/roles/win_collector/tasks/main.yml index 46ac1b1..603670b 100644 --- a/src/ansible/roles/win_collector/tasks/main.yml +++ b/src/ansible/roles/win_collector/tasks/main.yml @@ -1,61 +1,41 @@ --- -# Collector install: etw-python collector (etwcollect) + converter + etwctl; SilkETW/SilkService until verified. -# Installs SilkETW/SilkService, embeddable Python, deploys the converter/windowing tool/shipper/etwctl, -# registers the service. 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. +# Collector install: our ETW collector etwcollect (src/etw-python, DEVIATIONS D10) + embeddable Python + +# 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. VC++ runtime (SilkETW needs it) ---------- -- name: Install the VC++ 2015-2022 runtime - chocolatey.chocolatey.win_chocolatey: - name: vcredist140 - state: present - -# ---------- 2. SilkETW ---------- -- name: Download SilkETW {{ silketw_tag }} - ansible.windows.win_get_url: - url: "{{ silketw_url }}" - dest: "{{ tools_dir }}\\SilkETW_{{ silketw_tag }}.zip" - checksum: "{{ silketw_sha256 | regex_replace('^sha256:', '') or omit }}" - checksum_algorithm: sha256 - force: false # version-pinned URL: keep the existing file, do not re-download each run (idempotent) - register: silk_dl - -- name: Report the SilkETW zip sha256 (pin silketw_sha256 to this) - ansible.windows.win_stat: - path: "{{ tools_dir }}\\SilkETW_{{ silketw_tag }}.zip" - get_checksum: true - checksum_algorithm: sha256 - register: silk_stat - -- name: Show the sha256 to pin - ansible.builtin.debug: - msg: "SilkETW zip sha256 = {{ silk_stat.stat.checksum }} (set silketw_sha256: 'sha256:{{ silk_stat.stat.checksum }}')" - when: silketw_sha256 == "" - -- name: Extract SilkETW - community.windows.win_unzip: - src: "{{ tools_dir }}\\SilkETW_{{ silketw_tag }}.zip" - dest: "{{ silketw_dir }}" - creates: "{{ silketw_dir }}" - -- name: Locate SilkService.exe - ansible.windows.win_find: - paths: "{{ silketw_dir }}" - recurse: true - patterns: ["SilkService.exe"] - register: silksvc_find - -- name: Fail if SilkService.exe is missing - ansible.builtin.assert: - that: silksvc_find.files | length > 0 - fail_msg: "SilkService.exe not found under {{ silketw_dir }}" - -- name: Record the SilkService directory - ansible.builtin.set_fact: - silkservice_exe: "{{ silksvc_find.files[0].path }}" - silkservice_dir: "{{ silksvc_find.files[0].path | win_dirname }}" - -# ---------- 3. Embeddable Python (stdlib only, runs the converter) ---------- +# ---------- 1. Remove the old collector path (SilkETW/SilkService + Grafana Alloy, replaced 2026-10-26) ---------- +# 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: + name: SilkService + state: absent + +- name: Remove SilkETW files + ansible.windows.win_file: + path: "{{ item }}" + state: absent + loop: + - '{{ tools_dir }}\SilkETW' + - '{{ tools_dir }}\SilkETW_v0.8.zip' + +- name: Uninstall Grafana Alloy (it shipped SilkService's files; etwcollect pushes to Loki itself) + ansible.windows.win_shell: | + $ErrorActionPreference = 'Continue' + $dir = Join-Path $env:ProgramFiles 'GrafanaLabs\Alloy' + if (-not (Test-Path $dir) -and -not (Get-Service Alloy -ErrorAction SilentlyContinue)) { 'absent'; exit 0 } + Stop-Service Alloy -ErrorAction SilentlyContinue + $un = Join-Path $dir 'uninstall.exe' + if (Test-Path $un) { Start-Process -FilePath $un -ArgumentList '/S' -Wait } + Start-Sleep -Seconds 3 + if (Get-Service Alloy -ErrorAction SilentlyContinue) { sc.exe delete Alloy | Out-Null } + Remove-Item $dir, (Join-Path $env:ProgramData 'GrafanaLabs\Alloy') -Recurse -Force -ErrorAction SilentlyContinue + Remove-MpPreference -ExclusionPath $dir, (Join-Path $env:ProgramData 'GrafanaLabs\Alloy') -ErrorAction SilentlyContinue + Get-ChildItem '{{ tools_dir }}' -Filter 'alloy-installer-*.exe' -ErrorAction SilentlyContinue | Remove-Item -Force + 'removed' + register: alloy_rm + changed_when: "'removed' in alloy_rm.stdout" + +# ---------- 2. Embeddable Python (stdlib only, runs the converter) ---------- - name: Download embeddable Python {{ python_embed_version }} ansible.windows.win_get_url: url: "{{ python_embed_url }}" @@ -74,7 +54,7 @@ ansible.builtin.set_fact: python_exe: "{{ tools_dir }}\\python-embed\\{{ python_embed_version }}\\python.exe" -# ---------- 4. Deploy converter, shipper, etwctl, config ---------- +# ---------- 3. Deploy converter, shipper, etwctl, config ---------- - name: "Deploy the converter (source of truth: src/pipeline/etw2nodlink.py)" ansible.windows.win_copy: src: "{{ src_dir }}/pipeline/etw2nodlink.py" @@ -119,7 +99,7 @@ ansible.windows.win_command: '"{{ python_exe }}" "{{ lab_home }}\etwwindow.py" --selftest' changed_when: false -# ---------- 5. etw-python collector (src/etw-python, DEVIATIONS D10) ---------- +# ---------- 4. etw-python collector (src/etw-python, DEVIATIONS D10) ---------- # Source: mount (local lab: src/Vagrantfile shares src/etw-python as C:\etw-python, inventory.local.ini sets # etwpy_mode=mount) or clone (cloud default: git clone of repo_url@repo_branch). uv builds the venv on the VM's # own disk and downloads its own CPython 3.12 (.python-version); the embeddable Python above stays for the @@ -224,18 +204,3 @@ stop_if_going_on_batteries: false enabled: true state: present - -# ---------- 6. SilkService Windows service (kept only until etwcollect is verified; collector=silketw) ---------- -- name: Register the SilkService collector (startup = Manual) - ansible.windows.win_service: - name: "{{ service_name }}" - path: "{{ silkservice_exe }}" - display_name: "SilkETW collector (etwlab)" - start_mode: manual - state: stopped - -- name: Configure crash-restart (stay Manual; a reboot must not resume into an old run folder) - ansible.windows.win_command: >- - sc.exe failure {{ service_name }} reset= 86400 - actions= restart/30000/restart/30000/restart/30000 - changed_when: false diff --git a/src/ansible/roles/win_collector/templates/etwlab.json.j2 b/src/ansible/roles/win_collector/templates/etwlab.json.j2 index d89bd4f..95673d8 100644 --- a/src/ansible/roles/win_collector/templates/etwlab.json.j2 +++ b/src/ansible/roles/win_collector/templates/etwlab.json.j2 @@ -1,14 +1,11 @@ {#- Rendered to C:\ProgramData\etwlab\etwlab.json. to_nice_json escapes the Windows backslashes. -#} {{ { - "ServiceName": service_name, - "SilkServiceDir": silkservice_dir, "RawRoot": raw_root, "OutDir": out_dir, "Graph": graph_name, "Python": python_exe, "Converter": lab_home ~ "\\etw2nodlink.py", - "Collector": collector, "CollectorTask": collector_task, "CollectorSession": collector_session, "EtwPython": etwpy_python, diff --git a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 index 3d5fcf7..5575639 100644 --- a/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 +++ b/src/ansible/roles/win_shipper/templates/start-live.ps1.j2 @@ -3,8 +3,7 @@ start-live.ps1 (generated by Ansible: win_shipper role) Keeps a live ETW capture (split "test", run live-) ALWAYS running. Nothing is shipped by this - script: the collector (etwcollect, the SYSTEM task {{ collector_task }}; or SilkService + Alloy while - collector=silketw) pushes every line to Loki ({{ loki_url }}); the live server on the trainer follows the + script: the collector (etwcollect, the SYSTEM task {{ collector_task }}) pushes every line to Loki ({{ loki_url }}); the live server on the trainer follows the newest test run in Loki. This script only decides WHEN to start a fresh run, because the collector reads its output folder once at service start (a plain auto-start would append to the last run, possibly a training run). @@ -25,7 +24,7 @@ C:\scripts\start-live.ps1 -Resume # remove the hold; the capture restarts now Live UI: http://{{ trainer_host }}:{{ server_port }}/ Grafana: http://{{ trainer_host }}:{{ grafana_port }}/ - PowerShell notes: Get-Service reads a service's state, Get-ScheduledTask a task's state; a [switch] parameter is a flag that is either given + PowerShell notes: Get-ScheduledTask reads a task's state; a [switch] parameter is a flag that is either given or not; ConvertFrom-Json / ConvertTo-Json read / write JSON; Add-Content appends a line to a file; a System.Threading.Mutex is a machine-wide lock, so a manual call and a task tick never act at the same time. #> @@ -82,10 +81,8 @@ function Start-LiveRun { if ($code -eq 0) { Log "started test/$run" } else { Log "etwctl start test/$run exited $code (see lines above)" } } -# The collector's state as {Name, Status} with Status Running | Stopped | StartPending (the shape of a -# Get-Service result), so the decisions below read the same for etwcollect (a scheduled task) and SilkService. +# The collector task's state as {Name, Status} with Status Running | Stopped | StartPending. function Get-Collector { - if ($Cfg.Collector -eq 'silketw') { $s = Get-Service $Cfg.ServiceName; return [pscustomobject]@{ Name = $s.Name; Status = "$($s.Status)" } } $t = Get-ScheduledTask -TaskName $Cfg.CollectorTask $status = switch ("$($t.State)") { 'Running' { 'Running' } 'Queued' { 'StartPending' } default { 'Stopped' } } return [pscustomobject]@{ Name = "task $($Cfg.CollectorTask)"; Status = $status } @@ -126,7 +123,6 @@ function Show-LiveStatus($svc, $st) { Write-Host ("hold : " + $(if ($h) { "yes (by $($h.by) since $($h.since_utc))" } else { "no" })) $t = Get-ScheduledTask -TaskName '{{ live_task_name }}' -ErrorAction SilentlyContinue Write-Host ("task : " + $(if ($t) { "{{ live_task_name }} = $($t.State)" } else { "MISSING" })) - if ($Cfg.Collector -eq 'silketw') { Write-Host "alloy : $((Get-Service Alloy).Status)" } if (Test-Path $LogF) { Write-Host "log : last lines of $LogF"; Get-Content $LogF -Tail 8 | ForEach-Object { " $_" } } } @@ -151,7 +147,6 @@ function Invoke-Main { $rot = $false # continue as a normal tick, which starts a run if none is running } - if ($Cfg.Collector -eq 'silketw' -and (Get-Service Alloy).Status -ne 'Running') { Log "WARNING the Alloy service is not running: nothing reaches Loki" } $hold = Get-Hold if ($hold) { diff --git a/src/ansible/verify-windows.yml b/src/ansible/verify-windows.yml index 2ed7387..324fab1 100644 --- a/src/ansible/verify-windows.yml +++ b/src/ansible/verify-windows.yml @@ -9,14 +9,15 @@ tasks: # ---------- win_collector ---------- - - name: SilkService service is registered (win_collector) + - name: Old collector removed (SilkService + Alloy, replaced by etwcollect) ansible.windows.win_service_info: - name: "{{ service_name }}" - register: silksvc + name: "{{ item }}" + loop: [SilkService, Alloy] + register: old_svcs - ansible.builtin.assert: - that: silksvc.services | length == 1 - fail_msg: "SilkService not registered — run role win_collector" - success_msg: "SilkService registered (start_mode={{ silksvc.services[0].start_mode }})" + that: (old_svcs.results | map(attribute='services') | sum(start=[]) | length) == 0 + fail_msg: "SilkService or Alloy is still installed — run role win_collector (it removes them)" + success_msg: "SilkService and Alloy are gone" - name: Collector files present (win_collector) ansible.windows.win_stat: @@ -70,26 +71,6 @@ "{{ tools_dir }}\python-embed\{{ python_embed_version }}\python.exe" "{{ lab_home }}\etw2nodlink.py" --selftest changed_when: false - # ---------- win_alloy ---------- - - name: Alloy service state (win_alloy; running only for collector=silketw) - ansible.windows.win_service_info: - name: Alloy - register: alloy_svc - - ansible.builtin.assert: - that: - - alloy_svc.services | length == 1 - - alloy_svc.services[0].state == ('started' if collector == 'silketw' else 'stopped') - fail_msg: "Alloy is {{ alloy_svc.services[0].state | default('missing') }}, expected {{ 'started' if collector == 'silketw' else 'stopped (etwcollect pushes to Loki itself)' }} — run role win_alloy" - success_msg: "Alloy {{ alloy_svc.services[0].state }} (collector={{ collector }})" - - - name: Alloy config present (win_alloy) - ansible.windows.win_stat: - path: 'C:\Program Files\GrafanaLabs\Alloy\config.alloy' - register: alloy_cfg - - ansible.builtin.assert: - that: alloy_cfg.stat.exists - fail_msg: "config.alloy missing — run role win_alloy" - # ---------- win_shipper / win_benign ---------- - name: Shipper + benign scripts present (win_shipper, win_benign) ansible.windows.win_stat: diff --git a/src/ansible/windows.yml b/src/ansible/windows.yml index 0a9f70b..6f0f963 100644 --- a/src/ansible/windows.yml +++ b/src/ansible/windows.yml @@ -1,5 +1,5 @@ --- -# Windows Server 2022 collector VM: capture ETW, Alloy ships it to Loki (no training) + the DVWA vulnlab. +# Windows Server 2022 collector VM: capture ETW, etwcollect ships it to Loki (no training) + the DVWA vulnlab. - name: Configure the Windows collector VM hosts: windows gather_facts: true @@ -7,12 +7,11 @@ # Cloud mode supplies them from the vault: add `-e @group_vars/vault.yml --ask-vault-pass`. # Each role carries a tag so a single stage can be run alone, e.g. # ansible-playbook windows.yml --tags vulnlab -e vulnlab_enabled=true # only DVWA - # ansible-playbook windows.yml --tags collector,alloy # only those two + # ansible-playbook windows.yml --tags collector,shipper # only those two # Running with no --tags still does everything (unchanged default). roles: - { role: win_base, tags: [base] } # OS config: network profile, UTC+7 clock, no-sleep, RDP, folders, Defender - - { role: win_collector, tags: [collector] } # SilkETW/SilkService + embeddable Python + converter + etwctl + etwship - - { role: win_alloy, tags: [alloy] } # Grafana Alloy (native): raw SilkETW lines -> Loki on the trainer - - { role: win_shipper, tags: [shipper] } # start-live.ps1: start/stop a live (test) capture; Alloy ships it + - { role: win_collector, tags: [collector] } # etwcollect (uv; ETW -> files -> Loki) + embeddable Python + converter + etwctl + - { role: win_shipper, tags: [shipper] } # start-live.ps1: start/stop a live (test) capture; etwcollect ships it - { role: win_benign, tags: [benign] } # scripted benign workload generator (green windows for the demo) - { role: win_vulnlab, tags: [vulnlab], when: vulnlab_enabled | bool } # XAMPP + DVWA on {{ vulnlab_port }}; -e vulnlab_enabled=true diff --git a/src/etw-python/src/etwcollect/cli.py b/src/etw-python/src/etwcollect/cli.py index 328c3ea..834c876 100644 --- a/src/etw-python/src/etwcollect/cli.py +++ b/src/etw-python/src/etwcollect/cli.py @@ -133,8 +133,8 @@ def main(argv=None) -> int: r.add_argument("--out-dir", help="write here instead of the run folder in state.json") r.add_argument("--status", help="status file (default: collector-status.json next to etwlab.json)") r.add_argument("--no-push", action="store_true", help="files only, nothing to Loki") - r.add_argument("--exclude-image", action="append", default=["alloy"], - help="also drop the I/O of processes whose image starts with this (default: alloy)") + r.add_argument("--exclude-image", action="append", default=[], + help="also drop the I/O of processes whose image name starts with this (repeatable)") r.add_argument("--drain-s", type=float, default=30.0, help="seconds to finish shipping after a stop") s = sub.add_parser("stop") s.add_argument("--wait", type=float, default=60.0) diff --git a/src/etw-python/src/etwcollect/collector.py b/src/etw-python/src/etwcollect/collector.py index 86cadd7..64e1906 100644 --- a/src/etw-python/src/etwcollect/collector.py +++ b/src/etw-python/src/etwcollect/collector.py @@ -9,10 +9,10 @@ _on_event() per event (cheap first, so excluded events cost little): 1. which provider? (header GUID) unknown -> count, return - 2. kproc from an excluded PID? drop before decoding (rule a) + 2. kproc from an excluded PID? drop before decoding (rule a; ProcessStart is decoded first) 3. schema (cached) + decode the payload 4. kfile rules (a)+(b) / knet rule (c) drop our own I/O - 5. ProcessStart -> remember the child's name (and exclude it if it is Alloy, during the switch) + 5. ProcessStart -> remember the child's name (and exclude it if its image matches --exclude-image) 6. build the SilkETW-format line, hand it to the writer """ from __future__ import annotations @@ -49,7 +49,7 @@ class Config: loki_url: str | None = None # None or push=False: write files only push: bool = True session: str = SESSION - exclude_images: tuple = ("alloy",) + exclude_images: tuple = () drain_s: float = 30.0 extra_own_paths: tuple = field(default_factory=tuple) diff --git a/src/etw-python/src/etwcollect/filters.py b/src/etw-python/src/etwcollect/filters.py index 80f201e..6bba3f2 100644 --- a/src/etw-python/src/etwcollect/filters.py +++ b/src/etw-python/src/etwcollect/filters.py @@ -4,7 +4,7 @@ is a Kernel-File Read. Written out, those become more lines -> more events (docs/notes/silkservice-kfile-lag.md). Three rules, each counted (Excluder.counts -> collector-status.json): - (a) self_pid the event's header PID is ours (or, during the switch, Alloy's). kproc / kfile. + (a) self_pid the event's header PID is ours (or an --exclude-image process's). kproc / kfile. (b) own_file a Kernel-File event on one of OUR files, whoever issued it: a Create whose FileName is under the raw output root, or a Read/Write on a FileObject / FileKey learned from such a Create. This also catches System (PID 4) lazy-writer flushes of our files, which (a) cannot. diff --git a/src/live/README.md b/src/live/README.md index 7e9b789..5d94d08 100644 --- a/src/live/README.md +++ b/src/live/README.md @@ -1,8 +1,8 @@ # Live demo: VM → Loki → trainer scoring → browser ``` -VM SilkService → raw\test\live-\{kfile,knet,kproc}.json (start-live.ps1) - Grafana Alloy (service) tails them ──push──► Loki :3100 on the trainer +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 → @@ -13,7 +13,7 @@ trainer live_server.py --loki-url → loki_source.py (poll the newest test run, | 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 Alloy's shape (`--shift-to-now --speed N` for live) | +| `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 `/` | @@ -58,7 +58,7 @@ uv run python src/live/compare_replay.py --session src/live/sessions/replay-x-20 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 (Alloy → Loki, the default) +## 5. Live (etwcollect → Loki, the default) 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 @@ -66,7 +66,7 @@ The trainer runs `ocr-live` (systemd, `src/ansible/roles/ubuntu_project`), which **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, and leaves SilkService alone while a hold exists +run every 6 h, deletes raw `live-*` runs idle for 1 day, and leaves the collector alone while a hold exists (`07-build-train-dataset.ps1` pauses it for a train capture and resumes it after). By hand, in an elevated PowerShell on the VM: ``` diff --git a/src/live/loki_push.py b/src/live/loki_push.py index 66a0ee2..06e247f 100644 --- a/src/live/loki_push.py +++ b/src/live/loki_push.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 -"""loki_push.py - push a recorded SilkETW run folder into Loki in the same shape Alloy writes. Test feed for +"""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. -Alloy on the VM (roles/win_alloy/templates/config.alloy.j2) and this script must agree on: +etwcollect on the VM (src/etw-python/src/etwcollect/loki.py; Alloy until 2026-10-26) 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/loki_source.py b/src/live/loki_source.py index 513ca0e..74b3a80 100644 --- a/src/live/loki_source.py +++ b/src/live/loki_source.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """loki_source.py - feed engine.Engine from Loki instead of the HTTP shipper (live_server.py --loki-url). - Alloy (VM) -> Loki {job="silketw", split="test", run, provider} + etwcollect (VM) -> Loki {job="silketw", split="test", run, provider} -> poll every --poll-s: newest run in the split = the current session (a new run = a new session) -> per provider stream: query [cursor - overlap, now + grace), drop lines already seen -> engine.ingest({session: run, batches: [{stream: provider, offset_start, lines, ends}], clock_ms, dos_map}) @@ -14,7 +14,7 @@ measured lag (host now - newest event), so the last window of a stopped capture still closes. Why poll instead of /tail (websocket): no extra dependency, and reconnecting is just asking again from the -cursor. Why the overlap: Alloy ships each file in order, but small reorderings inside a file are possible; +cursor. Why the overlap: the VM ships each file in order, but small reorderings inside a file are possible; re-reading the last few seconds and de-duplicating costs little. uv run python src/live/loki_source.py --selftest diff --git a/src/pipeline/etw2nodlink.py b/src/pipeline/etw2nodlink.py index a3e0f69..c34d678 100644 --- a/src/pipeline/etw2nodlink.py +++ b/src/pipeline/etw2nodlink.py @@ -20,8 +20,9 @@ # awk -F, 'NR>1 {print $5, $2"->"$4}' SimulatedW10_train_edges.csv | sort | uniq -c DIRECTION = {"Load": "fwd", "Read": "fwd", "Write": "fwd", "Send": "fwd", "Recv": "fwd"} -# The collector writes its own output file, and the log shipper (Grafana Alloy) reads it, so Kernel-File -# sees both: drop their edges (feedback loop). Raw lines stay complete; only edges are dropped. +# Captures before 2026-10-26: SilkService wrote its own output file and Grafana Alloy read it, so Kernel-File +# saw both: drop their edges (feedback loop). etwcollect drops its own I/O before writing (DEVIATIONS D10); the +# names stay for old captures and replays. Raw lines stay complete; only edges are dropped. EXCLUDE_IMAGES = {"silkservice", "alloy"} _FRAC = re.compile(r"(\.\d{6})\d+") diff --git a/src/pipeline/loki_pull.py b/src/pipeline/loki_pull.py index 45aa79c..00c6180 100644 --- a/src/pipeline/loki_pull.py +++ b/src/pipeline/loki_pull.py @@ -8,7 +8,7 @@ Same raw layout 07-build-train-dataset.ps1 produced on the VM, so build_experiment.py (convert -> window -> check -> experiment.json) and everything after it are unchanged. Lines are written exactly as Loki returns -them (Alloy never rewrites a line), oldest first, one file per provider. +them (the VM's shipper never rewrites a line), oldest first, one file per provider. Pick what to pull: uv run python src/pipeline/loki_pull.py interactive (arrow keys): runs or a custom range @@ -169,7 +169,7 @@ def pull(lk, sel, out_dir, page=5000, log=print, job="silketw"): n, last_ts, at_ts = 0, None, set() for ts, lab, line in lk.query_all(q, sel["start_ns"], sel["end_ns"], page=page): key = (lab["split"], lab["run"], lab["provider"]) - # exact (ts, stream, line) repeats = the same event shipped twice (Alloy lost its positions, a + # exact (ts, stream, line) repeats = the same event shipped twice (the shipper lost its positions, a # re-push): drop and count them. Entries arrive in ts order, so only the current ts is kept. if ts != last_ts: last_ts, at_ts = ts, set() @@ -363,7 +363,7 @@ def main(argv=None): print("[loki_pull] cancelled") return 1 if time.time_ns() - sel["end_ns"] < 180 * NS and sel["mode"] == "run": - print("[loki_pull] WARNING: the run ended < 3 min ago; Alloy may still be shipping its last lines") + print("[loki_pull] WARNING: the run ended < 3 min ago; the VM may still be shipping its last lines") exp_id = a.id or default_id(sel) if interactive and not a.id: import questionary diff --git a/src/pipeline/lokiclient.py b/src/pipeline/lokiclient.py index 883e09e..b41311f 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 Alloy on the VM writes; src/ansible/roles/win_alloy/templates/config.alloy.j2): +Label scheme (what etwcollect on the VM pushes, src/etw-python/src/etwcollect/loki.py; Grafana Alloy before 2026-10-26): 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 diff --git a/src/scripts/07-build-train-dataset.ps1 b/src/scripts/07-build-train-dataset.ps1 index bb7f1de..edd63d6 100644 --- a/src/scripts/07-build-train-dataset.ps1 +++ b/src/scripts/07-build-train-dataset.ps1 @@ -284,7 +284,7 @@ if (-not (Test-Path $WorkloadScript)) { throw "workload script not found: $Workl if (-not (Get-Command $WorkloadScript).Parameters.ContainsKey('BeforeLedger')) { throw "$WorkloadScript has no -BeforeLedger parameter - apply the 2-line patch first" } -# `etwctl running` exits 0 while a capture runs (etwcollect task or SilkService, whichever etwlab.json names). +# `etwctl running` exits 0 while a capture runs (the etwcollect task). & $EtwctlPs1 running | Out-Null $capturing = ($LASTEXITCODE -eq 0) # The always-on live capture (start-live.ps1 watchdog, test/live-*) is paused below, right before the train @@ -376,20 +376,17 @@ finally { # also runs on Ctrl+C o # ---------------------------------------------------------------- 2b. workload ledger -> Loki (etwcollect) # The ledger is written AFTER the capture stopped (-BeforeLedger), so the collector cannot ship it; Alloy used # to tail labels\*.csv. loki_pull.py on the trainer finds it as {job="workload-ledger", exp=}. -if ("$($Cfg.Collector)" -ne 'silketw') { - Log "ledger $(Join-Path $exp 'labels') -> Loki" - & $Cfg.EtwPython -m etwcollect push-ledger --exp $stamp --dir (Join-Path $exp 'labels') | Out-Host - if ($LASTEXITCODE) { Write-Warning "ledger push failed; re-run: & '$($Cfg.EtwPython)' -m etwcollect push-ledger --exp $stamp --dir '$(Join-Path $exp 'labels')'" } -} +Log "ledger $(Join-Path $exp 'labels') -> Loki" +& $Cfg.EtwPython -m etwcollect push-ledger --exp $stamp --dir (Join-Path $exp 'labels') | Out-Host +if ($LASTEXITCODE) { Write-Warning "ledger push failed; re-run: & '$($Cfg.EtwPython)' -m etwcollect push-ledger --exp $stamp --dir '$(Join-Path $exp 'labels')'" } # ---------------------------------------------------------------- 3. collect raw into the experiment $src = Join-Path $Cfg.RawRoot "$Split\$run" $dst = Join-Path $exp "raw\$Split\$run" if (-not (Test-Path $src)) { throw "raw run folder not found: $src" } Log "collect $src -> $dst" -# COPY, not move: the collector's shipper (or Alloy with collector=silketw) reads $src to ship it to Loki (the -# training source on the trainer); etwctl stop already waited for etwcollect's final push, Alloy needs a few -# seconds after the stop, and moving files that are still open would fail. +# COPY, not move: the collector's shipper reads $src to ship it to Loki (the training source on the trainer); +# etwctl stop already waited for its final push, and a backlog left by a Loki outage is shipped at the next start. Log "wait ${ShipWaitSeconds}s for the last lines to reach Loki" Start-Sleep -Seconds $ShipWaitSeconds # robocopy /E = cp -r (keep the source for the shipper); exit codes 0-7 mean success From 5f538b59d797220c609bdbe8a87d51796b4fcde6 Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sat, 31 Oct 2026 21:10:02 +0700 Subject: [PATCH 6/8] Benign = idle pulled from Loki; remove the capture scripts The scripted benign workload taught the one-class model the attack's own living-off-the-land binaries (netcheck/download/files ran ipconfig/curl/ cmd/net), so on exp04 the live DVWA->RCE attack scored entirely below threshold and raised no alert, while benign windows were green. Switch the benign baseline to idle activity pulled directly from Loki (the always-on live capture already ships it): no capture script at all. Against an idle baseline the attack's discovery+RCE burst is out-of-distribution and separates cleanly. Verified live (exp05, session live-20261031T134030Z): idle windows green (<= Minor 8.0), the DVWA->RCE window red (subgraph 106.96, Significant, alert True) flagging the attacker stage IP, downloaded_tool.bin and the RCE powershell; LLM triage "attack" (0.85) + report; rejudge.sh reproduces the subgraph offline. - Remove src/scripts/06-benign-workload.ps1 and 07-build-train-dataset.ps1. - Remove the win_benign role (+ its line in windows.yml) and the legacy collect-train.yml; fix verify-windows.yml. - Update CLAUDE.md, DEVIATIONS D2, PROGRESS, and the READMEs/LABELING/teammate report to "benign = idle pulled from Loki". Caveat: an idle baseline is thin (net val_fpr=1.0), so the SG-Det cut-off carries the separation and benign demo windows must stay idle. Noted as follow-ups: render the live LLM report as HTML; steady the model with a larger idle pull. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DxFwFUt1hUmhjnRsfTCZpg --- CLAUDE.md | 39 +- docs/DEVIATIONS.md | 29 +- docs/PROGRESS.md | 67 ++-- docs/reports/teammate.md | 2 +- src/README.md | 7 +- src/ansible/README.md | 24 +- src/ansible/collect-train.yml | 83 ---- src/ansible/roles/win_benign/tasks/main.yml | 18 - src/ansible/verify-windows.yml | 18 +- src/ansible/windows.yml | 1 - src/atomic-attack-pack/LABELING.md | 5 +- src/atomic-attack-pack/README.md | 8 +- src/live/README.md | 5 +- src/scripts/06-benign-workload.ps1 | 235 ------------ src/scripts/07-build-train-dataset.ps1 | 398 -------------------- 15 files changed, 117 insertions(+), 822 deletions(-) delete mode 100644 src/ansible/collect-train.yml delete mode 100644 src/ansible/roles/win_benign/tasks/main.yml delete mode 100644 src/scripts/06-benign-workload.ps1 delete mode 100644 src/scripts/07-build-train-dataset.ps1 diff --git a/CLAUDE.md b/CLAUDE.md index cd15fc1..ba42070 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,14 +122,15 @@ numbers. If ambiguous, answer the most likely interpretation and state the assum `src/etw-python` (`etwcollect`, pushes to Loki itself) replaced SilkService AND Alloy, verified on `ws-etw` and both removed (D10, PROGRESS). exp03 does not match the new data (other collector, fixed NET owners), so live windows are red until a new model exists; that is not a detection result. -- Next step (user, 2026-10-27), in order; details and gates in PROGRESS "Next 3 steps": - 1. Benign train capture with etwcollect: `07-build-train-dataset.ps1` from the RDP desktop, browsing - included (browser FP). First real use of `etwctl` by 07 and of `etwcollect push-ledger`: check the - ledger reaches Loki. Gate on `lab status` coverage and Read/Write per window. - 2. `lab loop` → `exp04` → `lab promote exp04`; `ocr-live` restarts on it; benign live windows stay green. - 3. Full flow: DVWA→RCE from Kali during a live session → attack window red, LLM triage `attack` + report - (DeepSeek); laptop replay. - Then: the replay equivalence check, understanding the trainer (concepts 2–4). +- DONE (2026-10-31): the core concept demo works end to end. `exp04` (scripted workload) fixed benign but + MISSED the attack (LOLBin overlap); user switched to **benign = idle pulled from Loki**, removed both + capture scripts, and trained **exp05** on a 16-min idle Loki range. Result (session + `live-20261031T134030Z`): idle windows green (≤ Minor 8.0), DVWA→RCE attack **red** (subgraph 106.96, + Significant, alert True; flagged the Kali stage IP, `downloaded_tool.bin`, the RCE powershell), LLM triage + **`attack` 0.85** + report; offline re-judge reproduces it. See PROGRESS, D2, [[live-detector-benign-fp]]. +- Next: (a) the live UI renders the LLM report as raw markdown — add HTML rendering (user, 2026-10-31); + (b) idle model is thin (net `val_fpr=1.0`) — a larger idle pull would steady it; (c) understanding the + trainer (concepts 2–4). - Data: the user's own Windows 10 audit data (ETW), shaped to match the NODLINK simulated Windows 10 (W10) host format the repo expects. The graph is named `SimulatedW10` because the repo asserts host names. @@ -175,11 +176,15 @@ history of earlier progress) and, if relevant, this section. - Node identity: processes keyed by PID + start time (raw PIDs get reused and would corrupt idle-time features); FILE and NET nodes keyed by a hash of path / ip:port so IDs are stable across train and test. Windowed outputs prefix every node ID with its window (`w0007_...`). -- Benign workload: a custom scripted generator (seeded) rather than GHOSTS or the Caldera human plugin. - Apps are launched via explorer (Shell COM) so the benign graph does not learn the attack tooling's - parent (PowerShell) as normal. -- Windowing: train capture of ~20 min benign activity cut into 5-min sliding windows with a 2-min - stride. Detection uses the same 5-min window length. For the small scripted demo, tumbling windows +- Benign set: **idle machine activity, pulled directly from Loki** — no capture script. The always-on live + capture ships idle background activity to Loki; a clean idle time-range is pulled with + `lab pull --start --end --split test` and trained on. Both earlier scripts were removed 2026-10-31 + (`06-benign-workload.ps1`, then `07-build-train-dataset.ps1`): the scripted workload's netcheck/download/cmd + scenarios reused the attack's living-off-the-land binaries, making the DVWA→RCE chain in-distribution and + undetectable (exp04 miss). With an idle baseline the attack separates cleanly; keep benign demo windows + idle (an idle model is thin, so real activity can false-positive). See `docs/DEVIATIONS.md` D2. +- Windowing: an idle benign time-range pulled from Loki, cut into 5-min sliding windows with a 2-min + stride. Detection uses the same 5-min window length. For the small demo, tumbling windows (stride = window) are enough; sliding windows are the option for real attacks that cross window boundaries. - Feature extraction: a standalone re-implementation of the repo's behavior-feature step (paper @@ -199,8 +204,9 @@ history of earlier progress) and, if relevant, this section. collector as SYSTEM task `etwlab-collector`, `etwctl`, copies `src/pipeline/etw2nodlink.py` / `etwwindow.py` / `src/live/etwship.py`; the collector source is the Vagrant mount `C:\etw-python` locally and a git clone on cloud; it also removes the old SilkETW/SilkService and Grafana Alloy), - `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), `win_benign` (`src/scripts/06-benign-workload`, - `07-build-train-dataset`), `win_vulnlab` (XAMPP + DVWA). + `win_shipper` (`start-live.ps1` watchdog + SYSTEM task `etwlab-live`: always-on live capture), + `win_vulnlab` (XAMPP + DVWA). (The `win_benign` role and `src/scripts/` capture scripts were removed + 2026-10-31: benign = idle pulled from Loki.) - Improve loop: `lab` CLI (`src/lab/cli.py`, console script; `source .venv/bin/activate`): `lab loop` = pull + build → features → train into one run folder; `lab promote ` sets the current-model pointer (`src/artifacts/current.json`, overridden per machine by `current.local.json`) that @@ -241,7 +247,8 @@ history of earlier progress) and, if relevant, this section. Full entries (what / why / impact / claims limited) live in `docs/DEVIATIONS.md`. Summary: - Windowed, near-live detection instead of the paper's offline whole-log prediction. -- Own scripted Windows ETW data instead of NODLINK/DARPA datasets; benign activity is scripted. +- Own Windows ETW data instead of NODLINK/DARPA datasets; benign activity is natural desktop use (the + scripted workload was removed 2026-10-31, D2). - Own Python ETW collector (`src/etw-python`) instead of SilkETW: SilkETW-format lines with plain values, self/collector I/O excluded in the callback, pushes to Loki itself (D10). - Feature extraction: all 15 columns kept; idle scaler fit on train only; RDF skipped; per-window diff --git a/docs/DEVIATIONS.md b/docs/DEVIATIONS.md index 00fbc60..bb6c479 100644 --- a/docs/DEVIATIONS.md +++ b/docs/DEVIATIONS.md @@ -11,15 +11,28 @@ Tags: [PAPER] paper text · [AUTHOR CODE] verified in the authors' code (github. the window length (train max idle = 290 s, `src/artifacts/features/self-dataset/feature_scaler.json`). - Limits: no claim about whole-log detection quality. -## D2. Own scripted Windows ETW data +## D2. Own Windows ETW data; benign = idle, pulled from Loki - What: [PAPER] NODLINK / DARPA TC3 / OpTC. [OURS] ETW Kernel-Process/File/Network on a Windows VM (SilkETW - until 2026-10-26, then our own collector, D10), - converted to the NODLINK SimulatedW10 schema; benign activity from a seeded scripted workload - (`src/scripts/06-benign-workload.ps1`), plus background OS activity. -- Why: own end-to-end pipeline for the live demo; dataset small enough to inspect. -- Impact: benign behaviour is narrower than human use → likely optimistic false-positive rates; - converter drops/unresolves some events (see converter `_summary.json`). -- Limits: our numbers are not comparable with the paper's tables. + until 2026-10-26, then our own collector, D10), converted to the NODLINK SimulatedW10 schema. + Benign = **idle machine activity**: no capture script at all — the always-on live capture ships idle + background activity to Loki, and a clean idle time-range is pulled straight from Loki + (`lab pull --start --end --split test`) and trained on. There is no `src/scripts/` capture script. +- Why: simplest possible concept demo. Against an idle baseline the attack's whole discovery+RCE burst is + out-of-distribution, so it separates cleanly (idle = green, attack = red). +- History (2026-10-31), two failure modes before this: (1) a **seeded scripted workload** + (`06-benign-workload.ps1`: netcheck/download/files ran ipconfig/curl/cmd/net — the attack's own + living-off-the-land binaries) taught the model the attack's tools, so on exp04 every attack process scored + below τ_process (−0.400) and the attack did **not** alert. (2) A natural manual capture via a rewritten + `07` was tried, then both `06` and `07` were **removed** for the idle-from-Loki approach. exp05 (idle) + result: idle windows green (≤ Minor 8.0, no alert), the live DVWA→RCE attack **red** (subgraph 106.96, + Significant, alert True; flagged the attacker stage IP, `downloaded_tool.bin`, the RCE powershell), LLM + triage `attack` (0.85) + report. [[live-detector-benign-fp]]. +- Impact: an **idle baseline is thin** — the idle set that worked was ~16 min with only 6 net / 13 process + training nodes, so the per-node net threshold is noisy (`val_fpr=1.0`); the per-subgraph SG-Det cut-off + (Moderate ≥ 30) absorbs that noise, keeping idle windows green, but **any real user activity in a benign + window can raise false positives**, so the demo must keep benign windows idle. Not a general detector — + a concept demo baseline. Converter still drops/unresolves some events (see converter `_summary.json`). +- Limits: our numbers are not comparable with the paper's tables; no detection-quality claim. ## D3. Feature extraction re-implemented (`src/pipeline/encode_to_features.py`) - What: [AUTHOR CODE] `encode_to_PyG.py::feature_engineering` drops all-zero columns and fits the idle diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index d5a2686..4c9a71f 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -1,19 +1,32 @@ -# PROGRESS (status as of 2026-10-26) +# PROGRESS (status as of 2026-10-31) Replace lines in place when status changes; no history. "Verified" = checked in code/data. +Branch: **`make-sure-to-support-llm-investigator`**. ## Current focus -The "widen benign + calibrate" cycle ran on **1 HOUR** of benign data (not 2): kfile-fixed capture -`x-20261022T140932Z` → `exp03` trained + promoted → live DVWA→RCE attack. Work is on branch -**`collect-benign-data-for-1-hour`**. The full flow with LLM support ran live on 2026-10-25 (branch -`make-sure-to-support-llm-investigator`) and exposed a **collector blocker**: SilkService writes Kernel-File -events far behind real time, so the live engine drops every file event as late. Cause: its per-event file -writes feed back into Kernel-File (`docs/notes/silkservice-kfile-lag.md`). **Fixed 2026-10-26: our own Python -collector `src/etw-python` (`etwcollect`, pushes to Loki itself) is verified on `ws-etw`, and SilkService + -Alloy are removed** (DEVIATIONS D10, Done below). The always-on live capture now runs on it. **Now:** a benign -train capture with the new collector (07, from the RDP desktop) → `exp04` → full flow (Next 3 steps). No live -detection result so far is valid (DEVIATIONS D8 correction); exp03 does not match the new data (D10). +**The core concept demo WORKS end to end (2026-10-31, exp05, benign = idle pulled from Loki).** The path to +it: exp03 (broken SilkService data → all red) → exp04 (etwcollect scripted-workload capture: benign green but +attack MISSED, because the scripted workload's netcheck/download/cmd scenarios reused the attack's +living-off-the-land binaries) → user switched to **benign = idle, pulled directly from Loki, no capture +script** → **exp05**. + +- **exp05**: trained on a 16-min idle Loki range (`range-20261031T124500Z`, pre-attack idle, pulled with + `lab pull --start … --end … --split test`). Thin (FILE 339 / PROCESS 34 / NET 18 node-copies; net + `val_fpr=1.0`), but the per-subgraph SG-Det cut-off absorbs the per-node noise. +- **Result (session `live-20261031T134030Z`, fresh idle run):** idle windows **green** (13:45 = 13 flagged + but subgraph max 8.0 Minor, alert False; 13:50 green). Live DVWA→RCE attack (13:55Z, 2314 edges) **RED**: + 201 flagged, subgraph **106.96 Significant, alert True**; flagged nodes = the Kali stage IP + `10.21.2.30:8080`, `c:\users\public\downloaded_tool.bin` (T1105), the RCE `powershell.exe`, DVWA MariaDB + `127.0.0.1:3306`. **LLM triage `attack` (0.85)** + IOCs (full discovery chain) + report. Offline re-judge + (`rejudge.sh`) reproduces the subgraph + serialized attack document. End goal met. + +Note the subgraph correctly captured the discovery tools (whoami/net/systeminfo/schtasks) via their flagged +powershell parent even though each scored below τ individually — OCR-APT subgraph expansion working. + +**Cleanup done (2026-10-31):** both capture scripts removed (`06-benign-workload.ps1`, +`07-build-train-dataset.ps1`), `win_benign` role + `collect-train.yml` deleted, `windows.yml` / +`verify-windows.yml` / docs / memory updated. Benign = idle pulled from Loki (D2). DONE this session (2026-10-22, verified live): - **exp03** trained on the 1-h capture and **PROMOTED** (gate passed: 77-min kfile span, all 6 edge types @@ -52,9 +65,8 @@ OPEN (the real limitation): many per-instance processes are unseen in benign training → the *same* mechanism as the cradle. The fix is benign **variety** (training that covers browsing), **not** more capture time. DEVIATIONS D8, [[live-detector-benign-fp]]. -- LLM attack path (triage `attack` → IOCs → report) never run live: no attack subgraph yet. -- `06-benign-workload.ps1` **deadline-overrun bug** (the `while (now < deadline)` loop ran ~74 min for a - 60-min target because one scenario call blocked) — deferred, not yet debugged. +- LLM attack path (triage `attack` → IOCs → report) never run live: the exp04 attack formed no subgraph + (all attack nodes below τ), so the LLM never triggered. Pending exp05. ## Done @@ -181,7 +193,7 @@ OPEN (the real limitation): - Concepts 2 (rest) to 9. Phase 0 toy exercises; Phase 1 one-page paper summary + hyperparameter list. - LLM container; hardware recorded. - Replay equivalence check (`compare_replay.py`); user-confirmed runs of the selftests of - score_window.py / engine.py / etwship.py; a benign live run with `06-benign-workload.ps1`. + score_window.py / engine.py / etwship.py. - Test split capture, node labels, test scoring, NODLINK W10 detector baseline. - LLM: DeepSeek on a red window from a real attack (the RCE kill chain live), to see the attack path (triage → IOCs → report). Alg. 2 l.16–25 @@ -225,7 +237,6 @@ Code bugs found in the 2026-10-13 docs pass (verified in code, not fixed yet): - `build_node_labels.py` expects `node_id,type,name,timestamp`; the converter writes `node,node_type,node_attr` (no timestamp, types `PROCESS/FILE/NET`), and NET is checked as `network`. It cannot run as is. - `selftest.sh` skips `encode_to_features.py --selftest`. -- Runtime message names an old file: `07-build-train-dataset.ps1` ("05-collect-10-minutes-window.ps1"). - `src/Vagrantfile:13` names `./host-setup.sh`; the file is `src/setup-virtualbox.sh`. - `live_server.py --sg-moderate-from` hard-codes 30.0 instead of `alg1.MODERATE_FROM`. - Scenarios 05 (lsass handle access) and 09 (timestomp) may be invisible to the collector's file keywords @@ -237,15 +248,19 @@ Repo hygiene: - `src/out/etw/SimulatedW10_train_edges.csv` (old un-windowed capture) sits next to the experiment folders and is easy to pick by mistake (it caused the first, collapsed exp01 run). -## Next 3 steps (new collector in place — 2026-10-26) +## Next steps (2026-10-31, after the exp05 demo win) -1. Benign train capture with etwcollect: `07-build-train-dataset.ps1` from the RDP desktop (the first real use - of `etwctl` start/stop by 07 and of `etwcollect push-ledger`; check the ledger reaches Loki). Gate on - `lab status` coverage and Read/Write per window. Include browsing in the workload (browser FP). -2. `lab loop` → `exp04` → `lab promote exp04`; `ocr-live` restarts on it. Benign live windows should be green. -3. Full flow: DVWA→RCE from Kali during a live session: attack nodes flagged, LLM triage `attack` + report; - laptop replay as on 2026-10-25. +1. **Live UI: render the LLM report as HTML** (user, 2026-10-31). 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 + larger idle range from Loki (e.g. rotate a fresh idle run, let it sit ~30 min, `lab pull --latest + --split test`) and retrain for a less noisy per-node net model. The demo already works; this hardens it. +3. Concepts 2–4 (GNN basics, RGCN, one-class loss) for the write-up; replay equivalence via + `compare_replay.py` on the host (the trainer-side `rejudge.sh` already reproduced the attack subgraph). -Watch item: the first 15-min `07` run (`x-20261021T161810Z`) did not write `stopped_utc` (capture left -running); the 5-min smoke stopped cleanly, so likely a one-off — but confirm `07` stops the collector task -(`etwctl running` exits 1 afterwards) on the 2h run. +Note: benign = idle pulled from Loki (no capture script). To rebuild benign: `lab pull --start +--end --split test --yes` on a clean idle range, then `lab train --experiment --model `. +Training needs `_train_`-named edges, but a Loki idle pull is `--split test` → files are `_test_`: copy +`SimulatedW10_test_{edges,node_attrs}.csv` to `_train_` in the experiment folder before `lab train` +(or add split-awareness to `lab train`, which hardcodes `SimulatedW10_train_edges.csv`). diff --git a/docs/reports/teammate.md b/docs/reports/teammate.md index 33b98da..07683ed 100644 --- a/docs/reports/teammate.md +++ b/docs/reports/teammate.md @@ -22,7 +22,7 @@ Practical start for a teammate. Status lives in `docs/PROGRESS.md`, differences | replay a recorded capture | `./replay.sh ` | | re-judge a saved session (cut-off, LLM) | `./rejudge.sh [llm-provider]` | | build the VM | `src/ansible/README.md` | -| train data → model | `07-build-train-dataset.ps1` (VM) → `encode_to_features.py` → `train_gnn_models.py` (`src/README.md` → Data flow) | +| train data → model | benign = idle pulled from Loki (`lab pull --split test`) → `encode_to_features.py` → `train_gnn_models.py` (`src/README.md` → Data flow) | Step-by-step live runbook (replay check, live with the VM, alert rule, outputs): `src/live/README.md`. Before you touch anything, read the pitfalls table at the end of `src/README.md`. diff --git a/src/README.md b/src/README.md index ed6d4a1..9241aba 100644 --- a/src/README.md +++ b/src/README.md @@ -63,7 +63,7 @@ trained model is never overwritten. | `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) | -| `scripts/` | the two PowerShell scripts Ansible still deploys: `06-benign-workload.ps1`, `07-build-train-dataset.ps1` | VM | yes | +| _(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 | @@ -128,7 +128,6 @@ src/ │ ├── compare_replay.py checks that live results equal the offline pipeline │ ├── static/index.html the web UI │ └── sessions// per-session outputs (not in git) -├── scripts/ 06-benign-workload.ps1, 07-build-train-dataset.ps1 (deployed to C:\scripts) ├── 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 @@ -148,7 +147,7 @@ paths as they were at training time. They are a record of that run; do not edit ## Data flow -1. VM: `scripts/07` (training) or `start-live.ps1` (demo) captures; Alloy ships every line to Loki on the trainer. +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. @@ -162,7 +161,7 @@ records its sha256 and the live server compares it (`converter_check`). Edit it |---|---| | 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 workload → use `06-benign-workload.ps1` | +| 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) | diff --git a/src/ansible/README.md b/src/ansible/README.md index def0c17..88fcfbd 100644 --- a/src/ansible/README.md +++ b/src/ansible/README.md @@ -4,7 +4,7 @@ Provisions the lab the Vagrantfile builds (or any two cloud VMs in one subnet): | host (group) | address | role | |---|---|---| -| `ws-etw` (`windows`) | 10.21.2.10 | ETW collector **`etwcollect`** (`src/etw-python`, SYSTEM task `etwlab-collector`; it also pushes to Loki), benign workload, DVWA vulnlab (optional, `-e vulnlab_enabled=true`). No training. | +| `ws-etw` (`windows`) | 10.21.2.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. | | `ubuntu-trainer` (`ubuntu`) | 10.21.2.20 | **Loki + Grafana** (Docker, host network), repo + `uv sync`, training, `live_server.py` (systemd `ocr-live`, follows Loki). | > The lab also has a **Kali attacker VM** (`10.21.2.30`), but it is **not provisioned by Ansible** — it @@ -123,7 +123,7 @@ vagrant up # from src/, builds both bare VMs ansible ubuntu -m ping ansible windows -m ansible.windows.win_ping # use win_ping on Windows, NOT ping ansible-playbook site.yml --limit ubuntu # Loki + Grafana + repo + ocr-live -ansible-playbook site.yml --limit windows # etwcollect (uv) + scripts (+ vulnlab with -e vulnlab_enabled=true) +ansible-playbook site.yml --limit windows # etwcollect (uv) + start-live.ps1 (+ vulnlab with -e vulnlab_enabled=true) # cloud (the vault supplies the Windows + Grafana creds): ansible-playbook -i inventory.cloud.ini site.yml -e @group_vars/vault.yml --ask-vault-pass @@ -153,11 +153,14 @@ edit is live after `etwctl stop; etwctl start`; re-run `--tags collector` only w ```powershell # on ws-etw, elevated PowerShell in the RDP desktop session (not WinRM): -C:\scripts\06-benign-workload.ps1 -SelfTest # once per VM -C:\scripts\07-build-train-dataset.ps1 # 20-min benign capture, run x-; shipped to Loki live +# 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 --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 ``` -`07` still converts on the VM. That copy is now a cross-check; the training source is Loki. `etwctl stop` -waits until `etwcollect` has pushed its last lines, `07` then pushes the workload ledger +The training source is Loki (`etwcollect push-ledger`) and **copies** the raw files into the experiment folder. ```bash @@ -175,9 +178,6 @@ trainer) → `encode_to_features.py` → `train_gnn_models.py`, all into one run `group_vars` names the model. To share a model, commit its model folder and `lab promote --shared` (writes the tracked `current.json`). -`collect-train.yml` (tar the VM's experiment folder and fetch it) is the **legacy fallback**, for when Loki -is down. - **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`. @@ -188,9 +188,8 @@ is down. ## Demo (on `ws-etw`, elevated PowerShell in the RDP desktop session) ```powershell -C:\scripts\06-benign-workload.ps1 -SelfTest # once per VM C:\scripts\start-live.ps1 -Rotate # optional: fresh live run = a clean session for the demo -C:\scripts\06-benign-workload.ps1 -DurationMinutes 20 # benign activity (green windows) +# 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 @@ -234,7 +233,7 @@ windows stay green; the teammate's attack turns its window red. ## Layout ``` -ansible.cfg requirements.yml requirements.txt site.yml windows.yml ubuntu.yml collect-train.yml (legacy) +ansible.cfg requirements.yml requirements.txt site.yml windows.yml ubuntu.yml inventory.local.ini inventory.cloud.ini.example group_vars/ all.yml windows.yml ubuntu.yml vault.yml.example roles/ @@ -242,7 +241,6 @@ roles/ 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_benign 06-benign-workload.ps1 + 07-build-train-dataset.ps1 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) diff --git a/src/ansible/collect-train.yml b/src/ansible/collect-train.yml deleted file mode 100644 index cb4efac..0000000 --- a/src/ansible/collect-train.yml +++ /dev/null @@ -1,83 +0,0 @@ ---- -# Move a TRAIN experiment built by 07-build-train-dataset.ps1 off the Windows VM: -# Windows C:\lab-out\etw\experiments\ -> .tar.gz -> control node src/out/etw/experiments/ -# -> unpacked on the control node (EDA notebooks) and in the Ubuntu repo (training). -# -# ansible-playbook collect-train.yml # newest experiment -# ansible-playbook collect-train.yml -e collect_id=20261017T030000Z -# -# LEGACY fallback (Loki down). Normal path: `lab loop` on the trainer. collect_id = the experiment folder. - -- name: Pack the experiment on Windows and fetch it to the control node - hosts: windows - gather_facts: false - vars: - exp_root: 'C:\lab-out\etw\experiments' - tasks: - - name: List experiment folders - ansible.windows.win_find: - paths: "{{ exp_root }}" - file_type: directory - register: exp_dirs - when: collect_id is not defined - - - name: Pick the newest experiment (folder names are UTC timestamps, so name order = time order) - ansible.builtin.set_fact: - collect_id: "{{ exp_dirs.files | map(attribute='filename') | sort | last | default('') }}" - when: collect_id is not defined - - - name: Fail if there is nothing to collect - ansible.builtin.assert: - that: collect_id is defined and collect_id | length > 0 - fail_msg: "no experiment folder under {{ exp_root }}; run C:\\scripts\\07-build-train-dataset.ps1 first" - - - name: Pack it with the built-in tar.exe (Compress-Archive in PS 5.1 writes backslash zip paths) - ansible.windows.win_command: >- - tar.exe -czf "{{ exp_root }}\{{ collect_id }}.tar.gz" -C "{{ exp_root }}" "{{ collect_id }}" - args: - creates: '{{ exp_root }}\{{ collect_id }}.tar.gz' - - - name: Fetch the archive to the control node - ansible.builtin.fetch: - src: '{{ exp_root }}\{{ collect_id }}.tar.gz' - dest: "{{ src_dir }}/out/etw/experiments/{{ collect_id }}.tar.gz" - flat: true - -- name: Unpack on the control node - hosts: localhost - connection: local - gather_facts: false - vars: - collect_id: "{{ hostvars[groups['windows'][0]].collect_id }}" - tasks: - - name: Unpack into src/out/etw/experiments - ansible.builtin.unarchive: - src: "{{ src_dir }}/out/etw/experiments/{{ collect_id }}.tar.gz" - dest: "{{ src_dir }}/out/etw/experiments" - remote_src: true - creates: "{{ src_dir }}/out/etw/experiments/{{ collect_id }}/experiment.json" - -- name: Unpack in the Ubuntu repo - hosts: ubuntu - gather_facts: false - vars: - collect_id: "{{ hostvars[groups['windows'][0]].collect_id }}" - exp_dest: "{{ repo_dest }}/src/out/etw/experiments" - tasks: - - name: Ensure the experiments dir exists - ansible.builtin.file: - path: "{{ exp_dest }}" - state: directory - mode: "0755" - - - name: Copy and unpack the archive - ansible.builtin.unarchive: - src: "{{ src_dir }}/out/etw/experiments/{{ collect_id }}.tar.gz" - dest: "{{ exp_dest }}" - creates: "{{ exp_dest }}/{{ collect_id }}/experiment.json" - - - name: Next step - ansible.builtin.debug: - msg: >- - {{ collect_id }} is in {{ exp_dest }}. On the trainer: `lab train --experiment {{ collect_id }} --model `, then - `lab promote ` and `sudo systemctl restart ocr-live`. diff --git a/src/ansible/roles/win_benign/tasks/main.yml b/src/ansible/roles/win_benign/tasks/main.yml deleted file mode 100644 index 23ad4be..0000000 --- a/src/ansible/roles/win_benign/tasks/main.yml +++ /dev/null @@ -1,18 +0,0 @@ ---- -# Deploy the scripted benign workload (06) and the training-dataset orchestrator (07). -# 06 launches user apps THROUGH explorer.exe so the provenance graph does not learn PowerShell as the -# benign parent (CLAUDE §9). Both must run INTERACTIVELY in the RDP desktop session, not over WinRM: -# C:\scripts\06-benign-workload.ps1 -SelfTest # once per VM -# C:\scripts\07-build-train-dataset.ps1 # new TRAIN experiment (capture + 06 + windows) -# C:\scripts\06-benign-workload.ps1 -DurationMinutes 20 # during the demo, next to ship-live.ps1 -# 07 finds 06 via $PSScriptRoot, so both live in C:\scripts. Afterwards: ansible-playbook collect-train.yml - -- name: Deploy the benign workload generator - ansible.windows.win_copy: - src: "{{ src_dir }}/scripts/06-benign-workload.ps1" - dest: 'C:\scripts\06-benign-workload.ps1' - -- name: Deploy the training-dataset orchestrator - ansible.windows.win_copy: - src: "{{ src_dir }}/scripts/07-build-train-dataset.ps1" - dest: 'C:\scripts\07-build-train-dataset.ps1' diff --git a/src/ansible/verify-windows.yml b/src/ansible/verify-windows.yml index 324fab1..f12b163 100644 --- a/src/ansible/verify-windows.yml +++ b/src/ansible/verify-windows.yml @@ -71,19 +71,15 @@ "{{ tools_dir }}\python-embed\{{ python_embed_version }}\python.exe" "{{ lab_home }}\etw2nodlink.py" --selftest changed_when: false - # ---------- win_shipper / win_benign ---------- - - name: Shipper + benign scripts present (win_shipper, win_benign) + # ---------- win_shipper ---------- + - name: Shipper script present (win_shipper) ansible.windows.win_stat: - path: "{{ item }}" - loop: - - 'C:\scripts\start-live.ps1' - - 'C:\scripts\06-benign-workload.ps1' - - 'C:\scripts\07-build-train-dataset.ps1' - register: scripts_stat + path: 'C:\scripts\start-live.ps1' + register: shipper_stat - ansible.builtin.assert: - that: scripts_stat.results | map(attribute='stat.exists') | min - fail_msg: "A script is missing — run roles win_shipper / win_benign" - success_msg: "start-live.ps1 + benign workload (06/07) present" + that: shipper_stat.stat.exists + fail_msg: "start-live.ps1 missing — run role win_shipper" + success_msg: "start-live.ps1 present (always-on live capture)" # ---------- win_vulnlab / DVWA (only when enabled) ---------- - name: DVWA checks (win_vulnlab) diff --git a/src/ansible/windows.yml b/src/ansible/windows.yml index 6f0f963..2ebf798 100644 --- a/src/ansible/windows.yml +++ b/src/ansible/windows.yml @@ -13,5 +13,4 @@ - { role: win_base, tags: [base] } # OS config: network profile, UTC+7 clock, no-sleep, RDP, folders, Defender - { role: win_collector, tags: [collector] } # etwcollect (uv; ETW -> files -> Loki) + embeddable Python + converter + etwctl - { role: win_shipper, tags: [shipper] } # start-live.ps1: start/stop a live (test) capture; etwcollect ships it - - { role: win_benign, tags: [benign] } # scripted benign workload generator (green windows for the demo) - { role: win_vulnlab, tags: [vulnlab], when: vulnlab_enabled | bool } # XAMPP + DVWA on {{ vulnlab_port }}; -e vulnlab_enabled=true diff --git a/src/atomic-attack-pack/LABELING.md b/src/atomic-attack-pack/LABELING.md index 7f7b26e..b5e7cba 100644 --- a/src/atomic-attack-pack/LABELING.md +++ b/src/atomic-attack-pack/LABELING.md @@ -31,8 +31,9 @@ window times in `sessions//windows.csv`; same join. range narrows this; a process key (PID + start time) would narrow it further. - **Oracle errors move the metric:** over-labelling hurts the detector's apparent precision, under-labelling flatters it. -- **Embed attacks in benign noise:** run with `06-benign-workload.ps1`, or every node in an attack window is - malicious and the task collapses to "did anything happen". +- **Embed attacks in benign noise:** run the attack while the always-on live capture is recording natural + desktop activity (browse, docs), or every node in an attack window is malicious and the task collapses to + "did anything happen". - **Class imbalance:** malicious nodes are a tiny fraction; prefer P/R/F1 over accuracy. [PAPER] OCR-APT labels come from DARPA ground truth / analyst reports (§7 flags label-provenance issues even diff --git a/src/atomic-attack-pack/README.md b/src/atomic-attack-pack/README.md index c391994..dfcd8af 100644 --- a/src/atomic-attack-pack/README.md +++ b/src/atomic-attack-pack/README.md @@ -33,11 +33,13 @@ The launcher + scripts are mounted into the Kali VM at `/opt/attack-pack` by Vag ## Run during a live session (end-goal path) -1. **Target VM (`ws-etw`)**, RDP desktop, two shells: +1. **Target VM (`ws-etw`)**, RDP desktop: ```powershell - C:\scripts\start-live.ps1 # shell 1: start the test capture; Alloy ships it to Loki - C:\scripts\06-benign-workload.ps1 # shell 2: benign noise, so the window is not all-malicious + 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 mounted at `/opt/attack-pack`), the only required input is the vulnerable web URL: ```bash python3 -I /opt/attack-pack/tools/launch_exploit.py --target http://10.21.2.10:3000 diff --git a/src/live/README.md b/src/live/README.md index 5d94d08..a4976f5 100644 --- a/src/live/README.md +++ b/src/live/README.md @@ -66,14 +66,13 @@ The trainer runs `ocr-live` (systemd, `src/ansible/roles/ubuntu_project`), which **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, and leaves the collector alone while a hold exists -(`07-build-train-dataset.ps1` pauses it for a train capture and resumes it after). By hand, in an elevated +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 -C:\scripts\06-benign-workload.ps1 # benign activity, as in training (RDP desktop only; not automatic) +# 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. Old `live-*` session folders on the trainer (each holds a raw copy, ~2 GB/h) are deleted after 12 idle hours (`live_session_keep_hours`; a diff --git a/src/scripts/06-benign-workload.ps1 b/src/scripts/06-benign-workload.ps1 deleted file mode 100644 index 3b68165..0000000 --- a/src/scripts/06-benign-workload.ps1 +++ /dev/null @@ -1,235 +0,0 @@ -<# -.SYNOPSIS - 06-benign-workload.ps1 - scripted benign "office/developer user" activity for the - SimulatedW10 ETW lab (NT2102 / OCR-APT POC). - -.DESCRIPTION - Runs a seeded random sequence of benign scenarios (browse, notes, office docs, downloads, - file ops, network checks, Explorer, Paint) for -DurationMinutes. - User apps are launched THROUGH explorer.exe (Shell COM), so in the provenance graph their - parent is explorer.exe like a real user's, not this powershell.exe. Reason: the attack side - (Invoke-AtomicRedTeam) runs via powershell.exe; if benign training data showed powershell.exe - spawning everything, the one-class model would learn the attacker's parent process as "normal". - - The script writes NOTHING to disk itself during the run (the ledger is buffered in memory and - written at the end), so its own footprint in the capture stays small. - -.NOTES - Run INSIDE the VM in the interactive desktop session (console/RDP window that stays open and - unminimised), NOT via `vagrant powershell`/WinRM: that is a non-interactive session where GUI - apps and SendKeys don't behave like a user. - - Once per VM (before any capture): .\06-benign-workload.ps1 -SelfTest - Warm-up run (not captured), so first-run effects (Edge welcome, Office activation) are gone: - .\06-benign-workload.ps1 -DurationMinutes 5 -Seed 1 - Real capture (manual): etwctl start -Split train ; .\06-benign-workload.ps1 -DurationMinutes 20 -PauseBeforeLedger - Real capture (automated): .\07-build-train-dataset.ps1 (passes -BeforeLedger = "stop the capture") -#> -[CmdletBinding()] -param( - [int]$DurationMinutes = 20, - [int]$Seed = 42, # fixes the scenario sequence and choices (not OS timing) - [int]$MinGapSec = 10, # idle time between scenarios - [int]$MaxGapSec = 45, - [string]$WorkDir = "$env:USERPROFILE\Documents\work", - [string]$LedgerDir = 'C:\lab-labels\benign', - [switch]$IncludeUserPowerShell, # opt-in: benign powershell.exe usage (see DESCRIPTION) - [switch]$PauseBeforeLedger, # wait for Enter (after you run `etwctl stop`) before writing the ledger - [scriptblock]$BeforeLedger, # automation hook: run before the ledger is written (07 passes "stop capture") - [switch]$SelfTest # check launcher parentage, Office, curl/tar, session; then exit -) -Set-StrictMode -Version Latest # like "use strict": undefined variables are errors -$ErrorActionPreference = 'Stop' # make cmdlet errors throw (so try/catch works) - -# ---------------------------------------------------------------- helpers -$Rng = [System.Random]::new($Seed) # one seeded RNG for every random choice below -$Wsh = New-Object -ComObject WScript.Shell # in-process COM: AppActivate/SendKeys, spawns nothing -$Ledger = New-Object System.Collections.Generic.List[object] -$script:Shell = $null -$script:LaunchMode = 'direct' - -function Pick([object[]]$Items) { $Items[$Rng.Next($Items.Count)] } -function Dwell([int]$Min, [int]$Max) { Start-Sleep -Seconds $Rng.Next($Min, $Max + 1) } - -function Add-Ledger([string]$Scenario, [string]$Action, [string]$Target) { - $Ledger.Add([pscustomobject]@{ - utc = (Get-Date).ToUniversalTime().ToString('o'); scenario = $Scenario - action = $Action; target = $Target; launch_mode = $script:LaunchMode }) -} - -function Initialize-Launcher { - # ShellWindows / ShellBrowserWindow are COM objects SERVED BY the running explorer.exe. - # ShellExecute on them asks explorer to start the program => parent = explorer.exe. - $candidates = @( - @{ Clsid = '9BA05972-F6A8-11CF-A442-00A0C90A8F39'; Get = { param($o) $o.Item().Document.Application } }, # ShellWindows - @{ Clsid = 'C08AFD90-F2A1-11D1-8455-00A0C91F3880'; Get = { param($o) $o.Document.Application } } # ShellBrowserWindow - ) - foreach ($c in $candidates) { - try { - $obj = [Activator]::CreateInstance([Type]::GetTypeFromCLSID($c.Clsid)) - $app = & $c.Get $obj - if ($null -ne $app) { $script:Shell = $app; $script:LaunchMode = 'explorer-com'; return } - } catch { } - } - Write-Warning 'Explorer COM launcher unavailable -> Start-Process fallback (parent = powershell.exe).' -} - -function Invoke-App([string]$File, [string]$Arguments = '', [int]$Show = 1) { - # $Show: 1 = normal window, 0 = hidden (for cmd one-liners) - if ($script:Shell) { $script:Shell.ShellExecute($File, $Arguments, $WorkDir, 'open', $Show) } - else { - $p = @{ FilePath = $File; WorkingDirectory = $WorkDir } # @{} = hashtable; @p below = "splat" it as named args - if ($Arguments) { $p.ArgumentList = $Arguments } - if ($Show -eq 0) { $p.WindowStyle = 'Hidden' } - Start-Process @p - } -} - -# A "user typing in a terminal": cmd.exe child of explorer.exe, its tools children of cmd.exe. -function Invoke-Cmd([string]$CommandLine, [int]$WaitSec = 5) { - Invoke-App 'cmd.exe' "/c $CommandLine" 0 - Start-Sleep -Seconds $WaitSec -} - -# Politely close windows (WM_CLOSE), like clicking X. No process is spawned to do it. -function Close-Windows([string[]]$Names) { - Get-Process -Name $Names -ErrorAction SilentlyContinue | - Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero } | - ForEach-Object { [void]$_.CloseMainWindow() } -} - -function Close-ExplorerWindows { - # Close folder windows we opened (Quit() is a COM call into explorer, no new process). - (New-Object -ComObject Shell.Application).Windows() | - Where-Object { $_.LocationURL -like 'file:///*' } | ForEach-Object { $_.Quit() } -} - -function Get-OfficeInfo { - $ap = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths' - [pscustomobject]@{ Word = Test-Path "$ap\WINWORD.EXE"; Excel = Test-Path "$ap\EXCEL.EXE" } -} - -# ---------------------------------------------------------------- content pools (fixed => reproducible) -$Urls = @('https://en.wikipedia.org/wiki/Provenance', 'https://learn.microsoft.com/en-us/windows/', - 'https://github.com/explore', 'https://stackoverflow.com/questions', 'https://www.bbc.com/news', - 'https://docs.python.org/3/tutorial/') -$Downloads = @('https://www.rfc-editor.org/rfc/rfc2616.txt', 'https://www.gutenberg.org/cache/epub/1342/pg1342.txt', - 'https://www.python.org/static/img/python-logo.png') -$Sentences = @('Follow up with the team about the release.', 'Review the quarterly budget draft.', - 'Book a room for the Thursday meeting.', 'Update the onboarding checklist.') # no SendKeys specials: + ^ % ~ ( ) { } [ ] - -# ---------------------------------------------------------------- scenarios -$Scenarios = @{ - browse = { - $u = Pick $Urls; Invoke-App $u; Add-Ledger 'browse' 'open_url' $u # URL -> default browser (Edge) - Dwell 20 60 - if ($Rng.Next(2) -eq 0) { $u2 = Pick $Urls; Invoke-App $u2; Add-Ledger 'browse' 'open_url' $u2; Dwell 15 40 } - Close-Windows 'msedge' - } - notes = { - $f = Join-Path $WorkDir ('note_{0:yyyyMMdd_HHmmss}.txt' -f (Get-Date)) - Invoke-Cmd "echo Notes>`"$f`"" 3 # cmd.exe creates the file - Invoke-App 'notepad.exe' "`"$f`""; Add-Ledger 'notes' 'edit' $f - Start-Sleep -Seconds 3 - if ($Wsh.AppActivate([IO.Path]::GetFileName($f))) { # focus by window-title prefix - $Wsh.SendKeys('^{END}{ENTER}' + (Pick $Sentences)); Start-Sleep 1 - $Wsh.SendKeys('^s') # notepad.exe writes the file - } else { Add-Ledger 'notes' 'warn_no_focus' $f } - Dwell 5 20; Close-Windows 'notepad' - } - office = { - if ($Rng.Next(2) -eq 0) { - $f = Join-Path $WorkDir 'report.rtf' - Invoke-Cmd "echo {\rtf1\ansi Weekly report draft.}>`"$f`"" 3 - $handler = if ((Get-OfficeInfo).Word) { 'winword' } else { 'wordpad' } - } else { - $f = Join-Path $WorkDir 'inventory.csv' - Invoke-Cmd "(echo item,qty& echo laptop,3& echo monitor,5)>`"$f`"" 3 - $handler = if ((Get-OfficeInfo).Excel) { 'excel' } else { 'notepad' } - } - Invoke-App $f; Add-Ledger 'office' "open_via_$handler" $f # file association picks the app - Dwell 15 45; Close-Windows @('winword', 'wordpad', 'excel', 'notepad') - } - download = { - $u = Pick $Downloads; $dst = Join-Path $WorkDir ('dl\' + [IO.Path]::GetFileName($u)) - Invoke-Cmd "mkdir `"$WorkDir\dl`" 2>nul & curl.exe -sSL -o `"$dst`" $u" 10 - Add-Ledger 'download' 'curl' $u - } - files = { - $stamp = '{0:HHmmss}' -f (Get-Date) - Invoke-Cmd ("cd /d `"$WorkDir`" & xcopy /y /q *.txt backup_$stamp\ >nul & " + - "tar -a -c -f archive_$stamp.zip backup_$stamp & rmdir /s /q backup_$stamp") 8 - Add-Ledger 'files' 'copy_zip_cleanup' "archive_$stamp.zip" - } - netcheck = { - Invoke-Cmd 'ipconfig /all >nul & ping -n 2 1.1.1.1 >nul & nslookup github.com >nul' 8 - Add-Ledger 'netcheck' 'ipconfig_ping_nslookup' '' - } - explore = { - $d = Pick @($WorkDir, "$env:USERPROFILE\Downloads", "$env:USERPROFILE\Pictures") - Invoke-App $d; Add-Ledger 'explore' 'open_folder' $d - Dwell 5 20; Close-ExplorerWindows - } - paint = { - Invoke-App 'mspaint.exe'; Add-Ledger 'paint' 'open' 'mspaint.exe' - Dwell 10 30; Close-Windows 'mspaint' - } - user_powershell = { - Invoke-App 'powershell.exe' "-NoProfile -Command Get-ChildItem '$WorkDir' -Recurse | Measure-Object" 0 - Add-Ledger 'user_powershell' 'dir_count' $WorkDir; Start-Sleep 5 - } -} - -# Ordered list = weights (an ordered array, not a hashtable, so the pick sequence is deterministic). -$Weighted = @('browse','browse','browse','notes','notes','office','office','download', - 'files','netcheck','explore','paint') -if ($IncludeUserPowerShell) { $Weighted += 'user_powershell' } - -# ---------------------------------------------------------------- self-test -if ($SelfTest) { - Initialize-Launcher - $since = Get-Date - Invoke-App 'notepad.exe'; Start-Sleep 3 - $np = Get-Process notepad -ErrorAction SilentlyContinue | Where-Object { $_.StartTime -ge $since } | Select-Object -First 1 - $parent = if ($np) { - $ppid = (Get-CimInstance Win32_Process -Filter "ProcessId=$($np.Id)").ParentProcessId - (Get-Process -Id $ppid -ErrorAction SilentlyContinue).ProcessName } else { '' } - Close-Windows 'notepad' - [pscustomobject]@{ # returned as an object (07 reads it); the console shows it as a list - LaunchMode = $script:LaunchMode - NotepadParent = $parent # expect: explorer - InteractiveSess = (Get-Process -Id $PID).SessionId -ne 0 - WordInstalled = (Get-OfficeInfo).Word - ExcelInstalled = (Get-OfficeInfo).Excel - CurlPresent = [bool](Get-Command curl.exe -ErrorAction SilentlyContinue) - TarPresent = [bool](Get-Command tar.exe -ErrorAction SilentlyContinue) - } - return -} - -# ---------------------------------------------------------------- main loop -New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null # before capture ideally; idempotent -Initialize-Launcher -$started = (Get-Date).ToUniversalTime() -$deadline = (Get-Date).AddMinutes($DurationMinutes) -Write-Host "Benign workload: seed=$Seed, $DurationMinutes min, launcher=$($script:LaunchMode)" -try { - while ((Get-Date) -lt $deadline) { - $name = Pick $Weighted - Write-Host ("{0:HH:mm:ss} {1}" -f (Get-Date), $name) - try { & $Scenarios[$name] } catch { Add-Ledger $name 'error' $_.Exception.Message } - Start-Sleep -Seconds $Rng.Next($MinGapSec, $MaxGapSec + 1) - } -} -finally { # runs even on Ctrl+C, so the ledger is never lost - if ($BeforeLedger) { & $BeforeLedger } # automated: stop the capture first (07) - elseif ($PauseBeforeLedger) { Read-Host 'Run `etwctl stop` now, then press Enter to write the ledger' | Out-Null } - New-Item -ItemType Directory -Force -Path $LedgerDir | Out-Null - $base = Join-Path $LedgerDir ('benign_{0:yyyyMMddTHHmmssZ}' -f $started) - $Ledger | Export-Csv "$base.csv" -NoTypeInformation - [pscustomobject]@{ seed = $Seed; duration_min = $DurationMinutes; started_utc = $started.ToString('o') - launch_mode = $script:LaunchMode; office = Get-OfficeInfo - os_build = [Environment]::OSVersion.Version.ToString(); scenarios = ($Weighted | Select-Object -Unique) - } | ConvertTo-Json -Depth 3 | Set-Content "$base.json" - Write-Host "Ledger: $base.csv ($($Ledger.Count) actions)" -} \ No newline at end of file diff --git a/src/scripts/07-build-train-dataset.ps1 b/src/scripts/07-build-train-dataset.ps1 deleted file mode 100644 index edd63d6..0000000 --- a/src/scripts/07-build-train-dataset.ps1 +++ /dev/null @@ -1,398 +0,0 @@ -#Requires -RunAsAdministrator -<# -.SYNOPSIS - 07-build-train-dataset.ps1 - one benign TRAIN experiment, end to end, into its own folder - (NT2102 / OCR-APT POC, SimulatedW10 ETW lab VM). - -.DESCRIPTION - 1. preflight interactive desktop session, no other capture running (the always-on live capture is paused automatically), tools present, workload self-test - (explorer.exe must be the launcher, otherwise benign apps get powershell.exe as parent) - 2. capture etwctl start -Split train -Run x- -> settle -> 06-benign-workload.ps1 - -> etwctl stop (called from the workload's -BeforeLedger hook, so the ledger write - happens AFTER the capture and is not in the data) - 3. collect copy the run's raw JSON into \raw\train\x-\ (the collector has shipped it to Loki) - 4. convert etw2nodlink.py on \raw only -> \converted\ (un-windowed, + _summary.json) - 5. window etwwindow.py -> \ - SimulatedW10_train_edges.csv pooled windows, node IDs prefixed w0007_ <- host: encode_to_features.py - SimulatedW10_train_node_attrs.csv same prefixes - windows.csv, manifest.json per-window counts, parameters, totals - 6. check check_rdf_input.py: the pair meets transform_to_RDF.py's input contract -> \check.json - 7. record \experiment.json: seed, durations, window params, tool hashes, totals, label source - - = C:\lab-out\etw\experiments\\ ; \labels\ holds the workload ledger. - -.EXAMPLE - .\07-build-train-dataset.ps1 # 20-min workload, seed 42, 5-min windows / 2-min stride - .\07-build-train-dataset.ps1 -Seed 7 -DurationMinutes 30 - .\07-build-train-dataset.ps1 -PostProcess C:\lab-out\etw\experiments\20261009T150000Z # redo steps 4-7 only - -.NOTES - Run in an ELEVATED PowerShell inside the VM's RDP/console desktop (not vagrant powershell / WinRM). - Elevation is needed for the ETW collector; the workload still starts apps through explorer.exe, so they run - un-elevated with explorer as parent, like a real user. - Needs etwwindow.py, installed by the win_collector Ansible role. -#> -[CmdletBinding()] -param( - [ValidateRange(5, 1440)] [int] $DurationMinutes = 20, - [int] $Seed = 42, - [ValidateRange(1, 120)] [int] $WindowMinutes = 5, - [ValidateRange(1, 120)] [int] $StrideMinutes = 2, - [ValidateRange(10, 3600)] [int] $MaxGapSeconds = 120, - [ValidateRange(0, 600)] [int] $SettleSeconds = 30, # idle capture before the workload starts - [ValidateRange(0, 600)] [int] $ShipWaitSeconds = 15, # after the stop: let the tail reach Loki - [switch] $IncludeUserPowerShell, - [switch] $AllowFallbackLauncher, # accept powershell.exe as app parent (not advised) - [switch] $KeepWorkDir, # default: empty Documents\work so every run starts equal - [string] $ExperimentsRoot = 'C:\lab-out\etw\experiments', - [string] $WorkloadScript = (Join-Path $PSScriptRoot '06-benign-workload.ps1'), - [string] $PostProcess # existing folder: run steps 4-7 only -) -$ErrorActionPreference = 'Stop' # cmdlet errors throw. (No Set-StrictMode here: it would leak into etwctl.ps1.) - -$Split = 'train' -$LabDir = 'C:\ProgramData\etwlab' -$EtwctlPs1 = Join-Path $LabDir 'etwctl.ps1' -$WinPy = Join-Path $LabDir 'etwwindow.py' -$CheckPy = Join-Path $LabDir 'check_rdf_input.py' -$Utf8 = New-Object System.Text.UTF8Encoding($false) # UTF-8 without BOM (PS 5.1 Set-Content adds one) - -$CheckTool = @' -"""check_rdf_input.py - verify a __{edges,node_attrs}.csv pair meets what -OCR-APT's transform_to_RDF.py (--dataset nodlink) and encode_to_PyG.py assume. - - python check_rdf_input.py --dir [--graph SimulatedW10] [--split train] [--out check.json] - exit 0 = OK (warnings allowed), 1 = contract violated, 2 = files missing - -Contract (repo refs = OCR-APT transform_to_RDF.py / encode_to_PyG.py): - edges header source-id,source-type,destination-id,destination-type,edge-type,timestamp - (pd.read_csv with header, l.82; column names used l.89, l.219-227, l.253-260) - attrs header node,node_type,node_attr (l.158-162; node_type only read with --adjust-uuid) - ids, types, edge types are pasted into IRIs: prefix + "node/" + id, prefix + edge-type (l.134, l.222) - -> no whitespace or IRI-illegal characters - node_attr is pasted between double quotes into N-Triples (l.162, l.236-237) -> no " tab or newline - (backslashes are fine: the .nt writer doubles them, l.403-404) - timestamp integer epoch MILLISECONDS for SimulatedW10 (encode_to_PyG.py l.167-168 divides gaps by 1000) - one type per node id, or get_all_nodes_df (l.253-260) emits two node-type triples for it -Stdlib only. -""" -import argparse, collections, csv, json, os, re, sys -from datetime import datetime, timezone - -EDGE_HEADER = ["source-id", "source-type", "destination-id", "destination-type", "edge-type", "timestamp"] -NODE_HEADER = ["node", "node_type", "node_attr"] -IRI_BAD = re.compile(r'[\s<>"{}|^`\\]') # chars not allowed raw inside an IRI -MS_LO, MS_HI = 946684800000, 4102444800000 # 2000-01-01 .. 2100-01-01 in epoch ms -MIN_NODE_REPR = 5 # transform_to_RDF --min-node-representation default (l.20) - - -def check(d, graph, split): - edges = os.path.join(d, f"{graph}_{split}_edges.csv") - attrs = os.path.join(d, f"{graph}_{split}_node_attrs.csv") - for p in (edges, attrs): - if not os.path.isfile(p): - return {"ok": False, "errors": [f"missing {p}"], "warnings": []}, 2 - err, warn = collections.Counter(), collections.Counter() - ex = {} # first example per problem - - def bad(kind, sample, hard=True): - (err if hard else warn)[kind] += 1 - ex.setdefault(kind, sample) - - node_type, edge_types = {}, collections.Counter() - ts_min, ts_max, n_edges = None, None, 0 - with open(edges, newline="", encoding="utf-8") as fh: - r = csv.reader(fh) - hdr = next(r, None) - if hdr != EDGE_HEADER: - return {"ok": False, "errors": [f"edges header {hdr} != {EDGE_HEADER}"], "warnings": []}, 1 - for row in r: - n_edges += 1 - if len(row) != 6: - bad("edge_row_width", row); continue - s, st, o, ot, et, ts = row - for nid, nt in ((s, st), (o, ot)): - if not nid or IRI_BAD.search(nid): - bad("node_id_not_iri_safe", nid) - if not nt or IRI_BAD.search(nt): - bad("node_type_not_iri_safe", nt) - prev = node_type.setdefault(nid, nt) - if prev != nt: - bad("node_has_two_types", f"{nid}: {prev} / {nt}") - et_last = et.split("/")[-1] # SimulatedW10: edge-type split on '/' (l.89-90) - if not et_last or IRI_BAD.search(et_last): - bad("edge_type_not_iri_safe", et) - edge_types[et_last] += 1 - try: - t = int(ts) - except ValueError: - bad("timestamp_not_int", ts); continue - if not MS_LO <= t <= MS_HI: - bad("timestamp_not_epoch_ms", ts); continue - ts_min = t if ts_min is None else min(ts_min, t) - ts_max = t if ts_max is None else max(ts_max, t) - - attr_nodes, n_attrs = set(), 0 - with open(attrs, newline="", encoding="utf-8") as fh: - r = csv.reader(fh) - hdr = next(r, None) - if hdr != NODE_HEADER: - bad("attrs_header", hdr) - else: - for row in r: - n_attrs += 1 - if len(row) != 3: - bad("attr_row_width", row); continue - n, nt, a = row - if n in attr_nodes: - bad("attr_duplicate_node", n, hard=False) - attr_nodes.add(n) - if any(c in a for c in '"\t\r\n'): - bad("attr_breaks_ntriples", a) - if n in node_type and node_type[n] != nt: - bad("attr_type_differs_from_edges", f"{n}: {node_type[n]} / {nt}") - if n not in node_type: - bad("attr_for_node_without_edges", n, hard=False) - - missing = [n for n in node_type if n not in attr_nodes] - if missing: - warn["node_without_attr"] += len(missing) - ex.setdefault("node_without_attr", missing[0]) - type_counts = collections.Counter(node_type.values()) - for t, c in type_counts.items(): - if c <= MIN_NODE_REPR: # would be dropped by get_remove_nodeType_lst (l.266-288) - bad(f"node_type_rare:{t}", c, hard=False) - - def utc(ms): - return None if ms is None else datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat() - - res = { - "ok": not err, "dir": d, "graph": graph, "split": split, - "edges": n_edges, "attr_rows": n_attrs, "nodes": len(node_type), - "node_types": dict(type_counts.most_common()), "edge_types": dict(edge_types.most_common()), - "time_utc": [utc(ts_min), utc(ts_max)], - "minutes": None if ts_min is None else round((ts_max - ts_min) / 60000, 1), - "errors": dict(err), "warnings": dict(warn), "examples": {k: str(v)[:200] for k, v in ex.items()}, - } - return res, (0 if not err else 1) - - -def main(argv=None): - ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - ap.add_argument("--dir", required=True) - ap.add_argument("--graph", default="SimulatedW10") - ap.add_argument("--split", default="train") - ap.add_argument("--out") - a = ap.parse_args(argv) - res, code = check(a.dir, a.graph, a.split) - txt = json.dumps(res, indent=1) - if a.out: - with open(a.out, "w", encoding="utf-8") as fh: - fh.write(txt) - print(json.dumps({k: res.get(k) for k in ("ok", "edges", "nodes", "minutes", "errors", "warnings")})) - return code - - -if __name__ == "__main__": - sys.exit(main()) -'@ - -function Log([string]$m) { Write-Host ('[07 {0:HH:mm:ss}] {1}' -f (Get-Date), $m) } -function Utc-Now { (Get-Date).ToUniversalTime().ToString('o') } -function Write-Text([string]$Path, [string]$Text) { [IO.File]::WriteAllText($Path, $Text, $Utf8) } -function Write-Json([string]$Path, $Obj) { Write-Text $Path ($Obj | ConvertTo-Json -Depth 8) } -function Sha([string]$Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash.ToLower() } else { $null } } - -# Run a native program; throw unless its exit code is in $Ok. (Like `cmd || exit` in bash.) -function Invoke-Native([string]$Exe, [string[]]$ArgList, [int[]]$Ok = @(0)) { - $global:LASTEXITCODE = 0 - & $Exe @ArgList | Out-Host # show the tool's output; keep only the exit code as return value - if ($Ok -notcontains $LASTEXITCODE) { throw "$([IO.Path]::GetFileName($Exe)) exited with $LASTEXITCODE" } - return $LASTEXITCODE -} - -# ---------------------------------------------------------------- config + tools -$Cfg = Get-Content (Join-Path $LabDir 'etwlab.json') -Raw | ConvertFrom-Json # written by the win_collector role -foreach ($p in @($Cfg.Python, $Cfg.Converter, $EtwctlPs1)) { - if (-not (Test-Path $p)) { throw "missing $p - re-run windows.yml (win_collector)" } -} -if (-not (Test-Path $WinPy)) { throw "missing $WinPy - run '05-collect-10-minutes-window.ps1 -WindowOnly' once to install it" } -# install/refresh the checker only when its content changed (keeps the file's hash stable across runs) -if (-not (Test-Path $CheckPy) -or [IO.File]::ReadAllText($CheckPy) -ne $CheckTool) { Write-Text $CheckPy $CheckTool } -$Graph = $Cfg.Graph - -# ---------------------------------------------------------------- steps 4-7 (also used by -PostProcess) -function Complete-Experiment([string]$Exp, [System.Collections.IDictionary]$Record) { - $conv = Join-Path $Exp 'converted' - Log "convert $Exp\raw -> $conv" - Invoke-Native $Cfg.Python @($Cfg.Converter, '--raw-root', (Join-Path $Exp 'raw'), '--split', $Split, - '--graph', $Graph, '--out', $conv) | Out-Null # (Out-Null drops the returned 0) - - # etwwindow swaps its whole --out folder in atomically, so give it a private folder, never itself - $stage = Join-Path $Exp '_windowing' - Log "window ${WindowMinutes}-min windows, ${StrideMinutes}-min stride, max gap ${MaxGapSeconds}s" - $rc = Invoke-Native $Cfg.Python @($WinPy, '--indir', $conv, '--graph', $Graph, '--split', $Split, - '--window-min', $WindowMinutes, '--stride-min', $StrideMinutes, '--max-gap-s', $MaxGapSeconds, - '--out', $stage, '--force') -Ok @(0, 2) - if ($rc -eq 2) { throw "no full $WindowMinutes-min window in the capture (see $conv\${Graph}_${Split}_summary.json)" } - Get-ChildItem $stage -File | Move-Item -Destination $Exp -Force - Remove-Item $stage -Recurse -Force - - Log 'check transform_to_RDF input contract' - $rc = Invoke-Native $Cfg.Python @($CheckPy, '--dir', $Exp, '--graph', $Graph, '--split', $Split, - '--out', (Join-Path $Exp 'check.json')) -Ok @(0, 1) - $man = Get-Content (Join-Path $Exp 'manifest.json') -Raw | ConvertFrom-Json - $t = $man.totals - $Record.windowing = [ordered]@{ window_min = $WindowMinutes; stride_min = $StrideMinutes; max_gap_s = $MaxGapSeconds } - $Record.results = [ordered]@{ - windows = $t.windows; edges_in = $t.edges_in; edges_out = $t.edges_out - edges_in_no_window = $t.edges_in_no_window; nodes_unique = $t.nodes_unique - node_window_copies = $t.node_window_copies; contract_ok = ($rc -eq 0) - } - $Record.tools = [ordered]@{ - workload = Sha $WorkloadScript; etwctl = Sha $EtwctlPs1; converter = Sha $Cfg.Converter - etwwindow = Sha $WinPy; checker = Sha $CheckPy; orchestrator = Sha $PSCommandPath - } - $Record.postprocessed_utc = Utc-Now - Write-Json (Join-Path $Exp 'experiment.json') $Record - if ($rc -ne 0) { throw "contract check FAILED - see $Exp\check.json (files kept for inspection)" } - Log ("done {0} windows, {1} edges, {2} node copies -> {3}" -f $t.windows, $t.edges_out, $t.node_window_copies, $Exp) - Log "next on the trainer: lab loop (the collector has shipped this capture to Loki)" -} - -if ($PostProcess) { - $exp = (Resolve-Path $PostProcess).Path - $recPath = Join-Path $exp 'experiment.json' - $rec = [ordered]@{} - if (Test-Path $recPath) { - $old = Get-Content $recPath -Raw | ConvertFrom-Json - foreach ($pr in $old.PSObject.Properties) { $rec[$pr.Name] = $pr.Value } # PSCustomObject -> hashtable - # reuse the experiment's window parameters unless given explicitly on this command line - if ($old.PSObject.Properties['windowing']) { - if (-not $PSBoundParameters.ContainsKey('WindowMinutes')) { $WindowMinutes = $old.windowing.window_min } - if (-not $PSBoundParameters.ContainsKey('StrideMinutes')) { $StrideMinutes = $old.windowing.stride_min } - if (-not $PSBoundParameters.ContainsKey('MaxGapSeconds')) { $MaxGapSeconds = $old.windowing.max_gap_s } - } - } - Complete-Experiment $exp $rec - return -} - -# ---------------------------------------------------------------- 1. preflight (nothing goes into the train capture yet) -if ((Get-Process -Id $PID).SessionId -eq 0) { throw 'session 0 (service/WinRM): run this from the RDP or console desktop' } -if (-not (Test-Path $WorkloadScript)) { throw "workload script not found: $WorkloadScript" } -if (-not (Get-Command $WorkloadScript).Parameters.ContainsKey('BeforeLedger')) { - throw "$WorkloadScript has no -BeforeLedger parameter - apply the 2-line patch first" -} -# `etwctl running` exits 0 while a capture runs (the etwcollect task). -& $EtwctlPs1 running | Out-Null -$capturing = ($LASTEXITCODE -eq 0) -# The always-on live capture (start-live.ps1 watchdog, test/live-*) is paused below, right before the train -# capture starts. Any other running capture (train, or a hand-started test run) still stops us here. -$StateFile = Join-Path $LabDir 'state.json' -$HoldFile = Join-Path $LabDir 'live.hold' -$cur = if (Test-Path $StateFile) { Get-Content $StateFile -Raw | ConvertFrom-Json } else { $null } -$liveRunning = $capturing -and $cur -and $cur.split -eq 'test' -and "$($cur.run)" -like 'live-*' -if ($capturing -and -not $liveRunning) { - throw "another capture is running ($($cur.split)/$($cur.run)): 'etwctl stop' first" -} -$expected = [math]::Floor(($DurationMinutes - $WindowMinutes) / $StrideMinutes) + 1 -if ($expected -lt 1) { throw "-DurationMinutes $DurationMinutes is shorter than one $WindowMinutes-min window" } - -Log 'preflight workload self-test (spawns and closes notepad; not captured)' -$st = & $WorkloadScript -SelfTest | Select-Object -Last 1 -$st | Format-List | Out-Host -if ($st.LaunchMode -ne 'explorer-com' -or $st.NotepadParent -ne 'explorer') { - if (-not $AllowFallbackLauncher) { throw 'apps would not be launched by explorer.exe (see self-test above); fix it or pass -AllowFallbackLauncher' } - Write-Warning 'continuing with the fallback launcher: benign apps will have powershell.exe as parent' -} -if (-not $st.InteractiveSess) { throw 'self-test says the session is not interactive' } - -$workDir = Join-Path $env:USERPROFILE 'Documents\work' -if (-not $KeepWorkDir -and (Test-Path $workDir)) { - Log "reset $workDir (same starting state for every experiment)" - Get-ChildItem $workDir -Force | Remove-Item -Recurse -Force -} - -$stamp = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ') -$exp = Join-Path $ExperimentsRoot $stamp -$run = "x-$stamp" -New-Item -ItemType Directory -Force -Path (Join-Path $exp 'labels') | Out-Null -$rec = [ordered]@{ - id = $stamp; graph = $Graph; split = $Split; os_build = [Environment]::OSVersion.Version.ToString() - label_source = 'benign by construction: scripted workload, no attack executed; includes background OS activity' - capture = [ordered]@{ run = $run; settle_s = $SettleSeconds; started_utc = $null; stopped_utc = $null } - workload = [ordered]@{ script = $WorkloadScript; seed = $Seed; duration_min = $DurationMinutes - include_user_powershell = [bool]$IncludeUserPowerShell; launch_mode = $st.LaunchMode - ledger_dir = (Join-Path $exp 'labels') } - expected_windows = $expected -} -Write-Json (Join-Path $exp 'experiment.json') $rec # written BEFORE the capture starts -Log "experiment $exp (expect about $expected windows)" - -# ---------------------------------------------------------------- 2. capture -# A closure over a hashtable: the workload calls it from its own scope, and both sides see the same -# hashtable object, so "stopped" is shared and the stop runs exactly once. -$Cap = @{ Etwctl = $EtwctlPs1; Started = $false; Stopped = $false; StoppedUtc = $null } -$stopCapture = { - if ($Cap.Started -and -not $Cap.Stopped) { - & $Cap.Etwctl stop | Out-Host - $Cap.Stopped = $true - $Cap.StoppedUtc = (Get-Date).ToUniversalTime().ToString('o') - } -}.GetNewClosure() - -# Hold file: the start-live.ps1 watchdog (SYSTEM task, every few minutes) leaves the collector alone while it -# exists. Written BEFORE the live run is stopped, so a watchdog tick cannot restart live in between; removed -# in the finally below, so live resumes within one tick after the train capture. Our $PID lets the watchdog -# drop the hold if this PowerShell dies without running the finally. -$hold = [ordered]@{ pid = $PID; by = '07-build-train-dataset.ps1'; since_utc = (Utc-Now) } -Set-Content -Path $HoldFile -Value ($hold | ConvertTo-Json -Compress) -try { - & $EtwctlPs1 running | Out-Null - if ($LASTEXITCODE -eq 0) { - Log 'pause the always-on live capture (start-live.ps1 resumes it after this capture)' - & $EtwctlPs1 stop | Out-Host - } - $rec.capture.started_utc = Utc-Now - $Cap.Started = $true # set first: a half-started capture is still stopped - $global:LASTEXITCODE = 0 - & $EtwctlPs1 start -Split $Split -Run $run - if ($LASTEXITCODE) { throw "etwctl start failed ($LASTEXITCODE)" } - Log "settle ${SettleSeconds}s idle capture" - Start-Sleep -Seconds $SettleSeconds - $wl = @{ DurationMinutes = $DurationMinutes; Seed = $Seed; LedgerDir = (Join-Path $exp 'labels') - BeforeLedger = $stopCapture } # hashtable splat = named arguments - if ($IncludeUserPowerShell) { $wl.IncludeUserPowerShell = $true } - & $WorkloadScript @wl -} -finally { # also runs on Ctrl+C or any error - & $stopCapture - $rec.capture.stopped_utc = $Cap.StoppedUtc - Write-Json (Join-Path $exp 'experiment.json') $rec - Remove-Item $HoldFile -Force -ErrorAction SilentlyContinue # live capture resumes at the next watchdog tick -} - -# ---------------------------------------------------------------- 2b. workload ledger -> Loki (etwcollect) -# The ledger is written AFTER the capture stopped (-BeforeLedger), so the collector cannot ship it; Alloy used -# to tail labels\*.csv. loki_pull.py on the trainer finds it as {job="workload-ledger", exp=}. -Log "ledger $(Join-Path $exp 'labels') -> Loki" -& $Cfg.EtwPython -m etwcollect push-ledger --exp $stamp --dir (Join-Path $exp 'labels') | Out-Host -if ($LASTEXITCODE) { Write-Warning "ledger push failed; re-run: & '$($Cfg.EtwPython)' -m etwcollect push-ledger --exp $stamp --dir '$(Join-Path $exp 'labels')'" } - -# ---------------------------------------------------------------- 3. collect raw into the experiment -$src = Join-Path $Cfg.RawRoot "$Split\$run" -$dst = Join-Path $exp "raw\$Split\$run" -if (-not (Test-Path $src)) { throw "raw run folder not found: $src" } -Log "collect $src -> $dst" -# COPY, not move: the collector's shipper reads $src to ship it to Loki (the training source on the trainer); -# etwctl stop already waited for its final push, and a backlog left by a Loki outage is shipped at the next start. -Log "wait ${ShipWaitSeconds}s for the last lines to reach Loki" -Start-Sleep -Seconds $ShipWaitSeconds -# robocopy /E = cp -r (keep the source for the shipper); exit codes 0-7 mean success -Invoke-Native 'robocopy.exe' @($src, $dst, '/E', '/NFL', '/NDL', '/NJH', '/NJS', '/NP') -Ok (0..7) | Out-Null -$rec.capture.raw = $dst -Write-Json (Join-Path $exp 'experiment.json') $rec - -# ---------------------------------------------------------------- 4-7 -Complete-Experiment $exp $rec \ No newline at end of file From d537dd716cd1e5ad9dbdc80a4d5d8114cec39792 Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sat, 31 Oct 2026 21:14:08 +0700 Subject: [PATCH 7/8] Render the LLM report as HTML in the live UI The Alg. 2 attack report is markdown (headings, bold, inline-code paths, bullet lists, a GFM IoC table), but the UI's md() only styled headings and **bold**, so tables and lists showed as raw markdown text. Replace md() with a small self-contained markdown->HTML renderer (no external lib; the UI must work offline): headings, **bold**, *italic*, `code`, -/*/+ and ordered lists, GFM tables, and hr. Text is HTML-escaped first so LLM output can't inject tags. Expand the .report CSS to style the rendered elements (sans body, mono code, bordered table). Verified by rendering a real sg3_report.md: table -> 3 headers/36 cells, 9 lists, 128 code spans, no raw markdown leaking. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DxFwFUt1hUmhjnRsfTCZpg --- src/live/static/index.html | 62 +++++++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 5 deletions(-) diff --git a/src/live/static/index.html b/src/live/static/index.html index 0847484..522a9bd 100644 --- a/src/live/static/index.html +++ b/src/live/static/index.html @@ -67,9 +67,20 @@ .llmcard.attack{border-color:var(--anom)} .llmcard.false_positive{border-color:var(--warn)} .llmcard h3{font-size:.95rem;margin:0 0 6px} .llmcard .ev{font:400 .8rem/1.5 var(--mono);white-space:pre-wrap;word-break:break-all;margin:4px 0 8px} -.report{font:400 .82rem/1.55 var(--mono);white-space:pre-wrap;word-break:break-word;background:var(--paper); - border-radius:6px;padding:8px 10px;max-height:520px;overflow:auto} -.report b{font-family:var(--sans)} +.report{font:400 .82rem/1.55 var(--sans);word-break:break-word;background:var(--paper); + border-radius:6px;padding:8px 12px;max-height:520px;overflow:auto} +.report>:first-child{margin-top:0} +.report h4,.report h5,.report h6{font-family:var(--sans);margin:12px 0 4px;line-height:1.3} +.report h4{font-size:.92rem} .report h5{font-size:.85rem} .report h6{font-size:.8rem;color:var(--muted)} +.report p{margin:6px 0} +.report ul,.report ol{margin:6px 0;padding-left:20px} +.report li{margin:2px 0} +.report strong{font-weight:600} +.report code{font-family:var(--mono);font-size:.78rem;background:var(--line);border-radius:3px;padding:0 3px;word-break:break-all} +.report hr{border:0;border-top:1px solid var(--line);margin:10px 0} +.report table{border-collapse:collapse;width:100%;margin:8px 0;font-size:.76rem} +.report th,.report td{border:1px solid var(--line);padding:3px 6px;text-align:left;vertical-align:top;word-break:break-word} +.report th{background:var(--line);font-weight:600} /* detail */ .grid{display:grid;grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);gap:12px} @media (max-width:900px){.grid{grid-template-columns:1fr}} @@ -264,8 +275,49 @@

Top nodes per type (margin = sco renderTables(); } - // markdown from the LLM: escaped first, then only headings and **bold** are styled - const md = s => esc(s).replace(/^#{1,6} (.*)$/gm, "$1").replace(/\*\*(.+?)\*\*/g, "$1"); + // Minimal, self-contained markdown -> HTML for the LLM report (no external lib; the UI must work + // offline). Text is HTML-escaped first, so only our own tags reach innerHTML. + // Inline: `code`, then **bold**, then *italic*. (No _italic_: file paths like ucrtbase_clr0400.dll.) + const mdInline = s => esc(s) + .replace(/`([^`]+)`/g, "$1") + .replace(/\*\*([^*]+?)\*\*/g, "$1") + .replace(/\*([^*\n]+?)\*/g, "$1"); + const mdTableSep = s => /-/.test(s) && /^\s*\|?[\s:|-]+\|?\s*$/.test(s); + const mdRow = s => s.replace(/^\s*\|/, "").replace(/\|\s*$/, "").split("|").map(c => c.trim()); + function md(src) { + const L = String(src ?? "").replace(/\r\n?/g, "\n").split("\n"); + const out = []; + const isBlock = s => /^(#{1,6}\s|\s*[-*+]\s|\s*\d+\.\s)/.test(s); + for (let i = 0; i < L.length; ) { + const ln = L[i]; + if (!ln.trim()) { i++; continue; } + const h = ln.match(/^(#{1,6})\s+(.*)$/); + if (h) { const lv = Math.min(h[1].length + 3, 6); out.push(`${mdInline(h[2])}`); i++; continue; } + if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(ln)) { out.push("
"); i++; continue; } + if (ln.includes("|") && i + 1 < L.length && mdTableSep(L[i + 1])) { // GFM table + const head = mdRow(ln); i += 2; const body = []; + while (i < L.length && L[i].includes("|") && L[i].trim()) { body.push(mdRow(L[i])); i++; } + out.push(`${head.map(c => ``).join("")}${ + body.map(r => `${r.map(c => ``).join("")}`).join("")}
${mdInline(c)}
${mdInline(c)}
`); + continue; + } + if (/^\s*[-*+]\s+/.test(ln)) { // unordered list + const it = []; + while (i < L.length && /^\s*[-*+]\s+/.test(L[i])) { it.push(L[i].replace(/^\s*[-*+]\s+/, "")); i++; } + out.push(`
    ${it.map(x => `
  • ${mdInline(x)}
  • `).join("")}
`); continue; + } + if (/^\s*\d+\.\s+/.test(ln)) { // ordered list + const it = []; + while (i < L.length && /^\s*\d+\.\s+/.test(L[i])) { it.push(L[i].replace(/^\s*\d+\.\s+/, "")); i++; } + out.push(`
    ${it.map(x => `
  1. ${mdInline(x)}
  2. `).join("")}
`); continue; + } + const p = []; // paragraph (until blank/block) + while (i < L.length && L[i].trim() && !isBlock(L[i]) + && !(L[i].includes("|") && i + 1 < L.length && mdTableSep(L[i + 1]))) { p.push(L[i]); i++; } + out.push(`

${mdInline(p.join(" "))}

`); + } + return out.join(""); + } function renderLLM(w) { const st = w.llm?.status, L = detail.llm; From d3f5f9d0cb7a461fc7a7b4669c986a45bfd340cb Mon Sep 17 00:00:00 2001 From: Ngo Vu Minh Dat <26848033@grad.uit.edu.vn> Date: Sat, 31 Oct 2026 21:31:55 +0700 Subject: [PATCH 8/8] Update the deck for the idle baseline and etwcollect pipeline The slides still described the removed architecture: the pipeline diagram showed SilkETW -> Grafana Alloy -> Loki, and the benign data was a seeded scripted workload (06-benign-workload.ps1). - OurPipeline.vue: drop the Alloy node; the collector is now etwcollect pushing ETW->JSON directly to Loki (one HTTP arrow etw -> loki). - slides.md: benign = idle pulled from Loki (lab slide, windowing, runbook); drop the 06-benign-workload.ps1 demo command; refresh the cut-off limitation now that the attack was tested (idle <= 8.0 vs attack 106.96). - note.txt: add a Q&A backup with the verified exp05 demo result and why idle (keeps the LOLBin chain out of the benign distribution). No slides added/removed (35 delimiters unchanged, so slide-number citations hold). `npx slidev build` passes. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DxFwFUt1hUmhjnRsfTCZpg --- presentation/components/OurPipeline.vue | 12 +++++------- presentation/note.txt | 13 +++++++++++++ presentation/slides.md | 15 +++++++-------- 3 files changed, 25 insertions(+), 15 deletions(-) diff --git a/presentation/components/OurPipeline.vue b/presentation/components/OurPipeline.vue index be6f497..8d3d816 100644 --- a/presentation/components/OurPipeline.vue +++ b/presentation/components/OurPipeline.vue @@ -1,6 +1,6 @@ diff --git a/presentation/note.txt b/presentation/note.txt index 9faef35..ff23cc6 100644 --- a/presentation/note.txt +++ b/presentation/note.txt @@ -66,3 +66,16 @@ Mỗi lớp lấy trung bình với neighbor. Xếp quá nhiều lớp thì vect giống nhau (over-smoothing: trên slide "Xếp nhiều lớp", các màu sẽ thành cùng một màu xám), nên không còn phân biệt được node bất thường. OCR-APT dùng 3 lớp [PAPER §7.2.1]: đủ thấy chuỗi process -> file -> process -> mạng. + + +Q7. Demo đã chạy thật chưa? Kết quả thế nào? +--------------------------------------------- +Rồi (session live-20261031T134030Z, mô hình exp05). Benign (desktop idle) các window XANH +(subgraph ≤ Minor 8.0, không alert). Tấn công DVWA→RCE từ Kali: window đó ĐỎ — subgraph 106.96 +(Significant, alert), cờ đúng IP máy tấn công 10.21.2.30:8080, downloaded_tool.bin (T1105) và +powershell của RCE; LLM phân loại "attack" (0.85) + báo cáo Alg. 2. rejudge.sh tái hiện lại offline. + +Vì sao benign = idle? Nếu benign có sẵn các lệnh discovery (whoami/net/systeminfo/schtasks) — như +workload script cũ — thì mô hình học chúng là "bình thường" và bỏ sót tấn công (exp04). Nền idle giữ +chuỗi living-off-the-land của tấn công nằm ngoài phân phối benign nên tách rõ. Đánh đổi: mô hình idle +mỏng (net val_fpr=1.0), nên giữ các window benign ở trạng thái idle khi demo. diff --git a/presentation/slides.md b/presentation/slides.md index 1d795d9..8e6330d 100644 --- a/presentation/slides.md +++ b/presentation/slides.md @@ -489,7 +489,7 @@ $$s_i = \|\mathbf{z}_i - \mathbf{c}\|_2^2 - R^2$$
-
ws-etw · Windows Server 2022: etwcollect (collector Python tự viết: ghi ETW ra JSON; Kernel-Process, -File, -Network) tự gửi nguyên văn từng dòng về Loki; benign workload có seed; dịch vụ web chưa vá. Không huấn luyện.
+
ws-etw · Windows Server 2022: etwcollect (collector Python tự viết: ghi ETW ra JSON; Kernel-Process, -File, -Network) tự gửi nguyên văn từng dòng về Loki; benign = idle (lấy trực tiếp từ Loki, không có script thu thập); dịch vụ web chưa vá. Không huấn luyện.
ubuntu-trainer · Ubuntu 24.04: Loki (kho lưu log) + Grafana (dashboard); chuyển đổi, cắt window, feature, huấn luyện; máy chủ demo (FastAPI + web UI). Cả hai máy dựng bằng Ansible, chuyển lên cloud được.
@@ -507,7 +507,7 @@ clicks: 1 Ký hiệu $[t, t+5)$: gồm $t$, **không** gồm $t+5$ OURS -- Huấn luyện: bản ghi ~20 phút, **sliding** window; overlapping window → hàng feature tương quan +- Huấn luyện: bản ghi benign **idle** (lấy từ Loki, ~16 phút), **sliding** window; overlapping window → hàng feature tương quan - Demo: **tumbling** window (window lật), mỗi sự kiện thuộc đúng một window - Mỗi node được sao theo window (`w0007_…`) → max idle ≤ 290 s - Đồng hồ demo = thời gian sự kiện mới nhất − **20 s**; không có log mới → đồng hồ máy chủ @@ -624,8 +624,8 @@ layout: center - Phát hiện APT, tấn công nhiều host hay kéo dài nhiều ngày ### Hạn chế đã biết -- Dữ liệu benign hẹp (workload dạng script, một máy) -- Mốc 30 đặt từ **một** benign window, chưa kiểm chứng trên tấn công +- Benign = **idle** một máy → mô hình idle mỏng (net `val_fpr=1.0`), chỉ là baseline cho demo +- Mốc 30: demo tách rõ (idle ≤ Minor 8.0 vs tấn công **106.96**) nhưng dựa trên baseline idle, chưa tổng quát - Window 5 phút cắt rời hành vi kéo dài

@@ -656,11 +656,10 @@ transition: fade
```powershell -# ws-etw (PowerShell quyền admin): bắt đầu một lần thu thập live; etwcollect tự gửi về Loki -C:\scripts\start-live.ps1 -Minutes 30 +# ws-etw: live capture luôn chạy (SYSTEM task); etwcollect tự đẩy về Loki — chỉ cần một session sạch: +C:\scripts\start-live.ps1 -Rotate -# Song song: benign workload (khởi chạy ứng dụng qua explorer) -C:\scripts\06-benign-workload.ps1 -DurationMinutes 20 +# Benign = IDLE: giữ desktop không thao tác (baseline idle, lấy trực tiếp từ Loki) ``` ```bash