Ejemplo n.º 1
0
    def _initialize_check(self):
        """Runs checks against virtualization software when a machine manager
        is initialized.
        @note: in machine manager modules you may override or superclass
               his method.
        @raise CuckooMachineError: if a misconfiguration or a unkown vm state
                                   is found.
        """
        try:
            configured_vms = self._list()
        except NotImplementedError:
            return

        for machine in self.machines():
            # If this machine is already in the "correct" state, then we
            # go on to the next machine.
            if machine.label in configured_vms and \
                    self._status(machine.label) in [self.POWEROFF, self.ABORTED]:
                continue

            # This machine is currently not in its correct state, we're going
            # to try to shut it down. If that works, then the machine is fine.
            try:
                self.stop(machine.label)
            except CuckooMachineError as e:
                msg = "Please update your configuration. Unable to shut " \
                      "'{0}' down or find the machine in its proper state:" \
                      " {1}".format(machine.label, e)
                raise CuckooCriticalError(msg)

        if not self.options_globals.timeouts.vm_state:
            raise CuckooCriticalError("Virtual machine state change timeout "
                                      "setting not found, please add it to "
                                      "the config file.")
Ejemplo n.º 2
0
    def __init__(self):
        ip = cfg.resultserver.ip
        port = cfg.resultserver.port
        pool_size = cfg.resultserver.pool_size

        sock = gevent.socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            sock.bind((ip, port))
        except (OSError, socket.error) as e:
            if e.errno == errno.EADDRINUSE:
                raise CuckooCriticalError(
                    "Cannot bind ResultServer on port %d "
                    "because it was in use, bailing." % port)
            elif e.errno == errno.EADDRNOTAVAIL:
                raise CuckooCriticalError(
                    "Unable to bind ResultServer on %s:%s %s. This "
                    "usually happens when you start Cuckoo without "
                    "bringing up the virtual interface associated with "
                    "the ResultServer IP address. Please refer to "
                    "https://cuckoo.sh/docs/faq/#troubles-problem "
                    "for more information." % (ip, port, e))
            else:
                raise CuckooCriticalError(
                    "Unable to bind ResultServer on %s:%s: %s" % (ip, port, e))

        # We allow user to specify port 0 to get a random port, report it back
        # here
        _, self.port = sock.getsockname()
        sock.listen(128)

        self.thread = Thread(target=self.create_server, args=(sock, pool_size))
        self.thread.daemon = True
        self.thread.start()
Ejemplo n.º 3
0
    def initialize(self):
        """Initialize the machine manager."""
        global machinery, machine_lock

        machinery_name = self.cfg.cuckoo.machinery

        max_vmstartup_count = self.cfg.cuckoo.max_vmstartup_count
        if max_vmstartup_count:
            machine_lock = threading.Semaphore(max_vmstartup_count)
        else:
            machine_lock = threading.Lock()

        log.info("Using \"%s\" as machine manager", machinery_name)

        # Get registered class name. Only one machine manager is imported,
        # therefore there should be only one class in the list.
        plugin = list_plugins("machinery")[0]
        # Initialize the machine manager.
        machinery = plugin()

        # Find its configuration file.
        conf = os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % machinery_name)

        if not os.path.exists(conf):
            raise CuckooCriticalError("The configuration file for machine "
                                      "manager \"{0}\" does not exist at path:"
                                      " {1}".format(machinery_name, conf))

        # Provide a dictionary with the configuration options to the
        # machine manager instance.
        machinery.set_options(Config(machinery_name))

        # Initialize the machine manager.
        try:
            machinery.initialize(machinery_name)
        except CuckooMachineError as e:
            raise CuckooCriticalError("Error initializing machines: %s" % e)

        # At this point all the available machines should have been identified
        # and added to the list. If none were found, Cuckoo needs to abort the
        # execution.
        if not len(machinery.machines()):
            raise CuckooCriticalError("No machines available.")
        else:
            log.info("Loaded %s machine/s", len(machinery.machines()))

        if len(machinery.machines()) > 1 and self.db.engine.name == "sqlite":
            log.warning("As you've configured Cuckoo to execute parallel "
                        "analyses, we recommend you to switch to a MySQL or"
                        "a PostgreSQL database as SQLite might cause some "
                        "issues.")

        if len(machinery.machines()) > 4 and self.cfg.cuckoo.process_results:
            log.warning("When running many virtual machines it is recommended "
                        "to process the results in a separate process.py to "
                        "increase throughput and stability. Please read the "
                        "documentation about the `Processing Utility`.")
Ejemplo n.º 4
0
    def _initialize_check(self):
        """Ensures that credentials have been entered into the config file.
        @raise CuckooCriticalError: if no credentials were provided or if
            one or more physical machines are offline.
        """
        if not self.options.physical.user or not self.options.physical.password:
            raise CuckooCriticalError("Physical machine credentials are missing, please add it to the config file")

        for machine in self.machines():
            if self._status(machine.label) != self.RUNNING:
                raise CuckooCriticalError("Physical machine is currently offline")
Ejemplo n.º 5
0
    def _initialize_check(self):
        """Runs all checks when a machine manager is initialized.
        @raise CuckooMachineError: if VBoxManage is not found.
        """
        # VirtualBox specific checks.
        if not self.options.virtualbox.path:
            raise CuckooCriticalError("VirtualBox VBoxManage path missing, please add it to the config file")
        if not os.path.exists(self.options.virtualbox.path):
            raise CuckooCriticalError(f'VirtualBox VBoxManage not found at specified path "{self.options.virtualbox.path}"')

        # Base checks.
        super(VirtualBox, self)._initialize_check()
Ejemplo n.º 6
0
    def _initialize_check(self):
        """Ensures that credentials have been entered into the config file.
        @raise CuckooCriticalError: if no credentials were provided
        """
        if not self.options.proxmox.username or not self.options.proxmox.password:
            raise CuckooCriticalError(
                "Proxmox credentials are missing, please add them to "
                "the Proxmox machinery configuration file.")
        if not self.options.proxmox.hostname:
            raise CuckooCriticalError("Proxmox hostname not set")

        super(Proxmox, self)._initialize_check()
Ejemplo n.º 7
0
    def initialize(self):
        """Initialize the machine manager."""
        global machinery

        machinery_name = self.cfg.cuckoo.machinery

        log.info("Using \"%s\" machine manager", machinery_name)

        # Get registered class name. Only one machine manager is imported,
        # therefore there should be only one class in the list.
        plugin = list_plugins("machinery")[0]
        # Initialize the machine manager.
        machinery = plugin()

        # Find its configuration file.
        conf = os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % machinery_name)

        if not os.path.exists(conf):
            raise CuckooCriticalError("The configuration file for machine "
                                      "manager \"{0}\" does not exist at path:"
                                      " {1}".format(machinery_name, conf))

        # Provide a dictionary with the configuration options to the
        # machine manager instance.
        machinery.set_options(Config(machinery_name))

        # Initialize the machine manager.
        try:
            machinery.initialize(machinery_name)
        except CuckooMachineError as e:
            raise CuckooCriticalError("Error initializing machines: %s" % e)

        # At this point all the available machines should have been identified
        # and added to the list. If none were found, Cuckoo needs to abort the
        # execution.
        if not len(machinery.machines()):
            raise CuckooCriticalError("No machines available.")
        else:
            log.info("Loaded %s machine/s", len(machinery.machines()))

        if len(machinery.machines()) > 1 and self.db.engine.name == "sqlite":
            log.warning("The SQLite database is not compatible with "
                        "multi-threaded use-cases such as running multiple "
                        "virtual machine in parallel. Please upgrade to "
                        "PostgreSQL or MySQL when running multiple VMs.")

        if len(machinery.machines()) > 3 and self.cfg.cuckoo.process_results:
            log.warning("When running many virtual machines it is recommended "
                        "to process the results in a separate process.py to "
                        "increase throughput and stability. Please read the "
                        "documentation about the `Processing Utility`.")
Ejemplo n.º 8
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.analysishandlers = {}

        ip = self.cfg.resultserver.ip
        self.port = int(self.cfg.resultserver.port)
        while True:
            try:
                server_addr = ip, self.port
                SocketServer.ThreadingTCPServer.__init__(self,
                                                         server_addr,
                                                         ResultHandler,
                                                         *args,
                                                         **kwargs)
            except Exception as e:
                if e.errno == errno.EADDRINUSE:
                    if self.cfg.resultserver.force_port is True:
                        raise CuckooCriticalError("Cannot bind ResultServer on port %d, "
                            "bailing." % self.port
                        )
                    else:
                        # In Linux /usr/include/asm-generic/errno-base.h.
                        # EADDRINUSE  98 (Address already in use)
                        # In Mac OS X or FreeBSD:
                        # EADDRINUSE 48 (Address already in use)
                        log.warning("Cannot bind ResultServer on port %s, "
                                        "trying another port.", self.port)
                        self.port += 1
                elif e.errno == errno.EADDRNOTAVAIL:
                    raise CuckooCriticalError(
                        "Unable to bind ResultServer on %s:%s %s. This "
                        "usually happens when you start Cuckoo without "
                        "bringing up the virtual interface associated with "
                        "the ResultServer IP address. Please refer to "
                        "https://cuckoo.sh/docs/faq/#troubles-problem"
                        " for more information." % (ip, self.port, e)
                    )
                else:
                    raise CuckooCriticalError(
                        "Unable to bind ResultServer on %s:%s: %s" %
                        (ip, self.port, e)
                    )
            else:
                log.debug("ResultServer running on {0}:{1}.".format(ip, self.port))
                self.servethread = Thread(target=self.serve_forever)
                self.servethread.setDaemon(True)
                self.servethread.start()
                break
Ejemplo n.º 9
0
    def _initialize_check(self):
        """Runs all checks when a machine manager is initialized.
        @raise CuckooMachineError: if QEMU binary is not found.
        """
        # VirtualBox specific checks.
        if not self.options.qemu.path:
            raise CuckooCriticalError("QEMU binary path missing, "
                                      "please add it to the config file")
        if not os.path.exists(self.options.qemu.path):
            raise CuckooCriticalError("QEMU binary not found at "
                                      "specified path \"%s\"" %
                                      self.options.qemu.path)

        self.qemu_dir = os.path.dirname(self.options.qemu.path)
        self.qemu_img = os.path.join(self.qemu_dir, "qemu-img")
Ejemplo n.º 10
0
    def fog_init(self):
        """Initiate by indexing FOG regarding all available machines."""
        self.fog_machines = {}
        if self.options.fog.hostname == "none":
            return

        # TODO Handle exceptions such as not being able to connect.

        # Parse the HTML.
        r = requests.get(f"http://{self.options.fog.hostname}/fog/status", headers=headers, verify=False)

        if r.status_code != 200:
            raise CuckooCriticalError(f"The FOG server answered with the status code {r.status_code}")

        r_hosts = requests.get(f"http://{self.options.fog.hostname}/fog/host", headers=headers, verify=False)
        hosts = r_hosts.json()["hosts"]
        hostnames = []
        for host in hosts:
            hostnames.append(host["name"])
            print(f"Host {host['name']} has MAC {host['macs'][0]}")

            # Check whether all our machines are available on FOG.
        for machine in self.machines():
            if machine.label not in hostnames:
                raise CuckooMachineError(
                    f"The physical machine {machine.label} has not been defined in FOG, "
                    "please investigate and configure the configuration correctly"
                )
Ejemplo n.º 11
0
    def fog_init(self):
        """Initiate by indexing FOG regarding all available machines."""
        self.fog_machines = {}
        if not HAVE_FOG or self.options.fog.hostname == "none":
            return

        # TODO Handle exceptions such as not being able to connect.
        r = self.fog_query("node=tasks&sub=listhosts")

        # Parse the HTML.
        b = bs4.BeautifulSoup(r.content, "html.parser")
        if not b.find_all("table"):
            raise CuckooCriticalError(
                "The supplied FOG username and/or password do not allow us "
                "to login into FOG, please configure the correct credentials.")

        # Mapping for physical machine hostnames to their mac address and uri
        # for "downloading" a safe image onto the host. Great piece of FOG API
        # usage here.
        for row in b.find_all("table")[0].find_all("tr")[1:]:
            hostname, macaddr, download, upload, advanced = row.find_all("td")
            self.fog_machines[hostname.text] = (
                macaddr.text,
                next(download.children).attrs["href"][1:],
            )

        # Check whether all our machines are available on FOG.
        for machine in self.machines():
            if machine.label not in self.fog_machines:
                raise CuckooMachineError(
                    "The physical machine %s has not been defined in FOG, "
                    "please investigate and configure the configuration "
                    "correctly." % machine.label)
Ejemplo n.º 12
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.tasks = {}
        self.analysishandlers = {}

	# CHANGED: Save info about APIs, BPs and times for each trigger.
	self.bps = []
	self.volshell_bps = []
	self.machinery = None
        try:
            server_addr = self.cfg.resultserver.ip, self.cfg.resultserver.port
            SocketServer.ThreadingTCPServer.__init__(self,
                                                     server_addr,
                                                     Resulthandler,
                                                     *args,
                                                     **kwargs)
        except Exception as e:
            raise CuckooCriticalError("Unable to bind result server on "
                                      "{0}:{1}: {2}".format(
                                          self.cfg.resultserver.ip,
                                          self.cfg.resultserver.port, str(e)))
        else:
            self.servethread = Thread(target=self.serve_forever)
            self.servethread.setDaemon(True)
            self.servethread.start()
Ejemplo n.º 13
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.analysishandlers = {}

        ip = self.cfg.resultserver.ip
        port = int(self.cfg.resultserver.port)
        while True:
            try:
                server_addr = ip, port
                SocketServer.ThreadingTCPServer.__init__(self,
                                                         server_addr,
                                                         Resulthandler,
                                                         *args,
                                                         **kwargs)
            except Exception as e:
                if e.errno == 98:
                    log.warning("Cannot bind  ResultServer on port {0}, "
                                "trying another one...".format(port))
                    port += 1
                else:
                    raise CuckooCriticalError("Unable to bind ResultServer on "
                                              "{0}:{1}: {2}".format(
                                                  ip,
                                                  port,
                                                  str(e)))
            else:
                log.debug("ResultServer running on {0}:{1}".format(ip, port))
                self.servethread = Thread(target=self.serve_forever)
                self.servethread.setDaemon(True)
                self.servethread.start()
                break
Ejemplo n.º 14
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.analysishandlers = {}

        ip = self.cfg.resultserver.ip
        port = int(self.cfg.resultserver.port)
        while True:
            try:
                server_addr = ip, port
                SocketServer.ThreadingTCPServer.__init__(
                    self, server_addr, ResultHandler, *args, **kwargs)
            except Exception as e:
                # In Linux /usr/include/asm-generic/errno-base.h.
                # EADDRINUSE  98 (Address already in use)
                # In Mac OS X or FreeBSD:
                # EADDRINUSE 48 (Address already in use)
                if e.errno == 98 or e.errno == 48:
                    log.warning("Cannot bind ResultServer on port {0}, "
                                "trying another port.".format(port))
                    port += 1
                else:
                    raise CuckooCriticalError("Unable to bind ResultServer on "
                                              "{0}:{1}: {2}".format(
                                                  ip, port, str(e)))
            else:
                log.debug("ResultServer running on {0}:{1}.".format(ip, port))
                self.servethread = Thread(target=self.serve_forever)
                self.servethread.setDaemon(True)
                self.servethread.start()
                break
Ejemplo n.º 15
0
    def start_emulator(self, label):
        emulator_port = str(self.options.get(label)["emulator_port"])

        task_id = self.get_task_id(label)
        if task_id is None:
            raise CuckooCriticalError(
                "android emulator failed starting the machine ,can't find task_id"
            )
        """Starts the emulator"""
        pcap_dump_path = os.path.join(CUCKOO_ROOT, "storage", "analyses",
                                      str(task_id), "dump.pcap")
        cmd = [
            self.options.avd.emulator_path, "@{0}".format(label),
            "-no-snapshot-save", "-netspeed", "full", "-netdelay", "none",
            "-port", emulator_port, "-tcpdump", pcap_dump_path
        ]

        # In headless mode we remove the skin, audio, and window support.
        if self.options.avd.mode == "headless":
            cmd += ["-no-skin", "-no-audio", "-no-window"]

        self.emulator_processes[label] = OSCommand.executeAsyncCommand(cmd)
        time.sleep(10)
        #if not self.__checkADBRecognizeEmu(label):
        self.restart_adb_server()
        # waits for device to be ready
        self.wait_for_device_ready(label)
Ejemplo n.º 16
0
    def _initialize_check(self):
        """Ensure that credentials have been entered into the config file.
        @raise CuckooCriticalError: if no credentials were provided or if
            one or more physical machines are offline.
        """
        # TODO This should be moved to a per-machine thing.
        if not self.options.physical.user or not self.options.physical.password:
            raise CuckooCriticalError(
                "Physical machine credentials are missing, please add it to "
                "the Physical machinery configuration file."
            )

        global headers
        headers = {
        "fog-api-token": self.options.fog.apikey,
        "fog-user-token": self.options.fog.user_apikey,
        "Content-Type": "application/json"
        }

        self.fog_init()

        for machine in self.machines():
            status = self._status(machine.label)
            if status == self.STOPPED:
                # Send a Wake On Lan message (if we're using FOG).
                self.wake_on_lan(machine.label)
            elif status == self.ERROR:
                raise CuckooMachineError(
                    "Unknown error occurred trying to obtain the status of "
                    "physical machine %s. Please turn it on and check the "
                    "Cuckoo Agent." % machine.label
                )
Ejemplo n.º 17
0
def import_plugin(name):
    try:
        module = __import__(name, globals(), locals(), ["dummy"], -1)
    except ImportError as e:
        raise CuckooCriticalError("Unable to import plugin "
                                  "\"{0}\": {1}".format(name, e))
    else:
        load_plugins(module)
Ejemplo n.º 18
0
 def _connect(self):
     try:
         self.auth = [[
             libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT
         ], self._auth_callback, None]
         return libvirt.openAuth(self.dsn, self.auth, 0)
     except libvirt.libvirtError as libvex:
         raise CuckooCriticalError(
             "libvirt returned an exception on connection: %s" % libvex)
Ejemplo n.º 19
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.analysishandlers = {}

        ip = self.cfg.resultserver.ip
        self.port = int(self.cfg.resultserver.port)
        while True:
            try:
                server_addr = ip, self.port
                SocketServer.ThreadingTCPServer.__init__(
                    self, server_addr, ResultHandler, *args, **kwargs
                )
            except Exception as e:
                if e.errno == errno.EADDRINUSE:
                    if self.cfg.resultserver.get("force_port"):
                        raise CuckooCriticalError(
                            "Cannot bind ResultServer on port %d, "
                            "bailing." % self.port
                        )
                    else:
                        log.warning("Cannot bind ResultServer on port %s, "
                                    "trying another port.", self.port)
                        self.port += 1
                elif e.errno == errno.EADDRNOTAVAIL:
                    raise CuckooCriticalError(
                        "Unable to bind ResultServer on %s:%s %s. This "
                        "usually happens when you start Cuckoo without "
                        "bringing up the virtual interface associated with "
                        "the ResultServer IP address. Please refer to "
                        "http://docs.cuckoosandbox.org/en/latest/faq/#troubles-problem"
                        " for more information." % (ip, self.port, e)
                    )
                else:
                    raise CuckooCriticalError(
                        "Unable to bind ResultServer on %s:%s: %s" %
                        (ip, self.port, e)
                    )
            else:
                log.debug("ResultServer running on %s:%s.", ip, self.port)
                self.servethread = threading.Thread(target=self.serve_forever)
                self.servethread.setDaemon(True)
                self.servethread.start()
                break
Ejemplo n.º 20
0
    def _auth_callback(self, credentials, user_data):
        for credential in credentials:
            if credential[0] == libvirt.VIR_CRED_AUTHNAME:
                credential[4] = self.options.esx.username
            elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT:
                credential[4] = self.options.esx.password
            else:
                raise CuckooCriticalError("ESX machinery did not recieve an object to inject a username or password into")

        return 0
Ejemplo n.º 21
0
    def fog_init(self):
        """Initiate by indexing FOG regarding all available machines."""
        self.fog_machines = {}
        if not HAVE_FOG or self.options.fog.hostname == "none":
            return

        # TODO Handle exceptions such as not being able to connect.
        r = self.fog_query("node=task&sub=listhosts")

        # Parse the HTML.
        b = bs4.BeautifulSoup(r.content, "html.parser")
        if not b.find_all("table"):
            raise CuckooCriticalError(
                "The supplied FOG username and/or password do not allow us "
                "to login into FOG, please configure the correct credentials.")

        # Pull out the FOG version from the header and raise error if it is not 1.3.4
        v = b.find("div", {"id": "version"})
        runningVer = re.match(r"Running Version\s+(([0-9]+\.)+[0-9]+)",
                              v.text).group(1)
        if runningVer != "1.3.4":  # This may be better suited to go in lib.cuckoo.common.constants
            raise CuckooCriticalError(
                "The current version of FOG was detected as %s. "
                "The only supported version is 1.3.4." % runningVer)

        # Mapping for physical machine hostnames to their mac address and uri
        # for "downloading" a safe image onto the host. Great piece of FOG API
        # usage here.
        for row in b.find_all("table")[0].find_all("tr")[1:]:
            hostinfo, imagename, actions = row.find_all("td")

            self.fog_machines[hostinfo.find("a").text] = (
                hostinfo.find("small").text,
                actions.find(title="Deploy").parent.attrs["href"][1:],
            )

        # Check whether all our machines are available on FOG.
        for machine in self.machines():
            if machine.label not in self.fog_machines:
                raise CuckooMachineError(
                    "The physical machine %s has not been defined in FOG, "
                    "please investigate and configure the configuration "
                    "correctly." % machine.label)
Ejemplo n.º 22
0
def import_plugin(name):
    try:
        module = __import__(name, globals(), locals(), ["dummy"], -1)
    except ImportError as e:
        raise CuckooCriticalError("Unable to import plugin " '"{0}": {1}'.format(name, e))

    for name, value in inspect.getmembers(module):
        if inspect.isclass(value):
            if issubclass(value, Machinery) and value is not Machinery and value is not LibVirtMachinery:
                return value
Ejemplo n.º 23
0
 def _global_connect(self):
     """
     set the single connection handle
     """
     try:
         self.auth = [[
             libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT
         ], self._auth_callback, None]
         return libvirt.openAuth(self.dsn, self.auth, 0)
     except libvirt.libvirtError as libvex:
         raise CuckooCriticalError(
             f"libvirt returned an exception on connection: {libvex}")
Ejemplo n.º 24
0
    def initialize(self):
        """Initialize the machine manager."""
        global machinery

        machinery_name = self.cfg.cuckoo.machinery

        log.info("Using \"%s\" machine manager", machinery_name)

        # Get registered class name. Only one machine manager is imported,
        # therefore there should be only one class in the list.
        plugin = list_plugins("machinery")[0]
        # Initialize the machine manager.
        machinery = plugin()

        # Find its configuration file.
        conf = os.path.join(CUCKOO_ROOT, "conf", "%s.conf" % machinery_name)

        if not os.path.exists(conf):
            raise CuckooCriticalError("The configuration file for machine "
                                      "manager \"{0}\" does not exist at path:"
                                      " {1}".format(machinery_name, conf))

        # Provide a dictionary with the configuration options to the
        # machine manager instance.
        machinery.set_options(Config(conf))

        # Initialize the machine manager.
        try:
            machinery.initialize(machinery_name)
        except CuckooMachineError as e:
            raise CuckooCriticalError("Error initializing machines: %s" % e)

        # At this point all the available machines should have been identified
        # and added to the list. If none were found, Cuckoo needs to abort the
        # execution.
        if not len(machinery.machines()):
            raise CuckooCriticalError("No machines available")
        else:
            log.info("Loaded %s machine/s", len(machinery.machines()))
Ejemplo n.º 25
0
    def _initialize_check(self):
        """Runs checks against virtualization software when a machine manager 
        is initialized.
        @note: in machine manager modules you may override or superclass 
               his method.
        @raise CuckooMachineError: if a misconfiguration or a unkown vm state
                                   is found.
        """
        try:
            configured_vm = self._list()
        except NotImplementedError:
            return

        for machine in self.machines():
            if machine.label not in configured_vm:
                raise CuckooCriticalError(
                    "Configured machine {0} was not detected or it's not in proper state"
                    .format(machine.label))

        if not self.options_globals.timeouts.vm_state:
            raise CuckooCriticalError(
                "Virtual machine state change timeout setting not found, please add it to the config file"
            )
Ejemplo n.º 26
0
    def _initialize_check(self):
        """Runs all checks when a machine manager is initialized.
        @raise CuckooMachineError: if the android emulator is not found.
        """
        self.emulator_processes = {}

        if not self.options.avd.emulator_path:
            raise CuckooCriticalError("emulator path missing, "
                                      "please add it to the config file")

        if not os.path.exists(self.options.avd.emulator_path):
            raise CuckooCriticalError("emulator not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.emulator_path)

        if not self.options.avd.adb_path:
            raise CuckooCriticalError("adb path missing, "
                                      "please add it to the config file")

        if not os.path.exists(self.options.avd.adb_path):
            raise CuckooCriticalError("adb not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.adb_path)

        if not self.options.avd.avd_path:
            raise CuckooCriticalError("avd path missing, "
                                      "please add it to the config file")

        if not os.path.exists(self.options.avd.avd_path):
            raise CuckooCriticalError("avd not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.avd_path)

        if not self.options.avd.reference_machine:
            raise CuckooCriticalError("reference machine path missing, "
                                      "please add it to the config file")

        machine_path = os.path.join(self.options.avd.avd_path,
                                    self.options.avd.reference_machine)
        if not os.path.exists("%s.avd" % machine_path) or \
                not os.path.exists("%s.ini" % machine_path):
            raise CuckooCriticalError("reference machine not found at "
                                      "specified path \"%s\"" % machine_path)
Ejemplo n.º 27
0
    def _initialize_check(self):
        """Runs all checks when a machine manager is initialized.
        @raise CuckooMachineError: if VBoxManage is not found.
        """
        #todo:remove
        #self.options = Config(os.path.join(CUCKOO_ROOT, "conf", "avd_new.conf"))

        #todo check!!!
        self.emulator_processes = {}

        if not self.options.avd.emulator_path:
            raise CuckooCriticalError("emulator path missing, "
                                      "please add it to the config file")
        if not os.path.exists(self.options.avd.emulator_path):
            raise CuckooCriticalError("emulator not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.emulator_path)

        if not self.options.avd.adb_path:
            raise CuckooCriticalError("adb path missing, "
                                      "please add it to the config file")
        if not os.path.exists(self.options.avd.adb_path):
            raise CuckooCriticalError("adb not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.adb_path)

        if not self.options.avd.avd_path:
            raise CuckooCriticalError("avd path missing, "
                                      "please add it to the config file")
        if not os.path.exists(self.options.avd.avd_path):
            raise CuckooCriticalError("avd not found at "
                                      "specified path \"%s\"" %
                                      self.options.avd.avd_path)

        if not self.options.avd.reference_machine:
            raise CuckooCriticalError("reference machine path missing, "
                                      "please add it to the config file")
        machine_path = os.path.join(self.options.avd.avd_path,
                                    self.options.avd.reference_machine)
        if not (os.path.exists(machine_path + ".avd")
                and os.path.exists(machine_path + ".ini")):
            raise CuckooCriticalError("reference machine not found at "
                                      "specified path \"%s\"" % machine_path)
Ejemplo n.º 28
0
    def __init__(self, *args, **kwargs):
        self.cfg = Config()
        self.analysistasks = {}
        self.analysishandlers = {}

        try:
            SocketServer.ThreadingTCPServer.__init__(
                self, (self.cfg.resultserver.ip, self.cfg.resultserver.port),
                Resulthandler, *args, **kwargs)
        except Exception as e:
            raise CuckooCriticalError(
                "Unable to bind result server on {0}:{1}: {2}".format(
                    self.cfg.resultserver.ip, self.cfg.resultserver.port,
                    str(e)))
        else:
            self.servethread = Thread(target=self.serve_forever)
            self.servethread.setDaemon(True)
            self.servethread.start()
Ejemplo n.º 29
0
    def _initialize_check(self):
        """Ensures that credentials have been entered into the config file.
        @raise CuckooCriticalError: if no credentials were provided or if
            one or more physical machines are offline.
        """
        # TODO This should be moved to a per-machine thing.
        if not self.options.physical.user or not self.options.physical.password:
            raise CuckooCriticalError(
                "Physical machine credentials are missing, please add it to "
                "the Physical machinery configuration file.")

        self.fog_init()

        for machine in self.machines():
            status = self._status(machine.label)
            if status == self.STOPPED:
                self.wake_on_lan(machine.label)
            elif status == self.ERROR:
                raise CuckooMachineError(
                    "Unknown error occurred trying to obtain the status of "
                    "physical machine %s. Please turn it on and check the "
                    "Cuckoo Agent." % machine.label)
Ejemplo n.º 30
0
    def _initialize(self, module_name):
        """Read configuration.
            @param module_name: module name.
        """
        super(KVMRemote, self)._initialize(module_name)

        hypervs_labels = self.options.get("kvmremote")["hypervisors"]
        hypervs_labels = ("".join(hypervs_labels.split())).split(",")

        for machine in self.machines():
            machine_cfg = self.options.get(machine.label)

            if machine_cfg.hypervisor:
                if machine_cfg.hypervisor not in hypervs_labels:
                    raise CuckooCriticalError(
                        "Unknown hypervisor %s for %s" %
                        (machine_cfg.hypervisor, machine.label))

                hyperv_cfg = self.options.get(machine_cfg.hypervisor)

                machine_cfg.dsn = hyperv_cfg.dsn
                machine_cfg.interface = hyperv_cfg.interface