def run(self): global homenet global lock while 1: self.ctime = int(time.time()) try: f = open('/var/log/dnsmasq.leases', 'r') lines = f.readlines() if len(lines) > 0: with lock: for line in lines: line = line.strip() fields = line.split() ts = int(fields[0]) - 604800 mac = fields[1].upper() ip = str(fields[2]) hostname = str(fields[3]) if ip not in homenet.hosts: device = Host() device.ts = ts device.lseen = ts device.mac = mac device.ip = ip device.hostname = hostname device.vendor = utils.get_vendor(mac) homenet.hosts[ip] = device self.create_alert(ts, ip, mac, hostname) if mac not in homenet.mac_history: homenet.mac_history[mac] = [[ip, ts]] else: homenet.mac_history[mac].append([ip, ts]) else: if (ts > homenet.hosts[ip].lseen) and ( mac == homenet.hosts[ip].mac): homenet.hosts[ip].lseen = ts elif (ts > homenet.hosts[ip].lseen) and ( mac != homenet.hosts[ip].mac): del homenet.hosts[ip] device = Host() device.ts = ts device.lseen = ts device.mac = mac device.ip = ip device.hostname = hostname device.vendor = utils.get_vendor(mac) homenet.hosts[ip] = device self.create_alert(ts, ip, mac, hostname) if mac not in homenet.mac_history: homenet.mac_history[mac] = [[ip, ts]] else: homenet.mac_history[mac].append( [ip, ts]) else: pass except Exception as e: log.debug( 'FG-WARN: read_dhcp_leases_log - Issues reading /var/log/dnsmasq.leases file' ) time.sleep(5)
def create_alert(self, ts, ip, mac, hostname): ctime = int(time.time()) description = 'A new device was connected to your network. If this device was not ' \ 'connected or authorized by you we recommend to check your router ' \ 'configuration and disallow the access to this device.' reference = 'https://en.wikipedia.org/wiki/Networking_hardware' vendor = utils.get_vendor(mac) indicators = ip + '|' + mac + '|' + hostname + '|' + [lambda:vendor, lambda:''][not vendor]() a = [0, 'new_device', ts, ctime, 0, 0, 'New Device', ip, indicators, 0, description, reference] alert_id = utils.add_alert_to_db(a) homenet.hosts[ip].alerts.append(alert_id)