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
botsting/seal.py ADDED
@@ -0,0 +1,245 @@
1
+ """Seal a scan's evidence so that anyone can check later that none of it was changed.
2
+
3
+ `botsting seal RUN_DIR` packs every file of a finished run (reports, transcripts, the
4
+ egress trap's log, the teardown record) into one zip with a manifest, SEAL.json. The
5
+ manifest lists each file's SHA-256 and size and summarizes what the egress log shows.
6
+ Its own digest, the seal, is printed: send it to the customer separately, or put it in
7
+ the ticket, and the bundle can be checked against it at any time with
8
+ `botsting check-seal BUNDLE --seal HEX`.
9
+
10
+ The egress trap's log is a hash chain (see egress_trap.py). The manifest records
11
+ whether the chain was intact and closed when the bundle was sealed, and `check-seal`
12
+ fails if it was broken: a bundle can be exactly what was sealed and still hold a log
13
+ that someone edited first.
14
+
15
+ What a seal proves, and what it does not: a matching seal shows the bundle is exactly
16
+ what existed when the seal was made and shared. It does not show who made it, or that
17
+ the evidence was complete and honest at that moment. A seal made by the customer's own
18
+ CI, from code they can read, is the strongest form of this. Signing by a hosted
19
+ service is a later step.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import json
27
+ import zipfile
28
+ from datetime import UTC, datetime
29
+ from pathlib import Path, PurePosixPath
30
+ from typing import Any
31
+
32
+ from botsting import __version__
33
+ from botsting.exits import EXIT_CHECK_FAILED, EXIT_FAILED, EXIT_OK
34
+
35
+ MANIFEST = "SEAL.json"
36
+ EGRESS_LOG = "egress-trap.jsonl"
37
+ MAX_FILES = 10_000
38
+ MAX_TOTAL_BYTES = 2 * 1024**3
39
+
40
+
41
+ class SealError(Exception):
42
+ pass
43
+
44
+
45
+ def _canonical(value: Any) -> bytes:
46
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
47
+
48
+
49
+ def seal_of(files: list[dict[str, Any]], egress: dict[str, Any] | None) -> str:
50
+ """The seal: SHA-256 over the file list and the egress summary, in a fixed encoding."""
51
+ return hashlib.sha256(_canonical({"files": files, "egress": egress})).hexdigest()
52
+
53
+
54
+ def _egress_summary(lines: bytes) -> dict[str, Any]:
55
+ from botsting.egress_trap import check_chain
56
+
57
+ allowed: dict[str, int] = {}
58
+ refused: dict[str, int] = {}
59
+ unreadable = 0
60
+ entries: list[dict[str, Any]] = []
61
+ for raw in lines.splitlines():
62
+ if not raw.strip():
63
+ continue
64
+ try:
65
+ entry = json.loads(raw)
66
+ if not isinstance(entry, dict):
67
+ raise TypeError("not an object")
68
+ entries.append(entry)
69
+ if "event" in entry: # the trap's own start and stop lines
70
+ continue
71
+ target = str(entry["target"])
72
+ except (ValueError, KeyError, TypeError):
73
+ unreadable += 1
74
+ continue
75
+ bucket = allowed if entry.get("allowed") == "true" else refused
76
+ bucket[target] = bucket.get(target, 0) + 1
77
+ chain, closed = check_chain(entries) if not unreadable else ("broken: unreadable lines", False)
78
+ return {
79
+ "allowed": dict(sorted(allowed.items())),
80
+ "refused": dict(sorted(refused.items())),
81
+ "unreadable_lines": unreadable,
82
+ # "intact": no line was changed, removed, added or reordered after it was written.
83
+ # "closed": the log ends with the trap's stop line, so nothing was cut off the end.
84
+ "chain": chain,
85
+ "closed": closed,
86
+ }
87
+
88
+
89
+ def _collect(run_dir: Path) -> list[tuple[str, Path]]:
90
+ found: list[tuple[str, Path]] = []
91
+ for path in sorted(run_dir.rglob("*")):
92
+ if path.is_symlink():
93
+ raise SealError(f"refusing to seal a link: {path}")
94
+ if path.is_file():
95
+ name = path.relative_to(run_dir).as_posix()
96
+ if name == MANIFEST:
97
+ raise SealError(f"{run_dir} already contains {MANIFEST}")
98
+ found.append((name, path))
99
+ if not found:
100
+ raise SealError(f"no files in {run_dir}")
101
+ if len(found) > MAX_FILES:
102
+ raise SealError(f"more than {MAX_FILES} files in {run_dir}")
103
+ return found
104
+
105
+
106
+ def seal(run_dir: Path, out: Path) -> str:
107
+ """Write the bundle to `out` and return its seal."""
108
+ run_dir = Path(run_dir)
109
+ if not run_dir.is_dir():
110
+ raise SealError(f"not a directory: {run_dir}")
111
+ if out.resolve().is_relative_to(run_dir.resolve()):
112
+ raise SealError("write the bundle outside the run directory, or it would seal itself")
113
+ entries = _collect(run_dir)
114
+ files: list[dict[str, Any]] = []
115
+ egress: dict[str, Any] | None = None
116
+ total = 0
117
+ contents: list[tuple[str, bytes]] = []
118
+ for name, path in entries:
119
+ data = path.read_bytes()
120
+ total += len(data)
121
+ if total > MAX_TOTAL_BYTES:
122
+ raise SealError("the run directory is larger than 2 GB")
123
+ files.append({"path": name, "sha256": hashlib.sha256(data).hexdigest(), "bytes": len(data)})
124
+ contents.append((name, data))
125
+ if name == EGRESS_LOG:
126
+ egress = _egress_summary(data)
127
+ value = seal_of(files, egress)
128
+ manifest = {
129
+ "format": "botsting-seal/1",
130
+ "tool_version": __version__,
131
+ "sealed_at": datetime.now(UTC).isoformat(timespec="seconds"),
132
+ "files": files,
133
+ "egress": egress,
134
+ "seal": value,
135
+ }
136
+ out.parent.mkdir(parents=True, exist_ok=True)
137
+ with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as bundle:
138
+ for name, data in contents:
139
+ bundle.writestr(name, data)
140
+ bundle.writestr(MANIFEST, json.dumps(manifest, indent=2))
141
+ return value
142
+
143
+
144
+ def check(bundle_path: Path, expected: str | None = None) -> dict[str, Any]:
145
+ """Re-check a bundle without extracting it. Raises SealError on any mismatch."""
146
+ try:
147
+ bundle = zipfile.ZipFile(bundle_path)
148
+ except (OSError, zipfile.BadZipFile) as error:
149
+ raise SealError(f"not a readable bundle: {error}") from error
150
+ with bundle:
151
+ names = [info.filename for info in bundle.infolist() if not info.is_dir()]
152
+ if len(names) != len(set(names)):
153
+ raise SealError("the bundle holds two files with the same name")
154
+ if MANIFEST not in names:
155
+ raise SealError(f"no {MANIFEST} in the bundle")
156
+ try:
157
+ manifest = json.loads(bundle.read(MANIFEST))
158
+ listed = manifest["files"]
159
+ stated = manifest["seal"]
160
+ paths = [item["path"] for item in listed]
161
+ except (ValueError, KeyError, TypeError) as error:
162
+ raise SealError(f"{MANIFEST} is malformed: {error}") from error
163
+ for name in paths:
164
+ pure = PurePosixPath(name)
165
+ if pure.is_absolute() or ".." in pure.parts or "\\" in name:
166
+ raise SealError(f"unsafe path in the manifest: {name!r}")
167
+ present = sorted(n for n in names if n != MANIFEST)
168
+ if present != sorted(paths) or len(paths) != len(set(paths)):
169
+ missing = sorted(set(paths) - set(present))
170
+ extra = sorted(set(present) - set(paths))
171
+ raise SealError(f"the bundle's files do not match the manifest (missing {missing}, extra {extra})")
172
+ egress: dict[str, Any] | None = None
173
+ for item in listed:
174
+ data = bundle.read(item["path"])
175
+ if hashlib.sha256(data).hexdigest() != item["sha256"] or len(data) != item["bytes"]:
176
+ raise SealError(f"{item['path']} was changed after sealing")
177
+ if item["path"] == EGRESS_LOG:
178
+ egress = _egress_summary(data)
179
+ if egress != manifest.get("egress"):
180
+ raise SealError("the egress summary does not match the egress log")
181
+ recomputed = seal_of(listed, egress)
182
+ if recomputed != stated:
183
+ raise SealError("the manifest was changed after sealing")
184
+ if expected is not None and expected.strip().lower() != recomputed:
185
+ raise SealError("the bundle is intact but its seal is not the one you were given")
186
+ return manifest
187
+
188
+
189
+ def _seal_command(args: argparse.Namespace) -> int:
190
+ run_dir = Path(args.run_dir)
191
+ out = Path(args.out) if args.out else run_dir.with_name(run_dir.name + ".sealed.zip")
192
+ try:
193
+ value = seal(run_dir, out)
194
+ except SealError as error:
195
+ print(f"Not sealed: {error}")
196
+ return EXIT_FAILED
197
+ print(f"Sealed {out}")
198
+ print(f"Seal: {value}")
199
+ print("Share the seal separately from the bundle. Anyone can then check the bundle with:")
200
+ print(f" botsting check-seal {out} --seal {value}")
201
+ return EXIT_OK
202
+
203
+
204
+ def _check_command(args: argparse.Namespace) -> int:
205
+ try:
206
+ manifest = check(Path(args.bundle), args.seal)
207
+ except SealError as error:
208
+ print(f"FAILED: {error}")
209
+ return EXIT_CHECK_FAILED
210
+ print(f"Intact: {len(manifest['files'])} files, sealed {manifest['sealed_at']}, seal {manifest['seal']}")
211
+ if args.seal is None:
212
+ print("No --seal given: this shows the bundle is consistent, not that it is the one you were sent.")
213
+ egress = manifest.get("egress")
214
+ if egress is None:
215
+ print("No egress log in this bundle.")
216
+ else:
217
+ allowed = ", ".join(f"{k} ({v})" for k, v in egress["allowed"].items()) or "none"
218
+ refused = ", ".join(f"{k} ({v})" for k, v in egress["refused"].items()) or "none"
219
+ print(f"Outbound traffic allowed: {allowed}")
220
+ print(f"Outbound traffic refused: {refused}")
221
+ chain = egress.get("chain", "absent")
222
+ if chain == "intact" and egress.get("closed"):
223
+ print("Outbound log: every line is chained to the one before, and it ends with the trap's stop line.")
224
+ print(" (This shows no line was edited or dropped on its own. A log rewritten in full before sealing would")
225
+ print(" also check; the seal shared when the run ended is what rules that out.)")
226
+ elif chain == "intact":
227
+ print("Outbound log: chained, BUT it has no stop line: it may have been cut short.")
228
+ elif chain == "absent":
229
+ print("Outbound log: not chained (an older version wrote it), so edits made before sealing would not show.")
230
+ else:
231
+ print(f"Outbound log: THE CHAIN IS {chain.upper()}. The log was changed after it was written.")
232
+ print("FAILED: the bundle is what was sealed, but its outbound log cannot be relied on.")
233
+ return EXIT_CHECK_FAILED
234
+ return EXIT_OK
235
+
236
+
237
+ def register(commands: argparse._SubParsersAction) -> None:
238
+ sealing = commands.add_parser("seal", help="pack a finished run's evidence into a bundle anyone can check later")
239
+ sealing.add_argument("run_dir", help="the directory holding the run's reports and logs")
240
+ sealing.add_argument("--out", help="where to write the bundle (default: next to the directory)")
241
+ sealing.set_defaults(handler=_seal_command)
242
+ checking = commands.add_parser("check-seal", help="check that a sealed bundle was not changed")
243
+ checking.add_argument("bundle")
244
+ checking.add_argument("--seal", help="the seal you were given separately")
245
+ checking.set_defaults(handler=_check_command)
botsting/shell.py ADDED
@@ -0,0 +1,40 @@
1
+ """Commands shown to the user must do the same thing in every shell, or not be shown.
2
+
3
+ No single quoting style is correct in bash, PowerShell and cmd at once: inside double
4
+ quotes bash and PowerShell expand `$` and backticks, and cmd expands `%`. So instead of
5
+ guessing the shell, a value is only ever emitted when it reads the same in all three:
6
+ either it needs no quoting, or it needs double quotes only because of characters none
7
+ of them treats specially inside double quotes. Anything else is replaced by a
8
+ placeholder for the user to fill in.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import string
14
+
15
+ _BARE = frozenset(string.ascii_letters + string.digits + "-_./:=")
16
+ # Harmless inside double quotes in bash, PowerShell and cmd alike.
17
+ _QUOTED_ONLY = frozenset(" (),+@#~[]{}'")
18
+
19
+
20
+ def quote_arg(value: str) -> str | None:
21
+ """`value` as one argument that every common shell reads identically, or None if there is no such form."""
22
+ if not value or value.startswith("-"):
23
+ return None # a leading dash would be read as an option, quoted or not
24
+ characters = set(value)
25
+ if characters <= _BARE:
26
+ return value
27
+ if characters <= _BARE | _QUOTED_ONLY:
28
+ return f'"{value}"'
29
+ return None
30
+
31
+
32
+ def replay_command(report_path: str, finding_id: str) -> str:
33
+ """The command that replays a finding, safe to copy and paste.
34
+
35
+ Backslashes in the path are written as forward slashes: Windows accepts both, and
36
+ bash would otherwise swallow them.
37
+ """
38
+ path = quote_arg(report_path.replace("\\", "/")) or "<path to this report>"
39
+ finding = quote_arg(finding_id) or "<finding id>"
40
+ return f"botsting replay {path} --finding {finding}"