Esempio n. 1
0
def __load_modules__(base_path=None, module_path='silentdune_client/modules'):
    """
    Search for modules to load.  Modules must reside under the modules directory and
    have a "module_list" dict defined in the __init__.py file. Each entry in the
    "module_list" must list a Class that subclasses BaseModule.
    """

    module_list = list()

    # Loop through the directories looking for modules to import.
    for root, dirs, files in os.walk(os.path.join(base_path, module_path),
                                     topdown=True):
        # Skip our directory.
        if root == '.':
            continue

        # Look only at __init__.py files.
        for name in files:
            if name == '__init__.py':

                # Remove base_path and convert to dotted path.
                mp = root.replace(base_path + '/',
                                  '').replace('./', '').replace('/', '.')

                # Attempt to import 'module_list' from __init__.py file.
                try:
                    ml = import_by_str(mp + '.module_list')

                # If we get an Exception check to see if the python module loaded but there was no
                # client module definition found, otherwise just reraise the last Exception for debugging.
                except ModuleLoadError:
                    # Looks like a clean import error. IE: __init__.py is not a real module.
                    continue
                except:
                    # Found a module to load, but it threw an Exception. Just pass the Exception up.
                    raise

                for mname, mdict in ml.items():
                    _logger.debug(
                        'Found module definition "{0}" in path {1}'.format(
                            mname, mp))
                    for key, name in mdict.items():

                        if key == 'module':
                            tpath = mp + '.' + name
                            try:
                                mod = import_by_str(tpath)
                                module_list.append(mod())
                                _logger.debug(
                                    'Adding "{0}" module ({1}).'.format(
                                        mname, tpath))
                            except ImportError:
                                _logger.error(
                                    'Adding "{0}" module failed. ({1}).'.
                                    format(mname, tpath))
                                pass

    module_list.sort(key=lambda x: x.priority)

    return module_list
Esempio n. 2
0
def __load_modules__(base_path=None, module_path='silentdune_client/modules'):
    """
    Search for modules to load.  Modules must reside under the modules directory and
    have a "module_list" dict defined in the __init__.py file. Each entry in the
    "module_list" must list a Class that subclasses BaseModule.
    """

    module_list = list()

    # Loop through the directories looking for modules to import.
    for root, dirs, files in os.walk(os.path.join(base_path, module_path), topdown=True):
        # Skip our directory.
        if root == '.':
            continue

        # Look only at __init__.py files.
        for name in files:
            if name == '__init__.py':

                # Remove base_path and convert to dotted path.
                mp = root.replace(base_path + '/', '').replace('./', '').replace('/', '.')

                # Attempt to import 'module_list' from __init__.py file.
                try:
                    ml = import_by_str(mp + '.module_list')

                # If we get an Exception check to see if the python module loaded but there was no
                # client module definition found, otherwise just reraise the last Exception for debugging.
                except ModuleLoadError:
                    # Looks like a clean import error. IE: __init__.py is not a real module.
                    continue
                except:
                    # Found a module to load, but it threw an Exception. Just pass the Exception up.
                    raise

                for mname, mdict in ml.items():
                    _logger.debug('Found module definition "{0}" in path {1}'.format(mname, mp))
                    for key, name in mdict.items():

                        if key == 'module':
                            tpath = mp + '.' + name
                            try:
                                mod = import_by_str(tpath)
                                module_list.append(mod())
                                _logger.debug('Adding "{0}" module ({1}).'.format(mname, tpath))
                            except ImportError:
                                _logger.error('Adding "{0}" module failed. ({1}).'.format(mname, tpath))
                                pass

    module_list.sort(key=lambda x: x.priority)

    return module_list
Esempio n. 3
0
    def check_service(self, name):
        """
        Check the service for rules and add them to the firewall.
        :param name: Service discovery module name
        """
        module_name, class_name = name.rsplit('.', 1)

        _logger.debug('{0}: Loading service object {1}'.format(self.get_name(), class_name))

        module = import_by_str(name)
        cls = module(config=self.config)
        disabled = getattr(self, cls.get_config_property_name())
        if type(disabled) is str:  # Python 2.7 returns string type from getattr(), Python 3.4 returns bool.
            disabled = ast.literal_eval(disabled)

        # _logger.debug('Property: {0}: Value: {1}'.format(cls.get_config_property_name(), disabled))
        # See if this discovery service has been disabled. Name value must match one of our property names.
        if disabled:
            _logger.debug('{0}: {1} service disabled by config.'.format(self.get_name(), class_name))
            return 0

        rules, slot = cls.discover()

        if rules:

            # See if we already have saved rules for this slot id
            if slot in self._mss_slots:
                if self.rules_have_changed(self._mss_slots[slot], rules):

                    _logger.debug('{0}: {1}: Rules have changed, notifying firewall manager.'.format(
                        self.get_name(), class_name))

                    # Notify the firewall module to delete the old rules.
                    task = QueueTask(TASK_FIREWALL_DELETE_RULES,
                                     src_module=self.get_name(),
                                     dest_module=SilentDuneClientFirewallModule().get_name(),
                                     data=self._mss_slots[slot])
                    self.send_parent_task(task)
                else:
                    return 0

            # Save rules so we can check against them next time.
            self._mss_slots[slot] = rules

            # Notify the firewall module to reload the rules.
            task = QueueTask(TASK_FIREWALL_INSERT_RULES,
                             src_module=self.get_name(),
                             dest_module=SilentDuneClientFirewallModule().get_name(),
                             data=rules)
            self.send_parent_task(task)
        else:
            _logger.info('{0}: {1}: service did not return any rules.'.format(
                self.get_name(), class_name))

            return 0

        return len(rules)
Esempio n. 4
0
    def check_service(self, name):
        """
        Check the service for rules and add them to the firewall.
        :param name: Service discovery module name
        """
        module_name, class_name = name.rsplit('.', 1)

        _logger.debug('{0}: Loading service object {1}'.format(self.get_name(), class_name))

        module = import_by_str(name)
        cls = module(config=self.config)
        disabled = getattr(self, cls.get_config_property_name())
        if type(disabled) is str:  # Python 2.7 returns string type from getattr(), Python 3.4 returns bool.
            disabled = ast.literal_eval(disabled)

        # _logger.debug('Property: {0}: Value: {1}'.format(cls.get_config_property_name(), disabled))
        # See if this discovery service has been disabled. Name value must match one of our property names.
        if disabled:
            _logger.debug('{0}: {1} service disabled by config.'.format(self.get_name(), class_name))
            return 0

        rules, slot = cls.discover()

        if rules:

            # See if we already have saved rules for this slot id
            if slot in self._mss_slots:
                if self.rules_have_changed(self._mss_slots[slot], rules):

                    _logger.debug('{0}: {1}: Rules have changed, notifying firewall manager.'.format(
                        self.get_name(), class_name))

                    # Notify the firewall module to delete the old rules.
                    task = QueueTask(TASK_FIREWALL_DELETE_RULES,
                                     src_module=self.get_name(),
                                     dest_module=SilentDuneClientFirewallModule().get_name(),
                                     data=self._mss_slots[slot])
                    self.send_parent_task(task)
                else:
                    return 0

            # Save rules so we can check against them next time.
            self._mss_slots[slot] = rules

            # Notify the firewall module to reload the rules.
            task = QueueTask(TASK_FIREWALL_INSERT_RULES,
                             src_module=self.get_name(),
                             dest_module=SilentDuneClientFirewallModule().get_name(),
                             data=rules)
            self.send_parent_task(task)
        else:
            _logger.info('{0}: {1}: service did not return any rules.'.format(
                self.get_name(), class_name))

            return 0

        return len(rules)
Esempio n. 5
0
    def check_service(self, name):
        """
        Check the service for rules and add them to the firewall.
        :param name: Service discovery module name
        """
        module_name, class_name = name.rsplit('.', 1)

        _logger.debug('{0}: Loading auto discover object {1}'.format(self.get_name(), class_name))

        module = import_by_str(name)
        cls = module(config=self.config)
        disabled = getattr(self, cls.get_config_property_name())
        if type(disabled) is str:  # Python 2.7 returns string type from getattr(), Python 3.4 returns bool.
            disabled = ast.literal_eval(disabled)

        # _logger.debug('Property: {0}: Value: {1}'.format(cls.get_config_property_name(), disabled))
        # See if this discovery service has been disabled. Name value must match one of our property names.
        if disabled:
            _logger.debug('{0}: {1} discovery service disabled by config.'.format(self.get_name(), class_name))
            return 0

        rules, slot = cls.discover(self)

        rules = self.flatten_rules(rules)

        if rules:

            # Notify the firewall module to delete the old rules.
            task = QueueTask(TASK_FIREWALL_DELETE_SLOT,
                             src_module=self.get_name(),
                             dest_module=SilentDuneClientFirewallModule().get_name(),
                             data=slot)
            self.send_parent_task(task)

            # Notify the firewall module to load the new rules.
            task = QueueTask(TASK_FIREWALL_INSERT_RULES,
                             src_module=self.get_name(),
                             dest_module=SilentDuneClientFirewallModule().get_name(),
                             data=rules)
            self.send_parent_task(task)

            time.sleep(1)  # Let the firewall apply the rule changes
        else:
            _logger.info('{0}: {1}: discovery service did not return any rules.'.format(
                self.get_name(), class_name))

            _logger.debug('SLOTS: {0}: {1}'.format(Slots.ntp, slot))

            # If there were no rules discovered for NTP, open up access to all NTP servers.
            # In self._t_ntp_check_interval seconds we will check to see if any NTP servers are active.
            if slot == Slots.ntp and is_service_running('ntpd'):
                self._all_ntp_access_enabled = True
                _logger.debug('{0}: Asking Firewall Module to enable generic NTP access.'.format(self.get_name()))
                task = QueueTask(TASK_FIREWALL_ALLOW_ALL_NTP_ACCESS,
                                 src_module=self.get_name(),
                                 dest_module=SilentDuneClientFirewallModule().get_name())
                self.send_parent_task(task)

            return 0

        return len(rules)
    def check_service(self, name):
        """
        Check the service for rules and add them to the firewall.
        :param name: Service discovery module name
        """
        module_name, class_name = name.rsplit('.', 1)

        _logger.debug('{0}: Loading auto discover object {1}'.format(
            self.get_name(), class_name))

        module = import_by_str(name)
        cls = module(config=self.config)
        disabled = getattr(self, cls.get_config_property_name())
        if type(
                disabled
        ) is str:  # Python 2.7 returns string type from getattr(), Python 3.4 returns bool.
            disabled = ast.literal_eval(disabled)

        # _logger.debug('Property: {0}: Value: {1}'.format(cls.get_config_property_name(), disabled))
        # See if this discovery service has been disabled. Name value must match one of our property names.
        if disabled:
            _logger.debug(
                '{0}: {1} discovery service disabled by config.'.format(
                    self.get_name(), class_name))
            return 0

        rules, slot = cls.discover(self)

        rules = self.flatten_rules(rules)

        if rules:

            # Notify the firewall module to delete the old rules.
            task = QueueTask(
                TASK_FIREWALL_DELETE_SLOT,
                src_module=self.get_name(),
                dest_module=SilentDuneClientFirewallModule().get_name(),
                data=slot)
            self.send_parent_task(task)

            # Notify the firewall module to load the new rules.
            task = QueueTask(
                TASK_FIREWALL_INSERT_RULES,
                src_module=self.get_name(),
                dest_module=SilentDuneClientFirewallModule().get_name(),
                data=rules)
            self.send_parent_task(task)

            time.sleep(1)  # Let the firewall apply the rule changes
        else:
            _logger.info(
                '{0}: {1}: discovery service did not return any rules.'.format(
                    self.get_name(), class_name))

            _logger.debug('SLOTS: {0}: {1}'.format(Slots.ntp, slot))

            # If there were no rules discovered for NTP, open up access to all NTP servers.
            # In self._t_ntp_check_interval seconds we will check to see if any NTP servers are active.
            if slot == Slots.ntp and is_service_running('ntpd'):
                self._all_ntp_access_enabled = True
                _logger.debug(
                    '{0}: Asking Firewall Module to enable generic NTP access.'
                    .format(self.get_name()))
                task = QueueTask(
                    TASK_FIREWALL_ALLOW_ALL_NTP_ACCESS,
                    src_module=self.get_name(),
                    dest_module=SilentDuneClientFirewallModule().get_name())
                self.send_parent_task(task)

            return 0

        return len(rules)