Instantly share code, notes, and snippets.

@kurochan kurochan/domain_filter.py
Last active Apr 23, 2018

Embed
What would you like to do?
UnboundでDNSのドメインフィルタリングを実装する方法です
BLOCK_DOMAINS_FILE = "/etc/unbound/block_domains.txt"
block_domains = set()
def load_file(file_name):
try:
with open(file_name, "r") as f:
for line in f:
block_domains.add(line.rstrip())
except IOError:
log_info("pythonmod: failed to load %s" % file_name)
log_info("pythonmod: load block_domains from: %s" % file_name)
def filter_domain(qstate, id):
domain = qstate.qinfo.qname_str.rstrip('.')
if domain in block_domains:
qstate.return_rcode = RCODE_NXDOMAIN
qstate.ext_state[id] = MODULE_FINISHED
else:
qstate.ext_state[id] = MODULE_WAIT_MODULE
def init(id, cfg):
log_info("pythonmod: init called, module id is %d port: %d script: %s" % (id, cfg.port, cfg.python_script))
load_file(BLOCK_DOMAINS_FILE)
return True
def deinit(id):
log_info("pythonmod: deinit called, module id is %d" % id)
return True
def inform_super(id, qstate, superqstate, qdata):
return True
def operate(id, event, qstate, qdata):
log_info("pythonmod: operate called, id: %d, event:%s" % (id, strmodulevent(event)))
if event == MODULE_EVENT_NEW:
filter_domain(qstate, id)
return True
if event == MODULE_EVENT_MODDONE:
qstate.ext_state[id] = MODULE_FINISHED
return True
if event == MODULE_EVENT_PASS:
filter_domain(qstate, id)
return True
log_err("pythonmod: BAD event")
qstate.ext_state[id] = MODULE_ERROR
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment