Files
dbb9a590e5 fix(engine): utf-8 encoding for all file/console I/O (Windows cp1252 crash) (#191)
Fixes #189. On Windows (and any non-UTF-8 locale) text-mode open() inherits the
code page (cp1252), so writing the engine's '->' / em-dash characters to the log,
arsenal map, or report crashed with UnicodeEncodeError, and reading them back
could mojibake.

- Pin encoding="utf-8" on every text-mode open() in engine/ (state.py, engine.py,
  memory.py, scope.py) and the subprocess-reading tests.
- Reconfigure stdout/stderr to utf-8 in engine main() so console output of the same
  characters does not crash the CLI run.
- Make Engagement.log()'s print non-fatal on a non-UTF-8 console: logging is a side
  channel and must never crash the run; the full line is already in the utf-8 log.
- Parent-side decode of child engine output in the mock subprocess tests pinned to
  utf-8 (the two tests #189 reports failing on Windows).

New engine/test_windows_encoding.py reproduces the crash deterministically on any
host by forcing an ASCII default (PYTHONUTF8=0 PYTHONCOERCECLOCALE=0 LC_ALL=C), so
the regression is caught on the existing ubuntu CI without a windows runner.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-20 21:23:22 +05:30

162 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""
state.py — persistent, resumable engagement state.
Everything the engine learns lives on disk so a long run is auditable and can be
killed/resumed without losing progress. Layout:
<base>/<name>/
state.json surface items, worklist, tested set, candidate + confirmed findings, phase
engine.log append-only run log
evidence/ per-finding evidence files
report.md generated at the end
"""
import json
import os
from datetime import datetime, timezone
def _now():
return datetime.now(timezone.utc).isoformat()
class Engagement:
def __init__(self, base, name):
self.dir = os.path.join(os.path.expanduser(base), name)
self.name = name
os.makedirs(os.path.join(self.dir, "evidence"), exist_ok=True)
self.state_path = os.path.join(self.dir, "state.json")
self.log_path = os.path.join(self.dir, "engine.log")
self.state = self._load()
self.state.setdefault("rejected", [])
DEFAULTS = {"targets": [], "surface": [], "tested": [], "candidates": [], "confirmed": [],
"coverage": {}, "coverage_by_item": {}}
def _fresh_defaults(self):
# Fresh copies — never alias the mutable class-level DEFAULTS into instance state.
return {k: (dict(v) if isinstance(v, dict) else list(v)) for k, v in self.DEFAULTS.items()}
def _load(self):
if os.path.isfile(self.state_path):
s = json.load(open(self.state_path, encoding="utf-8"))
for k, v in self._fresh_defaults().items(): # forward-compat with pre-ledger engagements
s.setdefault(k, v)
return s
return {"name": self.name, "created": _now(), "phase": "init", **self._fresh_defaults()}
def save(self):
tmp = self.state_path + ".tmp"
json.dump(self.state, open(tmp, "w", encoding="utf-8"), indent=2)
os.replace(tmp, self.state_path)
def log(self, msg):
line = f"{_now()} {msg}"
with open(self.log_path, "a", encoding="utf-8") as f:
f.write(line + "\n")
try:
print(" " + msg, flush=True)
except UnicodeEncodeError:
# A non-UTF-8 console (Windows cp1252) must not crash the run; the
# full line is already in the UTF-8 log file.
print(" " + msg.encode("ascii", "replace").decode("ascii"), flush=True)
# ---- phase ----
def set_phase(self, phase):
self.state["phase"] = phase
self.save()
# ---- surface (discovered, scope-checked endpoints/params) ----
def add_surface(self, items):
seen = {(s["url"], s.get("param", ""), s.get("vuln_class", "")) for s in self.state["surface"]}
added = 0
for it in items:
key = (it["url"], it.get("param", ""), it.get("vuln_class", ""))
if key not in seen:
self.state["surface"].append(it)
seen.add(key)
added += 1
self.save()
return added
def worklist(self):
"""Ranked, not-yet-tested surface items."""
tested = set(self.state["tested"])
items = [s for s in self.state["surface"] if self._key(s) not in tested]
return sorted(items, key=lambda s: -s.get("priority", 0))
@staticmethod
def _key(s):
return f"{s['url']}|{s.get('param','')}|{s.get('vuln_class','')}"
def mark_tested(self, item, candidate=None, coverage=None, note=""):
k = self._key(item)
if k not in self.state["tested"]:
if candidate is not None:
candidate["ts"] = _now()
self.state["candidates"].append(candidate)
self.state["tested"].append(k)
if coverage is not None:
self._set_item_coverage(item, coverage, note)
self.save()
# ---- findings ----
def add_candidate(self, finding):
finding["ts"] = _now()
self.state["candidates"].append(finding)
self.save()
def confirm(self, finding, verdict):
finding = {**finding, "verdict": verdict, "confirmed_ts": _now()}
self.state["confirmed"].append(finding)
self.save()
# ---- coverage ledger (writer: hunt) ----
# A count of tested items cannot answer "which classes were never tried on
# host X". This can, and the report renders its caveats from it.
def _set_item_coverage(self, item, verdict, note):
from closure import VERDICTS
if verdict not in VERDICTS:
raise ValueError(f"unknown coverage verdict {verdict!r}; expected one of {sorted(VERDICTS)}")
self.state["coverage_by_item"][self._key(item)] = {
"verdict": verdict, "note": note, "ts": _now()}
def record_coverage(self, item, verdict, note=""):
self._set_item_coverage(item, verdict, note)
self.save()
def evidence_path(self, fname):
return os.path.join(self.dir, "evidence", fname)
# ---- progress ----
def summary(self):
return {"surface": len(self.state["surface"]), "tested": len(self.state["tested"]),
"candidates": len(self.state["candidates"]), "confirmed": len(self.state["confirmed"]),
"phase": self.state["phase"]}
def _selftest():
import tempfile, shutil
d = tempfile.mkdtemp()
try:
e = Engagement(d, "demo")
assert e.add_surface([{"url": "http://t/a", "param": "id", "vuln_class": "idor", "priority": 5},
{"url": "http://t/a", "param": "id", "vuln_class": "idor"}]) == 1 # dedup
e.add_surface([{"url": "http://t/b", "param": "q", "vuln_class": "xss", "priority": 9}])
wl = e.worklist()
assert wl[0]["url"] == "http://t/b" # higher priority first
e.mark_tested(wl[0])
assert all(s["url"] != "http://t/b" or s.get("param") != "q" for s in e.worklist())
e.add_candidate({"url": "http://t/a", "vuln_class": "idor", "evidence": "x"})
e.confirm(e.state["candidates"][0], {"real": True})
# resume: a fresh handle on the same dir sees persisted state
e2 = Engagement(d, "demo")
assert e2.summary() == {"surface": 2, "tested": 1, "candidates": 1, "confirmed": 1, "phase": "init"}
print("state.py self-test: PASS")
finally:
shutil.rmtree(d)
if __name__ == "__main__":
_selftest()