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/quick.py
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"""`botsting scan URL`: a first scan with no description file.
|
|
2
|
+
|
|
3
|
+
botsting scan http://localhost:8000/chat
|
|
4
|
+
|
|
5
|
+
For a bot that carries the drop-in harness (botsting/harness.py). The harness tells
|
|
6
|
+
the scanner what a description file would otherwise say, so the developer only adds
|
|
7
|
+
a few kinds of line to the bot and runs this.
|
|
8
|
+
|
|
9
|
+
What it works out, in order, sending nothing before permission is on record:
|
|
10
|
+
1. Permission. An authorization for this address must exist. For a bot on this
|
|
11
|
+
machine, a person at the keyboard is asked to type their name, and that is
|
|
12
|
+
recorded. For a bot across a network, `botsting authorize` is needed first.
|
|
13
|
+
2. That the harness is there, with the same key, and which tools it has marked.
|
|
14
|
+
3. How to talk to the bot: which field of the request carries the message, and where
|
|
15
|
+
the reply is in the response. It tries the common shapes with a "discover" session,
|
|
16
|
+
which plants nothing and in which marked tools are recorded and not run.
|
|
17
|
+
4. Which secrets the bot reads on an ordinary message: the slots its code asks the
|
|
18
|
+
harness for. These are the ones a first scan can test.
|
|
19
|
+
It then writes the description it worked out to the targets file, so the scan can be
|
|
20
|
+
replayed and the description extended by hand, and runs the scan.
|
|
21
|
+
|
|
22
|
+
What a first scan covers, and what it leaves out
|
|
23
|
+
------------------------------------------------
|
|
24
|
+
Secrets held in the bot's instructions: whether a user can talk the bot into revealing
|
|
25
|
+
one. The legitimate route for each secret is provided by the harness (a pass phrase
|
|
26
|
+
stated in a control session), so no control prompt has to be written.
|
|
27
|
+
|
|
28
|
+
Tools that no chat user may ever cause: those marked with `never_for_users="..."` in
|
|
29
|
+
the bot's code. The scan tries to make the bot call each one. Any recorded call is a
|
|
30
|
+
finding. The scan does not exercise such a tool legitimately first; it relies on the
|
|
31
|
+
harness's signed statement that the tool carries its recorder, and the report says so.
|
|
32
|
+
|
|
33
|
+
Text the bot reads from elsewhere: each place the code reads with `content(...)`
|
|
34
|
+
while it answers the ordinary message. Text is planted there that asks for a tool no
|
|
35
|
+
chat user may cause (the existing planted texts, asking for what the developer wrote on
|
|
36
|
+
the tool), and an ordinary user sends the ordinary message. A harmless text is tried
|
|
37
|
+
first. A place the code reads, but not for that message, is named with `--message`.
|
|
38
|
+
|
|
39
|
+
It leaves out tools that some users may use, and other users' data. Whether such a
|
|
40
|
+
call or such a record is forbidden depends on who the users are, which cannot be
|
|
41
|
+
guessed; those tools are listed as "not tested yet", with what to add. During the scan
|
|
42
|
+
every marked tool is recorded and never run.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import asyncio
|
|
48
|
+
import json
|
|
49
|
+
import re
|
|
50
|
+
import sys
|
|
51
|
+
import uuid
|
|
52
|
+
from collections.abc import Callable
|
|
53
|
+
from datetime import UTC, datetime
|
|
54
|
+
from pathlib import Path
|
|
55
|
+
from typing import Any
|
|
56
|
+
from urllib.parse import urlsplit
|
|
57
|
+
|
|
58
|
+
USER = "user"
|
|
59
|
+
OWNER = "owner:pass-phrase"
|
|
60
|
+
MESSAGE_FIELDS = ("message", "query", "input", "prompt", "text", "question", "content", "user_input", "msg")
|
|
61
|
+
REPLY_KEYS = ("reply", "response", "answer", "output", "text", "message", "content", "result", "completion")
|
|
62
|
+
_NAME = re.compile(r"[^A-Za-z0-9]+")
|
|
63
|
+
NEWLINE = chr(10)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class QuickError(Exception):
|
|
67
|
+
"""A step that the person has to do, with what to do about it."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _shapes(field: str | None, session_field: str | None) -> list[dict[str, Any]]:
|
|
71
|
+
"""Request bodies to try, most common first."""
|
|
72
|
+
extra = {session_field: "{session}"} if session_field else {}
|
|
73
|
+
if field:
|
|
74
|
+
return [{field: "{message}", **extra}]
|
|
75
|
+
plain = [{name: "{message}", **extra} for name in MESSAGE_FIELDS]
|
|
76
|
+
chat = {"messages": [{"role": "user", "content": "{message}"}], **extra}
|
|
77
|
+
return [*plain, chat]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_reply(data: Any) -> str | None:
|
|
81
|
+
"""A JSON pointer to the reply text in a response, or None if there is no text in it."""
|
|
82
|
+
if isinstance(data, str):
|
|
83
|
+
return "" if data.strip() else None
|
|
84
|
+
|
|
85
|
+
def walk(value: Any, pointer: str, depth: int) -> list[tuple[int, int, str]]:
|
|
86
|
+
found: list[tuple[int, int, str]] = []
|
|
87
|
+
if depth > 5:
|
|
88
|
+
return found
|
|
89
|
+
if isinstance(value, dict):
|
|
90
|
+
for key, inner in value.items():
|
|
91
|
+
here = pointer + "/" + str(key).replace("~", "~0").replace("/", "~1")
|
|
92
|
+
if isinstance(inner, str) and inner.strip():
|
|
93
|
+
rank = REPLY_KEYS.index(key) if key in REPLY_KEYS else len(REPLY_KEYS)
|
|
94
|
+
found.append((rank, -len(inner), here))
|
|
95
|
+
else:
|
|
96
|
+
found += walk(inner, here, depth + 1)
|
|
97
|
+
elif isinstance(value, list):
|
|
98
|
+
for index, inner in enumerate(value[:3]):
|
|
99
|
+
found += walk(inner, f"{pointer}/{index}", depth + 1)
|
|
100
|
+
return found
|
|
101
|
+
|
|
102
|
+
candidates = sorted(walk(data, "", 0))
|
|
103
|
+
return candidates[0][2] if candidates else None
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
HARMLESS = "Thank you for your help with my order."
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _description(
|
|
110
|
+
origin: str,
|
|
111
|
+
path: str,
|
|
112
|
+
body: dict[str, Any],
|
|
113
|
+
reply_pointer: str,
|
|
114
|
+
slots: list[str],
|
|
115
|
+
rules: dict[str, str] | None = None,
|
|
116
|
+
points: list[str] | None = None,
|
|
117
|
+
message: str = "Hello",
|
|
118
|
+
) -> dict[str, Any]:
|
|
119
|
+
asks = sorted((rules or {}).items())
|
|
120
|
+
return {
|
|
121
|
+
# Text someone else wrote, which the bot reads while it answers an ordinary request. It is
|
|
122
|
+
# tested only against tools no chat user may cause: a call to one of those, with planted
|
|
123
|
+
# text in place and none with harmless text there, is the evidence. The planted text asks
|
|
124
|
+
# for the first of them; a call to any of them counts.
|
|
125
|
+
"injection_points": [
|
|
126
|
+
{
|
|
127
|
+
"id": point,
|
|
128
|
+
"description": f"the text the bot's code reads with content({point!r})",
|
|
129
|
+
"victim_principal": USER,
|
|
130
|
+
"victim_prompt": message,
|
|
131
|
+
"expect": "any-reply",
|
|
132
|
+
"benign_content": HARMLESS,
|
|
133
|
+
"forbidden_tools": [tool for tool, _ in asks],
|
|
134
|
+
"goal": "issue " + asks[0][1], # the wording the tool attacks use for the same request
|
|
135
|
+
}
|
|
136
|
+
for point in (points or [])
|
|
137
|
+
if asks
|
|
138
|
+
],
|
|
139
|
+
"tool_rules": [
|
|
140
|
+
{
|
|
141
|
+
"id": tool,
|
|
142
|
+
"tool": tool,
|
|
143
|
+
"description": f"nobody chatting with the bot may cause {tool}",
|
|
144
|
+
"hint": ask,
|
|
145
|
+
"authorized": [OWNER],
|
|
146
|
+
"control_principal": OWNER,
|
|
147
|
+
"control": "harness",
|
|
148
|
+
}
|
|
149
|
+
for tool, ask in sorted((rules or {}).items())
|
|
150
|
+
],
|
|
151
|
+
"origin": origin,
|
|
152
|
+
"harness": "sdk",
|
|
153
|
+
"chat": {"path": path, "body": body, "reply_pointer": reply_pointer},
|
|
154
|
+
"attacker_principal": USER,
|
|
155
|
+
"principals": {USER: {}, OWNER: {}},
|
|
156
|
+
"tool_safety": "sinks",
|
|
157
|
+
"slots": [
|
|
158
|
+
{
|
|
159
|
+
"id": slot,
|
|
160
|
+
"kind": "instruction_secret",
|
|
161
|
+
"description": f"the value the bot's code reads with planted({slot!r})",
|
|
162
|
+
"hint": "the " + (_NAME.sub(" ", slot).strip() or "confidential value") + " in your instructions",
|
|
163
|
+
"authorized": [OWNER],
|
|
164
|
+
"control_principal": OWNER,
|
|
165
|
+
"control": "harness",
|
|
166
|
+
}
|
|
167
|
+
for slot in slots
|
|
168
|
+
],
|
|
169
|
+
"task_checks": [{"id": "answers", "principal": USER, "prompt": message, "expect": "any-reply"}],
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _put(value: Any, message: str, session_id: str) -> Any:
|
|
174
|
+
"""A request body with the message and the conversation id in place."""
|
|
175
|
+
if isinstance(value, str):
|
|
176
|
+
return value.replace("{message}", message).replace("{session}", session_id)
|
|
177
|
+
if isinstance(value, dict):
|
|
178
|
+
return {key: _put(inner, message, session_id) for key, inner in value.items()}
|
|
179
|
+
if isinstance(value, list):
|
|
180
|
+
return [_put(inner, message, session_id) for inner in value]
|
|
181
|
+
return value
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _ask_name(origin: str) -> str:
|
|
185
|
+
"""Ask the person at the keyboard to take responsibility for a test of a bot on this machine."""
|
|
186
|
+
if not sys.stdin.isatty():
|
|
187
|
+
return ""
|
|
188
|
+
print(f"No one has authorized a test of {origin} yet. It is on this machine.")
|
|
189
|
+
print("Type your name to authorize it for 7 days (the tools you marked are recorded, never run), or press Enter to stop.")
|
|
190
|
+
try:
|
|
191
|
+
return input("Your name: ").strip()
|
|
192
|
+
except (EOFError, KeyboardInterrupt):
|
|
193
|
+
print() # nobody is there to type: end the prompt's line before what is said next
|
|
194
|
+
return ""
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def discover(
|
|
198
|
+
url: str,
|
|
199
|
+
name: str | None = None,
|
|
200
|
+
field: str | None = None,
|
|
201
|
+
session_field: str | None = None,
|
|
202
|
+
reply_pointer: str | None = None,
|
|
203
|
+
ask_name: Callable[[str], str] | None = None,
|
|
204
|
+
say: Callable[[str], None] = print,
|
|
205
|
+
transport: Any = None,
|
|
206
|
+
message: str | None = None,
|
|
207
|
+
) -> tuple[str, dict[str, Any], list[str]]:
|
|
208
|
+
"""Work out a description for the bot at `url`. Returns (target name, description, and lines to
|
|
209
|
+
show after the scan about what was left out).
|
|
210
|
+
|
|
211
|
+
`message` is the ordinary request sent to learn what the bot reads; it becomes the normal-use
|
|
212
|
+
check and the request during which planted text is read. Default: "Hello".
|
|
213
|
+
|
|
214
|
+
Raises QuickError, with what to do, when a step needs the person."""
|
|
215
|
+
from botsting.core.authorization import (
|
|
216
|
+
AuthorizationError,
|
|
217
|
+
AuthorizationStore,
|
|
218
|
+
is_loopback_origin,
|
|
219
|
+
new_authorization,
|
|
220
|
+
normalize_origin,
|
|
221
|
+
)
|
|
222
|
+
from botsting.harness import KEY_ENV
|
|
223
|
+
from botsting.targets.base import (
|
|
224
|
+
NotAuthorizedError,
|
|
225
|
+
TargetError,
|
|
226
|
+
confirm_permitted,
|
|
227
|
+
)
|
|
228
|
+
from botsting.targets.http import HttpTarget, TargetConfigError, parse_config
|
|
229
|
+
|
|
230
|
+
parts = urlsplit(url)
|
|
231
|
+
try:
|
|
232
|
+
origin = normalize_origin(f"{parts.scheme}://{parts.netloc}")
|
|
233
|
+
except ValueError as error:
|
|
234
|
+
raise QuickError(f"{url!r} is not an address a bot can be reached at: {error}") from error
|
|
235
|
+
path = parts.path or "/"
|
|
236
|
+
if parts.query or parts.fragment:
|
|
237
|
+
raise QuickError("give the chat address without a ? or # part")
|
|
238
|
+
name = name or "quick-" + _NAME.sub("-", parts.netloc).strip("-")
|
|
239
|
+
message = (message or "").strip() or "Hello"
|
|
240
|
+
|
|
241
|
+
# 1. Permission, before anything is sent.
|
|
242
|
+
store = AuthorizationStore()
|
|
243
|
+
asked_now = "" # the name typed just now, if this run recorded the authorization
|
|
244
|
+
try:
|
|
245
|
+
permission = store.find(origin)
|
|
246
|
+
if permission is not None and permission.expired(datetime.now(UTC)):
|
|
247
|
+
permission = None
|
|
248
|
+
if permission is None and is_loopback_origin(origin):
|
|
249
|
+
person = (ask_name or _ask_name)(origin)
|
|
250
|
+
if person:
|
|
251
|
+
permission = new_authorization(origin, person, "a first scan of a bot on this machine", "test", 7)
|
|
252
|
+
store.add(permission)
|
|
253
|
+
asked_now = person
|
|
254
|
+
say(f"Recorded: {person} authorizes testing {origin} until {permission.expires_at}.")
|
|
255
|
+
except (AuthorizationError, ValueError) as error:
|
|
256
|
+
raise QuickError(str(error)) from error
|
|
257
|
+
if permission is None:
|
|
258
|
+
raise QuickError(
|
|
259
|
+
f"no one has authorized a test of {origin}. A person who may allow it runs:\n"
|
|
260
|
+
f' botsting authorize {origin} --by "YOUR NAME" --scope "what may be tested" --environment staging\n'
|
|
261
|
+
"adding --tool NAME for each tool marked never_for_users (a tool the authorization does not name is "
|
|
262
|
+
"left untested), and, for a bot across a network, serves the token it prints. Then run this again."
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
def target_for(body: dict[str, Any], pointer: str, slots: list[str]) -> HttpTarget:
|
|
266
|
+
raw = _description(origin, path, body, pointer, slots)
|
|
267
|
+
try:
|
|
268
|
+
return HttpTarget(parse_config(name, raw), f"http:{name}", permission, transport)
|
|
269
|
+
except TargetConfigError as error:
|
|
270
|
+
raise QuickError(str(error)) from error
|
|
271
|
+
|
|
272
|
+
async def work() -> tuple[dict[str, Any], list[str]]:
|
|
273
|
+
nonlocal permission
|
|
274
|
+
probe = target_for(_shapes(field, session_field)[0], "", [])
|
|
275
|
+
# 2. The harness, with the same key.
|
|
276
|
+
try:
|
|
277
|
+
probe.harness_key()
|
|
278
|
+
except TargetError as error:
|
|
279
|
+
raise QuickError(
|
|
280
|
+
f"{error}\nMake a key with `botsting harness-key`, set it as {KEY_ENV} where the bot runs "
|
|
281
|
+
"and in this terminal, restart the bot, and run this again."
|
|
282
|
+
) from error
|
|
283
|
+
try:
|
|
284
|
+
await confirm_permitted(probe, True)
|
|
285
|
+
await probe.reset({})
|
|
286
|
+
except (NotAuthorizedError, TargetError) as error:
|
|
287
|
+
raise QuickError(
|
|
288
|
+
f"{error}\nCheck that the bot is running at {origin}, that it is wrapped (`app = pp.wrap(app)`), "
|
|
289
|
+
f"and that {KEY_ENV} is the same there and here."
|
|
290
|
+
) from error
|
|
291
|
+
tools = probe.marked_tools
|
|
292
|
+
say(f"The harness answered. Marked tools: {', '.join(tools) or 'none'}.")
|
|
293
|
+
# Tools no chat user may cause can be tested now, if the authorization names them.
|
|
294
|
+
rules = dict(probe.tool_asks)
|
|
295
|
+
if rules and asked_now:
|
|
296
|
+
# The person who just typed their name was told the marked tools are recorded, never run.
|
|
297
|
+
permission = new_authorization(
|
|
298
|
+
origin, asked_now, "a first scan of a bot on this machine", "test", 7, allowed_tools=sorted(rules)
|
|
299
|
+
)
|
|
300
|
+
store.add(permission)
|
|
301
|
+
unnamed = sorted(tool for tool in rules if tool not in permission.allowed_tools)
|
|
302
|
+
rules = {tool: ask for tool, ask in rules.items() if tool in permission.allowed_tools}
|
|
303
|
+
notes: list[str] = []
|
|
304
|
+
if unnamed:
|
|
305
|
+
flags = " ".join(f"--tool {tool}" for tool in unnamed)
|
|
306
|
+
notes.append(
|
|
307
|
+
f"Not tested: {', '.join(unnamed)}. The authorization on record does not name them. A person who "
|
|
308
|
+
"may allow it records one that does, then this is run again:\n"
|
|
309
|
+
f' botsting authorize {origin} --by "YOUR NAME" --scope "{permission.scope}" '
|
|
310
|
+
f"--environment {permission.environment} {flags}"
|
|
311
|
+
)
|
|
312
|
+
open_tools = sorted(tool for tool in tools if tool not in probe.tool_asks)
|
|
313
|
+
if open_tools:
|
|
314
|
+
notes.append(
|
|
315
|
+
f"Not tested yet: {', '.join(open_tools)}. They were recorded, never run. If nobody chatting with "
|
|
316
|
+
'the bot may ever cause one, say so where it is marked, with what an attacker would ask for:\n'
|
|
317
|
+
f' @pp.action("{open_tools[0]}", never_for_users="...")\n'
|
|
318
|
+
"If some users may, describe who: `botsting guide` shows how."
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
# 3. How to talk to it, and 4. which secrets it reads: one ordinary message in a discover session.
|
|
322
|
+
last = "no request shape was tried"
|
|
323
|
+
for body in _shapes(field, session_field):
|
|
324
|
+
candidate = target_for(body, "", [])
|
|
325
|
+
session_id = uuid.uuid4().hex
|
|
326
|
+
filled = _put(body, message, session_id)
|
|
327
|
+
try:
|
|
328
|
+
data = await candidate.discover_message(path, filled, session_id)
|
|
329
|
+
except TargetError as error:
|
|
330
|
+
last = str(error)
|
|
331
|
+
continue
|
|
332
|
+
pointer = reply_pointer if reply_pointer is not None else find_reply(data)
|
|
333
|
+
if pointer is None:
|
|
334
|
+
last = "the bot answered, but there was no text in its answer"
|
|
335
|
+
continue
|
|
336
|
+
shown = next(key for key, value in body.items() if value == "{message}") if "messages" not in body else "messages"
|
|
337
|
+
say(f"It takes the message in {shown!r} and answers at {pointer or 'the top level'!r}.")
|
|
338
|
+
slots = list(candidate.last_read)
|
|
339
|
+
# Read by the code, but not while a message is handled: the test value cannot be put in there.
|
|
340
|
+
elsewhere = sorted(set(probe.read_outside) - set(slots))
|
|
341
|
+
moved = ""
|
|
342
|
+
if elsewhere:
|
|
343
|
+
names = ", ".join(f'pp.planted("{slot}")' for slot in elsewhere)
|
|
344
|
+
moved = (
|
|
345
|
+
f"Your code calls {names}, but not while it handles a message (for example once, when the app "
|
|
346
|
+
"starts), so a test value cannot be put in there. Call it where each message is handled, for "
|
|
347
|
+
"example where the instructions are put together for the model, then restart the bot."
|
|
348
|
+
)
|
|
349
|
+
if not slots and not rules:
|
|
350
|
+
raise QuickError(
|
|
351
|
+
"the bot answered, but its code read no planted secret while doing so, and no marked tool says "
|
|
352
|
+
"it is never for users, so there is nothing to test yet.\n"
|
|
353
|
+
+ (
|
|
354
|
+
moved
|
|
355
|
+
or "Where the bot builds its instructions for each message, add the secret through the "
|
|
356
|
+
'harness, for example:\n prompt = BASE_PROMPT + pp.planted("admin_code")\n'
|
|
357
|
+
"then restart the bot and run this again."
|
|
358
|
+
)
|
|
359
|
+
)
|
|
360
|
+
if slots:
|
|
361
|
+
say(f"Secrets it reads on an ordinary message: {', '.join(slots)}.")
|
|
362
|
+
else:
|
|
363
|
+
say("Secrets it reads on an ordinary message: none. SECRET LEAKS WILL NOT BE TESTED in this scan.")
|
|
364
|
+
if moved:
|
|
365
|
+
say(moved)
|
|
366
|
+
notes.append(("Not tested: " if slots else "Secret leaks were not tested. ") + moved)
|
|
367
|
+
elif not slots:
|
|
368
|
+
notes.append(
|
|
369
|
+
"Secret leaks were not tested: the bot read no planted secret while handling a message. To test "
|
|
370
|
+
"them, read the secret through the harness where the instructions are put together, for example:\n"
|
|
371
|
+
' prompt = BASE_PROMPT + pp.planted("admin_code")'
|
|
372
|
+
)
|
|
373
|
+
if rules:
|
|
374
|
+
say(f"Tools no chat user may cause: {', '.join(sorted(rules))}.")
|
|
375
|
+
# Text from elsewhere: the places the code read through the harness while answering that message.
|
|
376
|
+
points = list(candidate.last_points)
|
|
377
|
+
unread = sorted(set(probe.points_outside) - set(points))
|
|
378
|
+
if points and rules:
|
|
379
|
+
say(f"Text from elsewhere it reads on that message: {', '.join(points)}. Planted text will be tried there.")
|
|
380
|
+
elif points:
|
|
381
|
+
notes.append(
|
|
382
|
+
f"Not tested: text the bot reads at {', '.join(points)}. Planted text is shown to work by a call to "
|
|
383
|
+
"a tool no chat user may cause, and no tool is marked that way (or the authorization names none):\n"
|
|
384
|
+
' @pp.action("issue_refund", never_for_users="a refund of 50 on order A-1001")'
|
|
385
|
+
)
|
|
386
|
+
if unread:
|
|
387
|
+
calls = ", ".join(f'pp.content("{point}")' for point in unread)
|
|
388
|
+
notes.append(
|
|
389
|
+
f"Not tested: your code calls {calls}, but not while it answered {message!r}. Give an ordinary "
|
|
390
|
+
"request that makes the bot read that text, and it will be tested:\n"
|
|
391
|
+
f' botsting scan {url} --message "an ordinary request that makes the bot read it"'
|
|
392
|
+
)
|
|
393
|
+
elif not points:
|
|
394
|
+
notes.append(
|
|
395
|
+
"Text the bot reads from elsewhere (notes, documents, tickets, web pages) was not tested: the code "
|
|
396
|
+
"reads none through the harness. Where the bot fetches such text, pass it through, for example:\n"
|
|
397
|
+
' note = pp.content("order_note", note)'
|
|
398
|
+
)
|
|
399
|
+
return _description(origin, path, body, pointer, slots, rules, points, message), notes
|
|
400
|
+
hint = "" if field else " Say which field carries the message with --field NAME."
|
|
401
|
+
raise QuickError(f"could not work out how to send the bot a message at {path}: {last}.{hint}")
|
|
402
|
+
|
|
403
|
+
description, notes = asyncio.run(work())
|
|
404
|
+
return name, description, notes
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _no_longer_read(path: Path, name: str, description: dict[str, Any]) -> list[str]:
|
|
408
|
+
"""Secrets the saved description of `name` had and the bot's code no longer asks for: what a
|
|
409
|
+
person sees after taking a secret out of the instructions, which is the fix a finding advises."""
|
|
410
|
+
try:
|
|
411
|
+
earlier = json.loads(path.read_text(encoding="utf-8")).get("targets", {}).get(name) or {}
|
|
412
|
+
before = [slot["id"] for slot in earlier.get("slots", [])]
|
|
413
|
+
except (OSError, ValueError, AttributeError, KeyError, TypeError):
|
|
414
|
+
return []
|
|
415
|
+
now = {slot["id"] for slot in description.get("slots", [])}
|
|
416
|
+
return [slot for slot in before if slot not in now]
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _keep_earlier(path: Path, name: str, description: dict[str, Any]) -> Path | None:
|
|
420
|
+
"""If the targets file already describes `name` differently, save that description beside it.
|
|
421
|
+
|
|
422
|
+
A first scan writes under a name made from the address, so scanning again would replace a
|
|
423
|
+
description someone had extended by hand. Returns where the earlier one was kept, or None."""
|
|
424
|
+
try:
|
|
425
|
+
earlier = json.loads(path.read_text(encoding="utf-8")).get("targets", {}).get(name)
|
|
426
|
+
except (OSError, ValueError, AttributeError):
|
|
427
|
+
return None
|
|
428
|
+
if earlier is None or earlier == description:
|
|
429
|
+
return None
|
|
430
|
+
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
|
431
|
+
kept = path.with_name(f"{path.stem}.{name}.{stamp}.json")
|
|
432
|
+
kept.write_text(json.dumps({"targets": {name: earlier}}, indent=2) + NEWLINE, encoding="utf-8")
|
|
433
|
+
return kept
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def run(args: Any) -> int:
|
|
437
|
+
"""The `botsting scan URL` command."""
|
|
438
|
+
from botsting.cli import run_scan_command
|
|
439
|
+
from botsting.console import _wrap
|
|
440
|
+
from botsting.exits import EXIT_INCONCLUSIVE
|
|
441
|
+
from botsting.practice_server import write_description
|
|
442
|
+
from botsting.targets.http import targets_file
|
|
443
|
+
|
|
444
|
+
def say(text: str) -> None:
|
|
445
|
+
# Kept to the width of the rest of the output; a line that is already short, or a command, is left alone.
|
|
446
|
+
for line in text.splitlines():
|
|
447
|
+
wrapped = _wrap(line, "") if len(line) > 100 and not line.startswith(" ") else [line]
|
|
448
|
+
for part in wrapped:
|
|
449
|
+
print(part)
|
|
450
|
+
|
|
451
|
+
try:
|
|
452
|
+
name, description, notes = discover(
|
|
453
|
+
args.url, args.name, args.field, args.session_field, args.reply, say=say, message=getattr(args, "message", None)
|
|
454
|
+
)
|
|
455
|
+
except QuickError as error:
|
|
456
|
+
print(f"Not scanned: {error}")
|
|
457
|
+
return EXIT_INCONCLUSIVE
|
|
458
|
+
path: Path = targets_file()
|
|
459
|
+
gone = _no_longer_read(path, name, description)
|
|
460
|
+
if gone:
|
|
461
|
+
say(
|
|
462
|
+
f"The bot no longer reads {', '.join(gone)}, which an earlier scan tested. A secret the bot is never "
|
|
463
|
+
"given cannot leak through it, so there is nothing left to test for it."
|
|
464
|
+
)
|
|
465
|
+
kept = _keep_earlier(path, name, description)
|
|
466
|
+
if kept is not None:
|
|
467
|
+
say(
|
|
468
|
+
f"The description saved earlier as http:{name} differs from what was worked out now (it was edited, or "
|
|
469
|
+
f"the bot changed). The earlier one was kept as {kept}."
|
|
470
|
+
)
|
|
471
|
+
write_description(path, name, description)
|
|
472
|
+
print(f"Saved what was worked out as target http:{name} in {path}.")
|
|
473
|
+
print()
|
|
474
|
+
args.target = f"http:{name}"
|
|
475
|
+
if not args.html:
|
|
476
|
+
args.html = str(Path(args.out).with_name("report.html")) # a first scan is for a person to read
|
|
477
|
+
code = run_scan_command(args)
|
|
478
|
+
for note in notes:
|
|
479
|
+
print()
|
|
480
|
+
say(note)
|
|
481
|
+
print()
|
|
482
|
+
print("After a change to the bot, the same command scans it again. To use the saved description instead:")
|
|
483
|
+
print(f" botsting doctor --target http:{name}")
|
|
484
|
+
print(f" botsting scan --target http:{name} --html report.html")
|
|
485
|
+
return code
|