· 9 years ago · Jan 18, 2017, 12:02 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 enterDNS(items[1])
70
71#first generate macs from config file using method
72
73macList = getMACs()
74
75#generate our IPs to monitor and call checkTables to ensure our SQL table exists
76checkTables()
77
78#begin running the tcpdump subprocess piping output to stdout
79
80#capture start time of the process and save to clock variable
81setTime()
82
83
84def printer(packet):
85 src = packet[0][0].src
86 dst = packet[0][0].dst
87 global clock
88 global macList
89
90 if src in macList:
91 listVals = [packet[0][0].src, packet[0][1].dst, packet[0][1].dport, packet[0][1].len, 'out']
92 tablePush(listVals)
93 elif dst in macList:
94 listVals = [packet[0][0].dst ,packet[0][1].src, packet[0][1].sport, packet[0][1].len, 'in']
95 tablePush(listVals)
96
97 if getTime() - refresh_rate > clock:
98 #update monitored IPs and update clock
99 macList = getMACs()
100 clock = getTime()
101 #print 'updatedIPs'
102 #commit changes to database
103 conn.commit()
104
105#create an INET, STREAMing socket
106sniff(filter="tcp or udp", prn=printer, store=0)