Skip to content

armgit / bbot

Public Imported from GitHub
0

The recursive internet scanner for hackers. 🧡

Overhaul api_request rate limiting and add config deprecation support (#3461)

Paul Mueller525865b60000
diff --git a/bbot/core/config/models.py b/bbot/core/config/models.py
index 08c6233d0..c7fd6a57a 100644
--- a/bbot/core/config/models.py
+++ b/bbot/core/config/models.py
@@ -39,9 +39,16 @@ ConfidenceLiteral = Annotated[
]
-def Field(default=PydanticUndefined, *, sensitive: bool = False, mandatory: bool = False, **kwargs):
+def Field(
+ default=PydanticUndefined,
+ *,
+ sensitive: bool = False,
+ mandatory: bool = False,
+ deprecated: bool = False,
+ **kwargs,
+):
"""
- Drop-in replacement for `pydantic.Field` that records two BBOT-specific
+ Drop-in replacement for `pydantic.Field` that records BBOT-specific
flags as field metadata:
- `sensitive=True`: value should be redacted when serializing configs
@@ -49,8 +56,11 @@ def Field(default=PydanticUndefined, *, sensitive: bool = False, mandatory: bool
- `mandatory=True`: option must be supplied for the module to function;
drives the "Needs API Key" column in `bbot -l` and the
`BaseModule.auth_required` property.
+ - `deprecated=True`: option is no longer used. It is still accepted so
+ existing presets keep working, but it is ignored, left out of defaults
+ and docs, and setting it logs a warning at scan startup.
- Both flags are stashed under `json_schema_extra` so pydantic preserves
+ The flags are stashed under `json_schema_extra` so pydantic preserves
them on `FieldInfo.json_schema_extra` (and in any generated JSON schema)
without affecting validation. All other arguments pass through unchanged.
"""
@@ -59,6 +69,8 @@ def Field(default=PydanticUndefined, *, sensitive: bool = False, mandatory: bool
extra["sensitive"] = True
if mandatory:
extra["mandatory"] = True
+ if deprecated:
+ extra["deprecated"] = True
if extra:
kwargs["json_schema_extra"] = extra
return _PydanticField(default, **kwargs)
@@ -78,6 +90,10 @@ def is_mandatory(field) -> bool:
return bool(field_flags(field).get("mandatory"))
+def is_deprecated(field) -> bool:
+ return bool(field_flags(field).get("deprecated"))
+
+
def _unwrap_optional(annotation):
"""Strip a single `Optional[X]` / `Union[X, None]` wrapper, return X. Pass-through otherwise."""
import typing
@@ -231,6 +247,28 @@ def partition_sensitive_config(config, model, *, keep_sensitive: bool):
return out
+def find_deprecated_config(config, model, prefix=""):
+ """
+ Walk `config` (a dict) alongside the pydantic `model` and return the dotted
+ paths of every `deprecated=True` option that is set, e.g. `["modules.slack.retries"]`.
+ """
+ found = []
+ if not isinstance(config, dict) or model is None:
+ return found
+ for key, val in config.items():
+ field = _resolve_field(model, key)
+ if field is None:
+ continue
+ dotted = f"{prefix}.{key}" if prefix else str(key)
+ if is_deprecated(field):
+ found.append(dotted)
+ continue
+ sub_model = _field_submodel(field)
+ if sub_model is not None:
+ found.extend(find_deprecated_config(val, sub_model, dotted))
+ return found
+
+
class ScopeConfig(BaseModel):
model_config = STRICT
@@ -485,6 +523,8 @@ __all__ = [
"coerce_config",
"coerce_value",
"field_flags",
+ "find_deprecated_config",
+ "is_deprecated",
"is_mandatory",
"is_sensitive",
"partition_sensitive_config",
diff --git a/bbot/core/modules.py b/bbot/core/modules.py
index cee81ef6f..98045f868 100644
--- a/bbot/core/modules.py
+++ b/bbot/core/modules.py
@@ -224,6 +224,7 @@ def _extract_pydantic_config(config_class: ast.ClassDef) -> tuple[dict, dict, se
description = ""
is_sensitive = False
is_mandatory = False
+ is_deprecated = False
value = node.value
if isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "Field":
@@ -245,15 +246,22 @@ def _extract_pydantic_config(config_class: ast.ClassDef) -> tuple[dict, dict, se
elif kw.arg == "mandatory":
with suppress(ValueError, TypeError, SyntaxError):
is_mandatory = bool(ast.literal_eval(kw.value))
+ elif kw.arg == "deprecated":
+ with suppress(ValueError, TypeError, SyntaxError):
+ is_deprecated = bool(ast.literal_eval(kw.value))
elif kw.arg == "json_schema_extra":
with suppress(ValueError, TypeError, SyntaxError):
extra = ast.literal_eval(kw.value)
if isinstance(extra, dict):
is_sensitive = is_sensitive or bool(extra.get("sensitive"))
is_mandatory = is_mandatory or bool(extra.get("mandatory"))
+ is_deprecated = is_deprecated or bool(extra.get("deprecated"))
elif value is not None:
default = _eval_ast_default(value)
+ # deprecated options are still accepted, but they get no default and aren't listed
+ if is_deprecated:
+ continue
if default is _UNEVALUATED:
# couldn't statically determine; fall back to None so listing still works
default = None
diff --git a/bbot/modules/base.py b/bbot/modules/base.py
index ae77a0cd0..2d553d35c 100644
--- a/bbot/modules/base.py
+++ b/bbot/modules/base.py
@@ -1,13 +1,17 @@
+import time
import asyncio
import logging
import traceback
from sys import exc_info
from contextlib import suppress
+from email.utils import parsedate_to_datetime
+from datetime import datetime, timezone
from ..core.helpers.misc import get_size # noqa
from ..errors import HttpCompareError, ValidationError, WebError
from ..core.helpers.async_helpers import TaskCounter, ShuffleQueue
from ..core.event import is_event
+from .. import __version__
class BaseModule:
@@ -67,7 +71,7 @@ class BaseModule:
batch_size (int): Size of batches processed by handle_batch(). Default is 1.
- api_failure_abort_threshold (int): Threshold for setting error state after failed HTTP requests (only takes effect when `api_request()` is used. Default is 5.
+ api_failure_abort_threshold (int): Threshold for setting error state after consecutive failed HTTP requests, not counting rate limits (only takes effect when `api_request()` is used).
_preserve_graph (bool): When set to True, accept events that may be duplicates but are necessary for construction of complete graph. Typically only enabled for output modules that need to maintain full chains of events, e.g. `neo4j` and `json`. Default is False.
@@ -112,6 +116,11 @@ class BaseModule:
# disable the module after this many failed attempts in a row
_api_failure_abort_threshold = 3
+ # disable the module after this many rate-limited attempts in a row (per API key)
+ _api_rate_limit_abort_threshold = 10
+ # seconds to wait before retrying a failed API request (doubles with each retry)
+ _api_retry_backoff = 1
+ _api_retry_max_backoff = 30
# whether to retry on 429s when first pinging the API at scan start
_ping_retry_on_http_429 = False
@@ -164,6 +173,9 @@ class BaseModule:
# track number of failures (for .api_request())
self._api_request_failures = 0
+ # consecutive rate-limited responses, and when we may send again (shared by all event handlers)
+ self._api_rate_limit_count = 0
+ self._api_rate_limited_until = 0.0
self._default_api_retries = self.scan.config.get("web", {}).get("api_retries", 2)
@@ -370,6 +382,10 @@ class BaseModule:
def api_failure_abort_threshold(self):
return (self.api_retries * self._api_failure_abort_threshold) + 1
+ @property
+ def api_rate_limit_abort_threshold(self):
+ return self._api_rate_limit_abort_threshold * max(1, len(self._api_keys))
+
async def ping(self, url=None):
"""Asynchronously checks the health of the configured API.
@@ -1352,57 +1368,80 @@ class BaseModule:
async def api_request(self, *args, **kwargs):
"""
Makes an HTTP request while automatically:
- - avoiding rate limits (sleep/retry)
+ - obeying rate limits (Retry-After), shared across all of the module's event handlers
- cycling API keys
- - cancelling after too many failed attempts
+ - backing off between retries of failed requests
+ - cancelling after too many failed or rate-limited attempts
"""
url = args[0] if args else kwargs.pop("url", "")
retry_on_http_429 = kwargs.pop("retry_on_http_429", True)
-
- # loop until we have a successful request
- for _ in range(self.api_retries):
- if "headers" not in kwargs:
- kwargs["headers"] = {}
- if "ssl_verify" not in kwargs:
- kwargs["ssl_verify"] = self.helpers.web.ssl_verify_infrastructure
- if "timeout" not in kwargs:
- kwargs["timeout"] = self.http_timeout_infrastructure
+ # we do all the retrying here; blasthttp's own retries would ignore Retry-After
+ kwargs["retries"] = 0
+ # API calls identify themselves honestly instead of using the scan's (browser) user agent
+ kwargs["headers"] = dict(kwargs.get("headers") or {})
+ if not any(k.lower() == "user-agent" for k in kwargs["headers"]):
+ kwargs["headers"]["User-Agent"] = f"BBOT/{__version__}"
+ if "ssl_verify" not in kwargs:
+ kwargs["ssl_verify"] = self.helpers.web.ssl_verify_infrastructure
+ if "timeout" not in kwargs:
+ kwargs["timeout"] = self.http_timeout_infrastructure
+
+ r = None
+ backoff = self._api_retry_backoff
+ for attempt in range(self.api_retries):
+ if self.errored:
+ break
+ # obey the rate limit, which another event handler may have extended while we waited
+ while (remaining := self._api_rate_limited_until - time.monotonic()) > 0:
+ await asyncio.sleep(remaining)
new_url, kwargs = self.prepare_api_request(url, kwargs)
kwargs["url"] = new_url
r = await self.helpers.request(**kwargs)
- success = r is not None and self._api_response_is_success(r)
-
- if success:
+ if r is not None and self._api_response_is_success(r):
self._api_request_failures = 0
- else:
- status_code = getattr(r, "status_code", 0)
- response_text = getattr(r, "text", "")
- self.trace(f"API response to {url} failed with status code {status_code}: {response_text}")
- self._api_request_failures += 1
- if self._api_request_failures >= self.api_failure_abort_threshold:
+ self._api_rate_limit_count = 0
+ break
+
+ status_code = getattr(r, "status_code", 0)
+ response_text = getattr(r, "text", "")
+ self.trace(f"API response to {url} failed with status code {status_code}: {response_text}")
+ retry_after = self._get_retry_after(r)
+
+ if status_code == 429 or retry_after is not None:
+ if not retry_on_http_429:
+ # e.g. a setup ping, where a 429 usually means the quota is used up; don't wait on it
+ if len(self._api_keys) < 2:
+ break
+ self.cycle_api_key()
+ continue
+ # rate limits aren't failures, but being rate limited over and over despite obeying is
+ self._api_rate_limit_count += 1
+ if self._api_rate_limit_count >= self.api_rate_limit_abort_threshold:
self.set_error_state(
- f"Setting error state due to {self._api_request_failures:,} failed HTTP requests"
+ f"Setting error state after being rate limited {self._api_rate_limit_count:,} times in a row"
)
- else:
- # sleep for a bit if we're being rate limited
- retry_after = self._get_retry_after(r)
- if (retry_after or status_code == 429) and retry_on_http_429:
- sleep_interval = int(retry_after) if retry_after is not None else self._429_sleep_interval
- if retry_after and retry_after > self._429_max_sleep_interval:
- self.verbose(
- f"Got an excessive retry-after header of {retry_after} from {new_url}, using {self._429_max_sleep_interval} instead"
- )
- sleep_interval = self._429_max_sleep_interval
- self.verbose(
- f"Sleeping for {sleep_interval:,} seconds due to rate limit (HTTP status: {status_code})"
- )
- await asyncio.sleep(sleep_interval)
- elif self._api_keys:
- # if request failed, cycle API keys and try again
- self.cycle_api_key()
- continue
- break
+ break
+ sleep_interval = self._429_sleep_interval if retry_after is None else retry_after
+ if sleep_interval > self._429_max_sleep_interval:
+ self.verbose(
+ f"Got an excessive retry-after of {sleep_interval} from {new_url}, using {self._429_max_sleep_interval} instead"
+ )
+ sleep_interval = self._429_max_sleep_interval
+ self.verbose(f"Rate limited (HTTP status: {status_code}), waiting {sleep_interval:,} seconds")
+ self._api_rate_limited_until = max(self._api_rate_limited_until, time.monotonic() + sleep_interval)
+ self.cycle_api_key()
+ continue
+
+ self._api_rate_limit_count = 0
+ self._api_request_failures += 1
+ if self._api_request_failures >= self.api_failure_abort_threshold:
+ self.set_error_state(f"Setting error state due to {self._api_request_failures:,} failed HTTP requests")
+ break
+ self.cycle_api_key()
+ if attempt < self.api_retries - 1:
+ await asyncio.sleep(backoff)
+ backoff = min(backoff * 2, self._api_retry_max_backoff)
return r
@@ -1434,11 +1473,20 @@ class BaseModule:
body_json = r.json()
if isinstance(body_json, dict):
retry_after = body_json.get("retry_after", None)
- if retry_after is not None:
- # we don't allow retry-after smaller than 1 second
- # this is to prevent cases where APIs erroneously return a retry-after value of 0
- # e.g. https://github.com/blacklanternsecurity/bbot/issues/2826
- return max(1.0, float(retry_after))
+ if retry_after is None:
+ return None
+ try:
+ seconds = float(retry_after)
+ except (TypeError, ValueError):
+ # Retry-After can also be an HTTP date
+ try:
+ seconds = (parsedate_to_datetime(retry_after) - datetime.now(timezone.utc)).total_seconds()
+ except (TypeError, ValueError):
+ return None
+ # we don't allow retry-after smaller than 1 second
+ # this is to prevent cases where APIs erroneously return a retry-after value of 0
+ # e.g. https://github.com/blacklanternsecurity/bbot/issues/2826
+ return max(1.0, seconds)
def _prepare_api_iter_req(self, url, page, page_size, offset, **requests_kwargs):
"""
diff --git a/bbot/modules/output/discord.py b/bbot/modules/output/discord.py
index 82656e0e3..fd06f46f3 100644
--- a/bbot/modules/output/discord.py
+++ b/bbot/modules/output/discord.py
@@ -14,4 +14,4 @@ class Discord(WebhookOutputModule):
webhook_url: str = Field("", description="Discord webhook URL", sensitive=True)
event_types: list[str] = Field(["FINDING"], description="Types of events to send")
min_severity: str = Field("LOW", description="Only allow FINDING events of this severity or higher")
- retries: int = Field(10, description="Number of times to retry sending the message before skipping the event")
+ retries: int | None = Field(None, deprecated=True, description="No longer used")
diff --git a/bbot/modules/output/elastic.py b/bbot/modules/output/elastic.py
index 768a48bb6..7718a9cd3 100644
--- a/bbot/modules/output/elastic.py
+++ b/bbot/modules/output/elastic.py
@@ -23,9 +23,13 @@ class Elastic(webhook):
username: str = Field("elastic", description="Elastic username", sensitive=True)
password: str = Field("bbotislife", description="Elastic password", sensitive=True)
timeout: int = Field(10, description="HTTP timeout")
+ ssl_verify: bool | None = Field(
+ False,
+ description="Verify SSL certificates (Elastic usually serves a self-signed cert; set to null to use the global web.ssl_verify_infrastructure setting)",
+ )
async def cleanup(self):
# refresh the index
doc_regex = self.helpers.re.compile(r"/[^/]+$")
refresh_url = doc_regex.sub("/_refresh", self.url)
- await self.helpers.request(refresh_url, auth=self.auth)
+ await self.helpers.request(refresh_url, auth=self.auth, ssl_verify=self.ssl_verify)
diff --git a/bbot/modules/output/slack.py b/bbot/modules/output/slack.py
index 3b80daf9e..c42c992eb 100644
--- a/bbot/modules/output/slack.py
+++ b/bbot/modules/output/slack.py
@@ -16,7 +16,7 @@ class Slack(WebhookOutputModule):
webhook_url: str = Field("", description="Slack webhook URL", sensitive=True)
event_types: list[str] = Field(["FINDING"], description="Types of events to send")
min_severity: str = Field("LOW", description="Only allow FINDING events of this severity or higher")
- retries: int = Field(10, description="Number of times to retry sending the message before skipping the event")
+ retries: int | None = Field(None, deprecated=True, description="No longer used")
content_key = "text"
diff --git a/bbot/modules/output/teams.py b/bbot/modules/output/teams.py
index 4954bea29..e93f06e3a 100644
--- a/bbot/modules/output/teams.py
+++ b/bbot/modules/output/teams.py
@@ -14,7 +14,7 @@ class Teams(WebhookOutputModule):
webhook_url: str = Field("", description="Teams webhook URL", sensitive=True)
event_types: list[str] = Field(["FINDING"], description="Types of events to send")
min_severity: str = Field("LOW", description="Only allow FINDING events of this severity or higher")
- retries: int = Field(10, description="Number of times to retry sending the message before skipping the event")
+ retries: int | None = Field(None, deprecated=True, description="No longer used")
async def handle_event(self, event):
data = self.format_message(event)
diff --git a/bbot/modules/output/webhook.py b/bbot/modules/output/webhook.py
index 8d5d9f21f..6948e69b9 100644
--- a/bbot/modules/output/webhook.py
+++ b/bbot/modules/output/webhook.py
@@ -19,11 +19,17 @@ class webhook(BaseOutputModule):
password: str = Field("", description="Password (basic auth)", sensitive=True)
headers: dict = Field({}, description="Additional headers to send with the request", sensitive=True)
timeout: int = Field(10, description="HTTP timeout")
+ ssl_verify: bool | None = Field(
+ None, description="Verify SSL certificates (defaults to the global web.ssl_verify_infrastructure setting)"
+ )
async def setup(self):
self.url = self.config.get("url", "")
self.method = self.config.get("method", "POST")
self.timeout = self.config.get("timeout", 10)
+ self.ssl_verify = self.config.get("ssl_verify", None)
+ if self.ssl_verify is None:
+ self.ssl_verify = self.helpers.web.ssl_verify_infrastructure
self.headers = dict(self.config.get("headers") or {})
bearer = self.config.get("bearer", "")
if bearer:
@@ -42,27 +48,13 @@ class webhook(BaseOutputModule):
return True
async def handle_event(self, event):
- while 1:
- event_json = event.json()
- event_pydantic = Event(**event_json)
- event_json = event_pydantic.model_dump(exclude_none=True)
- response = await self.helpers.request(
- url=self.url,
- method=self.method,
- auth=self.auth,
- headers=self.headers,
- json=event_json,
- )
- is_success = False if response is None else response.is_success
- if not is_success:
- status_code = getattr(response, "status_code", 0)
- self.warning(f"Error sending {event} (HTTP status code: {status_code}), retrying...")
- body = getattr(response, "text", "")
- self.debug(body)
- if status_code == 429:
- sleep_interval = 10
- else:
- sleep_interval = 1
- await self.helpers.sleep(sleep_interval)
- continue
- break
+ event_json = Event(**event.json()).model_dump(exclude_none=True)
+ await self.api_request(
+ url=self.url,
+ method=self.method,
+ auth=self.auth,
+ headers=dict(self.headers),
+ json=event_json,
+ timeout=self.timeout,
+ ssl_verify=self.ssl_verify,
+ )
diff --git a/bbot/modules/shodan_idb.py b/bbot/modules/shodan_idb.py
index 9eec8104a..4519c0863 100644
--- a/bbot/modules/shodan_idb.py
+++ b/bbot/modules/shodan_idb.py
@@ -51,13 +51,7 @@ class shodan_idb(BaseModule):
}
class Config(BaseModuleConfig):
- retries: Optional[int] = Field(
- None,
- description="How many times to retry API requests (e.g. after a 429 error). Overrides the global web.api_retries setting.",
- )
-
- # we typically don't want to abort this module
- _api_failure_abort_threshold = 9999999999
+ retries: Optional[int] = Field(None, deprecated=True, description="No longer used")
# since there are rate limits, we set a lower qsize
# this way when our queue is full, we can give the API a break
@@ -83,11 +77,6 @@ class shodan_idb(BaseModule):
def _incoming_dedup_hash(self, event):
return hash(self.get_ip(event))
- @property
- def api_retries(self):
- # allow the module to override global retry setting
- return self.config.get("retries", None) or super().api_retries
-
async def handle_event(self, event):
ip = self.get_ip(event)
if ip is None:
diff --git a/bbot/modules/subdomainradar.py b/bbot/modules/subdomainradar.py
index a99063b3d..bdcc314cf 100644
--- a/bbot/modules/subdomainradar.py
+++ b/bbot/modules/subdomainradar.py
@@ -75,7 +75,7 @@ class SubdomainRadar(subdomain_enum_apikey):
return True
def prepare_api_request(self, url, kwargs):
- kwargs["headers"] = {"Authorization": f"Bearer {self.api_key}"}
+ kwargs.setdefault("headers", {})["Authorization"] = f"Bearer {self.api_key}"
return url, kwargs
async def handle_event(self, event):
diff --git a/bbot/modules/templates/webhook.py b/bbot/modules/templates/webhook.py
index 162fdacdb..d68eefa31 100644
--- a/bbot/modules/templates/webhook.py
+++ b/bbot/modules/templates/webhook.py
@@ -14,11 +14,6 @@ class WebhookOutputModule(BaseOutputModule):
severities = ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"]
confidences = ["UNKNOWN", "LOW", "MEDIUM", "HIGH", "CONFIRMED"]
- # abort module after 10 failed requests (not including retries)
- _api_failure_abort_threshold = 10
- # retry each request up to 10 times, respecting the Retry-After header
- _default_api_retries = 10
-
async def setup(self):
self.webhook_url = self.config.get("webhook_url", "")
self.min_severity = self.config.get("min_severity", "LOW").strip().upper()
@@ -31,10 +26,6 @@ class WebhookOutputModule(BaseOutputModule):
return False
return await super().setup()
- @property
- def api_retries(self):
- return self.config.get("retries", self._default_api_retries)
-
async def handle_event(self, event):
message = self.format_message(event)
data = {self.content_key: message}
diff --git a/bbot/scanner/scanner.py b/bbot/scanner/scanner.py
index 324049d98..f5b8455b2 100644
--- a/bbot/scanner/scanner.py
+++ b/bbot/scanner/scanner.py
@@ -17,6 +17,7 @@ from .manager import ScanIngress, ScanEgress
from bbot.core.helpers.misc import sha1, rand_string
from bbot.core.helpers.names_generator import random_name
from bbot.core.config.logger import GzipRotatingFileHandler
+from bbot.core.config.models import find_deprecated_config
from bbot.core.multiprocess import SHARED_INTERPRETER_STATE
from bbot.core.helpers.async_helpers import async_to_sync_gen
from bbot.logger import log_to_stderr
@@ -375,6 +376,12 @@ class Scanner:
f.write('# To include secrets, set "redact_secrets: false" in your preset or BBOT config.\n\n')
f.write(self.preset.to_yaml(redact_secrets=redact_secrets))
+ # deprecated options are accepted but ignored, so make sure the user knows
+ for path in find_deprecated_config(
+ self.preset.core.custom_config, self.preset.module_loader.config_schema
+ ):
+ self.hugewarning(f'Config option "{path}" is deprecated and will be ignored', trace=False)
+
# log scan overview
start_msg = f"Scan seeded with {len(self.seeds.event_seeds):,} seed(s)"
details = []
diff --git a/bbot/test/test_step_1/test_api_request.py b/bbot/test/test_step_1/test_api_request.py
new file mode 100644
index 000000000..f6f0448be
--- /dev/null
+++ b/bbot/test/test_step_1/test_api_request.py
@@ -0,0 +1,195 @@
+import time
+import asyncio
+
+from ..bbot_fixtures import * # noqa: F403
+
+from bbot import __version__
+from bbot.modules.base import BaseModule
+from bbot.test.mock_blasthttp import MockResponse, TimeoutException
+
+
+API_URL = "https://api.evilcorp.com/lookup?key={api_key}"
+
+
+async def _make_module(scan, api_keys=None):
+ class dummy_api(BaseModule):
+ _name = "dummy_api"
+ watched_events = ["DNS_NAME"]
+ # keep backoff short so tests stay fast
+ _api_retry_backoff = 0.05
+
+ module = dummy_api(scan)
+ if api_keys:
+ module.api_key = api_keys
+ return module
+
+
+def _responder(blasthttp_mock, *statuses, headers=None):
+ """Answer requests with the given statuses in order (the last one repeats), recording each request."""
+ requests = []
+
+ def callback(request):
+ index = min(len(requests), len(statuses) - 1)
+ requests.append((time.monotonic(), request))
+ status = statuses[index]
+ if status == "timeout":
+ raise TimeoutException("timeout")
+ return MockResponse(status_code=status, headers=headers or {})
+
+ blasthttp_mock.add_callback(callback)
+ return requests
+
+
+async def test_api_request_rate_limits_are_not_failures(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner(config={"web": {"429_sleep_interval": 0}})
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, 429)
+ # more rate limits than the failure threshold, but fewer than the rate limit threshold
+ for _ in range(3):
+ await module.api_request(API_URL)
+ assert len(requests) == 9
+ assert module._api_request_failures == 0
+ assert module._api_rate_limit_count == 9
+ assert module.errored is False
+
+
+async def test_api_request_persistent_rate_limit_errors(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner(config={"web": {"429_sleep_interval": 0}})
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, 429)
+ for _ in range(5):
+ await module.api_request(API_URL)
+ assert module.api_rate_limit_abort_threshold == 10
+ assert len(requests) == 10
+ assert module._api_request_failures == 0
+ assert module.errored is True
+
+
+async def test_api_request_rate_limit_threshold_scales_with_keys(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner(config={"web": {"429_sleep_interval": 0}})
+ module = await _make_module(scan, api_keys=["key1", "key2", "key3"])
+ requests = _responder(blasthttp_mock, 429)
+ for _ in range(20):
+ await module.api_request(API_URL)
+ if module.errored:
+ break
+ assert module.api_rate_limit_abort_threshold == 30
+ assert len(requests) == 30
+ assert module.errored is True
+
+
+async def test_api_request_non_429_resets_rate_limit_count(bbot_scanner, blasthttp_mock):
+ """Any response other than a 429 resets the rate limit count. A real failure counts as a failure."""
+ scan = bbot_scanner(config={"web": {"429_sleep_interval": 0}})
+ module = await _make_module(scan)
+
+ _responder(blasthttp_mock, 429, 429, 200, 429, 429, 500)
+ await module.api_request(API_URL)
+ assert module._api_rate_limit_count == 0
+ assert module._api_request_failures == 0
+
+ await module.api_request(API_URL)
+ assert module._api_rate_limit_count == 0
+ assert module._api_request_failures == 1
+ assert module.errored is False
+
+
+async def test_api_request_cycles_key_on_429(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner(config={"web": {"429_sleep_interval": 0}})
+ module = await _make_module(scan, api_keys=["key1", "key2"])
+ requests = _responder(blasthttp_mock, 429, 200)
+ r = await module.api_request(API_URL)
+ assert r.status_code == 200
+ assert [str(req.url) for _, req in requests] == [
+ "https://api.evilcorp.com/lookup?key=key1",
+ "https://api.evilcorp.com/lookup?key=key2",
+ ]
+ assert module._api_rate_limit_count == 0
+
+
+async def test_api_request_obeys_retry_after_across_handlers(bbot_scanner, blasthttp_mock):
+ """A Retry-After received by one caller holds back every caller in the module."""
+ scan = bbot_scanner()
+ module = await _make_module(scan)
+ requests = []
+
+ def callback(request):
+ requests.append(time.monotonic())
+ if len(requests) == 1:
+ return MockResponse(status_code=429, headers={"Retry-After": "1"})
+ return MockResponse(status_code=200)
+
+ blasthttp_mock.add_callback(callback)
+
+ first = asyncio.create_task(module.api_request(API_URL))
+ # let the first caller receive its 429 before the second one starts
+ while not requests:
+ await asyncio.sleep(0.01)
+ await asyncio.sleep(0.05)
+ second = asyncio.create_task(module.api_request(API_URL))
+ await asyncio.gather(first, second)
+
+ assert len(requests) == 3
+ # both follow-up requests waited out the Retry-After
+ assert all(t - requests[0] >= 1 for t in requests[1:])
+
+
+async def test_api_request_backs_off_between_failures(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner()
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, "timeout")
+ await module.api_request(API_URL)
+ times = [t for t, _ in requests]
+ assert len(times) == 3
+ assert times[1] - times[0] >= 0.05
+ assert times[2] - times[1] >= 0.1
+ assert module._api_request_failures == 3
+
+
+async def test_api_request_404_is_not_a_failure(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner()
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, 404)
+ for _ in range(module.api_failure_abort_threshold + 5):
+ await module.api_request(API_URL)
+ assert len(requests) == module.api_failure_abort_threshold + 5
+ assert module._api_request_failures == 0
+ assert module.errored is False
+
+
+async def test_api_request_ping_does_not_wait_on_429(bbot_scanner, blasthttp_mock):
+ """With retry_on_http_429=False (setup pings), a 429 returns right away and isn't counted."""
+ scan = bbot_scanner()
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, 429)
+ start = time.monotonic()
+ r = await module.api_request(API_URL, retry_on_http_429=False)
+ assert time.monotonic() - start < 1
+ assert r.status_code == 429
+ assert len(requests) == 1
+ assert module._api_rate_limit_count == 0
+ assert module._api_rate_limited_until == 0
+
+
+async def test_api_request_user_agent(bbot_scanner, blasthttp_mock):
+ scan = bbot_scanner(config={"web": {"user_agent_suffix": "engagement-1234"}})
+ module = await _make_module(scan)
+ requests = _responder(blasthttp_mock, 200)
+ await module.api_request(API_URL)
+ await module.api_request(API_URL, headers={"User-Agent": "custom"})
+ user_agents = [dict(req.headers).get("User-Agent") for _, req in requests]
+ assert user_agents == [f"BBOT/{__version__}", "custom"]
+
+
+async def test_api_request_retry_after_parsing(bbot_scanner):
+ scan = bbot_scanner()
+ module = await _make_module(scan)
+ assert module._get_retry_after(MockResponse(status_code=429, headers={"Retry-After": "5"})) == 5
+ assert module._get_retry_after(MockResponse(status_code=429, headers={"Retry-After": "1.5"})) == 1.5
+ # a zero or negative Retry-After is raised to one second
+ assert module._get_retry_after(MockResponse(status_code=429, headers={"Retry-After": "0"})) == 1
+ # an HTTP date in the past is also raised to one second, rather than raising an error
+ date = "Wed, 21 Oct 2015 07:28:00 GMT"
+ assert module._get_retry_after(MockResponse(status_code=429, headers={"Retry-After": date})) == 1
+ assert module._get_retry_after(MockResponse(status_code=429, headers={"Retry-After": "garbage"})) is None
+ assert module._get_retry_after(MockResponse(status_code=429)) is None
diff --git a/bbot/test/test_step_1/test_validate_preset.py b/bbot/test/test_step_1/test_validate_preset.py
index be95d985c..5b2481191 100644
--- a/bbot/test/test_step_1/test_validate_preset.py
+++ b/bbot/test/test_step_1/test_validate_preset.py
@@ -325,9 +325,40 @@ def test_validate_preset_baddns_subclass_severity_is_validated():
assert "Expected one of" in errs[0].message
-def test_validate_preset_shodan_idb_retries_is_int():
- """shodan_idb.retries is numeric; the natural `retries: 3` must validate (was typed str)."""
- assert validate_preset({"config": {"modules": {"shodan_idb": {"retries": 3}}}}) == []
+def test_validate_preset_deprecated_options_still_validate():
+ """Deprecated options are ignored, but presets that still set them must keep validating."""
+ for module in ("shodan_idb", "discord", "slack", "teams"):
+ assert validate_preset({"config": {"modules": {module: {"retries": 3}}}}) == []
+
+
+def test_deprecated_options_have_no_defaults():
+ from bbot.core.modules import MODULE_LOADER
+
+ for module in ("shodan_idb", "discord", "slack", "teams"):
+ assert "retries" not in MODULE_LOADER.preloaded()[module]["config"]
+
+
+def test_find_deprecated_config():
+ from bbot.core.modules import MODULE_LOADER
+ from bbot.core.config.models import find_deprecated_config
+
+ config = {
+ "web": {"http_retries": 1},
+ "modules": {"slack": {"retries": 5, "webhook_url": "https://example.com"}, "shodan_idb": {"retries": 2}},
+ }
+ assert sorted(find_deprecated_config(config, MODULE_LOADER.config_schema)) == [
+ "modules.shodan_idb.retries",
+ "modules.slack.retries",
+ ]
+ assert find_deprecated_config({"modules": {"slack": {"webhook_url": "x"}}}, MODULE_LOADER.config_schema) == []
+
+
+async def test_deprecated_option_warns_at_scan_start(caplog):
+ from bbot.scanner import Scanner
+
+ scan = Scanner(config={"modules": {"shodan_idb": {"retries": 3}}})
+ await scan._prep()
+ assert 'Config option "modules.shodan_idb.retries" is deprecated and will be ignored' in caplog.text
def test_validate_preset_lightfuzz_avoid_wafs_accepts_bool():
diff --git a/bbot/test/test_step_2/module_tests/test_module_webhook.py b/bbot/test/test_step_2/module_tests/test_module_webhook.py
index 769b9254a..261ed5925 100644
--- a/bbot/test/test_step_2/module_tests/test_module_webhook.py
+++ b/bbot/test/test_step_2/module_tests/test_module_webhook.py
@@ -52,3 +52,57 @@ class TestWebhook(ModuleTestBase):
assert self.headers_correct is True
assert self.method_correct is True
assert self.url_correct is True
+
+
+class TestWebhookGivesUp(TestWebhook):
+ """A webhook endpoint that always fails must not hang the scan; the module errors out instead."""
+
+ module_name = "webhook"
+ # enough events to reach the failure threshold
+ targets = ["blacklanternsecurity.com", "evilcorp.com", "evilcorp.net", "evilcorp.org"]
+
+ async def setup_after_prep(self, module_test):
+ module_test.module._api_retry_backoff = 0.01
+ self.requests = 0
+
+ async def custom_callback(request):
+ self.requests += 1
+ return MockResponse(status_code=500)
+
+ module_test.blasthttp_mock.add_callback(custom_callback)
+
+ def check(self, module_test, events):
+ assert self.requests == module_test.module.api_failure_abort_threshold
+ assert module_test.module.errored is True
+
+
+class TestWebhookSSLVerify(TestWebhook):
+ """By default the webhook follows web.ssl_verify_infrastructure, like other API calls."""
+
+ module_name = "webhook"
+ expected_ssl_verify = True
+
+ async def setup_after_prep(self, module_test):
+ await super().setup_after_prep(module_test)
+ self.ssl_verify = []
+ web = module_test.scan.helpers.web
+ original_request = web.request
+
+ async def recording_request(*args, **kwargs):
+ self.ssl_verify.append(kwargs.get("ssl_verify"))
+ return await original_request(*args, **kwargs)
+
+ web.request = recording_request
+
+ def check(self, module_test, events):
+ super().check(module_test, events)
+ assert self.ssl_verify and all(v is self.expected_ssl_verify for v in self.ssl_verify)
+
+
+class TestWebhookSSLVerifyOverride(TestWebhookSSLVerify):
+ """The module's ssl_verify option overrides the global setting."""
+
+ config_overrides = {
+ "modules": {"webhook": {**TestWebhook.config_overrides["modules"]["webhook"], "ssl_verify": False}}
+ }
+ expected_ssl_verify = False