From 89c6e2b7bc062f7f15082d93934809e59a175f7f Mon Sep 17 00:00:00 2001 From: Kekoa Kaaikala Date: Tue, 27 Sep 2022 18:58:13 +0000 Subject: [PATCH] Island: Extract methods in handle_scan_data --- .../agent_event_handlers/handle_scan_data.py | 46 ++++++++++--------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/monkey/monkey_island/cc/agent_event_handlers/handle_scan_data.py b/monkey/monkey_island/cc/agent_event_handlers/handle_scan_data.py index b3c7eee2b..b3a44085b 100644 --- a/monkey/monkey_island/cc/agent_event_handlers/handle_scan_data.py +++ b/monkey/monkey_island/cc/agent_event_handlers/handle_scan_data.py @@ -28,30 +28,34 @@ class handle_scan_data: def __call__(self, event: PingScanEvent): try: - # Get or create the destination machine - # NOTE: Assuming IP's are unique for now - if not isinstance(event.target, IPv4Address): - logger.error("Unable to process scan data: Unknown target") - return - dest_machines = self._machine_repository.get_machines_by_ip(event.target) - if not dest_machines: - machine = Machine(id=self._machine_repository.get_new_id()) - dest_machines = [machine] - self._machine_repository.upsert_machine(machine) - - # Update the destination machine - dest_machine = dest_machines[0] - if event.scan_data.os is not None: - dest_machine.operating_system = event.scan_data.os - self._machine_repository.upsert_machine(dest_machine) - - # Get the source machine - agent = self._agent_repository.get_agent_by_id(event.source) - src_machine = self._machine_repository.get_machine_by_id(agent.machine_id) + dest_machine = self._get_destination_machine(event) + self._update_destination_machine(dest_machine, event) + src_machine = self._get_source_machine(event) # Update or create the node self._node_repository.upsert_communication( src_machine.id, dest_machine.id, CommunicationType.SCANNED ) - except (RetrievalError, StorageError, UnknownRecordError) as err: + except (RetrievalError, StorageError, TypeError, UnknownRecordError) as err: logger.error(f"Unable to process scan data: {err}") + + def _get_destination_machine(self, event: PingScanEvent) -> Machine: + # NOTE: Assuming IP's are unique for now + if not isinstance(event.target, IPv4Address): + raise TypeError("Unknown target") + dest_machines = self._machine_repository.get_machines_by_ip(event.target) + if not dest_machines: + machine = Machine(id=self._machine_repository.get_new_id()) + dest_machines = [machine] + self._machine_repository.upsert_machine(machine) + + return dest_machines[0] + + def _get_source_machine(self, event: PingScanEvent) -> Machine: + agent = self._agent_repository.get_agent_by_id(event.source) + return self._machine_repository.get_machine_by_id(agent.machine_id) + + def _update_destination_machine(self, machine: Machine, event: PingScanEvent): + if event.scan_data.os is not None: + machine.operating_system = event.scan_data.os + self._machine_repository.upsert_machine(machine)