Merge branch 'master' of https://github.uci.edu/rtrimana/smart_home_traffic
[pingpong.git] / parser / parse_packet_frequency.py
1 #!/usr/bin/python
2
3 """
4 Script that takes a file (output by wireshark/tshark, in JSON format) and analyze
5 the traffic frequency of a certain device at a certain time.
6 """
7
8 import sys
9 import json
10 import numpy as np
11 from collections import defaultdict
12 from dateutil import parser
13 from datetime import datetime
14 from decimal import *
15
16 JSON_KEY_SOURCE = "_source"
17 JSON_KEY_LAYERS = "layers"
18
19 JSON_KEY_ETH = "eth"
20 JSON_KEY_ETH_DST = "eth.dst"
21 JSON_KEY_ETH_SRC = "eth.src"
22 JSON_KEY_FRAME = "frame"
23 JSON_KEY_FRAME_TIME = "frame.time"
24 TABLE_HEADER_X = "Timestamp (hh:mm:ss)"
25 TABLE_HEADER_Y = "Packet frequency (pps)"
26 INCOMING_APPENDIX = "_incoming"
27 OUTGOING_APPENDIX = "_outgoing"
28 FILE_APPENDIX = ".dat"
29
30 # Use this constant as a flag
31 WINDOW_SIZE = 5
32 USE_MOVING_AVERAGE = False
33 USE_BINNING = True
34 # Range = 6, i.e. 3 to left and 3 to right (in seconds)
35 TOTAL_RANGE = 60 # TOTAL_RANGE = 2 x RANGE
36 RANGE = 30
37
38
39 def moving_average(array, window=3):
40     """ Calculate moving average
41         Args:
42             array: array of numbers
43             window: window of moving average (default = 3)
44         Adapted from: 
45             https://stackoverflow.com/questions/14313510/how-to-calculate-moving-average-using-numpy
46     """
47     # Check if window > len(array)
48     if window > len(array):
49         window = len(array)
50     # Calculate cumulative sum of each array element
51     retarr = np.cumsum(array, dtype=float)
52     # Adjust cumulative sum of each array element
53     #   based on window size
54     retarr[window:] = retarr[window:] - retarr[:-window]
55     # Pad the first array elements with zeroes
56     retarr[:window - 1] = np.zeros(window - 1)
57     # Calculate moving average starting from the element
58     #   at window size, e.g. element 4 for window=5
59     retarr[window - 1:] = retarr[window - 1:] / window
60     return retarr
61
62 def hms_to_seconds(t):
63     """ Calculate hms to seconds
64         Args:
65             t = time in hh:mm:ss string
66         Adapted from:
67             https://stackoverflow.com/questions/10742296/python-time-conversion-hms-to-seconds
68     """
69     h, m, s = [int(i) for i in t.split(':')]
70     return 3600*h + 60*m + s
71     
72 def seconds_to_hms(t):
73     """ Calculate seconds to hms
74         Args:
75             t = time in seconds
76         Adapted from:
77             https://stackoverflow.com/questions/10742296/python-time-conversion-hms-to-seconds
78     """
79     h = t / 3600
80     m = (t - (h * 3600)) / 60
81     s = t - (h * 3600) - (m * 60)
82     hh = str(h)
83     if len(hh) is 1:
84         hh = "0" + hh
85     mm = str(m)
86     if len(mm) is 1:
87         mm = "0" + mm
88     ss = str(s) 
89     if len(ss) is 1:
90         ss = "0" + ss
91     return hh + ":" + mm + ":" + ss
92     
93 def include_timestamps_zero_packets(timefreq):
94     """ Include every second that has zero packets (no packets/transmission)
95         Args:
96             timefreq = dictionary that maps timestamps to number of packets
97     """
98     sortedkeylist = []
99     for key in sorted(timefreq):
100         sortedkeylist.append(key)
101     first = sortedkeylist[0]
102     last = sortedkeylist[len(sortedkeylist)-1]
103     # Calculate the number of seconds between first and last packets
104     first_seconds = hms_to_seconds(first)
105     last_seconds = hms_to_seconds(last)
106     seconds = last_seconds - first_seconds
107     # Start counting and filling in timestamps with zero packets
108     counter = 0
109     while counter < seconds:
110         timestamp = seconds_to_hms(first_seconds + counter)
111         if timestamp not in timefreq:
112             timefreq[timestamp] = 0
113         counter += 1
114     return timefreq
115     
116
117 def save_to_file(tblheader, dictionary, filenameout):
118     """ Show summary of statistics of PCAP file
119         Args:
120             tblheader: header for the saved table
121             dictionary: dictionary to be saved
122             filename_out: file name to save
123     """
124     # Appending, not overwriting!
125     f = open(filenameout, 'a')
126     # Write the table header
127     f.write("# " + tblheader + "\n")
128     f.write("# " + TABLE_HEADER_X + " " + TABLE_HEADER_Y + "\n")
129     # Write "0 0" if dictionary is empty
130     if not dictionary:
131         f.write("0 0")
132         f.close()
133         print "Writing zeroes to file: ", filenameout
134         return
135
136     if USE_MOVING_AVERAGE:
137         # Use moving average if this flag is true
138         sortedarr = []
139         for key in sorted(dictionary):
140             sortedarr.append(dictionary[key])
141         valarr = moving_average(sortedarr, WINDOW_SIZE)
142         #print vallist
143         # Iterate over dictionary and write (key, value) pairs
144         ind = 0
145         for key in sorted(dictionary):
146             # Space separated
147             f.write(str(key) + " " + str(valarr[ind]) + "\n")
148             ind += 1
149
150     elif USE_BINNING:
151         sortedlist = []
152         # Iterate over dictionary and write (key, value) pairs
153         ind = 0
154         first = 0
155         last = 0
156         for key in sorted(dictionary):
157             sortedlist.append(key)
158             print "Key: ", key, " - Value: ", dictionary[key], " - Ind: ", ind
159             ind += 1
160         first = hms_to_seconds(sortedlist[0])
161         #print "First: ", key
162         last = hms_to_seconds(sortedlist[ind-1])
163         #print "Last: ", key
164         resultdict = dict()
165         # Put new binning keys
166         time_ind = first
167         ind = 0
168         while time_ind < last:
169             # Initialize with the first key in the list
170             curr_key = sortedlist[ind]
171             curr_key_secs = hms_to_seconds(curr_key)
172             # Initialize with 0 first
173             resultdict[time_ind] = 0
174             # Check if this is still within RANGE - bin the value if it is
175             while time_ind - RANGE <= curr_key_secs and curr_key_secs <= time_ind + RANGE:
176                 resultdict[time_ind] += dictionary[curr_key]
177                 print "Time index: ", seconds_to_hms(time_ind), " Value: ", resultdict[time_ind]
178                 ind += 1
179                 if ind > len(dictionary)-1:
180                     break
181                 # Initialize with the key in the list
182                 curr_key = sortedlist[ind]
183                 curr_key_secs = hms_to_seconds(curr_key)
184             # Increment time index
185             time_ind += TOTAL_RANGE
186         # Now write to file after binning
187         for key in sorted(resultdict):
188             # Space separated
189             f.write(seconds_to_hms(key) + " " + str(resultdict[key]) + "\n")
190             #print seconds_to_hms(key) + " " + str(resultdict[key])
191
192     else:
193         # Iterate over dictionary and write (key, value) pairs
194         for key in sorted(dictionary):
195             # Space separated
196             f.write(str(key) + " " + str(dictionary[key]) + "\n")
197     f.close()
198     print "Writing output to file: ", filenameout
199
200
201 def main():
202     """ Main function
203     """
204     if len(sys.argv) < 5:
205         print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
206         return
207     # Parse the file for the specified MAC address
208     timefreq_incoming = parse_json(sys.argv[1], sys.argv[4], True)
209     timefreq_incoming = include_timestamps_zero_packets(timefreq_incoming)
210     timefreq_outgoing = parse_json(sys.argv[1], sys.argv[4], False)
211     timefreq_outgoing = include_timestamps_zero_packets(timefreq_outgoing)
212     # Write statistics into file
213     print "====================================================================="
214     print "==> Analyzing incoming traffic ..."
215     save_to_file(sys.argv[3] + INCOMING_APPENDIX, timefreq_incoming, sys.argv[2] + INCOMING_APPENDIX + FILE_APPENDIX)
216     print "====================================================================="
217     print "==> Analyzing outgoing traffic ..."
218     save_to_file(sys.argv[3] + OUTGOING_APPENDIX, timefreq_outgoing, sys.argv[2] + OUTGOING_APPENDIX + FILE_APPENDIX)
219     print "====================================================================="
220     #for time in time_freq.keys():
221     #for key in sorted(time_freq):
222     #    print key, " => ", time_freq[key]
223     #print "====================================================================="
224
225
226 # Convert JSON file containing DNS traffic to a map in which a hostname points to its set of associated IPs.
227 def parse_json(filepath, macaddress, incomingoutgoing):
228     """ Show summary of statistics of PCAP file
229         Args:
230             filepath: path of the read file
231             macaddress: MAC address of a device to analyze
232             incomingoutgoing: boolean to define whether we collect incoming or outgoing traffic
233                               True = incoming, False = outgoing
234     """
235     # Maps timestamps to frequencies of packets
236     timefreq = dict()
237     with open(filepath) as jf:
238         # Read JSON.
239         # data becomes reference to root JSON object (or in our case json array)
240         data = json.load(jf)
241         # Loop through json objects in data
242         # Each entry is a pcap entry (request/response (packet) and associated metadata)
243         for p in data:
244             # p is a JSON object, not an index
245             layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
246             # Get timestamp
247             frame = layers.get(JSON_KEY_FRAME, None)
248             datetime = frame.get(JSON_KEY_FRAME_TIME, None)
249             # Get into the Ethernet address part
250             eth = layers.get(JSON_KEY_ETH, None)
251             # Skip any non DNS traffic
252             if eth is None:
253                 print "[ WARNING: Packet has no ethernet address! ]"
254                 continue
255             # Get source and destination MAC addresses
256             src = eth.get(JSON_KEY_ETH_SRC, None)
257             dst = eth.get(JSON_KEY_ETH_DST, None)
258             # Get just the time part
259             datetimeobj = parser.parse(datetime)
260             # Remove the microsecond part
261             timestr = str(datetimeobj.time())[:8]
262             print str(timestr) + " - src:" + str(src) + " - dest:" + str(dst)
263             # Get and count the traffic for the specified MAC address
264             if incomingoutgoing:           
265                 if dst == macaddress:
266                     # Check if timestamp already exists in the map
267                     # If yes, then just increment the frequency value...
268                     if timestr in timefreq:
269                         timefreq[timestr] = timefreq[timestr] + 1
270                     else: # If not, then put the value one there
271                         timefreq[timestr] = 1
272             else:
273                 if src == macaddress:
274                     # Check if timestamp already exists in the map
275                     # If yes, then just increment the frequency value...
276                     if timestr in timefreq:
277                         timefreq[timestr] = timefreq[timestr] + 1
278                     else: # If not, then put the value one there
279                         timefreq[timestr] = 1
280
281     return timefreq
282
283
284 if __name__ == '__main__':
285     main()
286