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