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/sterility.py
ADDED
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
"""Check a test deployment's supplied configuration for known production signals.
|
|
2
|
+
|
|
3
|
+
A clean report means no unallowed live signal matched. It cannot establish which
|
|
4
|
+
configuration the deployment actually uses or whether an opaque credential or
|
|
5
|
+
endpoint belongs to production. The check runs locally and never contacts a service.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Collection, Mapping
|
|
16
|
+
from dataclasses import asdict, dataclass
|
|
17
|
+
from ipaddress import ip_address
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Literal
|
|
20
|
+
from urllib.parse import unquote
|
|
21
|
+
|
|
22
|
+
from botsting.exits import EXIT_CHECK_FAILED, EXIT_FAILED, EXIT_OK
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class _Match:
|
|
27
|
+
rule: str
|
|
28
|
+
severity: Literal["live", "unknown"]
|
|
29
|
+
reason: str
|
|
30
|
+
marker: str | None = None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, kw_only=True)
|
|
34
|
+
class Finding(_Match):
|
|
35
|
+
name: str
|
|
36
|
+
allowed: bool = False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Report:
|
|
41
|
+
findings: tuple[Finding, ...]
|
|
42
|
+
checked_count: int
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def live_count(self) -> int:
|
|
46
|
+
return sum(f.severity == "live" and not f.allowed for f in self.findings)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def unknown_count(self) -> int:
|
|
50
|
+
return sum(f.severity == "unknown" and not f.allowed for f in self.findings)
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def ok(self) -> bool:
|
|
54
|
+
return self.live_count == 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class EnvFileError(ValueError):
|
|
58
|
+
"""An env file could not be read or parsed."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
_ASSIGNMENT = re.compile(r"(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)")
|
|
62
|
+
_QUOTED = re.compile(r"""(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')\s*(?:#.*)?""")
|
|
63
|
+
_ESCAPES = {"n": "\n", "r": "\r", "t": "\t", '"': '"', "\\": "\\"}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _env_value(raw: str, number: int) -> str:
|
|
67
|
+
value = raw.lstrip()
|
|
68
|
+
if value.startswith(('"', "'")):
|
|
69
|
+
quoted = _QUOTED.fullmatch(value)
|
|
70
|
+
if quoted is None:
|
|
71
|
+
raise EnvFileError(f"Invalid quoted value on line {number}.")
|
|
72
|
+
double, single = quoted.groups()
|
|
73
|
+
if single is not None:
|
|
74
|
+
return re.sub(r"\\(['\\])", r"\1", single)
|
|
75
|
+
return re.sub(r"\\(.)", lambda m: _ESCAPES.get(m[1], m[0]), double)
|
|
76
|
+
if raw[:1].isspace() and value.startswith("#"):
|
|
77
|
+
return ""
|
|
78
|
+
return re.split(r"\s+#", value, maxsplit=1)[0].rstrip()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def read_env_file(path: str | os.PathLike[str]) -> dict[str, str]:
|
|
82
|
+
"""Read literal UTF-8 assignments without executing or interpolating them."""
|
|
83
|
+
try:
|
|
84
|
+
with Path(path).open(encoding="utf-8-sig") as source:
|
|
85
|
+
variables = {}
|
|
86
|
+
for number, line in enumerate(source, 1):
|
|
87
|
+
line = line.strip()
|
|
88
|
+
if not line or line.startswith("#"):
|
|
89
|
+
continue
|
|
90
|
+
assignment = _ASSIGNMENT.fullmatch(line)
|
|
91
|
+
if assignment is None or "\x00" in line:
|
|
92
|
+
raise EnvFileError(f"Expected KEY=value on line {number}.")
|
|
93
|
+
name, raw = assignment.groups()
|
|
94
|
+
variables[name] = _env_value(raw, number)
|
|
95
|
+
return variables
|
|
96
|
+
except EnvFileError:
|
|
97
|
+
raise
|
|
98
|
+
except (OSError, ValueError):
|
|
99
|
+
# A decoder or OS error can include bytes or other user-controlled text.
|
|
100
|
+
pass
|
|
101
|
+
raise EnvFileError("Could not read the env file as UTF-8.")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
_PRODUCTION_MARKERS = ("prod", "production", "live")
|
|
105
|
+
_TEST_MARKERS = ("test", "staging", "dev", "preview", "sandbox")
|
|
106
|
+
_ENVIRONMENT_NAMES = {
|
|
107
|
+
"NODE_ENV",
|
|
108
|
+
"APP_ENV",
|
|
109
|
+
"ENV",
|
|
110
|
+
"ENVIRONMENT",
|
|
111
|
+
"RAILS_ENV",
|
|
112
|
+
"RACK_ENV",
|
|
113
|
+
"FLASK_ENV",
|
|
114
|
+
"ASPNETCORE_ENVIRONMENT",
|
|
115
|
+
"DOTNET_ENVIRONMENT",
|
|
116
|
+
"VERCEL_ENV",
|
|
117
|
+
"VERCEL_TARGET_ENV",
|
|
118
|
+
"RAILWAY_ENVIRONMENT_NAME",
|
|
119
|
+
"RAILWAY_ENVIRONMENT",
|
|
120
|
+
"DEPLOY_ENV",
|
|
121
|
+
"DEPLOYMENT_ENV",
|
|
122
|
+
"CONTEXT", # Netlify deployment context
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
# These are application variable aliases for the providers' documented mode settings.
|
|
126
|
+
_MODES = (
|
|
127
|
+
# https://developer.paypal.com/api/rest/requests/
|
|
128
|
+
("paypal", {"PAYPAL_MODE", "PAYPAL_ENV", "PAYPAL_ENVIRONMENT"}, ("live", "production"), ("sandbox",)),
|
|
129
|
+
# https://developer.squareup.com/docs/devtools/sandbox/overview
|
|
130
|
+
("square", {"SQUARE_ENV", "SQUARE_ENVIRONMENT", "SQUARE_MODE"}, ("production",), ("sandbox",)),
|
|
131
|
+
# https://developer.paypal.com/braintree/docs/start/go-live/node/
|
|
132
|
+
("braintree", {"BRAINTREE_ENV", "BRAINTREE_ENVIRONMENT"}, ("production",), ("sandbox",)),
|
|
133
|
+
# https://developer.paddle.com/sdks/sandbox/
|
|
134
|
+
("paddle", {"PADDLE_ENV", "PADDLE_ENVIRONMENT"}, ("live", "production"), ("sandbox",)),
|
|
135
|
+
# https://docs.adyen.com/development-resources/client-side-authentication
|
|
136
|
+
("adyen", {"ADYEN_ENV", "ADYEN_ENVIRONMENT"}, ("live",), ("test",)),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
# The documented hosts identify the selected payment API, independently of its credentials.
|
|
140
|
+
_PAYMENT_ENDPOINTS = {
|
|
141
|
+
"PAYPAL": ("api-m.paypal.com", "api-m.sandbox.paypal.com"),
|
|
142
|
+
"SQUARE": ("connect.squareup.com", "connect.squareupsandbox.com"),
|
|
143
|
+
"PADDLE": ("api.paddle.com", "sandbox-api.paddle.com"),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
# Those with a distinctive documented prefix can also be recognized under arbitrary names.
|
|
147
|
+
# https://docs.stripe.com/keys
|
|
148
|
+
_STRIPE_LIVE = ("sk_live_", "rk_live_", "pk_live_")
|
|
149
|
+
_STRIPE_TEST = ("sk_test_", "rk_test_", "pk_test_")
|
|
150
|
+
# https://developer.paddle.com/api-reference/about/authentication/
|
|
151
|
+
_PADDLE_LIVE = "pdl_live_apikey_"
|
|
152
|
+
_PADDLE_TEST = "pdl_sdbx_apikey_"
|
|
153
|
+
|
|
154
|
+
# These formats or names identify a credential but lack a documented live/test
|
|
155
|
+
# discriminator. Each is unknown, even when a separate mode setting is present.
|
|
156
|
+
_OPAQUE_CREDENTIALS = (
|
|
157
|
+
# https://docs.stripe.com/keys (includes webhook signing secrets)
|
|
158
|
+
("Stripe", r"STRIPE_(?:.*_)?(?:KEY|TOKEN|SECRET)", ("whsec_",)),
|
|
159
|
+
# https://developer.paypal.com/api/rest/requests/
|
|
160
|
+
("PayPal", r"PAYPAL_(?:.*_)?(?:CLIENT_ID|SECRET|TOKEN)", ()),
|
|
161
|
+
# https://developer.squareup.com/docs/build-basics/access-tokens
|
|
162
|
+
("Square", r"SQUARE_(?:.*_)?(?:ACCESS_TOKEN|APPLICATION_ID|APP_ID|SECRET)", ()),
|
|
163
|
+
# https://developer.paypal.com/braintree/articles/control-panel/important-gateway-credentials/
|
|
164
|
+
("Braintree", r"BRAINTREE_(?:.*_)?(?:PUBLIC_KEY|PRIVATE_KEY|MERCHANT_ID|TOKEN)", ()),
|
|
165
|
+
# https://developer.paddle.com/api-reference/about/authentication/ (legacy API keys)
|
|
166
|
+
("Paddle", r"PADDLE_(?:.*_)?(?:KEY|TOKEN|SECRET)", ()),
|
|
167
|
+
# https://docs.adyen.com/development-resources/api-credentials
|
|
168
|
+
("Adyen", r"ADYEN_(?:.*_)?(?:KEY|TOKEN|SECRET|PASSWORD)", ()),
|
|
169
|
+
# https://www.twilio.com/docs/iam/test-credentials
|
|
170
|
+
("Twilio", r"TWILIO_(?:.*_)?(?:ACCOUNT_SID|AUTH_TOKEN|API_KEY|API_KEY_SID|API_SECRET)", ()),
|
|
171
|
+
# https://help.twilio.com/articles/10284917001627
|
|
172
|
+
("SendGrid", r"SENDGRID_(?:.*_)?(?:KEY|TOKEN)", ("SG.",)),
|
|
173
|
+
# https://documentation.mailgun.com/docs/mailgun/api-reference/mg-auth
|
|
174
|
+
("Mailgun", r"MAILGUN_(?:.*_)?(?:KEY|TOKEN|PASSWORD)", ()),
|
|
175
|
+
# https://postmarkapp.com/developer/user-guide/sandbox-mode
|
|
176
|
+
("Postmark", r"POSTMARK_(?:.*_)?(?:KEY|TOKEN|PASSWORD)", ()),
|
|
177
|
+
# https://github.com/resend/resend-cli#authentication
|
|
178
|
+
("Resend", r"RESEND_(?:.*_)?(?:KEY|TOKEN)", ("re_",)),
|
|
179
|
+
# https://docs.slack.dev/authentication/tokens/
|
|
180
|
+
("Slack", r"SLACK_(?:.*_)?(?:TOKEN|SECRET)", ("xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxe-", "xapp-")),
|
|
181
|
+
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html
|
|
182
|
+
("AWS", r"AWS_(?:ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN|SECURITY_TOKEN)", ("AKIA", "ASIA")),
|
|
183
|
+
# https://docs.cloud.google.com/endpoints/docs/openapi/get-started-app-engine
|
|
184
|
+
# https://developers.google.com/android-publisher/authorization
|
|
185
|
+
("Google", r"(?:GOOGLE|GCP|GEMINI)_(?:.*_)?(?:KEY|TOKEN|CLIENT_SECRET|CREDENTIALS)", ("AIza", "ya29.")),
|
|
186
|
+
# https://docs.github.com/en/organizations/managing-programmatic-access-to-your-organization/github-credential-types
|
|
187
|
+
(
|
|
188
|
+
"GitHub",
|
|
189
|
+
r"(?:GITHUB|GH)_(?:.*_)?(?:TOKEN|PAT|PRIVATE_KEY|CLIENT_SECRET)",
|
|
190
|
+
("ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_"),
|
|
191
|
+
),
|
|
192
|
+
)
|
|
193
|
+
_CREDENTIAL_RULES = tuple(
|
|
194
|
+
(provider, re.compile(r"(?:^|_)" + names + "$"), prefixes) for provider, names, prefixes in _OPAQUE_CREDENTIALS
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
_DATABASE_URL = re.compile(
|
|
198
|
+
r"(?:^|_)(?:DATABASE|DB|POSTGRES(?:QL)?|PG|MYSQL|MARIADB|MSSQL|SQLSERVER|SQLALCHEMY|"
|
|
199
|
+
r"REDIS|VALKEY|MONGO(?:DB)?|AMQP|RABBITMQ|MEMCACHED|ELASTICSEARCH|OPENSEARCH)"
|
|
200
|
+
r"_(?:[A-Z0-9]+_)*(?:URL|URI|DSN|CONNECTION_STRING)(?:_|$)"
|
|
201
|
+
)
|
|
202
|
+
_SERVICE_URL = re.compile(r"(?:^|_)(?:SERVICE|API|BASE)_(?:URL|URI)$")
|
|
203
|
+
_WEBHOOK_URL = re.compile(r"(?:^|_)WEBHOOK(?:_.*)?_(?:URL|URI|ENDPOINT)$")
|
|
204
|
+
_MAIL_ENDPOINT = re.compile(
|
|
205
|
+
r"(?:^|_)(?:SMTP|MAIL|EMAIL|MAILER)(?:_SMTP|_SERVER|_TRANSPORT)?_(?:HOST|SERVER|URL|URI|DSN|ENDPOINT)$"
|
|
206
|
+
)
|
|
207
|
+
_URL = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*:)?//([^/?#]+)(/[^?#]*)?(?:[?#].*)?")
|
|
208
|
+
_HOST_PORT = re.compile(r"(\[[0-9A-Fa-f:.]+\]|[\w.-]+)(?::[0-9]+)?")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _hosts(authority: str) -> tuple[str, ...]:
|
|
212
|
+
hosts = []
|
|
213
|
+
for address in authority.rsplit("@", 1)[-1].split(","):
|
|
214
|
+
match = _HOST_PORT.fullmatch(address)
|
|
215
|
+
if match is None:
|
|
216
|
+
return ()
|
|
217
|
+
hosts.append(match[1].strip("[]").lower().rstrip("."))
|
|
218
|
+
return tuple(hosts)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _loopback(host: str) -> bool:
|
|
222
|
+
if host == "localhost" or host.endswith(".localhost"):
|
|
223
|
+
return True
|
|
224
|
+
try:
|
|
225
|
+
address = ip_address(host)
|
|
226
|
+
except ValueError:
|
|
227
|
+
return False
|
|
228
|
+
mapped = getattr(address, "ipv4_mapped", None)
|
|
229
|
+
return (mapped or address).is_loopback
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _words(value: str) -> set[str]:
|
|
233
|
+
return set(re.findall(r"[^\W_]+", value.lower()))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _endpoint(name: str, value: str) -> _Match | None:
|
|
237
|
+
is_webhook = _WEBHOOK_URL.search(name)
|
|
238
|
+
is_mail = _MAIL_ENDPOINT.search(name)
|
|
239
|
+
is_database = _DATABASE_URL.search(name)
|
|
240
|
+
if not (is_webhook or is_mail or is_database or _SERVICE_URL.search(name)):
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
# Parse only the authority and path. Avoid URL parsers that cache raw URLs.
|
|
244
|
+
url = _URL.fullmatch(value)
|
|
245
|
+
hosts = _hosts(url[1]) if url else ()
|
|
246
|
+
if is_webhook or is_mail:
|
|
247
|
+
if is_mail and url is None:
|
|
248
|
+
host = value.lower().rstrip(".")
|
|
249
|
+
hosts = (host,) if _loopback(host) else _hosts(host)
|
|
250
|
+
if hosts and all(map(_loopback, hosts)):
|
|
251
|
+
return None
|
|
252
|
+
rule, kind = ("webhook-url", "webhook") if is_webhook else ("mail-endpoint", "outbound mail")
|
|
253
|
+
return _Match(rule, "unknown", f"No loopback destination could be established for this {kind} setting.")
|
|
254
|
+
|
|
255
|
+
provider = name.partition("_")[0]
|
|
256
|
+
if provider in _PAYMENT_ENDPOINTS and len(hosts) == 1:
|
|
257
|
+
live, sandbox = _PAYMENT_ENDPOINTS[provider]
|
|
258
|
+
if hosts[0] == sandbox:
|
|
259
|
+
return None
|
|
260
|
+
if hosts[0] == live:
|
|
261
|
+
return _Match(f"{provider.lower()}-endpoint", "live", "This is the provider's documented production host.")
|
|
262
|
+
|
|
263
|
+
database = unquote(url[2][1:].partition("/")[0]) if is_database and hosts and url and url[2] else ""
|
|
264
|
+
database_words = _words(database)
|
|
265
|
+
host_words = [_words(host) for host in hosts]
|
|
266
|
+
words = database_words.union(*host_words)
|
|
267
|
+
rule = "database-url" if is_database else "service-url"
|
|
268
|
+
for marker in _PRODUCTION_MARKERS:
|
|
269
|
+
if marker in words:
|
|
270
|
+
return _Match(rule, "live", "The host or database name has a production marker.", marker)
|
|
271
|
+
test_markers = set(_TEST_MARKERS)
|
|
272
|
+
if hosts and (
|
|
273
|
+
database_words & test_markers or all(_loopback(host) or parts & test_markers for host, parts in zip(hosts, host_words))
|
|
274
|
+
):
|
|
275
|
+
return None
|
|
276
|
+
return _Match(rule, "unknown", "The host or database name gives no clear environment signal.")
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _match(name: str, value: str) -> _Match | None:
|
|
280
|
+
for prefix in _STRIPE_LIVE:
|
|
281
|
+
if value.startswith(prefix):
|
|
282
|
+
return _Match("stripe-key", "live", "Stripe identifies this prefix as live mode.", prefix)
|
|
283
|
+
if value.startswith(_STRIPE_TEST + (_PADDLE_TEST,)):
|
|
284
|
+
return None
|
|
285
|
+
if value.startswith(_PADDLE_LIVE):
|
|
286
|
+
return _Match("paddle-key", "live", "Paddle identifies this API key prefix as live mode.", _PADDLE_LIVE)
|
|
287
|
+
|
|
288
|
+
for provider, names, live, test in _MODES:
|
|
289
|
+
if name in names:
|
|
290
|
+
mode = value.lower()
|
|
291
|
+
for marker in live:
|
|
292
|
+
if mode == marker:
|
|
293
|
+
return _Match(f"{provider}-mode", "live", "This mode selects the provider's production environment.", marker)
|
|
294
|
+
if mode in test:
|
|
295
|
+
return None
|
|
296
|
+
return _Match(f"{provider}-mode", "unknown", "This mode does not identify a documented provider environment.")
|
|
297
|
+
if name in _ENVIRONMENT_NAMES:
|
|
298
|
+
for marker in _PRODUCTION_MARKERS:
|
|
299
|
+
if value.lower() == marker:
|
|
300
|
+
return _Match("production-environment", "live", "This setting declares a production environment.", marker)
|
|
301
|
+
|
|
302
|
+
# Both client-key formats use generic prefixes, so require the provider in the name.
|
|
303
|
+
# https://developer.paddle.com/paddle-js/about/client-side-tokens/
|
|
304
|
+
# https://docs.adyen.com/development-resources/client-side-authentication
|
|
305
|
+
for suffix, provider in (("PADDLE_CLIENT_TOKEN", "Paddle"), ("ADYEN_CLIENT_KEY", "Adyen")):
|
|
306
|
+
if name == suffix or name.endswith("_" + suffix):
|
|
307
|
+
if value.startswith("test_"):
|
|
308
|
+
return None
|
|
309
|
+
if value.startswith("live_"):
|
|
310
|
+
return _Match(
|
|
311
|
+
f"{provider.lower()}-client-key", "live", f"{provider} identifies this client prefix as live mode.", "live_"
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
# https://postmarkapp.com/developer/api/overview (public no-delivery test value)
|
|
315
|
+
if name in {"POSTMARK_API_KEY", "POSTMARK_API_TOKEN", "POSTMARK_SERVER_TOKEN", "POSTMARK_SERVER_API_TOKEN"}:
|
|
316
|
+
if value == "POSTMARK_API_TEST":
|
|
317
|
+
return None
|
|
318
|
+
|
|
319
|
+
endpoint = _endpoint(name, value)
|
|
320
|
+
if endpoint is not None:
|
|
321
|
+
return endpoint
|
|
322
|
+
for provider, names, prefixes in _CREDENTIAL_RULES:
|
|
323
|
+
if names.search(name) or value.startswith(prefixes):
|
|
324
|
+
return _Match(
|
|
325
|
+
f"{provider.lower()}-credential",
|
|
326
|
+
"unknown",
|
|
327
|
+
f"The {provider} credential does not identify a live or test environment.",
|
|
328
|
+
)
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def check(variables: Mapping[str, str], allow: Collection[str] = ()) -> Report:
|
|
333
|
+
"""Report clues about production wiring without retaining any input values."""
|
|
334
|
+
allowed = set(allow)
|
|
335
|
+
findings = []
|
|
336
|
+
for name, raw in sorted(variables.items()):
|
|
337
|
+
value = raw.strip()
|
|
338
|
+
if value and (match := _match(name.upper(), value)) is not None:
|
|
339
|
+
findings.append(
|
|
340
|
+
Finding(
|
|
341
|
+
match.rule,
|
|
342
|
+
match.severity,
|
|
343
|
+
match.reason,
|
|
344
|
+
match.marker,
|
|
345
|
+
name=name,
|
|
346
|
+
allowed=name in allowed,
|
|
347
|
+
)
|
|
348
|
+
)
|
|
349
|
+
return Report(tuple(findings), len(variables))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _command(args: argparse.Namespace) -> int:
|
|
353
|
+
if not args.env_file and not args.environment:
|
|
354
|
+
print("error: sterile-check requires --env-file or --environment.", file=sys.stderr)
|
|
355
|
+
return EXIT_FAILED
|
|
356
|
+
reports = []
|
|
357
|
+
for number, path in enumerate(args.env_file, 1):
|
|
358
|
+
try:
|
|
359
|
+
reports.append(check(read_env_file(path), args.allow))
|
|
360
|
+
except EnvFileError as error:
|
|
361
|
+
print(f"error: --env-file #{number}. {error}", file=sys.stderr)
|
|
362
|
+
return EXIT_FAILED
|
|
363
|
+
if args.environment:
|
|
364
|
+
reports.append(check(os.environ, args.allow))
|
|
365
|
+
report = Report(
|
|
366
|
+
tuple(f for source in reports for f in source.findings),
|
|
367
|
+
sum(source.checked_count for source in reports),
|
|
368
|
+
)
|
|
369
|
+
if args.json:
|
|
370
|
+
print(
|
|
371
|
+
json.dumps(
|
|
372
|
+
{
|
|
373
|
+
**asdict(report),
|
|
374
|
+
"live_count": report.live_count,
|
|
375
|
+
"unknown_count": report.unknown_count,
|
|
376
|
+
"ok": report.ok,
|
|
377
|
+
},
|
|
378
|
+
indent=2,
|
|
379
|
+
)
|
|
380
|
+
)
|
|
381
|
+
else:
|
|
382
|
+
for finding in report.findings:
|
|
383
|
+
name = finding.name if finding.name.isprintable() else ascii(finding.name)
|
|
384
|
+
marker = f" ({finding.marker})" if finding.marker is not None else ""
|
|
385
|
+
allowed = " (allowed by the owner)" if finding.allowed else ""
|
|
386
|
+
print(f"{name} [{finding.rule}, {finding.severity}]{marker}{allowed}. {finding.reason}")
|
|
387
|
+
print(
|
|
388
|
+
f"Checked {report.checked_count} variable(s). {report.live_count} live, "
|
|
389
|
+
f"{report.unknown_count} unknown, {sum(f.allowed for f in report.findings)} allowed by the owner."
|
|
390
|
+
)
|
|
391
|
+
return EXIT_OK if report.ok else EXIT_CHECK_FAILED
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def register(commands: argparse._SubParsersAction) -> None:
|
|
395
|
+
parser = commands.add_parser("sterile-check", help="check test deployment settings for production signals")
|
|
396
|
+
parser.add_argument("--env-file", action="extend", nargs="+", default=[], metavar="PATH")
|
|
397
|
+
parser.add_argument("--environment", action="store_true", help="check the current process environment")
|
|
398
|
+
parser.add_argument(
|
|
399
|
+
"--allow",
|
|
400
|
+
action="extend",
|
|
401
|
+
nargs="+",
|
|
402
|
+
default=[],
|
|
403
|
+
metavar="NAME",
|
|
404
|
+
help="mark findings for these exact variable names as allowed by the owner",
|
|
405
|
+
)
|
|
406
|
+
parser.add_argument("--json", action="store_true", help="write a JSON report")
|
|
407
|
+
parser.set_defaults(handler=_command)
|
|
File without changes
|
botsting/targets/base.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""The interface between the scan runner and a system under test."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping, Sequence
|
|
6
|
+
from typing import Protocol
|
|
7
|
+
|
|
8
|
+
from botsting.core.authorization import (
|
|
9
|
+
Authorization,
|
|
10
|
+
AuthorizationError,
|
|
11
|
+
confirm_proof,
|
|
12
|
+
require_authorized,
|
|
13
|
+
)
|
|
14
|
+
from botsting.core.models import InjectionPoint, Reply, Slot, TaskCheck, ToolRule
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TargetError(RuntimeError):
|
|
18
|
+
"""The target could not be reset or did not answer."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Session(Protocol):
|
|
22
|
+
"""One conversation with the target as one principal."""
|
|
23
|
+
|
|
24
|
+
async def send(self, text: str) -> Reply | str:
|
|
25
|
+
"""Send a message and return what came back. Raise TargetError on failure.
|
|
26
|
+
|
|
27
|
+
A target with tools returns a Reply carrying the tool calls its recorder saw
|
|
28
|
+
during this message. A target without tools may return plain text.
|
|
29
|
+
"""
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Target(Protocol):
|
|
34
|
+
# Enough to reconnect later, e.g. "toy:vulnerable?model=scripted". Stored in reports.
|
|
35
|
+
spec: str
|
|
36
|
+
# Who the attacker is. Must not be authorized for any slot under test.
|
|
37
|
+
attacker_principal: str
|
|
38
|
+
# Where the target runs: "in-process", "loopback" or "network". Read by the
|
|
39
|
+
# authorization gate (core/authorization.py) before anything is sent; a target
|
|
40
|
+
# without one is refused, so there is no default when it is missing.
|
|
41
|
+
reach: str
|
|
42
|
+
# Every target must say what its tools can do, because any attack, including one
|
|
43
|
+
# that only asks for a secret, may make a tool fire. Read by the gate in this
|
|
44
|
+
# module (require_contained_tools) of every target:
|
|
45
|
+
# "no-tools" the target can do nothing but answer in text.
|
|
46
|
+
# "sinks" every tool that sends, pays, books or deletes writes to a recording
|
|
47
|
+
# sink with test data.
|
|
48
|
+
# A target that says anything else, or says nothing, is refused: saying nothing is
|
|
49
|
+
# not the same as being harmless. This is the adapter's promise, not proof: the
|
|
50
|
+
# runner cannot inspect where a tool writes.
|
|
51
|
+
tool_safety: str
|
|
52
|
+
|
|
53
|
+
async def describe(self) -> Mapping[str, str]:
|
|
54
|
+
"""The configuration under test (build, model, weights digest, settings).
|
|
55
|
+
|
|
56
|
+
Stored with every report so a replay can tell whether it faces the same thing.
|
|
57
|
+
Must not raise.
|
|
58
|
+
"""
|
|
59
|
+
...
|
|
60
|
+
|
|
61
|
+
def slots(self) -> Sequence[Slot]:
|
|
62
|
+
"""Where canaries can be planted, and who may see each."""
|
|
63
|
+
...
|
|
64
|
+
|
|
65
|
+
def task_checks(self) -> Sequence[TaskCheck]:
|
|
66
|
+
"""Normal uses that must keep working, so a 'fix' that breaks the bot is caught."""
|
|
67
|
+
...
|
|
68
|
+
|
|
69
|
+
async def reset(self, fixtures: Mapping[str, str], content: Mapping[str, str] | None = None) -> None:
|
|
70
|
+
"""Return to a known starting state.
|
|
71
|
+
|
|
72
|
+
`fixtures` maps slot id to the canary value to plant. `content` maps injection
|
|
73
|
+
point id to the text to place there; points not mentioned get their harmless
|
|
74
|
+
default. Everything from earlier conversations, including recorded tool calls
|
|
75
|
+
and their effects, must be gone afterwards.
|
|
76
|
+
"""
|
|
77
|
+
...
|
|
78
|
+
|
|
79
|
+
async def open_session(self, principal: str) -> Session:
|
|
80
|
+
"""Start a new conversation as `principal`."""
|
|
81
|
+
...
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ActionTarget(Target, Protocol):
|
|
85
|
+
"""A target whose tools can be observed. Needed for action and injection attacks."""
|
|
86
|
+
|
|
87
|
+
def tool_rules(self) -> Sequence[ToolRule]:
|
|
88
|
+
"""Which tools may run, and at whose request."""
|
|
89
|
+
...
|
|
90
|
+
|
|
91
|
+
def injection_points(self) -> Sequence[InjectionPoint]:
|
|
92
|
+
"""Where text from someone else ends up in front of the target."""
|
|
93
|
+
...
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class NetworkTarget(Target, Protocol):
|
|
97
|
+
"""A target that leaves this process (reach "loopback" or "network"), such as HttpTarget.
|
|
98
|
+
|
|
99
|
+
Every operation on it is checked against a recorded authorization. The gate in
|
|
100
|
+
core/authorization.py reads these attributes (`require_authorized`, the scope check
|
|
101
|
+
and `authorization_summary`); the scan itself never does. A target that runs
|
|
102
|
+
in-process has none of them.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
# The place the target is reached at, e.g. "https://staging.example.com". Read by
|
|
106
|
+
# the gate to find the authorization for exactly this origin; when it is missing
|
|
107
|
+
# or not text, the gate refuses the target.
|
|
108
|
+
origin: str
|
|
109
|
+
# The recorded permission to test this origin. Read by the gate before every
|
|
110
|
+
# operation and summarized in the report; missing means no authorization, and the
|
|
111
|
+
# gate refuses the target.
|
|
112
|
+
authorization: Authorization | None
|
|
113
|
+
# Which agent the deployment serves, when it serves several behind one origin.
|
|
114
|
+
# Read by the gate's scope check against the authorization's --agent limit; the
|
|
115
|
+
# default when missing is "not declared", which an agent-limited authorization refuses.
|
|
116
|
+
agent_id: str
|
|
117
|
+
# Same, for the tenant the deployment serves (--tenant limit); default "not declared".
|
|
118
|
+
tenant: str
|
|
119
|
+
# Tools the scan may ask the harness to carry out for real, inside the caps written
|
|
120
|
+
# in the bot's code. Read by the gate's scope check against the authorization's
|
|
121
|
+
# live tools; the default when missing is (), nothing is ever carried out for real.
|
|
122
|
+
live_actions: tuple[str, ...]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class HarnessedTarget(ActionTarget, Protocol):
|
|
126
|
+
"""A target wired with the drop-in harness (botsting/harness.py), such as an HttpTarget
|
|
127
|
+
with "harness": "sdk" or "inputs". The preflight reads what the harness reports."""
|
|
128
|
+
|
|
129
|
+
# Tools the harness listed as marked in its signed readiness answer. Read by the
|
|
130
|
+
# preflight when a tool rule's control is the harness's attestation; the default
|
|
131
|
+
# when missing is (), so an attested rule fails its check on a target without the harness.
|
|
132
|
+
marked_tools: tuple[str, ...]
|
|
133
|
+
# True when the fake secrets travel in each chat request ("harness": "inputs").
|
|
134
|
+
# Read by the preflight's repeated-slot check; the default when missing is False,
|
|
135
|
+
# so the check does not run and every slot is attacked as usual.
|
|
136
|
+
secrets_travel_in_requests: bool
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def tool_rules(target: Target) -> Sequence[ToolRule]:
|
|
140
|
+
"""The target's tool rules; none for a target without observable tools."""
|
|
141
|
+
return tuple(getattr(target, "tool_rules", lambda: ())())
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def injection_points(target: Target) -> Sequence[InjectionPoint]:
|
|
145
|
+
return tuple(getattr(target, "injection_points", lambda: ())())
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class UnsafeTargetError(ValueError):
|
|
149
|
+
"""The target has not promised that an attack cannot cause real actions."""
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class NotAuthorizedError(UnsafeTargetError):
|
|
153
|
+
"""There is no valid authorization to send anything to this target."""
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def require_contained_tools(target: Target) -> None:
|
|
157
|
+
"""The part of the gate that needs no network: run at every entry point and before every operation.
|
|
158
|
+
|
|
159
|
+
Refuses a target unless (1) it is allowed to be reached at all: it runs in this
|
|
160
|
+
process, or there is a current, named, in-scope authorization for exactly where it
|
|
161
|
+
runs; and (2) it declares that it has no tools, or that all of them are recording
|
|
162
|
+
sinks. A target that omits either declaration is refused: saying nothing is not the
|
|
163
|
+
same as being harmless. Whether a network target's proof of control is still in
|
|
164
|
+
place is checked by `confirm_permitted`.
|
|
165
|
+
"""
|
|
166
|
+
try:
|
|
167
|
+
require_authorized(target)
|
|
168
|
+
except AuthorizationError as exc:
|
|
169
|
+
raise NotAuthorizedError(str(exc)) from exc
|
|
170
|
+
_require_tool_declaration(target)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def confirm_permitted(target: Target, fresh: bool = False) -> None:
|
|
174
|
+
"""The whole gate, including fetching a network target's proof of control.
|
|
175
|
+
|
|
176
|
+
`fresh` fetches the proof whatever was remembered: used when a scan or replay starts.
|
|
177
|
+
"""
|
|
178
|
+
try:
|
|
179
|
+
authorization = require_authorized(target)
|
|
180
|
+
_require_tool_declaration(target)
|
|
181
|
+
if authorization is not None:
|
|
182
|
+
await confirm_proof(authorization, fresh=fresh)
|
|
183
|
+
# The fetch takes time; the authorization may have expired while it ran.
|
|
184
|
+
require_authorized(target)
|
|
185
|
+
except AuthorizationError as exc:
|
|
186
|
+
raise NotAuthorizedError(str(exc)) from exc
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _require_tool_declaration(target: Target) -> None:
|
|
190
|
+
declared = getattr(target, "tool_safety", None)
|
|
191
|
+
if declared == "sinks":
|
|
192
|
+
return
|
|
193
|
+
if declared == "no-tools":
|
|
194
|
+
if tool_rules(target) or injection_points(target):
|
|
195
|
+
raise UnsafeTargetError(
|
|
196
|
+
"this target says it has no tools but declares tool rules or injection points; "
|
|
197
|
+
"it must declare that its tools are recording sinks, or have none"
|
|
198
|
+
)
|
|
199
|
+
return
|
|
200
|
+
raise UnsafeTargetError(
|
|
201
|
+
"this target does not declare that it has no tools or that its tools are recording sinks with "
|
|
202
|
+
"test data; refusing to send it anything, because a successful attack would carry out real actions"
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def as_reply(value: Reply | str) -> Reply:
|
|
207
|
+
return value if isinstance(value, Reply) else Reply(text=value)
|