def _storage(self, dhcp_lease): with ConfigurationManager('dhcp_server') as dnx: dhcp_settings = dnx.load_configuration() leases = dhcp_settings['leases'] if (dhcp_lease.record is _NULL_LEASE): leases.pop(dhcp_lease.ip, None) else: leases[dhcp_lease.ip] = dhcp_lease.record dnx.write_configuration(dhcp_settings)
def del_open_wan_protocol(nat_info): with ConfigurationManager('ips') as dnx: open_protocol_settings = dnx.load_configuration() open_protocols = open_protocol_settings['open_protocols'] if (nat_info.protocol == 'icmp'): open_protocols['icmp'] = False else: open_protocols[nat_info.protocol].pop(nat_info.port, None) dnx.write_configuration(open_protocol_settings)
def update_ips_ip_whitelist(whitelist_ip, whitelist_name, *, action): with ConfigurationManager('ips') as dnx: ips_settings = dnx.load_configuration() ips_whitelist = ips_settings['ip_whitelist'] if (action is CFG.ADD): ips_whitelist[whitelist_ip] = whitelist_name elif (action is CFG.DEL): result = ips_whitelist.pop(whitelist_ip, None) if (result is None): return dnx.write_configuration(ips_settings)
def set_domain_categories(en_cats, *, ruleset): with ConfigurationManager('dns_proxy') as dnx: dns_proxy_categories = dnx.load_configuration() categories = dns_proxy_categories['categories'] if (ruleset in ['default', 'user_defined']): domain_cats = categories[ruleset] for cat, settings in domain_cats.items(): if (cat in ['malicious', 'cryptominer']): continue settings['enabled'] = True if cat in en_cats else False dnx.write_configuration(dns_proxy_categories)
def update_system_time_offset(new_offset_settings): with ConfigurationManager('logging_client') as dnx: offset_settings = dnx.load_configuration() if (new_offset_settings['time'] == 0): new_offset_settings['direction'] = '+' offset = offset_settings['time_offset'] offset.update({ 'direction': new_offset_settings['direction'], 'amount': new_offset_settings['time'] }) dnx.write_configuration(offset_settings)
def set_default_mac_flag(): with ConfigurationManager('config') as dnx: dnx_settings = dnx.load_configuration() wan_settings = dnx_settings['interfaces']['builtins']['wan'] if (not wan_settings['mac_set']): wan_settings.update({ 'default_mac': Interface.mac_address(interface=wan_settings['ident']), 'mac_set': True }) dnx.write_configuration(dnx_settings)
def update_custom_category_domain(category, domain, reason=None, *, action): with ConfigurationManager('dns_proxy') as dnx: custom_category_domains = dnx.load_configuration() ud_cats = custom_category_domains['categories']['user_defined'] if (action is CFG.DEL and category != 'enabled'): ud_cats[category].pop(domain, None) elif (action is CFG.ADD): if (domain in ud_cats[category]): raise ValidationError( 'Domain rule already exists for this category.') else: ud_cats[category][domain] = reason dnx.write_configuration(custom_category_domains)
def add_proxy_domain(settings, *, ruleset): input_time = int(fast_time()) expire_time = input_time + settings['timer'] * 60 with ConfigurationManager(ruleset) as dnx: domain_list = dnx.load_configuration() domain_list['time_based'].update({ settings['domain']: { 'time': input_time, 'rule_length': settings['timer'], 'expire': expire_time } }) dnx.write_configuration(domain_list)
def update_geolocation(region, *, rtype='country'): with ConfigurationManager('ip_proxy') as dnx: ip_proxy_settings = dnx.load_configuration() country_list = ip_proxy_settings['geolocation'] # setting individual country to user set value if (rtype == 'country'): country_list[region['country']] = region['cfg_dir'] # iterating over all countries within specified continent and setting their # direction as the user set value # TODO: implement this elif (rtype == 'continent'): pass dnx.write_configuration(ip_proxy_settings)
def set_syslog_servers(syslog_servers): with ConfigurationManager('syslog_client') as dnx: syslog_settings = dnx.load_configuration() servers = syslog_settings['servers'] for server, server_info in syslog_servers.items(): if (not server_info['ip_address']): continue servers.update({ server: { 'ip_address': server_info['ip_address'], 'port': int(server_info['port']) } }) dnx.write_configuration(syslog_settings)
def add_open_wan_protocol(nat_info): with ConfigurationManager('ips') as dnx: open_protocol_settings = dnx.load_configuration() open_protocols = open_protocol_settings['open_protocols'] # if dst port is present protocol is tcp/udp if (nat_info.dst_port): open_protocols[nat_info.protocol][ nat_info.dst_port] = nat_info.host_port # will only match icmp, which is configured as a boolean value else: open_protocols[nat_info.protocol] = True dnx.write_configuration(open_protocol_settings)
def dark_mode(): ''' the configured value will be stored as session['dark_mode'] so it can be accessed directly by the Flask template context. ''' # dark mode settings will only apply to logged in users. # NOTE: username validations are still required lower down to deal with log in/out transitions. user = session.get('user', None) if (not user): return dark_mode_update = request.args.get('dark_mode_update', DATA.MISSING) # this ensure value conforms to system before configuring if (dark_mode_update is not DATA.MISSING): try: dark_mode = CFG(validate.convert_int(dark_mode_update)) except: return with ConfigurationManager('logins', file_path='/dnx_webui/data') as webui: webui_settings = webui.load_configuration() active_users = webui_settings['users'] # this check prevents issues with log in/out transitions if (user['name'] not in active_users): return active_users[user['name']]['dark_mode'] = dark_mode webui.write_configuration(webui_settings) # standard request for page. did NOT submit dark mode fab. else: webui_settings = load_configuration('logins', filepath='dnx_webui/data') # this check prevents issues with log in/out transitions user = webui_settings['users'].get(user['name']) if (not user): return dark_mode = user['dark_mode'] session['dark_mode'] = dark_mode
def set_proxy_exception(exc_settings, *, ruleset): with ConfigurationManager(ruleset) as dnx: exceptions_list = dnx.load_configuration() proxy_exceptions = exceptions_list['pre_proxy'] action = exc_settings.pop('action') if (action is CFG.ADD): proxy_exceptions[exc_settings['domain']] = exc_settings['reason'] elif (action is CFG.DEL): result = proxy_exceptions.pop(exc_settings['domain'], None) # no need to write to disk if domain was already removed. if (result is None): return dnx.write_configuration(exceptions_list)
def add(self, pos, rule, *, section): '''insert or append operation of new firewall rule to the specified section.''' # for comparison operators, but will use str as key as required for json. pos_int = int(pos) with ConfigurationManager(DEFAULT_VERION, file_path=DEFAULT_PATH) as dnx_fw: firewall = dnx_fw.load_configuration() ruleset = firewall[section] # position is at the beginning of the ruleset. this is needed because the slice functions dont work # correctly for pos 1 insertions. if (pos_int == 1): temp_rules = [rule, *ruleset.values()] # assigning section with new ruleset firewall[section] = { f'{i}': rule for i, rule in enumerate(temp_rules, 1) } # position is after last element so can add to end of dict directly. elif (pos_int == len(ruleset) + 1): ruleset[pos] = rule # position falls somewhere within already allocated memory. using slices to split open position. else: temp_rules = list(ruleset.values()) # offset to adjust for rule num vs index temp_rules.insert(pos_int - 1, rule) # assigning section with new ruleset firewall[section] = { f'{i}': rule for i, rule in enumerate(temp_rules, 1) } dnx_fw.write_configuration(firewall) # updating instance variable for direct access self.firewall = firewall
def set_dns_servers(dns_server_info): field = {1: 'primary', 2: 'secondary'} with ConfigurationManager('dns_server') as dnx: dns_server_settings = dnx.load_configuration() public_resolvers = dns_server_settings['resolvers'] for i, (server_name, ip_address) in enumerate(dns_server_info.items(), 1): if (not server_name or not ip_address): continue public_resolvers[field[i]].update({ 'name': server_name, 'ip_address': ip_address }) dnx.write_configuration(dns_server_settings)
def update_custom_category(category, *, action): with ConfigurationManager('dns_proxy') as dnx: custom_category_lists = dnx.load_configuration() ud_cats = custom_category_lists['categories']['user_defined'] if (action is CFG.DEL and category != 'enabled'): ud_cats.pop(category, None) elif (action is CFG.ADD): if (len(ud_cats) >= 6): raise ValidationError( 'Only support for maximum of 6 custom categories.') elif (category in ud_cats): raise ValidationError('Custom category already exists.') ud_cats[category] = {'enabled': False} dnx.write_configuration(custom_category_lists)
def remove(self, pos, *, section): with ConfigurationManager(DEFAULT_VERION, file_path=DEFAULT_PATH) as dnx_fw: firewall = dnx_fw.load_configuration() ruleset = firewall[section] # this is safe if it fails because the context will immediately exit gracefully ruleset.pop(pos) firewall[section] = { f'{i}': rule for i, rule in enumerate(ruleset.values(), 1) } dnx_fw.write_configuration(firewall) # updating instance variable for direct access self.firewall = firewall
def set_wan_mac(action, mac_address=None): with ConfigurationManager('config') as dnx: dnx_settings = dnx.load_configuration() wan_settings = dnx_settings['interfaces']['builtins']['wan'] new_mac = mac_address if action is CFG.ADD else wan_settings[ 'default_mac'] wan_int = wan_settings['ident'] # iterating over the necessary command args, then sending over local socket # for control service to issue the commands args = [ f'{wan_int} down', f'{wan_int} hw ether {new_mac}', f'{wan_int} up' ] for arg in args: system_action(module='webui', command='ifconfig', args=arg) wan_settings['configured_mac'] = mac_address dnx.write_configuration(dnx_settings)
def view_ruleset(self, section='MAIN', version='pending'): '''returns dict of requested ruleset in raw form. additional processing is required for web ui or cli formats. args: section > will change which ruleset is returned.\n version > PENDING or ACTIVE rule tables. ''' if (version not in self.versions): return {} # raise ValueError(f'{version} is not a valid version.') if (section not in self.sections): return {} # raise ValueError(f'{version} is not a valid section.') with ConfigurationManager(f'firewall_{version}', file_path=DEFAULT_PATH) as dnx_fw: firewall = dnx_fw.load_configuration() return firewall[section]
def set_dns_over_tls(dns_tls_settings): with ConfigurationManager('dns_server') as dnx: dns_server_settings = dnx.load_configuration() tls_settings = dns_server_settings['tls'] enabled_settings = dns_tls_settings['enabled'] if ('dns_over_tls' in enabled_settings and 'udp_fallback' not in enabled_settings): tls_enabled = True udp_fallback = False elif ('dns_over_tls' in enabled_settings and 'udp_fallback' in enabled_settings): tls_enabled = True udp_fallback = True else: udp_fallback = False tls_enabled = False tls_settings.update({'enabled': tls_enabled, 'fallback': udp_fallback}) dnx.write_configuration(dns_server_settings)
def update_ip_restriction_settings(tr_settings): with ConfigurationManager('ip_proxy') as dnx: ip_proxy_settings = dnx.load_configuration() tr_settings['hour'] += 12 if tr_settings[ 'suffix'] == 'PM' else tr_settings['hour'] start_time = f'{tr_settings["hour"]}:{tr_settings["minutes"]}' tlen_hour = tr_settings['length_hour'] min_fraction = str(tr_settings['length_minutes'] / 60).strip('0.') res_length = f'{tlen_hour}.{min_fraction}' res_length = int(float(res_length) * 3600) ip_proxy_settings['time_restriction'].update({ 'start': start_time, 'length': res_length, 'enabled': tr_settings['enabled'] }) dnx.write_configuration(ip_proxy_settings)
def configure_user_account(account_info, action): acct = SimpleNamespace(**account_info) with ConfigurationManager('logins', file_path='/dnx_webui/data') as dnx: accounts = dnx.load_configuration() userlist = accounts['users'] if (action is CFG.DEL): userlist.pop(acct.username) elif (action is CFG.ADD and acct.username not in userlist): account = Authentication() hexpass = account.hash_password(acct.username, acct.password) userlist.update({ acct.username: { 'password': hexpass, 'role': acct.role, 'dark_mode': 0 } }) else: raise ValidationError('User account already exists.') dnx.write_configuration(accounts)