poc-harness 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. agent/__init__.py +18 -0
  2. agent/chain.py +86 -0
  3. agent/cli.py +71 -0
  4. agent/config.py +114 -0
  5. agent/dashboard.py +182 -0
  6. agent/diffing.py +100 -0
  7. agent/governance.py +94 -0
  8. agent/healing.py +76 -0
  9. agent/llm.py +200 -0
  10. agent/orchestrator.py +219 -0
  11. agent/payloads.py +49 -0
  12. agent/planner.py +89 -0
  13. agent/runner.py +22 -0
  14. agent/state.py +163 -0
  15. agent/tools.py +306 -0
  16. checks/__init__.py +0 -0
  17. checks/access_control.py +35 -0
  18. checks/blind_oast.py +42 -0
  19. checks/business_logic.py +44 -0
  20. checks/deserialization.py +48 -0
  21. checks/idor.py +61 -0
  22. checks/idor_semantic.py +79 -0
  23. checks/race_condition.py +73 -0
  24. checks/reflected_xss.py +64 -0
  25. cli/__init__.py +2 -0
  26. cli/__main__.py +4 -0
  27. cli/main.py +895 -0
  28. cli/output.py +164 -0
  29. harness.py +272 -0
  30. identity/__init__.py +1 -0
  31. identity/accounts.py +121 -0
  32. identity/tempmail.py +103 -0
  33. oast/__init__.py +4 -0
  34. oast/listener.py +121 -0
  35. poc_harness-0.4.0.dist-info/METADATA +266 -0
  36. poc_harness-0.4.0.dist-info/RECORD +53 -0
  37. poc_harness-0.4.0.dist-info/WHEEL +5 -0
  38. poc_harness-0.4.0.dist-info/entry_points.txt +2 -0
  39. poc_harness-0.4.0.dist-info/licenses/LICENSE +21 -0
  40. poc_harness-0.4.0.dist-info/top_level.txt +9 -0
  41. recon/__init__.py +1 -0
  42. recon/browser.py +247 -0
  43. recon/crawler.py +115 -0
  44. report.py +60 -0
  45. selftest/__init__.py +23 -0
  46. selftest/mock_target.py +148 -0
  47. selftest/run_advanced_selftest.py +145 -0
  48. selftest/run_agent_selftest.py +128 -0
  49. selftest/run_browser_integration.py +165 -0
  50. selftest/run_features_selftest.py +110 -0
  51. selftest/run_security_selftest.py +125 -0
  52. selftest/run_selftest.py +26 -0
  53. selftest/scope.yaml +8 -0
agent/__init__.py ADDED
@@ -0,0 +1,18 @@
1
+ """
2
+ agent/ — the autonomous orchestration layer for poc-harness.
3
+
4
+ This package turns the existing safety + evidence + checks core into a
5
+ black-box AI penetration-testing agent:
6
+
7
+ config.py engine + LLM configuration
8
+ llm.py pluggable reasoning engine (Ollama / Claude / OpenAI / Scripted)
9
+ state.py SQLite memory: sitemap, endpoints, identities, sessions, findings
10
+ governance.py permission manager + human-in-the-loop over the Scope Guard
11
+ tools.py the tool registry the agent is allowed to call
12
+ orchestrator.py the plan -> act -> observe -> record loop
13
+ cli.py command-line entry point
14
+
15
+ Design principles (from the system spec):
16
+ black-box, modular, tool-agnostic, stateful, human-in-the-loop, evidence-based.
17
+ Every network action still passes through harness.ScopeGuard first.
18
+ """
agent/chain.py ADDED
@@ -0,0 +1,86 @@
1
+ """
2
+ Chain execution — the dynamic phase of graph-based planning.
3
+
4
+ Runs a PlanGraph in dependency order. Each step's result is captured into a
5
+ Blackboard; later steps reference those values via ${var} placeholders, so the
6
+ output of one step becomes the input of the next (leak -> reuse -> escalate).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ VAR_RE = re.compile(r"\$\{([^}]+)\}")
13
+
14
+
15
+ def dig(obj, path: str):
16
+ """Walk a dotted path into nested dicts/lists: 'json.user.token' or 'list.0.id'."""
17
+ cur = obj
18
+ for part in path.split("."):
19
+ if isinstance(cur, dict) and part in cur:
20
+ cur = cur[part]
21
+ elif isinstance(cur, list) and part.isdigit() and int(part) < len(cur):
22
+ cur = cur[int(part)]
23
+ else:
24
+ return None
25
+ return cur
26
+
27
+
28
+ class Blackboard:
29
+ def __init__(self, initial: dict | None = None):
30
+ self.vars = dict(initial or {})
31
+
32
+ def set(self, name, value):
33
+ self.vars[name] = value
34
+
35
+ def resolve(self, obj):
36
+ """Recursively replace ${var} in strings. A string that is exactly '${x}'
37
+ returns the raw (possibly non-string) value; otherwise it's substituted in."""
38
+ if isinstance(obj, str):
39
+ m = VAR_RE.fullmatch(obj.strip())
40
+ if m:
41
+ return dig_vars(self.vars, m.group(1))
42
+ return VAR_RE.sub(lambda mm: str(dig_vars(self.vars, mm.group(1)) or ""), obj)
43
+ if isinstance(obj, dict):
44
+ return {k: self.resolve(v) for k, v in obj.items()}
45
+ if isinstance(obj, list):
46
+ return [self.resolve(v) for v in obj]
47
+ return obj
48
+
49
+
50
+ def dig_vars(vars: dict, name: str):
51
+ if name in vars:
52
+ return vars[name]
53
+ return dig(vars, name) # supports ${token} and ${result.json.id}
54
+
55
+
56
+ def run_chain(graph, toolbox, ctx, blackboard: Blackboard | None = None,
57
+ on_event=None) -> dict:
58
+ """
59
+ Execute every node in topological order. Returns a summary:
60
+ {steps:[...], vars:{...}, ok:bool}
61
+ A node fails soft: its error is recorded and the chain continues (later nodes
62
+ that needed its output will see empty values — visible in the summary).
63
+ """
64
+ bb = blackboard or Blackboard()
65
+ steps = []
66
+ for node in graph.topo_order():
67
+ if node.tool not in toolbox:
68
+ steps.append({"id": node.id, "ok": False, "error": f"unknown tool {node.tool}"})
69
+ continue
70
+ args = bb.resolve(node.args)
71
+ if on_event:
72
+ on_event({"kind": "chain_step", "id": node.id, "tool": node.tool, "args": args})
73
+ try:
74
+ result = toolbox[node.tool].handler(ctx, **args)
75
+ except Exception as e:
76
+ steps.append({"id": node.id, "tool": node.tool, "ok": False, "error": str(e)})
77
+ continue
78
+ captured = {}
79
+ for var, path in (node.capture or {}).items():
80
+ val = dig(result, path)
81
+ bb.set(var, val)
82
+ captured[var] = val
83
+ steps.append({"id": node.id, "tool": node.tool, "ok": bool(result.get("ok", True)),
84
+ "captured": captured, "result_status": result.get("status"),
85
+ "confirmed": result.get("confirmed")})
86
+ return {"ok": True, "steps": steps, "vars": bb.vars}
agent/cli.py ADDED
@@ -0,0 +1,71 @@
1
+ """
2
+ Command-line entry point for the agent.
3
+
4
+ python -m agent.cli --help
5
+ python -m agent.cli --start-url https://target/ --goal "map surface, test IDOR"
6
+ python -m agent.cli --config agent.yaml
7
+ python -m agent.cli --provider claude --model claude-opus-5 --yes
8
+
9
+ Scope always comes from scope.yaml (--scope to point elsewhere). The engine
10
+ cannot test anything the scope file does not authorize.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+
18
+ from .config import Config
19
+ from .orchestrator import Orchestrator
20
+
21
+
22
+ def main(argv=None):
23
+ ap = argparse.ArgumentParser(description="Autonomous black-box pentest agent (poc-harness).")
24
+ ap.add_argument("--config", help="agent.yaml path (optional)")
25
+ ap.add_argument("--scope", help="scope.yaml path (authorization contract)")
26
+ ap.add_argument("--start-url", help="where recon begins")
27
+ ap.add_argument("--goal", help="natural-language objective for this run")
28
+ ap.add_argument("--provider", help="ollama | claude | openai")
29
+ ap.add_argument("--model", help="model id")
30
+ ap.add_argument("--base-url", help="LLM base url (e.g. http://localhost:11434)")
31
+ ap.add_argument("--evidence-dir", help="where evidence/report/state go")
32
+ ap.add_argument("--max-steps", type=int, help="hard cap on agent iterations")
33
+ ap.add_argument("--yes", action="store_true", help="auto-approve sensitive actions (full-auto)")
34
+ ap.add_argument("--tui", action="store_true", help="live rich dashboard of the agent loop")
35
+ ap.add_argument("--profile", help="target profile JSON (register/login specs, start_url)")
36
+ args = ap.parse_args(argv)
37
+
38
+ cfg = Config.load(args.config)
39
+ if args.scope: cfg.scope_path = args.scope
40
+ if args.start_url: cfg.start_url = args.start_url
41
+ if args.goal: cfg.goal = args.goal
42
+ if args.provider: cfg.llm.provider = args.provider
43
+ if args.model: cfg.llm.model = args.model
44
+ if args.base_url: cfg.llm.base_url = args.base_url
45
+ if args.evidence_dir: cfg.evidence_dir = args.evidence_dir; cfg.state_path = args.evidence_dir + "/state.db"
46
+ if args.max_steps: cfg.limits.max_steps = args.max_steps
47
+ if args.yes: cfg.autonomy.auto_approve = True
48
+
49
+ profile = {}
50
+ if args.profile:
51
+ with open(args.profile, "r", encoding="utf-8") as f:
52
+ profile = json.load(f)
53
+ if cfg.start_url and "start_url" not in profile:
54
+ profile["start_url"] = cfg.start_url
55
+
56
+ print(f"== poc-harness agent ==")
57
+ print(f" program : {cfg.scope_path}")
58
+ print(f" brain : {cfg.llm.provider} / {cfg.llm.model}")
59
+ print(f" goal : {cfg.goal}")
60
+ print(f" autonomy: {'FULL-AUTO' if cfg.autonomy.auto_approve else 'human-in-the-loop'}")
61
+ print()
62
+
63
+ from .runner import execute
64
+ result = execute(cfg, profile, tui=args.tui)
65
+ print("\n== run complete ==")
66
+ print(json.dumps(result, indent=2, default=str))
67
+ return 0
68
+
69
+
70
+ if __name__ == "__main__":
71
+ sys.exit(main())
agent/config.py ADDED
@@ -0,0 +1,114 @@
1
+ """
2
+ Engine configuration for the agent.
3
+
4
+ Kept separate from scope.yaml on purpose:
5
+ - scope.yaml = the AUTHORIZATION CONTRACT (what you may touch). Sacred.
6
+ - agent.yaml = the ENGINE settings (which brain, how fast, how autonomous).
7
+
8
+ Load order for any field: explicit arg > environment variable > agent.yaml > default.
9
+ Nothing here can widen scope; scope is enforced only by harness.ScopeGuard.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ from dataclasses import dataclass, field, asdict
15
+
16
+ import yaml
17
+
18
+
19
+ @dataclass
20
+ class LLMConfig:
21
+ provider: str = "ollama" # ollama | claude | openai | scripted
22
+ model: str = "qwen35-9b-256k:latest"
23
+ base_url: str = "http://localhost:11434"
24
+ api_key_env: str = "" # e.g. ANTHROPIC_API_KEY / OPENAI_API_KEY
25
+ temperature: float = 0.1
26
+ max_tokens: int = 1024
27
+ num_ctx: int = 32768 # Ollama context window override
28
+
29
+
30
+ @dataclass
31
+ class LimitsConfig:
32
+ max_steps: int = 40 # hard cap on agent iterations
33
+ max_requests: int = 400 # hard cap on total HTTP requests
34
+ wall_clock_seconds: int = 1800 # overall time budget
35
+
36
+
37
+ @dataclass
38
+ class AutonomyConfig:
39
+ # Tools that always need a human yes before they run (destructive-ish / noisy).
40
+ require_approval_for: list = field(default_factory=lambda: [
41
+ "create_identity", "check_reflected_xss", "check_blind_oast", "browser_handoff",
42
+ "check_race_condition", "check_deserialization", "run_attack_chain", "http_request",
43
+ ])
44
+ auto_approve: bool = False # True = never prompt (use for offline tests / full-auto)
45
+
46
+
47
+ @dataclass
48
+ class EvidenceConfig:
49
+ scrub_secrets: bool = True # redact passwords/tokens/JWTs from logged bodies+URLs
50
+ log_bodies: bool = True # False = don't store request/response bodies at all
51
+ max_snippet: int = 2000 # cap on stored body/response length
52
+ persist_credentials: bool = False # store test-account password/session in the state DB
53
+
54
+
55
+ @dataclass
56
+ class OASTConfig:
57
+ bind_host: str = "127.0.0.1"
58
+ port: int = 0 # 0 = pick a free port
59
+ public_base: str = "" # tunnel/collaborator URL for EXTERNAL targets
60
+
61
+
62
+ @dataclass
63
+ class ServicesConfig:
64
+ # Utility services the IDENTITY layer may contact (NOT the target).
65
+ # These bypass the target Scope Guard by design, because a temp-email
66
+ # inbox is infrastructure, not the thing under test. Keep the list tiny.
67
+ tempmail_api: str = "https://api.mail.tm"
68
+
69
+
70
+ @dataclass
71
+ class Config:
72
+ goal: str = "Explore the target, map its attack surface, and safely test for access-control (IDOR) issues."
73
+ start_url: str = ""
74
+ scope_path: str = "scope.yaml"
75
+ evidence_dir: str = "evidence"
76
+ state_path: str = "evidence/state.db"
77
+ llm: LLMConfig = field(default_factory=LLMConfig)
78
+ limits: LimitsConfig = field(default_factory=LimitsConfig)
79
+ autonomy: AutonomyConfig = field(default_factory=AutonomyConfig)
80
+ services: ServicesConfig = field(default_factory=ServicesConfig)
81
+ oast: OASTConfig = field(default_factory=OASTConfig)
82
+ evidence: EvidenceConfig = field(default_factory=EvidenceConfig)
83
+
84
+ @staticmethod
85
+ def load(path: str | None = None) -> "Config":
86
+ raw: dict = {}
87
+ if path and os.path.exists(path):
88
+ with open(path, "r", encoding="utf-8") as f:
89
+ raw = yaml.safe_load(f) or {}
90
+
91
+ cfg = Config()
92
+ cfg.goal = raw.get("goal", cfg.goal)
93
+ cfg.start_url = raw.get("start_url", cfg.start_url)
94
+ cfg.scope_path = raw.get("scope_path", cfg.scope_path)
95
+ cfg.evidence_dir = raw.get("evidence_dir", cfg.evidence_dir)
96
+ cfg.state_path = raw.get("state_path", cfg.state_path)
97
+
98
+ for section, dc in (("llm", cfg.llm), ("limits", cfg.limits),
99
+ ("autonomy", cfg.autonomy), ("services", cfg.services),
100
+ ("oast", cfg.oast), ("evidence", cfg.evidence)):
101
+ for k, v in (raw.get(section) or {}).items():
102
+ if hasattr(dc, k):
103
+ setattr(dc, k, v)
104
+
105
+ # Environment overrides (handy for CI / quick swaps).
106
+ cfg.llm.provider = os.getenv("AGENT_LLM_PROVIDER", cfg.llm.provider)
107
+ cfg.llm.model = os.getenv("AGENT_LLM_MODEL", cfg.llm.model)
108
+ cfg.llm.base_url = os.getenv("AGENT_LLM_BASE_URL", cfg.llm.base_url)
109
+ if os.getenv("AGENT_AUTO_APPROVE"):
110
+ cfg.autonomy.auto_approve = os.getenv("AGENT_AUTO_APPROVE") == "1"
111
+ return cfg
112
+
113
+ def to_dict(self) -> dict:
114
+ return asdict(self)
agent/dashboard.py ADDED
@@ -0,0 +1,182 @@
1
+ """
2
+ Live terminal dashboard for the agent loop (uses `rich`).
3
+
4
+ Subscribes to orchestrator events and renders the pipeline in real time:
5
+
6
+ [ Plan ] -> [ ScopeCheck ] -> [ Act ] -> [ Verdict ]
7
+
8
+ plus a running table of steps, confirmed findings, and counts. This is the
9
+ README-GIF view. It's optional: without --tui the agent prints plain lines.
10
+
11
+ Wiring:
12
+ dash = Dashboard(cfg)
13
+ with dash.live():
14
+ Orchestrator(cfg, observer=dash.handle).run()
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from contextlib import contextmanager
19
+ import os
20
+ import time
21
+
22
+ try:
23
+ from rich import box
24
+ from rich.console import Console, Group
25
+ from rich.panel import Panel
26
+ from rich.table import Table
27
+ from rich.text import Text
28
+ from rich.live import Live
29
+ RICH_AVAILABLE = True
30
+ except Exception:
31
+ RICH_AVAILABLE = False
32
+
33
+ STAGES = ["Plan", "ScopeCheck", "Act", "Verdict"]
34
+ _KIND_TO_STAGE = {"plan": "Plan", "scope": "ScopeCheck", "act": "Act", "verdict": "Verdict"}
35
+
36
+
37
+ class Dashboard:
38
+ def __init__(self, cfg):
39
+ self.cfg = cfg
40
+ self.header = {"program": "?", "provider": cfg.llm.provider,
41
+ "model": cfg.llm.model, "goal": cfg.goal,
42
+ "max_steps": cfg.limits.max_steps}
43
+ self.active = None
44
+ self.steps: dict[int, dict] = {}
45
+ self.counts = {}
46
+ self.findings: list[dict] = []
47
+ self.done = False
48
+ self.summary = ""
49
+ self._live = None
50
+ self.started_at = None
51
+ self.elapsed = 0.0
52
+ self.current_step = 0
53
+
54
+ # -- event intake ------------------------------------------------------ #
55
+ def handle(self, ev: dict):
56
+ k = ev.get("kind")
57
+ if k == "start":
58
+ self.started_at = time.monotonic()
59
+ self.header.update({x: ev.get(x, self.header.get(x)) for x in
60
+ ("program", "provider", "model", "goal", "max_steps")})
61
+ elif k in _KIND_TO_STAGE:
62
+ self.active = _KIND_TO_STAGE[k]
63
+ step = ev.get("step")
64
+ if step is not None:
65
+ self.current_step = max(self.current_step, int(step))
66
+ s = self.steps.setdefault(step, {"action": "", "scope": "", "result": ""})
67
+ if k == "plan":
68
+ s["action"] = ev.get("action", "")
69
+ s["thought"] = (ev.get("thought") or "")[:60]
70
+ elif k == "scope":
71
+ s["scope"] = "allow" if ev.get("allowed") else "DENY"
72
+ if not ev.get("allowed"):
73
+ s["detail"] = (ev.get("reason") or "blocked")[:100]
74
+ elif k == "verdict":
75
+ r = ev.get("result") or {}
76
+ if "confirmed" in r:
77
+ s["result"] = "CONFIRMED" if r.get("confirmed") else "clear"
78
+ s["detail"] = (r.get("url") or "")[:100]
79
+ elif r.get("ok"):
80
+ s["result"] = "ok"
81
+ if "pages_crawled" in r:
82
+ s["detail"] = f"{r['pages_crawled']} pages, {r.get('forms_found', 0)} forms"
83
+ elif "status" in r:
84
+ s["detail"] = f"HTTP {r['status']}"
85
+ else:
86
+ s["result"] = "err"
87
+ s["detail"] = (r.get("error") or "action failed")[:100]
88
+ self.counts = ev.get("counts", self.counts)
89
+ elif k == "end":
90
+ self.done = True
91
+ if self.started_at is not None:
92
+ self.elapsed = time.monotonic() - self.started_at
93
+ self.summary = ev.get("summary", "")
94
+ self.counts = ev.get("counts", self.counts)
95
+ self.active = None
96
+ self._refresh()
97
+
98
+ # -- rendering --------------------------------------------------------- #
99
+ def _pipeline(self) -> Text:
100
+ t = Text()
101
+ for i, stage in enumerate(STAGES):
102
+ on = (stage == self.active)
103
+ style = "bold black on green" if on else ("green" if self.done else "dim")
104
+ t.append(f" {stage} ", style=style)
105
+ if i < len(STAGES) - 1:
106
+ t.append(" -> ", style="dim")
107
+ return t
108
+
109
+ def _steps_table(self) -> Table:
110
+ tb = Table(expand=True, highlight=True, box=box.SIMPLE_HEAD)
111
+ tb.add_column("#", width=4, justify="right")
112
+ tb.add_column("action", ratio=2)
113
+ tb.add_column("scope", width=7)
114
+ tb.add_column("verdict", width=10)
115
+ tb.add_column("note", ratio=3, style="dim")
116
+ for step in sorted(self.steps)[-12:]:
117
+ s = self.steps[step]
118
+ scope_style = "red" if s.get("scope") == "DENY" else "green"
119
+ res = s.get("result", "")
120
+ res_style = {"CONFIRMED": "bold red", "clear": "green",
121
+ "ok": "cyan", "err": "yellow"}.get(res, "")
122
+ note = s.get("detail") or s.get("thought", "")
123
+ tb.add_row(str(step), s.get("action", ""),
124
+ Text(s.get("scope", ""), style=scope_style),
125
+ Text(res, style=res_style), note)
126
+ return tb
127
+
128
+ def _render(self):
129
+ h = self.header
130
+ head = Text.assemble(
131
+ ("POCH", "bold cyan"),
132
+ (f" {h['program']}", "bold"),
133
+ (f" {h['provider']} / {h['model']}", "dim"),
134
+ )
135
+ goal = Text(f"goal: {h['goal']}", style="italic dim")
136
+ c = self.counts or {}
137
+ total_steps = max(1, int(h.get("max_steps") or 1))
138
+ progress_steps = min(self.current_step, total_steps)
139
+ progress_width = 22
140
+ filled = round(progress_width * progress_steps / total_steps)
141
+ elapsed = self.elapsed or (time.monotonic() - self.started_at if self.started_at else 0.0)
142
+ progress = Text.assemble(
143
+ (f"Step {progress_steps}/{total_steps} ", "bold"),
144
+ ("#" * filled, "cyan"),
145
+ ("-" * (progress_width - filled), "dim"),
146
+ (f" {elapsed:.1f}s", "dim"),
147
+ )
148
+ stats = Table.grid(expand=True, padding=(0, 2))
149
+ for _ in range(4):
150
+ stats.add_column(justify="center", ratio=1)
151
+ stat_values = [
152
+ ("PAGES", c.get("pages", 0)),
153
+ ("ENDPOINTS", c.get("endpoints", 0)),
154
+ ("IDENTITIES", c.get("identities", 0)),
155
+ ("CONFIRMED", c.get("confirmed_findings", 0)),
156
+ ]
157
+ stats.add_row(*(Text.assemble((str(value), "bold cyan"), (f"\n{label}", "dim"))
158
+ for label, value in stat_values))
159
+ body = [head, goal, Text(""), progress, self._pipeline(), Text(""),
160
+ self._steps_table(), Text(""), stats]
161
+ if self.done:
162
+ body.append(Text(f"\n{self.summary}", style="bold green"))
163
+ body.append(Text(f"Report: {os.path.join(self.cfg.evidence_dir, 'report.md')}", style="dim"))
164
+ return Panel(Group(*body), title="POCH / LIVE RUN",
165
+ border_style="green" if self.done else "cyan")
166
+
167
+ def _refresh(self):
168
+ if self._live:
169
+ self._live.update(self._render())
170
+
171
+ @contextmanager
172
+ def live(self):
173
+ if not RICH_AVAILABLE:
174
+ yield
175
+ return
176
+ with Live(self._render(), refresh_per_second=8, screen=False) as live:
177
+ self._live = live
178
+ try:
179
+ yield
180
+ finally:
181
+ self._refresh()
182
+ self._live = None
agent/diffing.py ADDED
@@ -0,0 +1,100 @@
1
+ """
2
+ Differential Response Engine — "noise-cancelling" response comparison.
3
+
4
+ Naive IDOR/BOLA checks compare two responses byte-for-byte and drown in false
5
+ positives: timestamps, CSRF tokens, request IDs and nonces differ on every
6
+ request even when the underlying DATA is identical. This utility normalises a
7
+ response (JSON or HTML/text) by neutralising those dynamic values, then compares
8
+ the stable remainder.
9
+
10
+ Used by checks/idor_semantic.py to prove "attacker A received the SAME data that
11
+ victim B sees for B's object" WITHOUT needing a hand-picked ownership marker.
12
+
13
+ No third-party deps — just stdlib. That keeps the plugin story clean.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ from difflib import SequenceMatcher
20
+
21
+ DYN = "<dyn>"
22
+
23
+ # Keys whose VALUES are volatile and must be neutralised before comparing.
24
+ DYNAMIC_KEY_PAT = re.compile(
25
+ r"(?i)(^|[_\-])("
26
+ r"ts|time|timestamp|datetime|date|created|updated|modified|expires?|"
27
+ r"nonce|csrf|xsrf|token|secret|request[_\-]?id|req[_\-]?id|trace[_\-]?id|"
28
+ r"correlation[_\-]?id|span[_\-]?id|session|sid|iat|exp|nbf|jti|etag|"
29
+ r"last[_\-]?modified|version|signature|sig|hash|checksum|cache|rand|seed"
30
+ r")($|[_\-])"
31
+ )
32
+
33
+ # Value patterns that are volatile regardless of their key.
34
+ VALUE_PATS = [
35
+ re.compile(r"\beyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\b"), # JWT
36
+ re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"), # UUID
37
+ re.compile(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+\-]\d{2}:?\d{2})?"), # ISO 8601
38
+ re.compile(r"\b1[0-9]{9,12}\b"), # unix epoch (s/ms)
39
+ re.compile(r"\b[0-9a-fA-F]{16,}\b"), # long hex token/hash
40
+ ]
41
+
42
+
43
+ def _neutralise_scalar(v):
44
+ if not isinstance(v, str):
45
+ return v
46
+ out = v
47
+ for pat in VALUE_PATS:
48
+ out = pat.sub(DYN, out)
49
+ return out
50
+
51
+
52
+ def normalize_json(obj, strip_keys=None):
53
+ """Recursively replace dynamic values with a constant so structure stays comparable."""
54
+ strip = {k.lower() for k in (strip_keys or [])}
55
+ if isinstance(obj, dict):
56
+ out = {}
57
+ for k, v in obj.items():
58
+ if k.lower() in strip or DYNAMIC_KEY_PAT.search(str(k)):
59
+ out[k] = DYN
60
+ else:
61
+ out[k] = normalize_json(v, strip_keys)
62
+ return out
63
+ if isinstance(obj, list):
64
+ return [normalize_json(x, strip_keys) for x in obj]
65
+ return _neutralise_scalar(obj)
66
+
67
+
68
+ def normalize_text(s: str) -> str:
69
+ out = s
70
+ for pat in VALUE_PATS:
71
+ out = pat.sub(DYN, out)
72
+ return re.sub(r"\s+", " ", out).strip()
73
+
74
+
75
+ def canonical(raw: str, content_type: str = "", strip_keys=None) -> str:
76
+ """Return a normalised, comparison-ready string for a raw response body."""
77
+ looks_json = "json" in (content_type or "").lower() or raw.strip()[:1] in ("{", "[")
78
+ if looks_json:
79
+ try:
80
+ return json.dumps(normalize_json(json.loads(raw), strip_keys), sort_keys=True)
81
+ except Exception:
82
+ pass
83
+ return normalize_text(raw)
84
+
85
+
86
+ def compare(a_raw: str, b_raw: str, content_type: str = "", strip_keys=None,
87
+ equal_threshold: float = 0.98) -> dict:
88
+ """
89
+ Compare two response bodies after noise-cancelling.
90
+ Returns {equal, similarity, a_len, b_len}. `similarity` is 0..1.
91
+ """
92
+ a = canonical(a_raw or "", content_type, strip_keys)
93
+ b = canonical(b_raw or "", content_type, strip_keys)
94
+ sim = SequenceMatcher(None, a, b).ratio() if (a or b) else 1.0
95
+ return {
96
+ "equal": sim >= equal_threshold,
97
+ "similarity": round(sim, 4),
98
+ "a_len": len(a),
99
+ "b_len": len(b),
100
+ }
agent/governance.py ADDED
@@ -0,0 +1,94 @@
1
+ """
2
+ Governance & Safety Controls.
3
+
4
+ The Scope Guard (in harness.py) already makes it physically impossible to send
5
+ a request off-target or to run a destructive method. This layer adds the
6
+ *decision* controls from the spec that sit ABOVE the network:
7
+
8
+ PermissionManager which tools may run autonomously vs. need a human 'yes'
9
+ Human-in-the-loop an approval prompt for sensitive actions
10
+ Audit every authorize() decision is written to the event log
11
+
12
+ Approval resolution order:
13
+ auto_approve == True -> allow everything (offline tests / full-auto)
14
+ tool not in require_approval_for -> allow
15
+ tool in require_approval_for -> ask the human (stdin). No TTY -> deny-safe.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import sys
21
+ from urllib.parse import urlsplit, urlunsplit
22
+
23
+ from harness import scrub_secrets
24
+
25
+
26
+ _HIDDEN_ARG_NAMES = {
27
+ "actions", "authorization", "body", "cookie", "cookies", "data", "fields",
28
+ "headers", "json_body", "nodes", "params", "password", "payload",
29
+ "register_spec", "request_body", "secret", "token",
30
+ }
31
+ _URL_ARG_NAMES = {"url", "url_template", "start_url"}
32
+
33
+
34
+ def _safe_url(value):
35
+ """Redact secret query values and any userinfo before showing a target."""
36
+ value = scrub_secrets(str(value))
37
+ parsed = urlsplit(value)
38
+ if parsed.netloc and "@" in parsed.netloc:
39
+ parsed = parsed._replace(netloc=parsed.netloc.rsplit("@", 1)[1])
40
+ return urlunsplit(parsed)
41
+
42
+
43
+ def _approval_view(value, key=""):
44
+ """Keep approval prompts readable without echoing request credentials/bodies."""
45
+ if key.lower() in _HIDDEN_ARG_NAMES:
46
+ return "<hidden>"
47
+ if key.lower() in _URL_ARG_NAMES:
48
+ return _safe_url(value)
49
+ if isinstance(value, dict):
50
+ return {k: _approval_view(v, str(k)) for k, v in value.items()}
51
+ if isinstance(value, (list, tuple)):
52
+ items = [_approval_view(v) for v in value[:8]]
53
+ if len(value) > 8:
54
+ items.append(f"... {len(value) - 8} more")
55
+ return items
56
+ if isinstance(value, str) and len(value) > 180:
57
+ return value[:177] + "..."
58
+ return value
59
+
60
+
61
+ class PermissionManager:
62
+ def __init__(self, autonomy_cfg, state):
63
+ self.cfg = autonomy_cfg
64
+ self.state = state
65
+
66
+ def authorize(self, step: int, tool: str, args: dict) -> tuple[bool, str]:
67
+ if self.cfg.auto_approve:
68
+ return self._log(step, tool, args, True, "auto_approve")
69
+ if tool not in self.cfg.require_approval_for:
70
+ return self._log(step, tool, args, True, "not-sensitive")
71
+
72
+ # Sensitive tool -> ask the operator.
73
+ if not sys.stdin or not sys.stdin.isatty():
74
+ return self._log(step, tool, args, False,
75
+ "sensitive tool needs approval but no interactive terminal")
76
+ print(f"\n SENSITIVE ACTION - approval required")
77
+ print(f" Step {step}: {tool}")
78
+ target = args.get("url") or args.get("url_template") or args.get("start_url")
79
+ if target:
80
+ print(f" Target: {args.get('method', 'GET')} {_safe_url(target)}")
81
+ details = _approval_view(args)
82
+ print(" Details: " + json.dumps(details, default=str))
83
+ print(" This can send requests to the configured target. Review the action; No is the default.")
84
+ try:
85
+ ans = input(" Continue? [y/N]: ").strip().lower()
86
+ except EOFError:
87
+ ans = ""
88
+ ok = ans in ("y", "yes")
89
+ return self._log(step, tool, args, ok, "human:" + ("yes" if ok else "no"))
90
+
91
+ def _log(self, step, tool, args, ok, reason):
92
+ self.state.record_event(step, "authorize",
93
+ {"tool": tool, "args": args, "allowed": ok, "reason": reason})
94
+ return ok, reason