· 9 years ago · Jan 18, 2017, 12:18 PM
1import socket, sys
2from scapy.all import *
3from struct import *
4import subprocess as sub
5import time
6import re
7import sqlite3 as sql
8import os
9
10#Defines refresh rate of the IP addresses to be monitored
11refresh_rate = 10
12interface_name = 'br-lan'
13
14#establishes connection to a database creating it if it doesn't exist
15conn = sql.connect('/tmp/tempHistory.db')
16cur = conn.cursor()
17tableName = 'connectionHistory'
18global macList
19
20
21def getTime():
22 #Function that gets the system time in seconds
23 return int(round(time.time()))
24def setTime():
25 global clock
26 clock = getTime()
27
28def getMACs ():
29 #Function that gets the IP addresses from the configuration file
30
31 #First accesses config file for monitored IPsf
32 ipConfigFile = open('/etc/config/cbi_file', 'r')
33
34 #Scans through file looking for DeviceIP objects and trims the string accordinglu to get the IP address
35 List = []
36 for line in ipConfigFile:
37 if "option mac" in line:
38 value = line[13:(len(line)-2)]
39 List.append(value)
40 #print List
41 return List
42
43def checkTables ():
44 #Function to check if table exists to hold data
45 cur.execute("CREATE TABLE IF NOT EXISTS connectionHistory (monitorMAC text, toIP text, connection text, port integer, length integer, PRIMARY KEY (monitorMAC, toIP, connection, port))")
46 #print 'Created master table'
47 cur.execute("CREATE TABLE IF NOT EXISTS dnsLookups (toIP text PRIMARY KEY, hostname text)")
48
49def enterDNS (ipAddr):
50
51 #if ip address does not already exist in table do following
52 nslookupProc = sub.Popen(('nslookup', ipAddr), stdout=sub.PIPE)
53 results = nslookupProc.communicate()[0]
54 #regular expression to pull hostname
55 dnsRecord = re.findall( r'([^\s]+\.[a-z]+)', results)
56 if dnsRecord != []:
57 entry = dnsRecord[0]
58 #print entry
59 cur.execute("INSERT OR IGNORE INTO dnsLookups VALUES (?,?)", (ipAddr, entry))
60 else:
61 cur.execute("INSERT OR IGNORE INTO dnsLookups VALUES (?,?)", (ipAddr, ""))
62
63def tablePush (items):
64
65 #Tries to update values in table
66 cur.execute("UPDATE connectionHistory SET length = length + ? WHERE monitorMAC = ? AND toIP = ? AND port = ? AND connection = ?", (items[3], items[0], items[1], items[2], items[4]))
67 cur.execute("INSERT OR IGNORE INTO connectionHistory VALUES (?,?,?,?,?)", (items[0], items[1], items[4], items[2], items[3]))
68 #print 'added value'
69 if cur.rowcount > 0:
70 enterDNS(items[1])
71
72#first generate macs from config file using method
73
74macList = getMACs()
75
76#generate our IPs to monitor and call checkTables to ensure our SQL table exists
77checkTables()
78
79#begin running the tcpdump subprocess piping output to stdout
80
81#capture start time of the process and save to clock variable
82setTime()
83
84
85def printer(packet):
86 src = packet[0][0].src
87 dst = packet[0][0].dst
88 global clock
89 global macList
90
91 if src in macList:
92 listVals = [packet[0][0].src, packet[0][1].dst, packet[0][1].dport, packet[0][1].len, 'out']
93 tablePush(listVals)
94 elif dst in macList:
95 listVals = [packet[0][0].dst ,packet[0][1].src, packet[0][1].sport, packet[0][1].len, 'in']
96 tablePush(listVals)
97
98 if getTime() - refresh_rate > clock:
99 #update monitored IPs and update clock
100 macList = getMACs()
101 clock = getTime()
102 print 'updatedIPs'
103 #commit changes to database
104 conn.commit()
105
106#create an INET, STREAMing socket
107sniff(filter="tcp or udp", prn=printer, store=0)
108#look up cacti for openwrt