Update dnsf.py

This commit is contained in:
2025-09-26 12:59:19 -06:00
parent 94d04e8b1d
commit 3f38868381

30
dnsf.py
View File

@@ -75,7 +75,7 @@ int dns_matching(struct __sk_buff *skb) {
'''
default_rules = '''
iptables -F
iptables -X
ipset destroy whitelist_hosts
ipset destroy static_hosts
ipset create whitelist_hosts hash:ip timeout 3600
@@ -90,6 +90,7 @@ iptables -A OUTPUT -j REJECT
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
systemd-resolve --flush-caches
'''
for c in default_rules.splitlines(False):
@@ -106,10 +107,9 @@ fcntl.fcntl(socket_fd, fcntl.F_SETFL, fl & ~os.O_NONBLOCK)
rules = {}
cnames = {}
blocked = []
def check_hostname(hostname,current_cnames,allow_list):
import re
for wl in allow_list:
match = re.fullmatch(wl, hostname)
if match:
@@ -120,11 +120,11 @@ def check_hostname(hostname,current_cnames,allow_list):
if hostname == current_cnames[c]["cname"] and current_cnames[c]["exp"] > datetime.now():
print('<check> hostname: '+str(hostname) + ' in cname')
return True
print('<check> hostname: '+str(hostname) + ' not permitted.')
blocked.append(hostname)
return False
import socket
def valid_ip(address):
@@ -137,7 +137,6 @@ def valid_ip(address):
dns_list = watch_file('dns_whitelist.conf')
host_list = watch_file('host_whitelist.conf')
import time
while True:
time.sleep(.05)
commands = []
@@ -145,6 +144,13 @@ while True:
dns_list.check_change()
if dns_list.contents:
dns_regex = dns_list.contents
for block in blocked:
add_rule = 'nslookup '+str(block)
commands.append(add_rule)
threaded(commands)
blocked = []
commands = []
host_list.check_change()
if host_list.contents:
@@ -176,9 +182,8 @@ while True:
payload_offset = ETH_HLEN + ip_header_length + UDP_HLEN
payload = packet_bytearray[payload_offset:]
dnsrec = dnslib.DNSRecord.parse(payload)
if dnsrec.rr:
if check_hostname(hostname=str(dnsrec.questions[0].qname),current_cnames=cnames,allow_list=dns_regex):
if True:
for i in range(0, len(dnsrec.rr)):
if str(dnsrec.rr[i].rtype) in ['5']:
cnames[str(dnsrec.questions[0].qname)] = {"cname":str(dnsrec.rr[i].rdata),"exp":datetime.now() + timedelta(seconds=dnsrec.rr[i].ttl)}
@@ -186,11 +191,10 @@ while True:
if str(dnsrec.rr[i].rtype) in ['1']:
#rtype 28 is v6
#print(str(dnsrec.rr[i].rtype))
add_rule = 'ipset -exist add whitelist_hosts '+str(dnsrec.rr[i].rdata)+' timeout '+str(int(dnsrec.rr[i].ttl)+360)
del_rule = 'ipset del whitelist_hosts '+str(dnsrec.rr[i].rdata)
print(add_rule)
commands.append(add_rule)
if check_hostname(hostname=str(dnsrec.questions[0].qname),current_cnames=cnames,allow_list=dns_regex):
add_rule = 'ipset -exist add whitelist_hosts '+str(dnsrec.rr[i].rdata)+' timeout '+str(int(dnsrec.rr[i].ttl)+360)
print(add_rule)
commands.append(add_rule)
threaded(commands)
else:
pass