The recursive internet scanner for hackers. 🧡
Python asmattack-surface-managementautomationbugbountyclieasmhackingneo4josintosint-frameworkpentestingpythonreconrecursionscannersubdomain-enumerationsubdomain-scannersubdomainsthreat-intelligencethreatintel
Let already-resolved events skip ahead in dnsresolve's queue (#3533)
Paul Mueller73eb9b12400b
diff --git a/bbot/core/helpers/async_helpers.py b/bbot/core/helpers/async_helpers.pyindex 4620dc834..526852c36 100644--- a/bbot/core/helpers/async_helpers.py+++ b/bbot/core/helpers/async_helpers.py@@ -4,6 +4,7 @@ import randomimport asyncioimport loggingimport functools+import itertoolsfrom contextlib import suppressfrom cachetools import keys, LRUCachefrom contextlib import asynccontextmanager@@ -20,6 +21,25 @@ class ShuffleQueue(asyncio.Queue):return self._queue.popleft()+class LaneQueue(asyncio.PriorityQueue):+ """+ A queue divided into lanes, where items in a lower lane are always dequeued before items in a higher one.++ `lane_fn` assigns each item its lane (an int). Items within the same lane are dequeued in FIFO order.+ """++ def __init__(self, lane_fn, maxsize=0):+ self._lane_fn = lane_fn+ self._sequence = itertools.count()+ super().__init__(maxsize)++ def _put(self, item):+ super()._put((self._lane_fn(item), next(self._sequence), item))++ def _get(self):+ return super()._get()[-1]++class _Lock(asyncio.Lock):def __init__(self, name):self.name = namediff --git a/bbot/modules/base.py b/bbot/modules/base.pyindex 2d553d35c..11ba12f63 100644--- a/bbot/modules/base.py+++ b/bbot/modules/base.py@@ -9,7 +9,7 @@ from datetime import datetime, timezonefrom ..core.helpers.misc import get_size # noqafrom ..errors import HttpCompareError, ValidationError, WebError-from ..core.helpers.async_helpers import TaskCounter, ShuffleQueue+from ..core.helpers.async_helpers import LaneQueue, TaskCounter, ShuffleQueuefrom ..core.event import is_eventfrom .. import __version__@@ -2051,6 +2051,18 @@ class BaseInterceptModule(BaseModule):"""return await self.incoming_event_queue.get()+ def make_intercept_queue(self):+ """+ Make the queue that feeds this module from the previous intercept module, divided into lanes by `incoming_lane()`+ """+ return LaneQueue(lambda item: self.incoming_lane(item[0]))++ def incoming_lane(self, event):+ """+ The lane an incoming event joins. Events in lower lanes are handled first.+ """+ return 0+async def forward_event(self, event, kwargs):"""Used for forwarding the event on to the next intercept modulediff --git a/bbot/modules/internal/dnsresolve.py b/bbot/modules/internal/dnsresolve.pyindex f4a5abae1..4abf2223a 100644--- a/bbot/modules/internal/dnsresolve.py+++ b/bbot/modules/internal/dnsresolve.py@@ -50,6 +50,13 @@ class DNSResolve(BaseInterceptModule):return True+ def incoming_lane(self, event):+ # events whose host was already resolved upstream skip ahead of hosts still awaiting resolution+ if not event.host:+ return 0+ dns_parent = self.find_dns_parent(event)+ return 0 if dns_parent is not None and dns_parent is not event else 1+async def filter_event(self, event):if (not event.host) or (event.type in ("IP_RANGE",)):return False, "event does not have host attribute"@@ -65,25 +72,23 @@ class DNSResolve(BaseInterceptModule):non_minimal_rdtypes = self.non_minimal_rdtypes# first, we find or create the main DNS_NAME or IP_ADDRESS associated with this event- main_host_event, in_target, blacklisted, new_event = self.get_dns_parent(event)+ main_host_event, new_event = self.get_dns_parent(event)original_tags = set(event.tags)# minimal resolution - first, we resolve A/AAAA records for scope purposes- if new_event or event is main_host_event:- await self.resolve_event(main_host_event, types=minimal_rdtypes)- # are any of its IPs in target scope or blacklisted?- in_target, blacklisted = self.check_scope(main_host_event)- if in_target and main_host_event.scope_distance > 0:- # when filter_ptrs is enabled, don't promote PTR-derived hostnames to in-scope- # this prevents rDNS results from triggering subdomain enumeration against unrelated domains- # (e.g. scanning 1.2.3.0/24 would otherwise enumerate every PTR parent like randomothercorp.com)- if self.filter_ptrs and "ptr" in main_host_event.tags:- self.debug(f"Not making {main_host_event} in-scope: PTR-derived hostname (filter_ptrs=true)")- else:- self.debug(- f"Making {main_host_event} in-scope because it resolves to an in-scope resource (A/AAAA)"- )- main_host_event.scope_distance = 0+ # done for every event, since a child can be handled before or alongside its parent (repeats are cache hits)+ await self.resolve_event(main_host_event, types=minimal_rdtypes)+ # are any of its IPs in target scope or blacklisted?+ in_target, blacklisted = self.check_scope(main_host_event)+ if in_target and main_host_event.scope_distance > 0:+ # when filter_ptrs is enabled, don't promote PTR-derived hostnames to in-scope+ # this prevents rDNS results from triggering subdomain enumeration against unrelated domains+ # (e.g. scanning 1.2.3.0/24 would otherwise enumerate every PTR parent like randomothercorp.com)+ if self.filter_ptrs and "ptr" in main_host_event.tags:+ self.debug(f"Not making {main_host_event} in-scope: PTR-derived hostname (filter_ptrs=true)")+ else:+ self.debug(f"Making {main_host_event} in-scope because it resolves to an in-scope resource (A/AAAA)")+ main_host_event.scope_distance = 0# abort if the event resolves to something blacklistedif blacklisted:@@ -333,22 +338,25 @@ class DNSResolve(BaseInterceptModule):except ValueError:continue+ def find_dns_parent(self, event):+ """+ Get the first DNS_NAME / IP_ADDRESS in an event's chain (including the event itself) with the same host, or None.+ """+ for parent in event.get_parents(include_self=True):+ if parent.host == event.host and parent.type in ("IP_ADDRESS", "DNS_NAME", "DNS_NAME_UNRESOLVED"):+ return parent+def get_dns_parent(self, event):"""Get the first parent DNS_NAME / IP_ADDRESS of an event. If one isn't found, create it.- Returns a 4-tuple of:+ Returns a 2-tuple of:- the parent event- - whether the parent is in target- - whether the parent is blacklisted- whether the parent is a new event, i.e. it is newly created or is the current event"""- for parent in event.get_parents(include_self=True):- if parent.host == event.host and parent.type in ("IP_ADDRESS", "DNS_NAME", "DNS_NAME_UNRESOLVED"):- blacklisted = any(t.startswith("dns-blacklisted-") for t in parent.tags)- in_target = any(t.startswith("dns-in-target-") for t in parent.tags)- new_event = parent is event- return parent, in_target, blacklisted, new_event+ parent = self.find_dns_parent(event)+ if parent is not None:+ return parent, parent is eventtags = set()if "seed" in event.tags:tags.add("seed")@@ -361,8 +369,6 @@ class DNSResolve(BaseInterceptModule):context="{event.parent.type} has host {event.type}: {event.host}",tags=tags,),- None,- None,True,)diff --git a/bbot/scanner/scanner.py b/bbot/scanner/scanner.pyindex 8bb8548cd..a61f74787 100644--- a/bbot/scanner/scanner.py+++ b/bbot/scanner/scanner.py@@ -414,7 +414,7 @@ class Scanner:self.debug(f"Setting intercept module {intercept_module.name}._incoming_event_queue to previous intercept module {prev_intercept_module.name}.outgoing_event_queue")- interqueue = asyncio.Queue()+ interqueue = intercept_module.make_intercept_queue()intercept_module._incoming_event_queue = interqueueprev_intercept_module._outgoing_event_queue = interqueuediff --git a/bbot/test/test_step_1/test_dns.py b/bbot/test/test_step_1/test_dns.pyindex aa5ac4524..78a3d29d0 100644--- a/bbot/test/test_step_1/test_dns.py+++ b/bbot/test/test_step_1/test_dns.py@@ -1007,3 +1007,241 @@ async def test_dns_brute_client_config(bbot_scanner, monkeypatch):# a DNS-disabled scan never resolves, so it must not be blocked by that checkscan = bbot_scanner(config={"dns": {"nameservers": ["not-an-ip"], "disable": True}})await scan._prep()+++async def test_dnsresolve_incoming_lanes(bbot_scanner):+ from bbot.core.helpers.async_helpers import LaneQueue++ scan = bbot_scanner("evilcorp.com")+ await scan._prep()+ dnsresolve = scan.modules["dnsresolve"]++ dns_name = scan.make_event("www.evilcorp.com", "DNS_NAME", parent=scan.root_event)+ open_port = scan.make_event("www.evilcorp.com:443", "OPEN_TCP_PORT", parent=dns_name)+ new_host_url = scan.make_event("http://new.evilcorp.com/", "URL_UNVERIFIED", parent=dns_name)+ finished = scan.make_event("FINISHED", "FINISHED", dummy=True)++ # hosts that still need resolving wait; hosts already resolved upstream (and hostless events) don't+ assert dnsresolve.incoming_lane(dns_name) == 1+ assert dnsresolve.incoming_lane(new_host_url) == 1+ assert dnsresolve.incoming_lane(open_port) == 0+ assert dnsresolve.incoming_lane(finished) == 0++ # the queue feeding dnsresolve is divided by those lanes+ queue = dnsresolve.incoming_event_queue+ assert isinstance(queue, LaneQueue)+ for event in (dns_name, new_host_url, open_port):+ queue.put_nowait((event, {}))+ assert [queue.get_nowait()[0] for _ in range(3)] == [open_port, dns_name, new_host_url]+++# a host and a child on that host, emitted together by one module (as urlscan and asset_inventory do)+parent_child_mock_data = {+ "evilcorp.com": {"A": ["127.0.0.1"]},+ "ok.evilcorp.com": {"A": ["127.0.0.3"]},+ # resolves to a blacklisted IP+ "bad.evilcorp.com": {"A": ["127.0.0.99"]},+ # in scope only because it resolves to a target IP+ "viaip.othercorp.net": {"A": ["127.0.1.5"]},+ # doesn't resolve+ "dead.evilcorp.com": {},+ # inside a wildcard zone+ r"regex:.*\.wild\.evilcorp\.com$": {"A": ["127.0.0.4"]},+}+parent_child_hosts = (+ "ok.evilcorp.com",+ "bad.evilcorp.com",+ "viaip.othercorp.net",+ "dead.evilcorp.com",+ "foo.wild.evilcorp.com",+)+++async def run_parent_child_scan(bbot_scanner, order):+ """+ Scan where a module emits each host in `parent_child_hosts` as a DNS_NAME plus an OPEN_TCP_PORT child of it.++ `order` controls the order dnsresolve handles them in:+ - "parent_first" / "child_first": one dnsresolve worker, FIFO queues, the given event emitted first+ - "lanes": one dnsresolve worker with its real lanes, held until every host and child is queued+ """+ import asyncio+ from bbot.modules.base import BaseModule++ class DummyModule(BaseModule):+ watched_events = ["DNS_NAME"]+ target_only = True++ async def handle_event(self, event):+ for host in parent_child_hosts:+ host_event = self.make_event(host, "DNS_NAME", parent=event)+ port_event = self.make_event(f"{host}:443", "OPEN_TCP_PORT", parent=host_event)+ pair = (port_event, host_event) if order == "child_first" else (host_event, port_event)+ for e in pair:+ await self.emit_event(e)++ scan = bbot_scanner(+ "evilcorp.com",+ "127.0.1.0/24",+ blacklist=["127.0.0.99"],+ config={"dns": {"threads": 1, "wildcard_ignore": []}},+ )+ await scan._prep()+ await scan.helpers.dns._mock_dns(parent_child_mock_data)+ dummy_module = DummyModule(scan)+ scan.modules["dummy_module"] = dummy_module+ dnsresolve = scan.modules["dnsresolve"]++ queue_filled = None+ if order == "lanes":+ # hold dnsresolve's only worker on the first of these events until the rest are queued behind it+ handle_event = dnsresolve.handle_event++ async def gated_handle_event(event, **kwargs):+ nonlocal queue_filled+ if queue_filled is None and event.host in parent_child_hosts:+ queue_filled = False+ for _ in range(100):+ if dnsresolve.incoming_event_queue.qsize() >= 2 * len(parent_child_hosts) - 1:+ queue_filled = True+ break+ await asyncio.sleep(0.05)+ return await handle_event(event, **kwargs)++ dnsresolve.handle_event = gated_handle_event+ else:+ # keep emission order all the way into dnsresolve+ dummy_module._outgoing_event_queue = asyncio.Queue()+ dnsresolve.incoming_lane = lambda event: 0++ events = [e async for e in scan.async_start()]+ if order == "lanes":+ assert queue_filled, "hosts and their children never queued up together"+ return events++[email protected]("order", ["parent_first", "child_first", "lanes"])+async def test_dnsresolve_parent_child_order(bbot_scanner, order):+ """A host and its child come out of dnsresolve the same way no matter which is handled first."""+ events = await run_parent_child_scan(bbot_scanner, order)++ def find(event_type, data):+ return [e for e in events if e.type == event_type and e.data == data]++ # the parent is resolved, not demoted to DNS_NAME_UNRESOLVED by its child's pass+ assert [e.type for e in events if e.host == "ok.evilcorp.com" and e.type.startswith("DNS_NAME")] == ["DNS_NAME"]+ # the child gets the parent's IPs and scope+ port = find("OPEN_TCP_PORT", "ok.evilcorp.com:443")+ assert len(port) == 1+ assert port[0].resolved_hosts == {"127.0.0.3"}+ assert port[0].scope_distance == 0++ # nothing on a host that resolves to a blacklisted IP gets into the scan+ assert not [e for e in events if e.host == "bad.evilcorp.com"]++ # a host that's in scope only through its IP brings its child into scope with it+ viaip = find("DNS_NAME", "viaip.othercorp.net")+ assert len(viaip) == 1+ assert viaip[0].scope_distance == 0+ port = find("OPEN_TCP_PORT", "viaip.othercorp.net:443")+ assert len(port) == 1+ assert port[0].scope_distance == 0+ assert port[0].resolved_hosts == {"127.0.1.5"}++ # a host that really doesn't resolve is still DNS_NAME_UNRESOLVED+ assert [e.type for e in events if e.host == "dead.evilcorp.com" and e.type.startswith("DNS_NAME")] == [+ "DNS_NAME_UNRESOLVED"+ ]+ port = find("OPEN_TCP_PORT", "dead.evilcorp.com:443")+ assert len(port) == 1+ assert not port[0].resolved_hosts++ # a wildcard host collapses (once per emitting module), and its child keeps its own host+ wild = [e.data for e in events if e.type.startswith("DNS_NAME") and e.data.endswith(".wild.evilcorp.com")]+ assert wild and set(wild) == {"_wildcard.wild.evilcorp.com"}+ port = find("OPEN_TCP_PORT", "foo.wild.evilcorp.com:443")+ assert len(port) == 1+ assert port[0].resolved_hosts == {"127.0.0.4"}++[email protected]("release", ["first_arrived_first", "last_arrived_first", "together"])+async def test_dnsresolve_parent_child_interleaved(bbot_scanner, release):+ """A host's DNS_NAME and its child give the same result when their lookups of that host overlap, in any order."""+ import asyncio+ from bbot.modules.base import BaseModule++ hosts = ("ok.evilcorp.com", "bad.evilcorp.com")++ class DummyModule(BaseModule):+ watched_events = ["DNS_NAME"]+ target_only = True++ async def handle_event(self, event):+ for host in hosts:+ host_event = self.make_event(host, "DNS_NAME", parent=event)+ await self.emit_event(host_event)+ await self.emit_event(f"{host}:443", "OPEN_TCP_PORT", parent=host_event)++ scan = bbot_scanner("evilcorp.com", blacklist=["127.0.0.99"])+ await scan._prep()+ await scan.helpers.dns._mock_dns(parent_child_mock_data)+ scan.modules["dummy_module"] = DummyModule(scan)++ # hold every A lookup of these hosts until both the DNS_NAME's pass and the child's pass are waiting on it+ dns = scan.helpers.dns+ resolve_multi_full = dns.resolve_multi_full+ waiting = {host: [] for host in hosts}+ all_waiting = {host: asyncio.Event() for host in hosts}++ async def held_resolve_multi_full(query, rdtypes):+ if query in waiting and "A" in rdtypes and len(waiting[query]) < 2:+ gate, done = asyncio.Event(), asyncio.Event()+ waiting[query].append((gate, done))+ if len(waiting[query]) == 2:+ all_waiting[query].set()+ await gate.wait()+ try:+ return await resolve_multi_full(query, rdtypes)+ finally:+ # set before returning, so the released pass applies its results before the next one is released+ done.set()+ return await resolve_multi_full(query, rdtypes)++ dns.resolve_multi_full = held_resolve_multi_full++ async def release_lookups(host):+ try:+ await asyncio.wait_for(all_waiting[host].wait(), timeout=10)+ except asyncio.TimeoutError:+ # only one pass looked the host up; let the scan finish so the assertions below report it+ for gate, _ in waiting[host]:+ gate.set()+ return+ lookups = list(waiting[host])+ if release == "last_arrived_first":+ lookups.reverse()+ if release == "together":+ for gate, _ in lookups:+ gate.set()+ else:+ for gate, done in lookups:+ gate.set()+ await done.wait()+ # let the released pass apply its results+ await asyncio.sleep(0.1)++ releasers = [asyncio.create_task(release_lookups(host)) for host in hosts]+ events = [e async for e in scan.async_start()]+ # both passes looked the host up themselves, and their lookups overlapped+ for task in releasers:+ await task+ assert all(len(lookups) == 2 for lookups in waiting.values())++ assert [e.type for e in events if e.host == "ok.evilcorp.com" and e.type.startswith("DNS_NAME")] == ["DNS_NAME"]+ port = [e for e in events if e.type == "OPEN_TCP_PORT" and e.data == "ok.evilcorp.com:443"]+ assert len(port) == 1+ assert port[0].resolved_hosts == {"127.0.0.3"}+ assert not [e for e in events if e.host == "bad.evilcorp.com"]diff --git a/bbot/test/test_step_1/test_helpers.py b/bbot/test/test_step_1/test_helpers.pyindex a8f7ae8b6..c3a53bc2f 100644--- a/bbot/test/test_step_1/test_helpers.py+++ b/bbot/test/test_step_1/test_helpers.py@@ -840,6 +840,33 @@ async def test_async_helpers():assert sorted(random_ints) == sorted(results)+async def test_lane_queue():+ from bbot.core.helpers.async_helpers import LaneQueue++ # lower lanes are dequeued first, and each lane is FIFO+ q = LaneQueue(lambda item: item[0])+ items = [(1, "a"), (0, "b"), (2, "c"), (0, "d"), (1, "e")]+ for item in items:+ q.put_nowait(item)+ assert q.qsize() == len(items)+ assert [q.get_nowait() for _ in items] == [(0, "b"), (0, "d"), (1, "a"), (1, "e"), (2, "c")]+ assert q.empty()++ # items with equal lanes are never compared to each other+ q = LaneQueue(lambda item: 0)+ q.put_nowait({"unorderable": 1})+ q.put_nowait({"unorderable": 2})+ assert q.get_nowait() == {"unorderable": 1}++ # maxsize still applies backpressure+ q = LaneQueue(lambda item: 0, maxsize=1)+ q.put_nowait("a")+ assert q.full()+ with pytest.raises(asyncio.QueueFull):+ q.put_nowait("b")++def test_portparse(helpers):assert helpers.parse_port_string("80,443,22") == [80, 443, 22]assert helpers.parse_port_string(80) == [80]diff --git a/bbot/test/test_step_2/module_tests/test_module_portscan.py b/bbot/test/test_step_2/module_tests/test_module_portscan.pyindex 85a1caecd..5298769fc 100644--- a/bbot/test/test_step_2/module_tests/test_module_portscan.py+++ b/bbot/test/test_step_2/module_tests/test_module_portscan.py@@ -1,3 +1,5 @@+import ipaddress+from .base import ModuleTestBase@@ -18,6 +20,29 @@ class TestPortscan(ModuleTestBase):masscan_output_2 = """{ "ip": "8.8.4.5", "timestamp": "1680197558", "ports": [ {"port": 80, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 54} ] }"""masscan_output_3 = """{ "ip": "8.8.4.6", "timestamp": "1680197558", "ports": [ {"port": 631, "proto": "tcp", "status": "open", "reason": "syn-ack", "ttl": 54} ] }"""+ expected_results = {+ ("DNS_NAME", "evilcorp.com"),+ ("DNS_NAME", "www.evilcorp.com"),+ ("DNS_NAME", "asdf.evilcorp.net"),+ ("DNS_NAME", "dummy.evilcorp.com"),+ ("DNS_NAME", "dummy.www.evilcorp.com"),+ ("DNS_NAME", "dummy.asdf.evilcorp.net"),+ ("IP_RANGE", "8.8.8.0/24"),+ ("IP_RANGE", "8.8.4.0/24"),+ ("IP_ADDRESS", "8.8.8.8"),+ ("IP_ADDRESS", "8.8.4.4"),+ ("IP_ADDRESS", "8.8.4.5"),+ ("IP_ADDRESS", "8.8.4.6"),+ ("OPEN_TCP_PORT", "8.8.8.8:443"),+ ("OPEN_TCP_PORT", "8.8.4.5:80"),+ ("OPEN_TCP_PORT", "8.8.4.6:631"),+ ("OPEN_TCP_PORT", "evilcorp.com:443"),+ ("OPEN_TCP_PORT", "www.evilcorp.com:443"),+ ("OPEN_TCP_PORT", "asdf.evilcorp.net:80"),+ ("OPEN_TCP_PORT", "dummy.asdf.evilcorp.net:80"),+ ("OPEN_TCP_PORT", "dummy.evilcorp.com:631"),+ }+masscan_output_ping = """{ "ip": "8.8.8.8", "timestamp": "1719862594", "ports": [ {"port": 0, "proto": "icmp", "status": "open", "reason": "none", "ttl": 54} ] }"""async def setup_after_prep(self, module_test):@@ -61,11 +86,15 @@ class TestPortscan(ModuleTestBase):else:self.syn_runs += 1self.syn_scanned += targets- if "8.8.8.0/24" in targets or "8.8.8.8/32" in targets:- yield self.masscan_output_1- if "8.8.4.0/24" in targets:- yield self.masscan_output_2- yield self.masscan_output_3+ # like real masscan, report an open port whenever its IP is covered by this run's targets+ networks = [ipaddress.ip_network(t) for t in targets]+ for ip, output in (+ ("8.8.8.8", self.masscan_output_1),+ ("8.8.4.5", self.masscan_output_2),+ ("8.8.4.6", self.masscan_output_3),+ ):+ if any(ipaddress.ip_address(ip) in n for n in networks):+ yield outputyield "]"else:async for l in module_test.scan.helpers.run_live(command, *args, **kwargs):@@ -110,12 +139,13 @@ class TestPortscan(ModuleTestBase):if e.type == "DNS_NAME" and e.data == "dummy.asdf.evilcorp.net" and str(e.module) == "dummy_module"])- # the reason these numbers aren't exactly predictable is because we can't predict which one arrives first- # to the portscan module. Sometimes, one that would normally be deduped is force-emitted because it led to a new open port.- assert 2 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.8.8"]) <= 4- assert 2 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.4"]) <= 4- assert 2 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.5"]) <= 4- assert 2 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.6"]) <= 4+ # how many IP_ADDRESS events there are depends on which parent an open port is first emitted under (a range,+ # or an IP that arrived first), but the distinct results don't+ assert 1 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.8.8"]) <= 4+ assert 1 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.4"]) <= 4+ assert 1 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.5"]) <= 4+ assert 1 <= len([e for e in events if e.type == "IP_ADDRESS" and e.data == "8.8.4.6"]) <= 4+ assert {(e.type, e.data) for e in events if e.type != "SCAN"} == self.expected_resultsassert 1 == len([e for e in events if e.type == "OPEN_TCP_PORT" and e.data == "8.8.8.8:443"])assert 1 == len([e for e in events if e.type == "OPEN_TCP_PORT" and e.data == "8.8.4.5:80"])assert 1 == len([e for e in events if e.type == "OPEN_TCP_PORT" and e.data == "8.8.4.6:631"])@@ -241,3 +271,36 @@ class TestPortscanSkipTags(ModuleTestBase):# the non-skipped host: portscan emitted 443 (real, non-internal), no speculated 80assert ("regular-host.com", 443) in consumer_seenassert ("regular-host.com", 80) not in consumer_seen+++class TestPortscanRangeLast(TestPortscan):+ """The results are the same when a range is scanned after a hostname inside it."""++ module_name = "portscan"++ async def setup_after_prep(self, module_test):+ await super().setup_after_prep(module_test)+ portscan = module_test.scan.modules["portscan"]+ handle_batch = portscan.handle_batch+ held_ranges = []+ asdf_scanned = False++ # hold back 8.8.4.0/24 until asdf.evilcorp.net (8.8.4.5) has been scanned on its own+ async def handle_batch_range_last(*events):+ nonlocal asdf_scanned+ held_ranges.extend(e for e in events if e.type == "IP_RANGE" and e.data == "8.8.4.0/24")+ events = [e for e in events if e not in held_ranges]+ if events:+ await handle_batch(*events)+ if any(e.type == "DNS_NAME" and e.data == "asdf.evilcorp.net" for e in events):+ asdf_scanned = True+ if asdf_scanned and held_ranges:+ ranges = list(held_ranges)+ held_ranges.clear()+ await handle_batch(*ranges)++ portscan.handle_batch = handle_batch_range_last++ def check(self, module_test, events):+ assert "8.8.4.5/32" in self.syn_scanned+ super().check(module_test, events)