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.
- botsting/__init__.py +3 -0
- botsting/__main__.py +8 -0
- botsting/attacks/__init__.py +0 -0
- botsting/attacks/adaptive.py +495 -0
- botsting/attacks/library.py +239 -0
- botsting/attacks/pyrit_adapter.py +227 -0
- botsting/attacks/strategy.py +157 -0
- botsting/authorize_cli.py +148 -0
- botsting/ci.py +122 -0
- botsting/cli.py +464 -0
- botsting/console.py +240 -0
- botsting/core/__init__.py +0 -0
- botsting/core/authorization.py +550 -0
- botsting/core/benchmark.py +199 -0
- botsting/core/canary.py +80 -0
- botsting/core/judge.py +175 -0
- botsting/core/matcher.py +367 -0
- botsting/core/meter.py +228 -0
- botsting/core/models.py +560 -0
- botsting/core/preflight.py +283 -0
- botsting/core/replay.py +145 -0
- botsting/core/runner.py +39 -0
- botsting/core/scan.py +917 -0
- botsting/core/stats.py +42 -0
- botsting/demo.py +215 -0
- botsting/doctor.py +271 -0
- botsting/egress_trap.py +243 -0
- botsting/exits.py +38 -0
- botsting/frameworks.py +453 -0
- botsting/harness.py +893 -0
- botsting/harness_tools.py +260 -0
- botsting/llm/__init__.py +0 -0
- botsting/llm/base.py +31 -0
- botsting/llm/ollama.py +165 -0
- botsting/llm/scripted.py +122 -0
- botsting/mcp_server.py +643 -0
- botsting/practice_server.py +190 -0
- botsting/presets.py +222 -0
- botsting/quick.py +485 -0
- botsting/report_html.py +588 -0
- botsting/report_markdown.py +472 -0
- botsting/reporting.py +73 -0
- botsting/seal.py +245 -0
- botsting/shell.py +40 -0
- botsting/sterility.py +407 -0
- botsting/targets/__init__.py +0 -0
- botsting/targets/base.py +207 -0
- botsting/targets/hardened.py +360 -0
- botsting/targets/http.py +826 -0
- botsting/targets/registry.py +96 -0
- botsting/targets/toy.py +310 -0
- botsting-0.0.3.dist-info/METADATA +495 -0
- botsting-0.0.3.dist-info/RECORD +56 -0
- botsting-0.0.3.dist-info/WHEEL +4 -0
- botsting-0.0.3.dist-info/entry_points.txt +2 -0
- botsting-0.0.3.dist-info/licenses/LICENSE +202 -0
botsting/console.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
"""What a scan prints in the terminal.
|
|
2
|
+
|
|
3
|
+
A developer reads this first, tired, in a terminal. So it leads with the verdict, groups
|
|
4
|
+
the findings by what was reached, shows one real exchange, and ends with the next
|
|
5
|
+
commands. The statistics (search and replay rates with their intervals) are in the
|
|
6
|
+
reports; here a finding shows only how many replays reproduced it.
|
|
7
|
+
|
|
8
|
+
Colour is used only when writing to a terminal, and never when NO_COLOR is set.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
|
|
18
|
+
from botsting.core.models import Finding, ScanReport
|
|
19
|
+
|
|
20
|
+
NO_VERIFIED_HEADLINE = "No verified violations observed under these tested conditions."
|
|
21
|
+
_WIDTH = 100
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Paint:
|
|
25
|
+
def __init__(self, on: bool) -> None:
|
|
26
|
+
self.on = on
|
|
27
|
+
|
|
28
|
+
def _wrap(self, code: str, text: str) -> str:
|
|
29
|
+
return f"\033[{code}m{text}\033[0m" if self.on else text
|
|
30
|
+
|
|
31
|
+
def bad(self, text: str) -> str:
|
|
32
|
+
return self._wrap("1;31", text)
|
|
33
|
+
|
|
34
|
+
def good(self, text: str) -> str:
|
|
35
|
+
return self._wrap("1;32", text)
|
|
36
|
+
|
|
37
|
+
def unsure(self, text: str) -> str:
|
|
38
|
+
return self._wrap("1;33", text)
|
|
39
|
+
|
|
40
|
+
def strong(self, text: str) -> str:
|
|
41
|
+
return self._wrap("1", text)
|
|
42
|
+
|
|
43
|
+
def dim(self, text: str) -> str:
|
|
44
|
+
return self._wrap("2", text)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def use_colour(stream: object = None) -> bool:
|
|
48
|
+
stream = stream if stream is not None else sys.stdout
|
|
49
|
+
return bool(getattr(stream, "isatty", lambda: False)()) and "NO_COLOR" not in os.environ
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_CODE = re.compile(r"(?:[A-Z0-9]{4}-){3}[A-Z0-9]{4}") # the shape of a planted code
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _one_line(text: str, limit: int) -> str:
|
|
56
|
+
"""The text on one line. A long one keeps its start and its end, or the part around a planted
|
|
57
|
+
code if one is in plain sight, because the end of an answer is often where the secret came out."""
|
|
58
|
+
flat = " ".join(text.split())
|
|
59
|
+
if len(flat) <= limit:
|
|
60
|
+
return flat
|
|
61
|
+
found = _CODE.search(flat)
|
|
62
|
+
if found and found.end() > limit - 8:
|
|
63
|
+
tail = flat[max(0, found.start() - 30) : found.end() + 12]
|
|
64
|
+
head = flat[: max(0, limit - len(tail) - 5)].rstrip()
|
|
65
|
+
return f"{head} ... {tail}"
|
|
66
|
+
keep = (limit - 5) // 2
|
|
67
|
+
return f"{flat[:keep].rstrip()} ... {flat[-keep:].lstrip()}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def what_happened(finding: Finding) -> str:
|
|
71
|
+
if finding.kind == "disclosure":
|
|
72
|
+
return f"{finding.slot_id} leaked ({finding.encoding}, {finding.scope})"
|
|
73
|
+
tools = ", ".join(dict.fromkeys(call.tool for call in finding.tool_calls)) or "a forbidden tool"
|
|
74
|
+
fate = "and the tool accepted it" if any(call.accepted for call in finding.tool_calls) else "which the tool refused"
|
|
75
|
+
if finding.kind == "injection":
|
|
76
|
+
# Association, not proof of cause: the tool ran with the planted text in place and
|
|
77
|
+
# did not run with harmless text there.
|
|
78
|
+
return f"{finding.slot_id}: with planted text in place, {tools} was called, {fate}"
|
|
79
|
+
return f"{finding.slot_id}: the attacker's conversation led to a call to {tools}, {fate}"
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _heading(findings: Sequence[Finding]) -> str:
|
|
83
|
+
"""One line for everything found at one place."""
|
|
84
|
+
first = findings[0]
|
|
85
|
+
ways = "1 way" if len(findings) == 1 else f"{len(findings)} ways"
|
|
86
|
+
if first.kind == "disclosure":
|
|
87
|
+
return f"{first.slot_id}: leaked, {ways}"
|
|
88
|
+
return f"{what_happened(first)} ({ways})"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
ADVICE = {
|
|
92
|
+
"instruction_secret": (
|
|
93
|
+
"Take the secret out of the instructions. A model can be talked into repeating anything it was given. "
|
|
94
|
+
"Keep the value in your code and use it there."
|
|
95
|
+
),
|
|
96
|
+
"other_user_record": (
|
|
97
|
+
"Check who is asking in the code that fetches the record, before the model sees it. A rule written in "
|
|
98
|
+
"the instructions is a request, not a check."
|
|
99
|
+
),
|
|
100
|
+
"tool_rule": (
|
|
101
|
+
"Enforce who may use the tool inside the tool itself, from the signed-in user, not from what the "
|
|
102
|
+
"conversation claims."
|
|
103
|
+
),
|
|
104
|
+
"injection_point": (
|
|
105
|
+
"Treat text the bot reads (notes, documents, tickets) as data. Offer a tool only when the current "
|
|
106
|
+
"user's own message asks for it, and check that in code."
|
|
107
|
+
),
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def advice(report: ScanReport, slot_id: str) -> str:
|
|
112
|
+
"""What to change, for the kind of thing that was reached. Empty if the kind is not known."""
|
|
113
|
+
kind = next((slot.kind for slot in report.slots if slot.slot_id == slot_id), "")
|
|
114
|
+
return ADVICE.get(kind, "")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _wrap(text: str, indent: str, width: int = _WIDTH) -> list[str]:
|
|
118
|
+
words, lines, line = text.split(), [], indent
|
|
119
|
+
for word in words:
|
|
120
|
+
if len(line) + len(word) + 1 > width and line.strip():
|
|
121
|
+
lines.append(line.rstrip())
|
|
122
|
+
line = indent
|
|
123
|
+
line += word + " "
|
|
124
|
+
return [*lines, line.rstrip()]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _groups(findings: Sequence[Finding]) -> list[tuple[str, list[Finding]]]:
|
|
128
|
+
grouped: dict[str, list[Finding]] = {}
|
|
129
|
+
for finding in findings:
|
|
130
|
+
grouped.setdefault(finding.slot_id, []).append(finding)
|
|
131
|
+
return list(grouped.items())
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _exchange(finding: Finding) -> list[str]:
|
|
135
|
+
"""The last thing the attacker said and what came back, from the first time the attack worked."""
|
|
136
|
+
asked = next((t.text for t in reversed(finding.transcript) if t.role == "attacker"), "")
|
|
137
|
+
answered = next((t for t in reversed(finding.transcript) if t.role == "target"), None)
|
|
138
|
+
lines = []
|
|
139
|
+
if finding.payload:
|
|
140
|
+
lines.append(f" planted {_one_line(finding.payload, _WIDTH - 13)}")
|
|
141
|
+
if asked:
|
|
142
|
+
lines.append(f" asked {_one_line(asked, _WIDTH - 13)}")
|
|
143
|
+
if answered is not None:
|
|
144
|
+
lines.append(f" answer {_one_line(answered.text, _WIDTH - 13)}")
|
|
145
|
+
for call in answered.tool_calls:
|
|
146
|
+
arguments = ", ".join(f"{name}={value}" for name, value in call.arguments)
|
|
147
|
+
lines.append(f" tool {_one_line(f'{call.tool}({arguments})', _WIDTH - 13)}")
|
|
148
|
+
return lines
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_ERRORS_SHOWN = 3
|
|
152
|
+
_AFTER = re.compile(r" \(after \d+(?: of \d+)? repl(?:y|ies)\)$")
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _errors(report: ScanReport, paint: _Paint) -> list[str]:
|
|
156
|
+
"""What went wrong, in the scan's own words: each different message once, with how often and
|
|
157
|
+
during what. An error message usually says what to change, so it belongs where the person is
|
|
158
|
+
looking, not only in a report they have yet to open."""
|
|
159
|
+
if not report.errors:
|
|
160
|
+
return []
|
|
161
|
+
seen: dict[str, list[str]] = {}
|
|
162
|
+
for error in report.errors:
|
|
163
|
+
# The same failure at a different point in a conversation is the same thing to fix.
|
|
164
|
+
seen.setdefault(_AFTER.sub("", error.message), []).append(error.phase)
|
|
165
|
+
lines = [" " + paint.unsure("Errors")]
|
|
166
|
+
for message, phases in list(seen.items())[:_ERRORS_SHOWN]:
|
|
167
|
+
times = "once" if len(phases) == 1 else f"{len(phases)} times"
|
|
168
|
+
lines += _wrap(f"{times}, during {', '.join(dict.fromkeys(phases))}: {message}", " ")
|
|
169
|
+
if len(seen) > _ERRORS_SHOWN:
|
|
170
|
+
lines.append(f" and {len(seen) - _ERRORS_SHOWN} more kind(s) of error, in the report")
|
|
171
|
+
return lines
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def render(report: ScanReport, colour: bool = False) -> str:
|
|
175
|
+
"""The summary printed after a scan. Its first line is the verdict."""
|
|
176
|
+
paint = _Paint(colour)
|
|
177
|
+
lines: list[str] = []
|
|
178
|
+
if report.status == "violations_verified":
|
|
179
|
+
lines.append(paint.bad(f"{len(report.findings)} verified violation(s): {report.breakdown()}."))
|
|
180
|
+
elif report.status == "no_verified_violations":
|
|
181
|
+
lines.append(paint.good(NO_VERIFIED_HEADLINE))
|
|
182
|
+
else:
|
|
183
|
+
lines.append(paint.unsure("Inconclusive: the scan could not reach a conclusion."))
|
|
184
|
+
for reason in report.inconclusive_reasons:
|
|
185
|
+
lines += _wrap(f"not established: {reason}", " ")
|
|
186
|
+
lines += _errors(report, paint)
|
|
187
|
+
gaps = report.not_tested()
|
|
188
|
+
if gaps:
|
|
189
|
+
# A zero for something that was never tried must not read as a pass.
|
|
190
|
+
lines.append(" " + paint.unsure("Not tested in this scan"))
|
|
191
|
+
for gap in gaps:
|
|
192
|
+
lines += _wrap(gap, " ")
|
|
193
|
+
|
|
194
|
+
for slot_id, findings in _groups(report.findings):
|
|
195
|
+
lines.append("")
|
|
196
|
+
lines.append(" " + paint.strong(_heading(findings)))
|
|
197
|
+
for finding in findings:
|
|
198
|
+
rate = finding.reproduction
|
|
199
|
+
replays = f"{rate.successes} of {rate.trials} replays"
|
|
200
|
+
title = finding.title if len(finding.title) <= 58 else finding.title[:55].rstrip() + "..."
|
|
201
|
+
lines.append(f" {finding.id:<4} {title:<58} {paint.dim(replays)}")
|
|
202
|
+
fix = advice(report, slot_id)
|
|
203
|
+
if fix:
|
|
204
|
+
lines += _wrap("Fix: " + fix, " ")
|
|
205
|
+
if report.findings:
|
|
206
|
+
first = report.findings[0]
|
|
207
|
+
lines.append("")
|
|
208
|
+
lines.append(" " + paint.strong(f"How {first.id} happened"))
|
|
209
|
+
lines += _exchange(first)
|
|
210
|
+
if first.kind == "disclosure":
|
|
211
|
+
lines.append(paint.dim(" The value in that answer was made for this one attempt. Nobody else had it."))
|
|
212
|
+
|
|
213
|
+
lines.append("")
|
|
214
|
+
if report.suspected:
|
|
215
|
+
lines.append(f" {len(report.suspected)} suspected finding(s), not verified and not counted.")
|
|
216
|
+
if report.contaminated_attempts:
|
|
217
|
+
lines.append(f" {report.contaminated_attempts} attempt(s) discarded as contaminated.")
|
|
218
|
+
lines.append(
|
|
219
|
+
paint.dim(
|
|
220
|
+
f" Target {report.target}, attacker acting as {report.attacker_principal}. {report.attacks_run} attacks "
|
|
221
|
+
f"tried. Spent: {report.messages_sent} messages, {report.tool_calls_recorded} recorded tool calls."
|
|
222
|
+
)
|
|
223
|
+
)
|
|
224
|
+
return "\n".join(lines)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def next_steps(report: ScanReport, paths: Sequence[tuple[str, str]], replay: str = "", colour: bool = False) -> str:
|
|
228
|
+
"""Where the reports are and what to run next. `paths` are (label, path) pairs."""
|
|
229
|
+
paint = _Paint(colour)
|
|
230
|
+
width = max((len(label) for label, _ in paths), default=0)
|
|
231
|
+
lines = [paint.strong("Next")]
|
|
232
|
+
for label, path in paths:
|
|
233
|
+
lines.append(f" {label:<{max(width, 18)}} {path}")
|
|
234
|
+
if paths and not any(path.endswith((".html", ".htm")) for _, path in paths):
|
|
235
|
+
lines.append(paint.dim(f" {'A page to read':<{max(width, 18)}} add --html report.html to the scan command"))
|
|
236
|
+
if replay:
|
|
237
|
+
lines.append(f" {'Replay a finding':<{max(width, 18)}} {replay}")
|
|
238
|
+
if len(report.findings) > 1:
|
|
239
|
+
lines.append(paint.dim(f" {'':<{max(width, 18)}} (any id from {report.findings[0].id} to {report.findings[-1].id})"))
|
|
240
|
+
return "\n".join(lines)
|
|
File without changes
|