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/egress_trap.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""A trap for outbound web traffic from a bot under test.
|
|
2
|
+
|
|
3
|
+
Start it, then start the bot with HTTP_PROXY and HTTPS_PROXY pointing at it (and
|
|
4
|
+
NO_PROXY covering only this machine). Every web request the bot tries to make to
|
|
5
|
+
anywhere else arrives here instead. The trap refuses all of them, sends nothing on,
|
|
6
|
+
and writes one JSON line per attempt to its log, so after the test the log shows
|
|
7
|
+
exactly what the bot tried to reach. An empty log is the evidence that it reached
|
|
8
|
+
for nothing.
|
|
9
|
+
|
|
10
|
+
A test sometimes needs one outside service, such as the bot's model API. Name it in
|
|
11
|
+
`allow` as "host:port"; an encrypted tunnel (CONNECT) to exactly that address is then
|
|
12
|
+
passed through and recorded as allowed. Everything else is still refused. The trap
|
|
13
|
+
sees only where a tunnel goes, not what is inside it.
|
|
14
|
+
|
|
15
|
+
The log is a chain. Every line carries its number and a hash of itself and the line
|
|
16
|
+
before it, the first line records the start and the last line the stop, with the count.
|
|
17
|
+
So a line that is changed, removed, added or reordered afterwards breaks the chain, and
|
|
18
|
+
a log cut short has no closing line. `botsting seal` checks both and says so.
|
|
19
|
+
|
|
20
|
+
What the chain does not stop: the hashes use no secret, so someone who rewrites the
|
|
21
|
+
whole log and recomputes every hash produces a log that checks. The chain catches a
|
|
22
|
+
partial edit; a full rewrite is caught by the seal, made when the run ended and shared
|
|
23
|
+
separately. Like the seal, the chain cannot show that the program writing the log was
|
|
24
|
+
honest.
|
|
25
|
+
|
|
26
|
+
No scan starts the trap by itself: a scan does not start the bot either. Run it next to
|
|
27
|
+
the bot, for example when testing a copy of a real system:
|
|
28
|
+
|
|
29
|
+
botsting egress-trap --log run/egress-trap.jsonl --allow api.anthropic.com:443
|
|
30
|
+
|
|
31
|
+
It prints the proxy settings to start the bot with, runs until Ctrl+C, and closes the
|
|
32
|
+
log. Put the log in the run's folder before sealing it.
|
|
33
|
+
|
|
34
|
+
Limits, stated in every report that relies on it: this catches traffic that honours
|
|
35
|
+
the proxy settings (ordinary HTTP clients do, unless a program turns that off). It
|
|
36
|
+
does not see raw TCP connections such as SMTP or a database protocol, so it is used
|
|
37
|
+
together with a check of the bot's open connections, not instead of it.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import hashlib
|
|
43
|
+
import json
|
|
44
|
+
import socket
|
|
45
|
+
import threading
|
|
46
|
+
from datetime import UTC, datetime
|
|
47
|
+
from pathlib import Path
|
|
48
|
+
|
|
49
|
+
from botsting.exits import EXIT_FAILED, EXIT_OK
|
|
50
|
+
|
|
51
|
+
_MAX_HEADER = 16_384
|
|
52
|
+
CHAIN_START = hashlib.sha256(b"botsting-egress/1").hexdigest()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def chain_hash(previous: str, entry: dict[str, object]) -> str:
|
|
56
|
+
"""The hash that links `entry` (without its own "chain" field) to the line before it."""
|
|
57
|
+
body = {key: value for key, value in entry.items() if key != "chain"}
|
|
58
|
+
canonical = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
|
59
|
+
return hashlib.sha256((previous + "|" + canonical).encode("ascii")).hexdigest()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def check_chain(lines: list[dict[str, object]]) -> tuple[str, bool]:
|
|
63
|
+
"""("absent" | "intact" | "broken at line N", closed). `closed` means the log ends with the trap's own
|
|
64
|
+
stop line and its count matches, so nothing was cut off the end."""
|
|
65
|
+
if not any("chain" in line for line in lines):
|
|
66
|
+
return "absent", False
|
|
67
|
+
previous = CHAIN_START
|
|
68
|
+
for number, line in enumerate(lines, start=1):
|
|
69
|
+
if line.get("n") != number or line.get("chain") != chain_hash(previous, line):
|
|
70
|
+
return f"broken at line {number}", False
|
|
71
|
+
previous = str(line["chain"])
|
|
72
|
+
first, last = lines[0], lines[-1]
|
|
73
|
+
attempts = sum(1 for line in lines if "event" not in line)
|
|
74
|
+
closed = first.get("event") == "started" and last.get("event") == "stopped" and last.get("attempts") == attempts
|
|
75
|
+
return "intact", closed
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class EgressTrap:
|
|
79
|
+
def __init__(
|
|
80
|
+
self, log_path: Path, host: str = "127.0.0.1", port: int = 0, allow: tuple[str, ...] = ()
|
|
81
|
+
) -> None:
|
|
82
|
+
if host not in ("127.0.0.1", "::1", "localhost"):
|
|
83
|
+
raise ValueError("the trap only listens on this machine")
|
|
84
|
+
for item in allow:
|
|
85
|
+
name, _, number = item.rpartition(":")
|
|
86
|
+
if not name or not number.isdigit():
|
|
87
|
+
raise ValueError(f"allow entries are host:port, got {item!r}")
|
|
88
|
+
self.allow = frozenset(item.lower() for item in allow)
|
|
89
|
+
self.log_path = Path(log_path)
|
|
90
|
+
self.attempts: list[dict[str, object]] = []
|
|
91
|
+
self._lock = threading.Lock()
|
|
92
|
+
self._server = socket.create_server((host, port))
|
|
93
|
+
self.port = self._server.getsockname()[1]
|
|
94
|
+
self._stopped = threading.Event()
|
|
95
|
+
self._lines = 0
|
|
96
|
+
self._chain = CHAIN_START
|
|
97
|
+
self._write({"event": "started", "allow": sorted(self.allow)})
|
|
98
|
+
threading.Thread(target=self._serve, daemon=True).start()
|
|
99
|
+
|
|
100
|
+
def _serve(self) -> None:
|
|
101
|
+
self._server.settimeout(0.2)
|
|
102
|
+
while not self._stopped.is_set():
|
|
103
|
+
try:
|
|
104
|
+
connection, _ = self._server.accept()
|
|
105
|
+
except TimeoutError:
|
|
106
|
+
continue
|
|
107
|
+
except OSError:
|
|
108
|
+
return
|
|
109
|
+
threading.Thread(target=self._refuse, args=(connection,), daemon=True).start()
|
|
110
|
+
|
|
111
|
+
def _refuse(self, connection: socket.socket) -> None:
|
|
112
|
+
with connection:
|
|
113
|
+
connection.settimeout(5)
|
|
114
|
+
data = b""
|
|
115
|
+
try:
|
|
116
|
+
while b"\r\n\r\n" not in data and len(data) < _MAX_HEADER:
|
|
117
|
+
chunk = connection.recv(4096)
|
|
118
|
+
if not chunk:
|
|
119
|
+
break
|
|
120
|
+
data += chunk
|
|
121
|
+
except OSError:
|
|
122
|
+
pass
|
|
123
|
+
first = data.split(b"\r\n", 1)[0].decode("latin-1", "replace")
|
|
124
|
+
method, _, rest = first.partition(" ")
|
|
125
|
+
target = rest.rsplit(" ", 1)[0] if " " in rest else rest
|
|
126
|
+
if method == "CONNECT" and target.lower() in self.allow:
|
|
127
|
+
self._record(method, target, allowed=True)
|
|
128
|
+
head, _, early = data.partition(b"\r\n\r\n")
|
|
129
|
+
self._tunnel(connection, target, early)
|
|
130
|
+
return
|
|
131
|
+
self._record(method or "(nothing)", target or "(nothing)")
|
|
132
|
+
try:
|
|
133
|
+
connection.sendall(
|
|
134
|
+
b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
|
135
|
+
)
|
|
136
|
+
except OSError:
|
|
137
|
+
pass
|
|
138
|
+
|
|
139
|
+
def _tunnel(self, client: socket.socket, target: str, early: bytes) -> None:
|
|
140
|
+
"""Pass an encrypted tunnel through to an allowed address, untouched, until either side closes."""
|
|
141
|
+
host, _, port = target.rpartition(":")
|
|
142
|
+
try:
|
|
143
|
+
upstream = socket.create_connection((host, int(port)), timeout=15)
|
|
144
|
+
except OSError:
|
|
145
|
+
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
|
146
|
+
return
|
|
147
|
+
with upstream:
|
|
148
|
+
client.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
|
|
149
|
+
if early:
|
|
150
|
+
upstream.sendall(early)
|
|
151
|
+
client.settimeout(None)
|
|
152
|
+
upstream.settimeout(None)
|
|
153
|
+
|
|
154
|
+
def pump(source: socket.socket, sink: socket.socket) -> None:
|
|
155
|
+
try:
|
|
156
|
+
while chunk := source.recv(65536):
|
|
157
|
+
sink.sendall(chunk)
|
|
158
|
+
except OSError:
|
|
159
|
+
pass
|
|
160
|
+
finally:
|
|
161
|
+
for side in (source, sink):
|
|
162
|
+
try:
|
|
163
|
+
side.shutdown(socket.SHUT_RDWR)
|
|
164
|
+
except OSError:
|
|
165
|
+
pass
|
|
166
|
+
|
|
167
|
+
back = threading.Thread(target=pump, args=(upstream, client), daemon=True)
|
|
168
|
+
back.start()
|
|
169
|
+
pump(client, upstream)
|
|
170
|
+
back.join(timeout=5)
|
|
171
|
+
|
|
172
|
+
def _record(self, method: str, target: str, allowed: bool = False) -> None:
|
|
173
|
+
entry = {"at": datetime.now(UTC).isoformat(timespec="seconds"), "method": method, "target": target}
|
|
174
|
+
if allowed:
|
|
175
|
+
entry["allowed"] = "true"
|
|
176
|
+
self.attempts.append(self._write(entry))
|
|
177
|
+
|
|
178
|
+
def _write(self, entry: dict[str, object]) -> dict[str, object]:
|
|
179
|
+
"""Append one line, numbered and chained to the line before."""
|
|
180
|
+
with self._lock:
|
|
181
|
+
self._lines += 1
|
|
182
|
+
entry = {"at": datetime.now(UTC).isoformat(timespec="seconds"), **entry, "n": self._lines}
|
|
183
|
+
entry["chain"] = self._chain = chain_hash(self._chain, entry)
|
|
184
|
+
self.log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
185
|
+
with self.log_path.open("a", encoding="utf-8") as log:
|
|
186
|
+
log.write(json.dumps(entry) + chr(10))
|
|
187
|
+
return entry
|
|
188
|
+
|
|
189
|
+
def proxy_environment(self) -> dict[str, str]:
|
|
190
|
+
"""Environment variables that send a program's web traffic here, except to this machine."""
|
|
191
|
+
url = f"http://127.0.0.1:{self.port}"
|
|
192
|
+
return {
|
|
193
|
+
"HTTP_PROXY": url,
|
|
194
|
+
"HTTPS_PROXY": url,
|
|
195
|
+
"http_proxy": url,
|
|
196
|
+
"https_proxy": url,
|
|
197
|
+
"ALL_PROXY": url,
|
|
198
|
+
"NO_PROXY": "localhost,127.0.0.1,::1",
|
|
199
|
+
"no_proxy": "localhost,127.0.0.1,::1",
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
def stop(self) -> None:
|
|
203
|
+
if self._stopped.is_set():
|
|
204
|
+
return
|
|
205
|
+
self._stopped.set()
|
|
206
|
+
self._server.close()
|
|
207
|
+
self._write({"event": "stopped", "attempts": len(self.attempts)})
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _command(args: object) -> int:
|
|
211
|
+
import time
|
|
212
|
+
|
|
213
|
+
try:
|
|
214
|
+
trap = EgressTrap(Path(args.log), port=args.port, allow=tuple(args.allow)) # type: ignore[attr-defined]
|
|
215
|
+
except (ValueError, OSError) as error:
|
|
216
|
+
print(f"error: {error}")
|
|
217
|
+
return EXIT_FAILED
|
|
218
|
+
print(f"Trap listening on 127.0.0.1:{trap.port}. Log: {Path(args.log).resolve()}") # type: ignore[attr-defined]
|
|
219
|
+
print(f"Passed through: {', '.join(sorted(trap.allow)) or 'nothing'}. Everything else is refused and recorded.")
|
|
220
|
+
print("Start the bot with these settings, so that its web traffic comes here:")
|
|
221
|
+
for name, value in trap.proxy_environment().items():
|
|
222
|
+
print(f" {name}={value}")
|
|
223
|
+
print("It sees traffic that honours proxy settings, not raw connections such as a database's. Ctrl+C to stop.")
|
|
224
|
+
try:
|
|
225
|
+
while True:
|
|
226
|
+
time.sleep(3600)
|
|
227
|
+
except KeyboardInterrupt:
|
|
228
|
+
pass
|
|
229
|
+
finally:
|
|
230
|
+
trap.stop()
|
|
231
|
+
refused = sum(1 for attempt in trap.attempts if attempt.get("allowed") != "true")
|
|
232
|
+
print(f"Stopped. {len(trap.attempts)} outbound attempt(s) recorded, {refused} refused. The log is closed.")
|
|
233
|
+
return EXIT_OK
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def register(commands: object) -> None:
|
|
237
|
+
parser = commands.add_parser( # type: ignore[attr-defined]
|
|
238
|
+
"egress-trap", help="record, and refuse, the outbound web traffic of a bot you run next to it"
|
|
239
|
+
)
|
|
240
|
+
parser.add_argument("--log", required=True, help="where to write the log, for example run/egress-trap.jsonl")
|
|
241
|
+
parser.add_argument("--allow", action="append", default=[], metavar="HOST:PORT", help="a destination to pass through, such as the bot's model service (repeat for each)")
|
|
242
|
+
parser.add_argument("--port", type=int, default=0, help="the port to listen on (default: a free one)")
|
|
243
|
+
parser.set_defaults(handler=_command)
|
botsting/exits.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The exit codes, in one place.
|
|
2
|
+
|
|
3
|
+
Every command exits 0 when it did what was asked and found nothing to act on. What
|
|
4
|
+
the other codes mean is each command's own; the table below is the whole list:
|
|
5
|
+
|
|
6
|
+
scan, ci 0 no verified violations; 1 violations verified; 2 inconclusive,
|
|
7
|
+
a usage error, nothing was tested, or the evidence could not be
|
|
8
|
+
sealed (ci with --fail-on never still exits 0)
|
|
9
|
+
replay 0 the finding was not reproduced; 1 it was reproduced; 2 inconclusive
|
|
10
|
+
benchmark 0 passed; 1 a control was violated or the margin was not met; 2 usage error
|
|
11
|
+
sterile-check 0 sterile; 1 a live action is present; 2 usage error
|
|
12
|
+
check-seal 0 intact; 1 the bundle was changed or its outbound log cannot be relied on
|
|
13
|
+
authorize 0 done; 2 could not
|
|
14
|
+
init 0 wrote the description; 2 could not
|
|
15
|
+
seal 0 sealed; 2 could not
|
|
16
|
+
demo 0 done; 2 the --dir was not empty
|
|
17
|
+
doctor 0 ready to scan; 2 not ready
|
|
18
|
+
egress-trap 0 stopped cleanly; 2 could not start
|
|
19
|
+
harness-key 0
|
|
20
|
+
practice-server 0 (2 if it could not start)
|
|
21
|
+
mcp serve 0
|
|
22
|
+
|
|
23
|
+
A script can therefore tell "found nothing" from "could not tell", and a broken
|
|
24
|
+
target can never be mistaken for a fixed one.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
# The scan verdicts, shared by `scan` (and the first scan behind it), `ci`, `replay`
|
|
28
|
+
# and `benchmark`.
|
|
29
|
+
EXIT_NO_VERIFIED = 0 # nothing was proven
|
|
30
|
+
EXIT_VIOLATIONS = 1 # violations were verified, a finding was reproduced, or a control failed
|
|
31
|
+
EXIT_INCONCLUSIVE = 2 # the scan could not tell, or could not run at all
|
|
32
|
+
|
|
33
|
+
# The other commands: what they return when they did their job and when they could not.
|
|
34
|
+
EXIT_OK = 0
|
|
35
|
+
EXIT_FAILED = 2
|
|
36
|
+
|
|
37
|
+
# A command whose 1 means the thing it checked failed the check.
|
|
38
|
+
EXIT_CHECK_FAILED = 1
|