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