示例#1
0
def set_syslog_settings(syslog_settings):
    with ConfigurationManager('syslog_client') as dnx:
        stored_syslog_settings = dnx.load_configuration()

        syslog = stored_syslog_settings
        tls_settings = syslog['tls']
        tcp_settings = syslog['tcp']

        for option in tls_settings:
            if (option in syslog_settings['tls'] and option != 'retry'):
                tls_settings[option] = True

            elif (option not in syslog_settings['tls']):
                tls_settings[option] = False

        for protocol in ['tcp', 'udp']:
            fallback = f'{protocol}_fallback'
            if (fallback in syslog_settings['fallback']):
                syslog[protocol]['fallback'] = True
            else:
                syslog[protocol]['fallback'] = False

        syslog['protocol'] = 6 if 'syslog_protocol' in syslog_settings else 17
        syslog[
            'enabled'] = True if 'syslog_enabled' in syslog_settings else False

        tls_settings['retry'] = int(syslog_settings['tls_retry']) * 60
        tcp_settings['retry'] = int(syslog_settings['tcp_retry']) * 60

        dnx.write_configuration(stored_syslog_settings)
示例#2
0
def set_dns_keywords(action):
    with ConfigurationManager('dns_proxy') as dnx:
        keyword_settings = dnx.load_configuration()

        keyword_settings['keyword']['enabled'] = action

        dnx.write_configuration(keyword_settings)
示例#3
0
    def _write_end_time(self, restriction_end):
        with ConfigurationManager('ip_proxy_timer') as dnx:
            time_restriction = dnx.load_configuration()

            time_restriction['end'] = restriction_end

            dnx.write_configuration(time_restriction)
示例#4
0
def update_ips_dns_whitelist(action):
    with ConfigurationManager('ips') as dnx:
        ips_settings = dnx.load_configuration()

        ips_settings['dns_servers'] = action

        dnx.write_configuration(ips_settings)
示例#5
0
def set_dhcp_reservation(dhcp_settings, action):
    with ConfigurationManager('dhcp_server') as dnx:
        dhcp_server_settings = dnx.load_configuration()

        leases = dhcp_server_settings['leases']
        reservations = dhcp_server_settings['reservations']
        reserved_ips = set(
            [info['ip_address'] for info in reservations.values()])

        if (action is CFG.ADD):

            # preventing reservations being created for ips with an active dhcp lease
            if (dhcp_settings['ip'] in leases):
                raise ValidationError(
                    f'There is an active lease with {dhcp_settings["ip"]}. Clear the lease and try again.'
                )

            # ensuring mac address and ip address are unique
            if (dhcp_settings['mac'] in reservations
                    or dhcp_settings['ip'] in reserved_ips):
                raise ValidationError(
                    f'{dhcp_settings["ip"]} is already reserved.')

            reservations.update({
                dhcp_settings['mac']: {
                    'zone': dhcp_settings['zone'],
                    'ip_address': dhcp_settings['ip'],
                    'description': dhcp_settings['description']
                }
            })

        elif (action is CFG.DEL):
            reservations.pop(dhcp_settings['mac'], None)

        dnx.write_configuration(dhcp_server_settings)
示例#6
0
def set_ips_ddos(action):
    with ConfigurationManager('ips') as dnx:
        ips_settings = dnx.load_configuration()

        ips_settings['ddos']['enabled'] = action

        dnx.write_configuration(ips_settings)
示例#7
0
def set_logging(log_settings):
    with ConfigurationManager('logging_client') as dnx:
        logging_settings = dnx.load_configuration()

        logging_settings['logging'] = log_settings

        dnx.write_configuration(logging_settings)
示例#8
0
def mark_completion_flag():
    with ConfigurationManager('config') as dnx:
        dnx_settings = dnx.load_configuration()

        dnx_settings['auto_loader'] = True

        dnx.write_configuration(dnx_settings)
示例#9
0
    def modify(self, static_pos, pos, rule, *, section):
        '''send new definition of rule and rule position to underlying firewall to be updated.

            section (rule type): BEFORE, MAIN, AFTER (will likely be an enum)
        '''

        move = True if pos != static_pos else False

        with ConfigurationManager(DEFAULT_VERION,
                                  file_path=DEFAULT_PATH) as dnx_fw:
            firewall = dnx_fw.load_configuration()

            ruleset = firewall[section]

            # update rule first using static_pos, then remove from list if it needs to move. cannot call add method from
            # here due to file lock being held by this current context (its not re entrant).
            ruleset[static_pos] = rule
            if (move):
                rule_to_move = ruleset.pop(static_pos)

            # write config even if it needs to move since external function will handle move operation (in the form of insertion).
            dnx_fw.write_configuration(firewall)

            # updating instance variable for direct access
            self.firewall = firewall

        # now that we are out of the context we can use add method to re insert the rule in specified place
        # NOTE: since the lock has been released it is possible for another process to get the lock and modify the firewall
        #  rules before the move can happen. only on rare cases would this even cause an issue, and of course, only the
        #  pending config will be effected and can be reverted if need be. in the future maybe we can figure out a way to
        #  deal with this operation without releasing the lock without having to duplicate code.
        if (move):
            self.add(pos, rule_to_move, section=section)
示例#10
0
    def revert(self):
        '''Copies active configuration to pending, which effectively wipes any uncommitted changes.'''

        with ConfigurationManager():
            shutil.copy(ACTIVE_RULE_FILE, COPY_RULE_FILE)

            os.replace(COPY_RULE_FILE, PENDING_RULE_FILE)
示例#11
0
def update_session_tracker(username,
                           user_role=None,
                           remote_addr=None,
                           *,
                           action=CFG.ADD):

    if (action is CFG.ADD and not remote_addr):
        raise ValueError(
            'remote_addr must be specified if action is set to add.')

    with ConfigurationManager('session_tracker',
                              file_path='dnx_webui/data') as session_tracker:
        stored_tracker = session_tracker.load_configuration()

        if (action is CFG.ADD):
            stored_tracker['active_users'][username] = {
                'role': user_role,
                'remote_addr': remote_addr,
                'logged_in': time.time(
                ),  # NOTE: can probably make this human readable format here.
                'last_seen': None
            }

        elif (action is CFG.DEL):
            stored_tracker['active_users'].pop(username, None)

        session_tracker.write_configuration(stored_tracker)
示例#12
0
def set_wan_interface(intf_type=INTF.DHCP):
    '''
    Change wan interface state between static or dhcp.

    1. Configure interface type
    2. Create netplan config from template
    3. Move file to /etc/netplan

    This does not configure an ip address of the interface when setting to static. see: set_wan_ip()
    '''

    # changing dhcp status of wan interface in config file.
    with ConfigurationManager('config') as dnx:
        interface_settings = dnx.load_configuration()

        wan = interface_settings['interfaces']['builtins']['wan']

        wan['state'] = intf_type

        dnx.write_configuration(interface_settings)

        # template used to generate yaml file with user configured fields
        intf_template = load_configuration('intf_config',
                                           filepath='dnx_system/interfaces')

        # setting for static. removing dhcp4 and dhcp_overrides keys, then adding addresses with empty list
        # NOTE: the ip configuration will unlock after the switch and can then be updated
        if (intf_type is INTF.STATIC):
            wan_intf = intf_template['network']['ethernets'][wan['ident']]

            wan_intf.pop('dhcp4')
            wan_intf.pop('dhcp4-overrides')

            # initializing static, but not configuring an ip address
            wan_intf['addresses'] = '[]'

        # grabbing configured dns servers
        dns_server_settings = load_configuration('dns_server')['resolvers']

        dns1 = dns_server_settings['primary']['ip_address']
        dns2 = dns_server_settings['secondary']['ip_address']

        # dns server replacement in template required for static or dhcp
        converted_config = json_to_yaml(intf_template)
        converted_config = converted_config.replace('_PRIMARY__SECONDARY_',
                                                    f'{dns1},{dns2}')

        # writing file into dnx_system folder due to limited permissions by the front end. netplan and the specific
        # mv args are configured as sudo/no-pass to get the config to netplan and it applied without a restart.
        with open(f'{HOME_DIR}/dnx_system/interfaces/01-dnx-interfaces.yaml',
                  'w') as dnx_intfs:
            dnx_intfs.write(converted_config)

        cmd_args = [
            '{HOME_DIR}/dnx_system/interfaces/01-dnx-interfaces.yaml',
            '/etc/netplan/01-dnx-interfaces.yaml'
        ]
        system_action(module='webui', command='os.replace', args=cmd_args)
        system_action(module='webui', command='netplan apply', args='')
示例#13
0
def modify_management_access(fields):
    with ConfigurationManager('config') as dnx:
        mgmt_settings = dnx.load_configuration()

        mgmt_settings['mgmt_access'][fields.zone][
            fields.service] = fields.action

        dnx.write_configuration(mgmt_settings)
示例#14
0
def reset_flask_key():
    with ConfigurationManager('config') as dnx:
        flask_settings = dnx.load_configuration()

        flask_config = flask_settings['flask']
        flask_config['key'] = token_urlsafe(32)

        dnx.write_configuration(flask_settings)
示例#15
0
def set_ips_general_settings(pb_length, ids_mode):
    with ConfigurationManager('ips') as dnx:
        ips_settings = dnx.load_configuration()

        ips_settings['passive_block_ttl'] = pb_length
        ips_settings['ids_mode'] = ids_mode

        dnx.write_configuration(ips_settings)
示例#16
0
    def commit(self):
        '''Copies pending configuration to active, which is being monitored by Control class
        to load into cfirewall.'''

        with ConfigurationManager():
            shutil.copy(PENDING_RULE_FILE, COPY_RULE_FILE)

            os.replace(COPY_RULE_FILE, ACTIVE_RULE_FILE)
示例#17
0
def check_already_ran():
    with ConfigurationManager('config') as dnx:
        dnx_settings = dnx.load_configuration()

    if (dnx_settings['auto_loader']):

        eprint(
            'dnxfirewall auto loader has already been completed. exiting...')
示例#18
0
    def _set_restriction_status(self, active):
        self._change_attribute('_active', active)

        with ConfigurationManager('ip_proxy_timer') as dnx:
            time_restriction = dnx.load_configuration()

            time_restriction['active'] = active

            dnx.write_configuration(time_restriction)
示例#19
0
def set_domain_category_keywords(en_keywords):
    with ConfigurationManager('dns_proxy') as dnx:
        dns_proxy_categories = dnx.load_configuration()

        domain_cats = dns_proxy_categories['categories']['default']
        for cat, settings in domain_cats.items():
            settings['keyword'] = True if cat in en_keywords else False

        dnx.write_configuration(dns_proxy_categories)
示例#20
0
def set_dhcp_settings(dhcp_settings):
    with ConfigurationManager('dhcp_server') as dnx:
        dhcp_server_settings = dnx.load_configuration()

        interface = dhcp_settings.pop('interface')

        dhcp_server_settings['interfaces'][interface].update(dhcp_settings)

        dnx.write_configuration(dhcp_server_settings)
示例#21
0
def set_domain_tlds(update_tlds):
    with ConfigurationManager('dns_proxy') as dnx:
        proxy_settings = dnx.load_configuration()

        tld_list = proxy_settings['tlds']
        for entry in tld_list:
            tld_list[entry] = True if entry in update_tlds else False

        dnx.write_configuration(proxy_settings)
示例#22
0
def set_ips_ddos_limits(ddos_limits):
    with ConfigurationManager('ips') as dnx:
        ips_settings = dnx.load_configuration()

        limits = ips_settings['ddos']['limits']['source']
        for protocol, limit in ddos_limits.items():
            limits[protocol] = limit

        dnx.write_configuration(ips_settings)
示例#23
0
def set_dns_cache_clear_flag(clear_dns_cache):
    with ConfigurationManager('dns_server') as dnx:
        dns_server_settings = dnx.load_configuration()

        dns_cache_flags = dns_server_settings['dns_server']['cache']
        for flag, setting in clear_dns_cache.items():
            if (setting):
                dns_cache_flags[flag] = True

        dnx.write_configuration(dns_server_settings)
示例#24
0
    def _reset_flag(cls, cache_type):
        setattr(cls, f'clear_{cache_type}', False)
        with ConfigurationManager('dns_server') as dnx:
            dns_settings = dnx.load_configuration()

            dns_settings['cache'][cache_type] = False

            dnx.write_configuration(dns_settings)

        Log.notice(f'{cache_type.replace("_", " ")} has been cleared.')
示例#25
0
def remove_dhcp_lease(ip_addr):
    with ConfigurationManager('dhcp_server') as dnx:
        dhcp_leases = dnx.load_configuration()

        leases = dhcp_leases['leases']

        if not leases.pop(ip_addr, None):
            raise ValidationError(INVALID_FORM)

        dnx.write_configuration(dhcp_leases)
示例#26
0
def add_proxy_ip_whitelist(whitelist_settings):
    with ConfigurationManager('whitelist') as dnx:
        whitelist = dnx.load_configuration()

        whitelist['ip_bypass'][whitelist_settings['ip']] = {
            'user': whitelist_settings['user'],
            'type': whitelist_settings['type']
        }

        dnx.write_configuration(whitelist)
示例#27
0
def set_dhcp_interfaces(user_intf_config):
    with ConfigurationManager('dhcp_server') as dhcp:
        dhcp_settings = dhcp.load_configuration()

        interface_settings = dhcp_settings['interfaces']

        for zone in ['LAN', 'DMZ']:

            interface_settings[zone.lower()]['ident'] = user_intf_config[zone]

        dhcp.write_configuration(dhcp_settings)
示例#28
0
def del_proxy_domain(domain, *, ruleset):
    with ConfigurationManager(ruleset) as dnx:
        domain_list = dnx.load_configuration()

        result = domain_list['time_based'].pop(domain, None)

        # if domain was not present (likely removed in another process), there is
        # no need to write file to disk
        if (result is not None):

            dnx.write_configuration(domain_list)
示例#29
0
def del_proxy_ip_whitelist(whitelist_ip):
    with ConfigurationManager('whitelist') as dnx:
        whitelist = dnx.load_configuration()

        result = whitelist['ip_bypass'].pop(whitelist_ip, None)

        # if ip was not present (likely removed in another process), there is
        # no need to write file to disk
        if (result is not None):

            dnx.write_configuration(whitelist)
示例#30
0
def update_ip_proxy_settings(category_settings, *, ruleset='reputation'):
    with ConfigurationManager('ip_proxy') as dnx:
        ip_proxy_settings = dnx.load_configuration()

        category_lists = ip_proxy_settings[ruleset]
        for category in category_settings:
            category, direction = category[:-2], int(category[-1])

            category_lists[category] = direction

        dnx.write_configuration(ip_proxy_settings)