Adding binning capabilities to parse_packet_frequency.py script to smoothen and empha...
[pingpong.git] / parser / parse_inter_arrival_time.py
1 #!/usr/bin/python
2
3 """
4 Script that takes a file (output by wireshark/tshark, in JSON format) and analyze
5 the packet inter-arrival times 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_epoch"
23 TABLE_HEADER_X = "Packet number"
24 TABLE_HEADER_Y = "Time (seconds)"
25 INCOMING_APPENDIX = "_incoming"
26 OUTGOING_APPENDIX = "_outgoing"
27 FILE_APPENDIX = ".dat"
28
29
30 def save_to_file(tblheader, timestamp_list, filenameout):
31     """ Show summary of statistics of PCAP file
32         Args:
33             tblheader: header for the saved table
34             dictionary: dictionary to be saved
35             filename_out: file name to save
36     """
37     # Appending, not overwriting!
38     f = open(filenameout, 'a')
39     # Write the table header
40     f.write("# " + tblheader + "\n")
41     f.write("# " + TABLE_HEADER_X + " " + TABLE_HEADER_Y + "\n")
42     # Write "0 0" if dictionary is empty
43     if not timestamp_list:
44         f.write("0 0")
45         f.close()
46         print "Writing zeroes to file: ", filenameout
47         return
48     ind = 0
49     # Iterate over list and write index-value pairs
50     for val in timestamp_list:
51         # Space separated
52         f.write(str(ind) + " " + str(timestamp_list[ind]) + "\n")
53         ind += 1
54     f.close()
55     print "Writing output to file: ", filenameout
56
57
58 def main():
59     """ Main function
60     """
61     if len(sys.argv) < 5:
62         print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
63         return
64     # Parse the file for the specified MAC address
65     timestamplist_incoming = parse_json(sys.argv[1], sys.argv[4], True)
66     timestamplist_outgoing = parse_json(sys.argv[1], sys.argv[4], False)
67     # Write statistics into file
68     print "====================================================================="
69     print "==> Analyzing incoming traffic ..."
70     save_to_file(sys.argv[3] + INCOMING_APPENDIX, timestamplist_incoming, sys.argv[2] + INCOMING_APPENDIX + FILE_APPENDIX)
71     print "====================================================================="
72     print "==> Analyzing outgoing traffic ..."
73     save_to_file(sys.argv[3] + OUTGOING_APPENDIX, timestamplist_outgoing, sys.argv[2] + OUTGOING_APPENDIX + FILE_APPENDIX)
74     print "====================================================================="
75
76
77 # Convert JSON file containing DNS traffic to a map in which a hostname points to its set of associated IPs.
78 def parse_json(filepath, macaddress, incomingoutgoing):
79     """ Show summary of statistics of PCAP file
80         Args:
81             filepath: path of the read file
82             macaddress: MAC address of a device to analyze
83     """
84     # Maps timestamps to frequencies of packets
85     timestamplist = list()
86     with open(filepath) as jf:
87         # Read JSON.
88         # data becomes reference to root JSON object (or in our case json array)
89         data = json.load(jf)
90         # Loop through json objects in data
91         # Each entry is a pcap entry (request/response (packet) and associated metadata)
92         # Preserve two pointers prev and curr to iterate over the timestamps
93         prev = None
94         curr = None
95         for p in data:
96             # p is a JSON object, not an index
97             layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
98             # Get timestamp
99             frame = layers.get(JSON_KEY_FRAME, None)
100             timestamp = Decimal(frame.get(JSON_KEY_FRAME_TIME, None))
101             # Get into the Ethernet address part
102             eth = layers.get(JSON_KEY_ETH, None)
103             # Skip any non DNS traffic
104             if eth is None:
105                 print "[ WARNING: Packet has no ethernet address! ]"
106                 continue
107             # Get source and destination MAC addresses
108             src = eth.get(JSON_KEY_ETH_SRC, None)
109             dst = eth.get(JSON_KEY_ETH_DST, None)
110             # Get and count the traffic for the specified MAC address
111             if incomingoutgoing:
112                 if dst == macaddress:
113                     # Check if timestamp already exists in the map
114                     # If yes, then just increment the frequency value...
115                     print str(timestamp) + " - src:" + str(src) + " - dest:" + str(dst)
116                     curr = timestamp
117                     if prev is not None:
118                         inter_arrival_time = curr - prev
119                         timestamplist.append(inter_arrival_time)
120                     prev = curr
121             else:
122                 if src == macaddress:
123                     # Check if timestamp already exists in the map
124                     # If yes, then just increment the frequency value...
125                     print str(timestamp) + " - src:" + str(src) + " - dest:" + str(dst)
126                     curr = timestamp
127                     if prev is not None:
128                         inter_arrival_time = curr - prev
129                         timestamplist.append(inter_arrival_time)
130                     prev = curr
131
132     return timestamplist
133
134
135 if __name__ == '__main__':
136     main()
137