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.
11 from collections import defaultdict
12 from dateutil import parser
13 from datetime import datetime
16 JSON_KEY_SOURCE = "_source"
17 JSON_KEY_LAYERS = "layers"
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"
30 # Use this constant as a flag
32 USE_MOVING_AVERAGE = False
34 # Range = 6, i.e. 3 to left and 3 to right (in seconds)
35 TOTAL_RANGE = 60 # TOTAL_RANGE = 2 x RANGE
39 def moving_average(array, window=3):
40 """ Calculate moving average
42 array: array of numbers
43 window: window of moving average (default = 3)
45 https://stackoverflow.com/questions/14313510/how-to-calculate-moving-average-using-numpy
47 # Check if window > len(array)
48 if 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
62 def hms_to_seconds(t):
63 """ Calculate hms to seconds
65 t = time in hh:mm:ss string
67 https://stackoverflow.com/questions/10742296/python-time-conversion-hms-to-seconds
69 h, m, s = [int(i) for i in t.split(':')]
70 return 3600*h + 60*m + s
72 def seconds_to_hms(t):
73 """ Calculate seconds to hms
77 https://stackoverflow.com/questions/10742296/python-time-conversion-hms-to-seconds
80 m = (t - (h * 3600)) / 60
81 s = t - (h * 3600) - (m * 60)
91 return hh + ":" + mm + ":" + ss
93 def include_timestamps_zero_packets(timefreq):
94 """ Include every second that has zero packets (no packets/transmission)
96 timefreq = dictionary that maps timestamps to number of packets
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
109 while counter < seconds:
110 timestamp = seconds_to_hms(first_seconds + counter)
111 if timestamp not in timefreq:
112 timefreq[timestamp] = 0
117 def save_to_file(tblheader, dictionary, filenameout):
118 """ Show summary of statistics of PCAP file
120 tblheader: header for the saved table
121 dictionary: dictionary to be saved
122 filename_out: file name to save
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
133 print "Writing zeroes to file: ", filenameout
136 if USE_MOVING_AVERAGE:
137 # Use moving average if this flag is true
139 for key in sorted(dictionary):
140 sortedarr.append(dictionary[key])
141 valarr = moving_average(sortedarr, WINDOW_SIZE)
143 # Iterate over dictionary and write (key, value) pairs
145 for key in sorted(dictionary):
147 f.write(str(key) + " " + str(valarr[ind]) + "\n")
152 # Iterate over dictionary and write (key, value) pairs
156 for key in sorted(dictionary):
157 sortedlist.append(key)
158 print "Key: ", key, " - Value: ", dictionary[key], " - Ind: ", ind
160 first = hms_to_seconds(sortedlist[0])
161 #print "First: ", key
162 last = hms_to_seconds(sortedlist[ind-1])
165 # Put new binning keys
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]
179 if ind > len(dictionary)-1:
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):
189 f.write(seconds_to_hms(key) + " " + str(resultdict[key]) + "\n")
190 #print seconds_to_hms(key) + " " + str(resultdict[key])
193 # Iterate over dictionary and write (key, value) pairs
194 for key in sorted(dictionary):
196 f.write(str(key) + " " + str(dictionary[key]) + "\n")
198 print "Writing output to file: ", filenameout
204 if len(sys.argv) < 5:
205 print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
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 "====================================================================="
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
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
235 # Maps timestamps to frequencies of packets
237 with open(filepath) as jf:
239 # data becomes reference to root JSON object (or in our case json array)
241 # Loop through json objects in data
242 # Each entry is a pcap entry (request/response (packet) and associated metadata)
244 # p is a JSON object, not an index
245 layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
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
253 print "[ WARNING: Packet has no ethernet address! ]"
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
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
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
284 if __name__ == '__main__':