The recursive internet scanner for hackers. 🧡
Python asmattack-surface-managementautomationbugbountyclieasmhackingneo4josintosint-frameworkpentestingpythonreconrecursionscannersubdomain-enumerationsubdomain-scannersubdomainsthreat-intelligencethreatintel
Convert dnsdumpster to the authenticated API (#3458)
Paul Mueller85ff8e77f88c
diff --git a/bbot/modules/dnsdumpster.py b/bbot/modules/dnsdumpster.pyindex 63fd34b59..7740341d2 100644--- a/bbot/modules/dnsdumpster.py+++ b/bbot/modules/dnsdumpster.py@@ -1,9 +1,8 @@-import json+from bbot.modules.templates.subdomain_enum import subdomain_enum_apikey+from bbot.core.config.models import BaseModuleConfig, Field-from bbot.modules.templates.subdomain_enum import subdomain_enum--class dnsdumpster(subdomain_enum):+class dnsdumpster(subdomain_enum_apikey):watched_events = ["DNS_NAME"]produced_events = ["DNS_NAME"]flags = ["safe", "subdomain-enum", "passive"]@@ -13,63 +12,48 @@ class dnsdumpster(subdomain_enum):"author": "@TheTechromancer",}- base_url = "https://dnsdumpster.com"-- async def setup(self):- self.apikey_regex = self.helpers.re.compile(r'<form[^>]*data-form-id="mainform"[^>]*hx-headers=\'([^\']*)\'')- return True-- async def query(self, domain):- ret = []- # first, get the JWT token from the main page- res1 = await self.api_request(self.base_url)- status_code = getattr(res1, "status_code", 0)- if status_code not in [200]:- self.verbose(f'Bad response code "{status_code}" from DNSDumpster')- return ret+ class Config(BaseModuleConfig):+ api_key: str | list[str] = Field("", description="DNSDumpster API key", sensitive=True, mandatory=True)+ max_pages: int = Field(10, description="Maximum result pages to request per domain")- # Extract JWT token from the form's hx-headers attribute using regex- jwt_token = None- try:- # Look for the form with data-form-id="mainform" and extract hx-headers- form_match = await self.helpers.re.search(self.apikey_regex, res1.text)- if form_match:- headers_json = form_match.group(1)- headers_data = json.loads(headers_json)- jwt_token = headers_data.get("Authorization")- except (AttributeError, json.JSONDecodeError, KeyError):- self.log.warning("Error obtaining JWT token")- return ret+ base_url = "https://api.dnsdumpster.com"- # Abort if we didn't get the JWT token- if not jwt_token:- self.verbose("Error obtaining JWT token")- self.errorState = True- return ret- else:- self.debug("Successfully obtained JWT token")-- if self.scan.stopping:- return ret-- # Query the API with the JWT token- res2 = await self.api_request(- "https://api.dnsdumpster.com/htmld/",- method="POST",- data={"target": str(domain).lower()},- headers={- "Authorization": jwt_token,- "Content-Type": "application/x-www-form-urlencoded",- "Origin": "https://dnsdumpster.com",- "Referer": "https://dnsdumpster.com/",- "HX-Request": "true",- "HX-Target": "results",- "HX-Current-URL": "https://dnsdumpster.com/",- },- )- status_code = getattr(res2, "status_code", 0)- if status_code not in [200]:- self.verbose(f'Bad response code "{status_code}" from DNSDumpster API')- return ret-- return await self.scan.extract_in_scope_hostnames(res2.text)+ async def setup(self):+ self.max_pages = self.config.get("max_pages", 10)+ return await super().setup()++ def prepare_api_request(self, url, kwargs):+ kwargs["headers"]["X-API-Key"] = self.api_key+ return url, kwargs++ async def query(self, query):+ results = set()+ a_records = 0+ for page in range(1, self.max_pages + 1):+ # page 1 is the bare URL; the API only accepts an explicit page number from 2 on+ url = f"{self.base_url}/domain/{query}"+ if page > 1:+ url = f"{url}?page={page}"+ r = await self.api_request(url)+ if r is None:+ self.verbose(f'No response for "{query}" (page {page})')+ break+ if page > 1 and r.status_code in (401, 403):+ self.verbose(f"Paging past the first page requires a paid membership (HTTP {r.status_code})")+ break+ try:+ data = r.json()+ except Exception:+ self.verbose(f'Error parsing JSON for "{query}" (HTTP {r.status_code})')+ break+ if not isinstance(data, dict):+ self.verbose(f'Unexpected response for "{query}" (HTTP {r.status_code}): {r.text[:200]}')+ break+ results.update(await self.scan.extract_in_scope_hostnames(r.text))+ # the response reports how many A records exist in total; stop once they have all been seen+ page_a_records = len(data.get("a") or [])+ a_records += page_a_records+ total = data.get("total_a_recs")+ if not isinstance(total, int) or not page_a_records or a_records >= total:+ break+ return resultsdiff --git a/bbot/test/test_step_2/module_tests/test_module_dnsdumpster.py b/bbot/test/test_step_2/module_tests/test_module_dnsdumpster.pyindex 5de39cb0b..432ea0e5f 100644--- a/bbot/test/test_step_2/module_tests/test_module_dnsdumpster.py+++ b/bbot/test/test_step_2/module_tests/test_module_dnsdumpster.py@@ -1,15 +1,99 @@+import json+from .base import ModuleTestBase+BASE_URL = "https://api.dnsdumpster.com/domain/blacklanternsecurity.com"+++def page(hosts, total=None, txt=()):+ """A response page shaped like the live API's, with `total_a_recs` defaulting to this page's A records."""+ records = [{"host": h, "ips": [{"ip": "127.0.0.1"}]} for h in hosts]+ body = {+ "a": records,+ "cname": [],+ "mx": [{"host": "0 mail.blacklanternsecurity.com", "ips": []}],+ "ns": [],+ "txt": list(txt),+ "total_a_recs": len(records) if total is None else total,+ }+ return json.dumps(body).encode()+class TestDNSDumpster(ModuleTestBase):+ """Pages are requested until every A record in `total_a_recs` has been seen."""++ config_overrides = {"modules": {"dnsdumpster": {"api_key": "asdf"}}}++ async def setup_after_prep(self, module_test):+ module_test.blasthttp_mock.add_response(url=BASE_URL, content=page(["asdf.blacklanternsecurity.com"], total=2))+ module_test.blasthttp_mock.add_response(+ url=f"{BASE_URL}?page=2", content=page(["qwerty.blacklanternsecurity.com"], total=2)+ )+ module_test.blasthttp_mock.add_response(+ url=f"{BASE_URL}?page=3", content=page(["unrequested.blacklanternsecurity.com"], total=2)+ )++ def check(self, module_test, events):+ assert any(e.data == "asdf.blacklanternsecurity.com" for e in events), "Failed to detect subdomain"+ assert any(e.data == "qwerty.blacklanternsecurity.com" for e in events), "Failed to paginate"+ assert not any(e.data == "unrequested.blacklanternsecurity.com" for e in events), "Paged past the total"+++class TestDNSDumpsterSinglePage(ModuleTestBase):+ """A first page holding every A record must not trigger a second request. Hostnames outside the host fields are kept."""++ modules_overrides = ["dnsdumpster"]+ config_overrides = {"modules": {"dnsdumpster": {"api_key": "asdf"}}}++ async def setup_after_prep(self, module_test):+ module_test.blasthttp_mock.add_response(+ url=BASE_URL,+ content=page(["asdf.blacklanternsecurity.com"], txt=["v=spf1 include:spf.blacklanternsecurity.com ~all"]),+ )+ module_test.blasthttp_mock.add_response(+ url=f"{BASE_URL}?page=2", content=page(["unrequested.blacklanternsecurity.com"])+ )++ def check(self, module_test, events):+ assert any(e.data == "asdf.blacklanternsecurity.com" for e in events), "Failed to detect subdomain"+ assert any(e.data == "spf.blacklanternsecurity.com" for e in events), "Failed to extract hostname from TXT"+ assert any(e.data == "mail.blacklanternsecurity.com" for e in events), "Failed to extract MX host"+ assert not any(e.data == "unrequested.blacklanternsecurity.com" for e in events), "Requested a second page"+++class TestDNSDumpsterNoTotal(ModuleTestBase):+ """Without `total_a_recs` there is no way to know more pages exist, so only the first is requested."""++ modules_overrides = ["dnsdumpster"]+ config_overrides = {"modules": {"dnsdumpster": {"api_key": "asdf"}}}++ async def setup_after_prep(self, module_test):+ body = json.loads(page(["asdf.blacklanternsecurity.com"]))+ del body["total_a_recs"]+ module_test.blasthttp_mock.add_response(url=BASE_URL, content=json.dumps(body).encode())+ module_test.blasthttp_mock.add_response(+ url=f"{BASE_URL}?page=2", content=page(["unrequested.blacklanternsecurity.com"])+ )++ def check(self, module_test, events):+ assert any(e.data == "asdf.blacklanternsecurity.com" for e in events), "Failed to detect subdomain"+ assert not any(e.data == "unrequested.blacklanternsecurity.com" for e in events), "Requested a second page"+++class TestDNSDumpsterFreeTier(ModuleTestBase):+ """A free key gets 401 when it asks for page 2; results so far are still kept."""++ modules_overrides = ["dnsdumpster"]+ config_overrides = {"modules": {"dnsdumpster": {"api_key": "asdf"}}}+async def setup_after_prep(self, module_test):module_test.blasthttp_mock.add_response(- url="https://dnsdumpster.com",- content=b"""<form data-form-id="mainform" class="mb-6" hx-post="https://api.dnsdumpster.com/htmld/" hx-target="#results" hx-headers='{"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjAsImlhdCI6MTc1OTAxODczOCwiZXhwIjoxNzU5MDE5NjM4LCJkYXRhIjoiZmMxMDcwOTVjYmRjN2Y5YjU1ZWJiM2ZlZGViNWQ5Y2M5MWU1NmEzNGEwYzliNzM5ZjRlYzg2Mjk4MmM0ZDI5YSIsIm1lbWJlcl9zdGF0dXMiOiJmcmVlIn0.7NWBC6TFSaDZH-_VKqDoXqv3nH4a1k30NUxrijg1KqI"}'><div class="form-group">""",+ url=BASE_URL, content=page(["asdf.blacklanternsecurity.com"], total=200))module_test.blasthttp_mock.add_response(- url="https://api.dnsdumpster.com/htmld/",- content=b"asdf.blacklanternsecurity.com",+ url=f"{BASE_URL}?page=2",+ status_code=401,+ content=b'{"error":"pagination requires plus or max membership"}',)def check(self, module_test, events):diff --git a/docs/modules/list_of_modules.md b/docs/modules/list_of_modules.mdindex 288416b87..66027149b 100644--- a/docs/modules/list_of_modules.md+++ b/docs/modules/list_of_modules.md@@ -78,7 +78,7 @@| dehashed | scan | Yes | Execute queries against dehashed.com for exposed credentials | email-enum, passive, safe | DNS_NAME | EMAIL_ADDRESS, HASHED_PASSWORD, PASSWORD, USERNAME | @SpamFaux | 2023-10-12 || dnsbimi | scan | No | Check DNS_NAME's for BIMI records to find image and certificate hosting URL's | cloud-enum, passive, safe, subdomain-enum | DNS_NAME | RAW_DNS_RECORD, URL_UNVERIFIED | @colin-stubbs | 2024-11-15 || dnscaa | scan | No | Check for CAA records | email-enum, passive, safe, subdomain-enum | DNS_NAME | DNS_NAME, EMAIL_ADDRESS, URL_UNVERIFIED | @colin-stubbs | 2024-05-26 |-| dnsdumpster | scan | No | Query dnsdumpster for subdomains | passive, safe, subdomain-enum | DNS_NAME | DNS_NAME | @TheTechromancer | 2022-03-12 |+| dnsdumpster | scan | Yes | Query dnsdumpster for subdomains | passive, safe, subdomain-enum | DNS_NAME | DNS_NAME | @TheTechromancer | 2022-03-12 || dnstlsrpt | scan | No | Check for TLS-RPT records | cloud-enum, email-enum, passive, safe, subdomain-enum | DNS_NAME | EMAIL_ADDRESS, RAW_DNS_RECORD, URL_UNVERIFIED | @colin-stubbs | 2024-07-26 || docker_pull | scan | No | Download images from a docker repository | code-enum, download, passive, safe, slow | CODE_REPOSITORY | FILESYSTEM | @domwhewell-sage | 2024-03-24 || dockerhub | scan | No | Search for docker repositories of discovered orgs/usernames | code-enum, passive, safe | ORG_STUB, SOCIAL | CODE_REPOSITORY, SOCIAL, URL_UNVERIFIED | @domwhewell-sage | 2024-03-12 |diff --git a/docs/scanning/configuration.md b/docs/scanning/configuration.mdindex b94a1d9d8..2f8272988 100644--- a/docs/scanning/configuration.md+++ b/docs/scanning/configuration.md@@ -637,6 +637,8 @@ In addition to the stated options for each module, the following universal optio| modules.dnscaa.emails | bool | emit EMAIL_ADDRESS events | True || modules.dnscaa.in_scope_only | bool | Only check in-scope domains | True || modules.dnscaa.urls | bool | emit URL_UNVERIFIED events | True |+| modules.dnsdumpster.api_key | str | list[str] | DNSDumpster API key | |+| modules.dnsdumpster.max_pages | int | Maximum result pages to request per domain | 10 || modules.dnstlsrpt.emit_emails | bool | Emit EMAIL_ADDRESS events | True || modules.dnstlsrpt.emit_raw_dns_records | bool | Emit RAW_DNS_RECORD events | False || modules.dnstlsrpt.emit_urls | bool | Emit URL_UNVERIFIED events | True |