예제 #1
0
    def test_get_settings_with_error(
        self, mock_check_output: MagicMock, _mock_logger: MagicMock
    ):
        mock_check_output.side_effect = subprocess.SubprocessError('foo')

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertFalse(settings)  # settings dict is empty

        mock_check_output.reset_mock()

        mock_check_output.side_effect = OSError('foo')

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertFalse(settings)  # settings dict is empty

        mock_check_output.reset_mock()

        # https://gehrcke.de/2015/12/how-to-raise-unicodedecodeerror-in-python-3/
        mock_check_output.side_effect = UnicodeDecodeError(
            'funnycodec', b'\x00\x00', 1, 2, 'This is just a fake reason!'
        )

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertFalse(settings)  # settings dict is empty
예제 #2
0
 def prepare_alive_test_option_for_openvas(self):
     """ Set alive test option. Overwrite the scan config settings.
     Check if test_alive_hosts_only feature of openvas is active.
     If active, put ALIVE_TEST enum in preferences. """
     settings = Openvas.get_settings()
     if settings:
         test_alive_hosts_only = settings.get('test_alive_hosts_only')
         if test_alive_hosts_only:
             if self.target_options.get('alive_test'):
                 try:
                     alive_test = int(self.target_options.get('alive_test'))
                 except ValueError:
                     logger.debug(
                         'Alive test settings not applied. '
                         'Invalid alive test value %s',
                         self.target_options.get('alive_test'),
                     )
                 # Put ALIVE_TEST enum in db, this is then taken
                 # by openvas to determine the method to use
                 # for the alive test.
                 if alive_test >= 1 and alive_test <= 31:
                     item = 'ALIVE_TEST|||%s' % str(alive_test)
                     self.kbdb.add_scan_preferences(self._openvas_scan_id,
                                                    [item])
         elif self.target_options.get('alive_test'):
             alive_test_opt = self.build_alive_test_opt_as_prefs(
                 self.target_options)
             self.kbdb.add_scan_preferences(self._openvas_scan_id,
                                            alive_test_opt)
예제 #3
0
    def get_database_address(cls) -> Optional[str]:
        if not cls._db_address:
            settings = Openvas.get_settings()

            cls._db_address = settings.get('db_address')

        return cls._db_address
예제 #4
0
 def prepare_alive_test_option_for_openvas(self):
     """ Set alive test option. Overwrite the scan config settings."""
     settings = Openvas.get_settings()
     if settings and self.target_options.get('alive_test'):
         alive_test_opt = self.build_alive_test_opt_as_prefs(
             self.target_options)
         self.kbdb.add_scan_preferences(self.scan_id, alive_test_opt)
    def __init__(self, metadata_path: str = None):

        openvas_object = Openvas()
        self.openvas_settings_dict = openvas_object.get_settings()
        self.__no_signature_check = self.openvas_settings_dict[
            "nasl_no_signature_check"]

        # Figure out the path to the metadata
        if not metadata_path:
            self.__metadata_path = self._get_metadata_path()
        else:
            self.__metadata_path = metadata_path

        self.__metadata_relative_path_string = "{}/".format(
            METADATA_DIRECTORY_NAME)

        # Get a list of all CSV files in that directory with their absolute path
        self.__csv_abs_filepaths_list = self._get_csv_filepaths()

        # Connect to the Redis KB
        try:
            self.__db_ctx = db.OpenvasDB.create_context(1)
            main_db = db.MainDB()
            self.__nvti_cache = nvticache.NVTICache(main_db)
        except SystemExit:
            # Maybe replace this with just a log message
            raise Exception("Could not connect to the Redis KB") from None
예제 #6
0
 def prepare_alive_test_option_for_openvas(self):
     """ Set alive test option. Overwrite the scan config settings."""
     settings = Openvas.get_settings()
     if settings and self.target_options.get('alive_test'):
         alive_test_opt = self.build_alive_test_opt_as_prefs(
             self.target_options)
         self._nvts_params.update(alive_test_opt)
예제 #7
0
    def set_params_from_openvas_settings(self):
        """Set OSPD_PARAMS with the params taken from the openvas executable."""
        param_list = Openvas.get_settings()

        for elem in param_list:
            if elem not in OSPD_PARAMS:
                self.scan_only_params[elem] = param_list[elem]
            else:
                OSPD_PARAMS[elem]['default'] = param_list[elem]
예제 #8
0
    def test_get_settings_with_error(self, mock_check_output: MagicMock,
                                     _mock_logger: MagicMock):
        mock_check_output.side_effect = subprocess.SubprocessError('foo')

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertFalse(settings)  # settings dict is empty

        mock_check_output.reset_mock()

        mock_check_output.side_effect = OSError('foo')

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertFalse(settings)  # settings dict is empty
예제 #9
0
    def test_get_settings(self, mock_check_output: MagicMock,
                          _mock_logger: MagicMock):
        mock_check_output.return_value = (
            b'non_simult_ports = 22 \n plugins_folder = /foo/bar\nfoo = yes\n'
            b'bar=no\nipsum= \nlorem\n')

        settings = Openvas.get_settings()

        mock_check_output.assert_called_with(['openvas', '-s'])

        self.assertEqual(settings['non_simult_ports'], '22')
        self.assertEqual(settings['plugins_folder'], '/foo/bar')
        self.assertEqual(settings['foo'], 1)
        self.assertEqual(settings['bar'], 0)
        self.assertFalse('ipsum' in settings)
        self.assertFalse('lorem' in settings)
예제 #10
0
    def prepare_boreas_alive_test(self):
        """Set alive_test for Boreas if boreas scanner config
        (BOREAS_SETTING_NAME) was set"""
        settings = Openvas.get_settings()
        alive_test = -1
        alive_test_ports = None

        if settings:
            boreas = settings.get(BOREAS_SETTING_NAME)
            if not boreas:
                return
            alive_test_ports = self.target_options.get('alive_test_ports')
            alive_test_str = self.target_options.get('alive_test')
            if alive_test_str is not None:
                try:
                    alive_test = int(alive_test_str)
                except ValueError:
                    logger.debug(
                        'Alive test preference for Boreas not set. '
                        'Invalid alive test value %s.',
                        alive_test_str,
                    )
            # ALIVE_TEST_SCAN_CONFIG_DEFAULT if no alive_test provided
            else:
                alive_test = AliveTest.ALIVE_TEST_SCAN_CONFIG_DEFAULT

        # If a valid alive_test was set then the bit mask
        # has value between 31 (11111) and 1 (10000)
        if 1 <= alive_test <= 31:
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST, pref_value=alive_test
            )
            self.kbdb.add_scan_preferences(self.scan_id, [pref])

        if alive_test == AliveTest.ALIVE_TEST_SCAN_CONFIG_DEFAULT:
            alive_test = AliveTest.ALIVE_TEST_ICMP
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST, pref_value=alive_test
            )
            self.kbdb.add_scan_preferences(self.scan_id, [pref])

        # Add portlist if present. Validity is checked on Boreas side.
        if alive_test_ports is not None:
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST_PORTS, pref_value=alive_test_ports
            )
            self.kbdb.add_scan_preferences(self.scan_id, [pref])
예제 #11
0
    def _get_vts_in_groups(
        self,
        filters: List[str],
    ) -> List[str]:
        """Return a list of vts which match with the given filter.

        Arguments:
            filters A list of filters. Each filter has key, operator and
                    a value. They are separated by a space.
                    Supported keys: family

        Returns a list of vt oids which match with the given filter.
        """
        settings = Openvas.get_settings()
        notus_enabled = settings.get("table_driven_lsc")

        vts_list = list()
        families = dict()

        notus = NotusMetadataHandler()
        lsc_families_and_drivers = notus.get_family_driver_linkers()

        oids = self.nvti.get_oids()

        for _, oid in oids:
            family = self.nvti.get_nvt_family(oid)
            if family not in families:
                families[family] = list()

            families[family].append(oid)

        for elem in filters:
            key, value = elem.split('=')
            # If the family is supported by Notus LSC and Notus
            # is enabled
            if (key == 'family' and notus_enabled
                    and value in lsc_families_and_drivers):
                driver_oid = lsc_families_and_drivers.get(value)
                vts_list.append(driver_oid)
                logger.debug('Add Notus driver for family "%s"', value)
            # If Notus disable or family not supported by notus.
            elif key == 'family' and value in families:
                vts_list.extend(families[value])
                logger.debug('Add VTs collection for family "%s"', value)

        return vts_list
예제 #12
0
 def openvas_setting(self):
     """Set OpenVAS option."""
     if self._openvas_settings_dict is None:
         openvas_object = Openvas()
         self._openvas_settings_dict = openvas_object.get_settings()
     return self._openvas_settings_dict
예제 #13
0
    def prepare_boreas_alive_test(self):
        """Set alive_test for Boreas if boreas scanner config
        (BOREAS_SETTING_NAME) was set"""
        settings = Openvas.get_settings()
        alive_test = None
        alive_test_ports = None
        target_options = self.target_options

        if settings:
            boreas = settings.get(BOREAS_SETTING_NAME)
            if not boreas:
                return
        else:
            return

        if target_options:
            alive_test_ports = target_options.get('alive_test_ports')
            # Alive test was speciefied as bit field.
            alive_test = target_options.get('alive_test')
            # Alive test was speciefied as individual methods.
            alive_test_methods = target_options.get('alive_test_methods')
            # <alive_test> takes precedence over <alive_test_methods>
            if alive_test is None and alive_test_methods:
                alive_test = alive_test_methods_to_bit_field(
                    icmp=target_options.get('icmp') == '1',
                    tcp_syn=target_options.get('tcp_syn') == '1',
                    tcp_ack=target_options.get('tcp_ack') == '1',
                    arp=target_options.get('arp') == '1',
                    consider_alive=target_options.get('consider_alive') == '1',
                )

        if alive_test is not None:
            try:
                alive_test = int(alive_test)
            except ValueError:
                logger.debug(
                    'Alive test preference for Boreas not set. '
                    'Invalid alive test value %s.',
                    alive_test,
                )
                # Use default alive test as fall back
                alive_test = AliveTest.ALIVE_TEST_SCAN_CONFIG_DEFAULT
        # Use default alive test if no valid alive_test was provided
        else:
            alive_test = AliveTest.ALIVE_TEST_SCAN_CONFIG_DEFAULT

        # If a valid alive_test was set then the bit mask
        # has value between 31 (11111) and 1 (10000)
        if 1 <= alive_test <= 31:
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST, pref_value=alive_test)
            self.kbdb.add_scan_preferences(self.scan_id, [pref])

        if alive_test == AliveTest.ALIVE_TEST_SCAN_CONFIG_DEFAULT:
            alive_test = AliveTest.ALIVE_TEST_ICMP
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST, pref_value=alive_test)
            self.kbdb.add_scan_preferences(self.scan_id, [pref])

        # Add portlist if present. Validity is checked on Boreas side.
        if alive_test_ports is not None:
            pref = "{pref_key}|||{pref_value}".format(
                pref_key=BOREAS_ALIVE_TEST_PORTS,
                pref_value=alive_test_ports,
            )
            self.kbdb.add_scan_preferences(self.scan_id, [pref])