From ff0a57aa939742d96acfa9d23c5481a450f93b3b Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Tue, 20 Sep 2022 14:24:30 -0400 Subject: [PATCH] Island: Add initialize_machine_repository() --- .../monkey_island/cc/repository/__init__.py | 2 ++ monkey/monkey_island/cc/repository/utils.py | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 monkey/monkey_island/cc/repository/utils.py diff --git a/monkey/monkey_island/cc/repository/__init__.py b/monkey/monkey_island/cc/repository/__init__.py index a172017f7..3840c3258 100644 --- a/monkey/monkey_island/cc/repository/__init__.py +++ b/monkey/monkey_island/cc/repository/__init__.py @@ -27,3 +27,5 @@ from .mongo_machine_repository import MongoMachineRepository from .mongo_agent_repository import MongoAgentRepository from .mongo_node_repository import MongoNodeRepository from .mongo_agent_event_repository import MongoAgentEventRepository + +from .utils import initialize_machine_repository diff --git a/monkey/monkey_island/cc/repository/utils.py b/monkey/monkey_island/cc/repository/utils.py new file mode 100644 index 000000000..1a2decff3 --- /dev/null +++ b/monkey/monkey_island/cc/repository/utils.py @@ -0,0 +1,34 @@ +import platform +from socket import gethostname +from uuid import getnode + +from common import OperatingSystem +from common.network.network_utils import get_network_interfaces +from monkey_island.cc.models import Machine + +from . import IMachineRepository, UnknownRecordError + + +def initialize_machine_repository(machine_repository: IMachineRepository): + """ + Populate an IMachineRepository with island machine data + + If the island is not already present in the IMachineRepository, add it. + + :param machine_repository: The repository to populate + :raises StorageError: If an error occurs while attempting to store data in the repository + """ + hardware_id = getnode() + + try: + machine_repository.get_machine_by_hardware_id(hardware_id) + except UnknownRecordError: + machine = Machine( + id=machine_repository.get_new_id(), + hardware_id=hardware_id, + network_interfaces=get_network_interfaces(), + operating_system=OperatingSystem(platform.system().lower()), + operating_system_version=platform.version(), + hostname=gethostname(), + ) + machine_repository.upsert_machine(machine)