#!/usr/bin/python3 import configparser import copy import json import os import smtplib import subprocess import sys import time from email.message import EmailMessage from pprint import pprint rundir=os.path.realpath(os.path.dirname(sys.argv[0])) os.chdir(rundir) sys.path.append(os.path.join(rundir,'sysbus/src')) from sysbus import sysbus from ovh import ovh def load_conf(): global zone_filename, log_filename global wan_hostname, zone_domain, zone_subdomain, zone_timeout global hosts_list, nat_list, pinhole_list global mail_from, mail_to, mail_ignore_list conf = configparser.ConfigParser(allow_no_value=True) conf.read('home.conf') zone_filename = conf['Files']['zonefile'] log_filename = conf['Files']['logfile'] wan_hostname = conf['Wan']['hostname'].lower() zone_domain = conf['Zone']['domain'].lower() zone_subdomain = conf['Zone']['subdomain'].lower() mail_from = conf['Mail']['from'] mail_to = conf['Mail']['to'] mail_ignore_list = [ host.lower() for host in conf['MailIgnore'] ] mail_ignore_list = [ '.'.join([h, zone_subdomain]) if not h.endswith('.'+zone_subdomain) else h for h in mail_ignore_list ] hosts_list = [ host.lower() for host in conf['Hosts'] ] nat_list = {} for e in conf.items('PortsNat'): if e[1]: nat_list[e[0]] = e[1].split(',') else: nat_list[e[0]] = [] pinhole_list = {} for e in conf.items('Firewall'): if e[1]: pinhole_list[e[0]] = e[1].split(',') else: pinhole_list[e[0]] = [] zone_timeout = conf['Zone']['keep'] if zone_timeout[-1] == 's': zone_timeout = int(zone_timeout[:-1]) elif zone_timeout[-1] == 'm': zone_timeout = int(zone_timeout[:-1]) * 60 elif zone_timeout[-1] == 'h': zone_timeout = int(zone_timeout[:-1]) * 3600 elif zone_timeout[-1] == 'd': zone_timeout = int(zone_timeout[:-1]) * 86400 else: zone_timeout = int(zone_timeout) def ping(hostname): cmd = "ping -c1 -w3 %s" % hostname ret = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) return 0 if ret.returncode else 1 def get_ipv6_hosts(): r = sysbus.requete('Devices:get') ipv6_hosts = dict() for h in r['status']: if not 'IPv6Address' in h or not h['IPv6Address']: continue ns = {} for n in h['Names']: ns[n['Source']] = n['Name'] hostname = h['Name'] hostname = ns.get('mdns', hostname) hostname = ns.get('dhcp', hostname) hostname = ns.get('webui', hostname) hostname = hostname.lower() for a in h['IPv6Address']: if a['Scope'] != 'global' or a['Status'] != 'reachable': continue if not hostname in ipv6_hosts: ipv6_hosts[hostname] = [] ipv6_hosts[hostname].append(a['Address']) return ipv6_hosts def get_wan_addr(): r = sysbus.requete('NMC:getWANStatus') wan = dict() wan['ipv4'] = r['data']['IPAddress'] wan['ipv6'] = r['data']['IPv6Address'] if wan['ipv4'] == '0.0.0.0': wan['ipv4'] = '' return wan def full_name(host, domain): host = host.replace('_', '-') return '.'.join([host, domain]) def zone_add_entry(zone, prot, name, addr, stamp): #print('zone_add_entry: {} {} {} {}'.format(prot, name, addr, stamp)) if not zone.get(prot): zone[prot] = {} if not zone[prot].get(name): zone[prot][name] = {} if not zone[prot][name].get(addr): zone[prot][name][addr] = { 'first': stamp } zone[prot][name][addr]['last'] = stamp def populate_zone(zone, wan_hostname, wan_addr, hosts, hosts_list, hosts_nat, domain, stamp): wan_hostname = full_name(wan_hostname, domain) if not zone.get('A'): zone['A'] = {} if not zone.get('AAAA'): zone['AAAA'] = {} if wan_addr['ipv4'] != '': zone_add_entry(zone, 'A', wan_hostname, wan_addr['ipv4'], stamp) for host in hosts_nat: if hosts.get(host): zone_add_entry(zone, 'A', full_name(host, domain), wan_addr['ipv4'], stamp) if wan_addr['ipv6'] != '': zone_add_entry(zone, 'AAAA', wan_hostname, wan_addr['ipv6'], stamp) for host in hosts_list: for addr in hosts.get(host, []): zone_add_entry(zone, 'AAAA', full_name(host, domain), addr, stamp) def process_zone(zone, stamp, grace_period): update = { 'add': [], 'delete': [] } for prot in zone: for name in zone[prot]: add = False for addr in zone[prot][name]: e = zone[prot][name][addr] if e['first'] == stamp: update['add'].append([prot, name, addr]) add = True for addr in zone[prot][name]: e = zone[prot][name][addr] if add and e['last'] < stamp: update['delete'].append([prot, name, addr]) elif not add and stamp - e['last'] > grace_period: update['delete'].append([prot, name, addr]) if not update['add'] and not update['delete']: update = None return update def read_zone_list(zone_filename): try: with open(zone_filename) as jsonfile: zone = json.load(jsonfile) return zone except FileNotFoundError: return {} def write_zone_list(zone_filename, zone, update): zone = copy.deepcopy(zone) if update: for prot, name, addr in update['delete']: del zone[prot][name][addr] if not zone[prot][name]: del zone[prot][name] with open(zone_filename, 'w') as jsonfile: json.dump(zone, jsonfile, indent=2, sort_keys=True) #def make_delete_zone_list(zone_list, prev_zone_list): # return make_update_zone_list(prev_zone_list, zone_list) # # #def make_update_zone_list(zone_list, prev_zone_list): # update_zone_list = [] # for entry in zone_list: # if not any(entry == x for x in prev_zone_list): # update_zone_list.append(entry) # return update_zone_list # # # for host,typefield,target in zone_list: # if not host in config: # config[host] = {} # if typefield in config[host]: # config[host][typefield] += '\n'+target # else: # config[host][typefield] = target # with open(zone_filename, 'w') as configfile: # config.write(configfile) def log(msg): stamp = time.strftime("%Y-%m-%d %H:%M:%S") with open(log_filename, 'a') as logfile: for line in msg.split('\n'): logfile.write("%s - %s\n" % (stamp, msg)) def log_update_zone(update): op_str = { 'add': '', 'delete': '[DEL]' } for op in update: for prot, name, addr in update[op]: op = op_str.get(op, op) log('%5s %-20s %-6s %s' % (op, name, prot, addr)) def ovh_update_zone(domain, update): try: client = ovh.Client() for prot, name, addr in update['delete']: result = client.get('/domain/zone/%s/record' % domain, fieldType=prot, subDomain=name) for id in result: r = client.get('/domain/zone/%s/record/%d' % (domain, id)) if r['fieldType'] == prot and r['target'] == addr: print("OVH: delete entry for %s %s %s (#%s)" % (name, prot, addr, id)) client.delete('/domain/zone/%s/record/%d' % (domain, id)) for prot, name, addr in update['add']: print("OVH: create entry for %s %s %s" % (name, prot, addr)) client.post('/domain/zone/%s/record' % domain, fieldType=prot, subDomain=name, target=addr, ttl=60) print("OVH: Refresh zone %s" % domain) client.post('/domain/zone/%s/refresh' % domain) return True except: print('OVH update error\n') return False def send_update_mail(mail_to, mail_from, zone_domain, update, mail_ignore_list, wan): okmail=False for op in update: for prot,name,addr in update[op]: if not name in mail_ignore_list: okmail = True break if not okmail: return print('Send email to %s' % mail_to) msg = EmailMessage() msg['Subject'] = "Livebox update in %s" % zone_domain msg['From'] = mail_from msg['To' ] = mail_to txt = "Livebox update\n\n" txt = txt + "WAN IPv4 : %s\n" % wan['ipv4'] txt = txt + "WAN IPv6 : %s\n" % wan['ipv6'] txt = txt + "\nZone %s has been updated:\n" % zone_domain for prot,name,addr in update['add']: txt = txt + " %-20s %-4s %s\n" % (name,prot,addr) txt = txt + "\nRemoved entries:\n" for prot,name,addr in update['delete']: txt = txt + " %-20s %-4s %s\n" % (name,prot,addr) txt = txt + '\n' msg.set_content(txt) s = smtplib.SMTP('localhost') s.send_message(msg) s.quit() #print(txt) load_conf() if not ping(wan_hostname): log("%s is down" % wan_hostname) sys.exit(0) sysbus.load_conf() r = sysbus.auth(False) if not r: print('Error: cannot authenticate on livebox') sys.exit(1) hosts = get_ipv6_hosts() wan = get_wan_addr() zone = read_zone_list(zone_filename) stamp = int(time.time()) populate_zone(zone, wan_hostname, wan, hosts, hosts_list, nat_list, zone_subdomain, stamp) update = process_zone(zone, stamp, zone_timeout) if update: log_update_zone(update) success = ovh_update_zone(zone_domain, update) if success: send_update_mail(mail_to, mail_from, zone_domain, update, mail_ignore_list, wan) write_zone_list(zone_filename, zone, update)