Separating incoming and outgoing traffic for a more fine-grained analysis
[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
14 JSON_KEY_SOURCE = "_source"
15 JSON_KEY_LAYERS = "layers"
16
17 JSON_KEY_ETH = "eth"
18 JSON_KEY_ETH_DST = "eth.dst"
19 JSON_KEY_ETH_SRC = "eth.src"
20 JSON_KEY_FRAME = "frame"
21 JSON_KEY_FRAME_TIME = "frame.time"
22 TABLE_HEADER_X = "Timestamp (hh:mm:ss)"
23 TABLE_HEADER_Y = "Packet frequency (pps)"
24 INCOMING_APPENDIX = "_incoming"
25 OUTGOING_APPENDIX = "_outgoing"
26 FILE_APPENDIX = ".dat"
27
28 # Use this constant as a flag
29 WINDOW_SIZE = 5
30 USE_MOVING_AVERAGE = False
31
32
33 def moving_average(array, window=3):
34     """ Calculate moving average
35         Args:
36             array: array of numbers
37             window: window of moving average (default = 3)
38         Adapted from: 
39             https://stackoverflow.com/questions/14313510/how-to-calculate-moving-average-using-numpy
40     """
41     # Check if window > len(array)
42     if window > len(array):
43         window = len(array)
44     # Calculate cumulative sum of each array element
45     retarr = np.cumsum(array, dtype=float)
46     # Adjust cumulative sum of each array element
47     #   based on window size
48     retarr[window:] = retarr[window:] - retarr[:-window]
49     # Pad the first array elements with zeroes
50     retarr[:window - 1] = np.zeros(window - 1)
51     # Calculate moving average starting from the element
52     #   at window size, e.g. element 4 for window=5
53     retarr[window - 1:] = retarr[window - 1:] / window
54     return retarr
55
56
57 def save_to_file(tblheader, dictionary, filenameout):
58     """ Show summary of statistics of PCAP file
59         Args:
60             tblheader: header for the saved table
61             dictionary: dictionary to be saved
62             filename_out: file name to save
63     """
64     # Appending, not overwriting!
65     f = open(filenameout, 'a')
66     # Write the table header
67     f.write("# " + tblheader + "\n")
68     f.write("# " + TABLE_HEADER_X + " " + TABLE_HEADER_Y + "\n")
69     # Write "0 0" if dictionary is empty
70     if not dictionary:
71         f.write("0 0")
72         f.close()
73         print "Writing zeroes to file: ", filenameout
74         return
75
76     if USE_MOVING_AVERAGE:
77         # Use moving average if this flag is true
78         sortedarr = []
79         for key in sorted(dictionary):
80             sortedarr.append(dictionary[key])
81         valarr = moving_average(sortedarr, WINDOW_SIZE)
82         #print vallist
83         # Iterate over dictionary and write (key, value) pairs
84         ind = 0
85         for key in sorted(dictionary):
86             # Space separated
87             f.write(str(key) + " " + str(valarr[ind]) + "\n")
88             ind += 1
89     else:
90         # Iterate over dictionary and write (key, value) pairs
91         for key in sorted(dictionary):
92             # Space separated
93             f.write(str(key) + " " + str(dictionary[key]) + "\n")
94     f.close()
95     print "Writing output to file: ", filenameout
96
97
98 def main():
99     """ Main function
100     """
101     if len(sys.argv) < 5:
102         print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
103         return
104     # Parse the file for the specified MAC address
105     timefreq_incoming = parse_json(sys.argv[1], sys.argv[4], True)
106     timefreq_outgoing = parse_json(sys.argv[1], sys.argv[4], False)
107     # Write statistics into file
108     print "====================================================================="
109     print "==> Analyzing incoming traffic ..."
110     save_to_file(sys.argv[3] + INCOMING_APPENDIX, timefreq_incoming, sys.argv[2] + INCOMING_APPENDIX + FILE_APPENDIX)
111     print "====================================================================="
112     print "==> Analyzing outgoing traffic ..."
113     save_to_file(sys.argv[3] + OUTGOING_APPENDIX, timefreq_outgoing, sys.argv[2] + OUTGOING_APPENDIX + FILE_APPENDIX)
114     print "====================================================================="
115     #for time in time_freq.keys():
116     #for key in sorted(time_freq):
117     #    print key, " => ", time_freq[key]
118     #print "====================================================================="
119
120
121 # Convert JSON file containing DNS traffic to a map in which a hostname points to its set of associated IPs.
122 def parse_json(filepath, macaddress, incomingoutgoing):
123     """ Show summary of statistics of PCAP file
124         Args:
125             filepath: path of the read file
126             macaddress: MAC address of a device to analyze
127             incomingoutgoing: boolean to define whether we collect incoming or outgoing traffic
128                               True = incoming, False = outgoing
129     """
130     # Maps timestamps to frequencies of packets
131     timefreq = dict()
132     with open(filepath) as jf:
133         # Read JSON.
134         # data becomes reference to root JSON object (or in our case json array)
135         data = json.load(jf)
136         # Loop through json objects in data
137         # Each entry is a pcap entry (request/response (packet) and associated metadata)
138         for p in data:
139             # p is a JSON object, not an index
140             layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
141             # Get timestamp
142             frame = layers.get(JSON_KEY_FRAME, None)
143             datetime = frame.get(JSON_KEY_FRAME_TIME, None)
144             # Get into the Ethernet address part
145             eth = layers.get(JSON_KEY_ETH, None)
146             # Skip any non DNS traffic
147             if eth is None:
148                 print "[ WARNING: Packet has no ethernet address! ]"
149                 continue
150             # Get source and destination MAC addresses
151             src = eth.get(JSON_KEY_ETH_SRC, None)
152             dst = eth.get(JSON_KEY_ETH_DST, None)
153             # Get just the time part
154             datetimeobj = parser.parse(datetime)
155             # Remove the microsecond part
156             timestr = str(datetimeobj.time())[:8]
157             print str(timestr) + " - src:" + str(src) + " - dest:" + str(dst)
158             # Get and count the traffic for the specified MAC address
159             if incomingoutgoing:           
160                 if dst == macaddress:
161                     # Check if timestamp already exists in the map
162                     # If yes, then just increment the frequency value...
163                     if timestr in timefreq:
164                         timefreq[timestr] = timefreq[timestr] + 1
165                     else: # If not, then put the value one there
166                         timefreq[timestr] = 1
167             else:
168                 if src == macaddress:
169                     # Check if timestamp already exists in the map
170                     # If yes, then just increment the frequency value...
171                     if timestr in timefreq:
172                         timefreq[timestr] = timefreq[timestr] + 1
173                     else: # If not, then put the value one there
174                         timefreq[timestr] = 1
175
176     return timefreq
177
178
179 if __name__ == '__main__':
180     main()
181