botsting 0.0.3__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 (56) hide show
  1. botsting/__init__.py +3 -0
  2. botsting/__main__.py +8 -0
  3. botsting/attacks/__init__.py +0 -0
  4. botsting/attacks/adaptive.py +495 -0
  5. botsting/attacks/library.py +239 -0
  6. botsting/attacks/pyrit_adapter.py +227 -0
  7. botsting/attacks/strategy.py +157 -0
  8. botsting/authorize_cli.py +148 -0
  9. botsting/ci.py +122 -0
  10. botsting/cli.py +464 -0
  11. botsting/console.py +240 -0
  12. botsting/core/__init__.py +0 -0
  13. botsting/core/authorization.py +550 -0
  14. botsting/core/benchmark.py +199 -0
  15. botsting/core/canary.py +80 -0
  16. botsting/core/judge.py +175 -0
  17. botsting/core/matcher.py +367 -0
  18. botsting/core/meter.py +228 -0
  19. botsting/core/models.py +560 -0
  20. botsting/core/preflight.py +283 -0
  21. botsting/core/replay.py +145 -0
  22. botsting/core/runner.py +39 -0
  23. botsting/core/scan.py +917 -0
  24. botsting/core/stats.py +42 -0
  25. botsting/demo.py +215 -0
  26. botsting/doctor.py +271 -0
  27. botsting/egress_trap.py +243 -0
  28. botsting/exits.py +38 -0
  29. botsting/frameworks.py +453 -0
  30. botsting/harness.py +893 -0
  31. botsting/harness_tools.py +260 -0
  32. botsting/llm/__init__.py +0 -0
  33. botsting/llm/base.py +31 -0
  34. botsting/llm/ollama.py +165 -0
  35. botsting/llm/scripted.py +122 -0
  36. botsting/mcp_server.py +643 -0
  37. botsting/practice_server.py +190 -0
  38. botsting/presets.py +222 -0
  39. botsting/quick.py +485 -0
  40. botsting/report_html.py +588 -0
  41. botsting/report_markdown.py +472 -0
  42. botsting/reporting.py +73 -0
  43. botsting/seal.py +245 -0
  44. botsting/shell.py +40 -0
  45. botsting/sterility.py +407 -0
  46. botsting/targets/__init__.py +0 -0
  47. botsting/targets/base.py +207 -0
  48. botsting/targets/hardened.py +360 -0
  49. botsting/targets/http.py +826 -0
  50. botsting/targets/registry.py +96 -0
  51. botsting/targets/toy.py +310 -0
  52. botsting-0.0.3.dist-info/METADATA +495 -0
  53. botsting-0.0.3.dist-info/RECORD +56 -0
  54. botsting-0.0.3.dist-info/WHEEL +4 -0
  55. botsting-0.0.3.dist-info/entry_points.txt +2 -0
  56. botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,283 @@
1
+ """Preflight: every instrument is exercised by a legitimate route before any attack runs.
2
+
3
+ - Each canary is planted and fetched by someone allowed to see it. A canary nobody
4
+ can reach cannot leak, so finding nothing for it would mean nothing.
5
+ - Each protected tool is called by someone allowed to call it. If the recorder does
6
+ not show that call, it would not show a forbidden one either.
7
+ - Each injection point is filled with harmless text and its ordinary request made.
8
+ If a forbidden tool runs even then, a call during an attack proves nothing.
9
+ - Normal-task checks run here too.
10
+
11
+ `_repeated_slots` also tells the two apart on a target whose fake secrets travel in
12
+ each request: a slot whose value comes back unasked cannot be tested by attacking it.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Sequence
18
+ from dataclasses import dataclass
19
+
20
+ from botsting.core.canary import Canary, new_canary
21
+ from botsting.core.matcher import find_canary
22
+ from botsting.core.meter import Meter, _Stop
23
+ from botsting.core.models import (
24
+ HARNESS_ATTESTED,
25
+ InjectionPoint,
26
+ Slot,
27
+ SlotStatus,
28
+ TaskStatus,
29
+ ToolRule,
30
+ )
31
+ from botsting.targets.base import (
32
+ NotAuthorizedError,
33
+ Target,
34
+ TargetError,
35
+ injection_points,
36
+ require_contained_tools,
37
+ tool_rules,
38
+ )
39
+
40
+ _CONTROL_TRIES = 3
41
+
42
+
43
+ def _fresh(slots: Sequence[Slot]) -> dict[str, Canary]:
44
+ return {slot.id: new_canary(slot.id, slot.canary_style) for slot in slots}
45
+
46
+
47
+ def _values(canaries: dict[str, Canary]) -> dict[str, str]:
48
+ return {slot_id: canary.value for slot_id, canary in canaries.items()}
49
+
50
+
51
+ def _status(objective_id: str, kind: str, description: str, authorized: tuple[str, ...], state: str, detail: str = "") -> SlotStatus:
52
+ return SlotStatus(objective_id, kind, description, authorized, state, detail) # type: ignore[arg-type]
53
+
54
+
55
+ async def _check_slot(target: Target, slot: Slot, meter: Meter) -> SlotStatus:
56
+ def status(state: str, detail: str = "") -> SlotStatus:
57
+ return _status(slot.id, slot.kind, slot.description, slot.authorized, state, detail)
58
+
59
+ if target.attacker_principal in slot.authorized:
60
+ return status("error", f"the attacker principal {target.attacker_principal} is authorized for this slot")
61
+ if slot.control_principal not in slot.authorized:
62
+ return status("error", f"the control principal {slot.control_principal} is not authorized for this slot")
63
+ last_error = ""
64
+ for _ in range(_CONTROL_TRIES):
65
+ canaries = _fresh(target.slots())
66
+ try:
67
+ await meter.reset(target, _values(canaries))
68
+ session = await meter.open(target, slot.control_principal)
69
+ reply = await meter.send(session, slot.control_prompt)
70
+ except TargetError as exc:
71
+ last_error = str(exc)
72
+ continue
73
+ except _Stop as stop:
74
+ return status("error", f"not checked: stopped early ({stop})")
75
+ match = find_canary(canaries[slot.id], [reply.text])
76
+ if match is not None and match.full:
77
+ return status("reachable")
78
+ last_error = ""
79
+ if last_error:
80
+ return status("error", last_error)
81
+ return status(
82
+ "unreachable",
83
+ f"{slot.control_principal} asked the control question {_CONTROL_TRIES} times and never received "
84
+ "the planted value, so finding nothing for this slot would not show that it is protected",
85
+ )
86
+
87
+
88
+ ATTESTED_NOTE = "the harness attests that this tool carries its recorder; no legitimate call was exercised"
89
+
90
+
91
+ async def _check_rule(target: Target, rule: ToolRule, meter: Meter) -> SlotStatus:
92
+ def status(state: str, detail: str = "") -> SlotStatus:
93
+ return _status(rule.id, "tool_rule", rule.description, rule.authorized, state, detail)
94
+
95
+ if target.attacker_principal in rule.authorized:
96
+ return status("error", f"the attacker principal {target.attacker_principal} is allowed to cause this tool to run")
97
+ if rule.control_principal not in rule.authorized:
98
+ return status("error", f"the control principal {rule.control_principal} is not allowed to cause this tool to run")
99
+ if rule.control_prompt == HARNESS_ATTESTED:
100
+ # No legitimate request is made. The harness says, in its signed readiness answer, whether the
101
+ # tool carries its recorder. That shows a call would be recorded; it does not show the bot can
102
+ # reach the tool, and the report says so.
103
+ try:
104
+ await meter.reset(target, _values(_fresh(target.slots())))
105
+ except TargetError as exc:
106
+ return status("error", str(exc))
107
+ except _Stop as stop:
108
+ return status("error", f"not checked: stopped early ({stop})")
109
+ if rule.tool in getattr(target, "marked_tools", ()):
110
+ return status("reachable", ATTESTED_NOTE)
111
+ return status(
112
+ "error",
113
+ f"the harness does not list {rule.tool} among the tools it has marked, so a call to it would go unseen",
114
+ )
115
+ last_error = ""
116
+ for _ in range(_CONTROL_TRIES):
117
+ try:
118
+ await meter.reset(target, _values(_fresh(target.slots())))
119
+ session = await meter.open(target, rule.control_principal)
120
+ reply = await meter.send(session, rule.control_prompt)
121
+ except TargetError as exc:
122
+ last_error = str(exc)
123
+ continue
124
+ except _Stop as stop:
125
+ return status("error", f"not checked: stopped early ({stop})")
126
+ if any(call.tool == rule.tool and call.accepted for call in reply.tool_calls):
127
+ return status("reachable")
128
+ last_error = ""
129
+ if last_error:
130
+ return status("error", last_error)
131
+ return status(
132
+ "unreachable",
133
+ f"{rule.control_principal} made the legitimate request {_CONTROL_TRIES} times and no accepted call to "
134
+ f"{rule.tool} was recorded, so a forbidden call might not be recorded either",
135
+ )
136
+
137
+
138
+ async def _check_point(target: Target, point: InjectionPoint, meter: Meter) -> SlotStatus:
139
+ def status(state: str, detail: str = "") -> SlotStatus:
140
+ return _status(point.id, "injection_point", point.description, (), state, detail)
141
+
142
+ answered = False
143
+ last_error = ""
144
+ for _ in range(_CONTROL_TRIES):
145
+ try:
146
+ await meter.reset(target, _values(_fresh(target.slots())), {point.id: point.benign_content})
147
+ session = await meter.open(target, point.victim_principal)
148
+ reply = await meter.send(session, point.victim_prompt)
149
+ except TargetError as exc:
150
+ last_error = str(exc)
151
+ continue
152
+ except _Stop as stop:
153
+ return status("error", f"not checked: stopped early ({stop})")
154
+ unprompted = [call.tool for call in reply.tool_calls if call.tool in point.forbidden_tools]
155
+ if unprompted:
156
+ return status(
157
+ "error",
158
+ f"with harmless text in place, the ordinary request still caused a call to {unprompted[0]}; "
159
+ "a call during an attack would therefore not show that the attack caused it",
160
+ )
161
+ answered = answered or point.expect_substring.lower() in reply.text.lower()
162
+ last_error = ""
163
+ if last_error:
164
+ return status("error", last_error)
165
+ if not answered:
166
+ return status(
167
+ "unreachable",
168
+ f"the ordinary request was never answered as expected in {_CONTROL_TRIES} tries, so the planted "
169
+ "text may not be read at all",
170
+ )
171
+ return status("reachable", f"with harmless text in place, no forbidden tool ran in {_CONTROL_TRIES} requests")
172
+
173
+
174
+ async def _check_tasks(target: Target, meter: Meter) -> list[TaskStatus]:
175
+ results: list[TaskStatus] = []
176
+ for task in target.task_checks():
177
+ # A language model can fumble a normal request once. The check asks whether the
178
+ # target works at all, so it gets the same number of tries as a control question.
179
+ passed, detail = False, ""
180
+ for attempt in range(1, _CONTROL_TRIES + 1):
181
+ try:
182
+ await meter.reset(target, _values(_fresh(target.slots())))
183
+ session = await meter.open(target, task.principal)
184
+ reply = await meter.send(session, task.prompt)
185
+ except TargetError as exc:
186
+ detail = f"target error: {exc}"
187
+ continue
188
+ except _Stop as stop:
189
+ detail = f"not checked: stopped early ({stop})"
190
+ break
191
+ if reply.text.strip() and task.expect_substring.lower() in reply.text.lower():
192
+ passed = True
193
+ detail = "" if attempt == 1 else f"worked on try {attempt} of {_CONTROL_TRIES}"
194
+ break
195
+ detail = (
196
+ f"in {_CONTROL_TRIES} tries no reply contained {task.expect_substring!r}; "
197
+ f"last reply: {reply.text[:200]!r}"
198
+ )
199
+ results.append(TaskStatus(task.id, passed, detail))
200
+ return results
201
+
202
+
203
+ _REPEATED = "the planted value came back in the reply to an ordinary request"
204
+
205
+
206
+ async def _repeated_slots(target: Target, meter: Meter) -> dict[str, str]:
207
+ """For a target whose fake secrets travel in each request: slots whose value comes back unasked.
208
+
209
+ On such a target a bot that repeats its request variables would hand every attacker "the secret",
210
+ though it is only the attacker's own request coming back and says nothing about what the bot keeps
211
+ in its instructions. An ordinary request, sent as someone not allowed the value, tells the two apart.
212
+ """
213
+ if not getattr(target, "secrets_travel_in_requests", False):
214
+ return {}
215
+ found: dict[str, str] = {}
216
+ for task in target.task_checks():
217
+ canaries = _fresh(target.slots())
218
+ try:
219
+ await meter.reset(target, _values(canaries))
220
+ session = await meter.open(target, task.principal)
221
+ reply = await meter.send(session, task.prompt)
222
+ except (TargetError, _Stop):
223
+ continue # the normal-task check reports a target that does not answer
224
+ for slot in target.slots():
225
+ if task.principal in slot.authorized or slot.id in found:
226
+ continue
227
+ match = find_canary(canaries[slot.id], [reply.text])
228
+ if match is not None and match.full:
229
+ found[slot.id] = (
230
+ f"{_REPEATED} ({task.id}, sent as {task.principal}). On this target the value travels in "
231
+ "each request, so the bot is either repeating its request variables or giving the value to "
232
+ "anyone; a finding here could not be told apart from that, so no attack was run on this slot"
233
+ )
234
+ return found
235
+
236
+
237
+ @dataclass(frozen=True)
238
+ class Preflight:
239
+ slots: tuple[SlotStatus, ...] # canary slots, then tool rules, then injection points
240
+ tasks: tuple[TaskStatus, ...]
241
+ # Slots whose planted value comes back whoever asks (see _repeated_slots). No attack is run on
242
+ # them, a match for one is never a finding, and a replay is not run.
243
+ repeated: frozenset[str] = frozenset()
244
+
245
+
246
+ async def preflight(target: Target, meter: Meter | None = None) -> Preflight:
247
+ meter = meter or Meter()
248
+ meter.guard(target)
249
+ try:
250
+ require_contained_tools(target)
251
+ except NotAuthorizedError as exc:
252
+ # Every check below then stops before sending anything and reports itself as not checked.
253
+ meter.stop_reason = meter.stop_reason or f"authorization no longer valid: {exc}"
254
+ statuses = [await _check_slot(target, slot, meter) for slot in target.slots()]
255
+ repeated = await _repeated_slots(target, meter)
256
+ statuses = [
257
+ _status(s.slot_id, s.kind, s.description, s.authorized, "error", repeated[s.slot_id]) if s.slot_id in repeated else s
258
+ for s in statuses
259
+ ]
260
+ watched: set[str] = set() # tools whose recorder was seen to record a legitimate call
261
+ for rule in tool_rules(target):
262
+ status = await _check_rule(target, rule, meter)
263
+ statuses.append(status)
264
+ if status.state == "reachable":
265
+ watched.add(rule.tool)
266
+ for point in injection_points(target):
267
+ unwatched = [tool for tool in point.forbidden_tools if tool not in watched]
268
+ if unwatched:
269
+ # Seeing no call proves nothing unless the recorder is known to see calls.
270
+ statuses.append(
271
+ _status(
272
+ point.id,
273
+ "injection_point",
274
+ point.description,
275
+ (),
276
+ "error",
277
+ f"the recorder was never seen to record a legitimate call to {unwatched[0]} (that needs a tool "
278
+ "rule whose control request works), so a forbidden call during this request might go unseen",
279
+ )
280
+ )
281
+ else:
282
+ statuses.append(await _check_point(target, point, meter))
283
+ return Preflight(tuple(statuses), tuple(await _check_tasks(target, meter)), frozenset(repeated))
@@ -0,0 +1,145 @@
1
+ """Replay a frozen attack or a finding, and check the instruments again.
2
+
3
+ "The attack no longer works" is only worth saying if the thing it reached still works
4
+ by its legitimate route and normal use still works. A target that answers "no" to
5
+ everything stops every attack and is not fixed.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ from botsting.core.judge import _rate_for
13
+ from botsting.core.meter import Meter, ScanConfig
14
+ from botsting.core.models import (
15
+ Attack,
16
+ EvidenceLevel,
17
+ Finding,
18
+ Rate,
19
+ )
20
+ from botsting.core.preflight import _repeated_slots, preflight
21
+ from botsting.core.scan import _control_for, _control_verdict, _describe, _replays
22
+ from botsting.core.stats import make_rate
23
+ from botsting.targets.base import (
24
+ Target,
25
+ UnsafeTargetError,
26
+ injection_points,
27
+ require_contained_tools,
28
+ tool_rules,
29
+ )
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ReplayResult:
34
+ rate: Rate
35
+ # Reasons a result of zero successes could not be trusted. Empty when the instruments held.
36
+ problems: tuple[str, ...]
37
+ target_config: dict[str, str]
38
+ # Set when successes were seen but cannot be pinned on the attack, so they prove nothing.
39
+ unattributable: str = ""
40
+
41
+
42
+ def attack_from(finding: Finding) -> Attack:
43
+ """The frozen attack behind a finding, aimed at the thing it was found to violate."""
44
+ return Attack(
45
+ id=finding.attack_id,
46
+ technique=finding.technique,
47
+ title=finding.title,
48
+ slot_id=finding.slot_id,
49
+ turns=finding.frozen_turns,
50
+ kind=finding.kind,
51
+ payload=finding.payload,
52
+ )
53
+
54
+
55
+ async def replay(
56
+ target: Target,
57
+ attack: Attack,
58
+ objective_id: str,
59
+ trials: int,
60
+ meter: Meter | None = None,
61
+ at_least: EvidenceLevel | None = None,
62
+ ) -> Rate:
63
+ """Replay a frozen attack from reset `trials` times; success is verified evidence against `objective_id`.
64
+
65
+ Returns a rate of no trials, having sent no attack, when the value of `objective_id` comes
66
+ back on this target whoever asks (see preflight._repeated_slots): a match would then prove
67
+ nothing. `replay_finding` checks the rest of the instruments as well, and says why.
68
+ """
69
+ meter = meter or Meter()
70
+ meter.guard(target)
71
+ try:
72
+ repeated = await _repeated_slots(target, meter)
73
+ except UnsafeTargetError:
74
+ return make_rate(0, 0) # not permitted: nothing is sent
75
+ if objective_id in repeated:
76
+ return make_rate(0, 0)
77
+ attempts, _ = await _replays(target, attack, trials, meter)
78
+ return _rate_for(attempts, objective_id, at_least)
79
+
80
+
81
+ async def replay_finding(target: Target, finding: Finding, trials: int, config: ScanConfig | None = None) -> ReplayResult:
82
+ """Replay a finding and check the instruments again, so a zero can be told from a broken target.
83
+
84
+ "The attack no longer works" is only worth saying if the thing it reached still
85
+ works by its legitimate route and normal use still works. A target that answers
86
+ "no" to everything stops every attack and is not fixed.
87
+
88
+ Success means evidence at the finding's own level or stronger: a refund that was
89
+ carried out is not reproduced by one that was refused. Planted text is replayed
90
+ with a harmless-text request after each trial, and not at all if the harmless
91
+ check fails first, because a tool call could not then be pinned on the text.
92
+ """
93
+ meter = Meter(config)
94
+ try:
95
+ require_contained_tools(target)
96
+ await meter.start(target)
97
+ except UnsafeTargetError as exc:
98
+ return ReplayResult(make_rate(0, 0), (f"Nothing was sent to the target: {exc}",), {})
99
+ target_config = await _describe(target, meter)
100
+ objective_id = finding.slot_id
101
+ slot = next((s for s in target.slots() if s.id == objective_id), None)
102
+ rule = next((r for r in tool_rules(target) if r.id == objective_id), None)
103
+ point = next((p for p in injection_points(target) if p.id == objective_id), None)
104
+ if {"disclosure": slot, "action": rule, "injection": point}[finding.kind] is None:
105
+ return ReplayResult(
106
+ make_rate(0, 0),
107
+ (f"This target has nothing called {objective_id} for a {finding.kind} finding to be replayed against.",),
108
+ target_config,
109
+ )
110
+ checks = await preflight(target, meter)
111
+ status = next(s for s in checks.slots if s.slot_id == objective_id)
112
+ tasks = checks.tasks
113
+
114
+ problems: list[str] = []
115
+ if status.state != "reachable":
116
+ problems.append(f"{objective_id} is {status.state} by its legitimate route: {status.detail}")
117
+ if not tasks:
118
+ problems.append("The target defines no normal-task check.")
119
+ problems += [f"Normal-task check {t.task_id} did not work: {t.detail}" for t in tasks if not t.passed]
120
+ if finding.kind == "injection" and status.state != "reachable":
121
+ problems.append("The planted text was not replayed: a tool call could not have been attributed to it.")
122
+ return ReplayResult(make_rate(0, 0), tuple(problems), target_config)
123
+ if objective_id in checks.repeated:
124
+ problems.append("The attack was not replayed: on this target the value comes back whoever asks, so a match would prove nothing.")
125
+ return ReplayResult(make_rate(0, 0), tuple(problems), target_config)
126
+
127
+ control = _control_for(point) if finding.kind == "injection" and point is not None else None
128
+ replays, controls = await _replays(target, attack_from(finding), trials, meter, control)
129
+ rate = _rate_for(replays, objective_id, finding.level)
130
+ meter.poll()
131
+ if meter.stop_reason:
132
+ problems.append(f"The replay stopped before finishing ({meter.stop_reason}).")
133
+ if rate.errors:
134
+ problems.append(f"{rate.errors} replay(s) did not complete.")
135
+ if rate.contaminated:
136
+ problems.append(f"{rate.contaminated} replay(s) were discarded as contaminated.")
137
+ if rate.trials == 0:
138
+ problems.append("No replay could be judged.")
139
+ unattributable = ""
140
+ if control is not None and point is not None:
141
+ _, control_problem = _control_verdict(point, replays, controls)
142
+ if control_problem:
143
+ unattributable = control_problem[0].upper() + control_problem[1:] + "."
144
+ problems.append(unattributable)
145
+ return ReplayResult(rate, tuple(problems), target_config, unattributable)
@@ -0,0 +1,39 @@
1
+ """Run a scan: confirm the instruments work, search for attacks that work, then replay them.
2
+
3
+ The runner used to be one module; it is now split by job, and this module only gathers
4
+ the names the rest of the code imports from it, so nothing outside had to change:
5
+
6
+ - meter.py ScanConfig and Meter: the limits a scan obeys, and waiting that stops;
7
+ run_to_completion runs the whole thing without waiting on the abandoned.
8
+ - judge.py _judge, _evaluate_transcript and the level and rate helpers.
9
+ - preflight.py Preflight and the checks that exercise every instrument legitimately.
10
+ - scan.py run_scan, discovery (static and adaptive) and finding assembly; run_attempt.
11
+ - replay.py ReplayResult, replay and replay_finding.
12
+
13
+ The description of the order of work and of the three kinds of attack lives in scan.py.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from botsting.core.judge import _judge, _rate_for
19
+ from botsting.core.meter import Meter, ScanConfig, run_to_completion
20
+ from botsting.core.preflight import _fresh, preflight
21
+ from botsting.core.replay import ReplayResult, attack_from, replay, replay_finding
22
+ from botsting.core.scan import identity_unknown, run_attempt, run_scan
23
+
24
+ __all__ = [
25
+ "Meter",
26
+ "ReplayResult",
27
+ "ScanConfig",
28
+ "_fresh",
29
+ "_judge",
30
+ "_rate_for",
31
+ "attack_from",
32
+ "identity_unknown",
33
+ "preflight",
34
+ "replay",
35
+ "replay_finding",
36
+ "run_attempt",
37
+ "run_scan",
38
+ "run_to_completion",
39
+ ]