TcpReassembler: skip non-IPv4 traffic; SignatureDetector: add paths to d-link evaluat...
[pingpong.git] / parser / parse_packet_size.py
1 #!/usr/bin/python
2
3 """
4 Script that takes a file (output by wireshark/tshark, in JSON format) and analyze
5 the variety of packet sizes 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 JSON_KEY_FRAME_LENGTH = "frame.len"
23 TABLE_HEADER_X = "Timestamp (hh:mm:ss)"
24 TABLE_HEADER_Y = "Packet sizes (bytes)"
25 INCOMING_APPENDIX = "_incoming"
26 OUTGOING_APPENDIX = "_outgoing"
27 FILE_APPENDIX = ".dat"
28
29
30 def save_to_file(tblheader, dictionary, 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 dictionary:
44         f.write("0 0")
45         f.close()
46         print "Writing zeroes to file: ", filenameout
47         return
48
49     # Iterate over dictionary and write (key, value) pairs
50     for key in sorted(dictionary):
51         # Space separated
52         f.write(str(key) + " " + str(dictionary[key]) + "\n")
53     f.close()
54     print "Writing output to file: ", filenameout
55
56
57 def main():
58     """ Main function
59     """
60     if len(sys.argv) < 5:
61         print "Usage: python", sys.argv[0], "<input_file> <output_file> <device_name> <mac_address>"
62         return
63     # Parse the file for the specified MAC address
64     timefreq_incoming = parse_json(sys.argv[1], sys.argv[4], True)
65     timefreq_outgoing = parse_json(sys.argv[1], sys.argv[4], False)
66     # Write statistics into file
67     print "====================================================================="
68     print "==> Analyzing incoming traffic ..."
69     save_to_file(sys.argv[3] + INCOMING_APPENDIX, timefreq_incoming, sys.argv[2] + INCOMING_APPENDIX + FILE_APPENDIX)
70     print "====================================================================="
71     print "==> Analyzing outgoing traffic ..."
72     save_to_file(sys.argv[3] + OUTGOING_APPENDIX, timefreq_outgoing, sys.argv[2] + OUTGOING_APPENDIX + FILE_APPENDIX)
73     print "====================================================================="
74
75
76 # Convert JSON file containing DNS traffic to a map in which a hostname points to its set of associated IPs.
77 def parse_json(filepath, macaddress, incomingoutgoing):
78     """ Show summary of statistics of PCAP file
79         Args:
80             filepath: path of the read file
81             macaddress: MAC address of a device to analyze
82             incomingoutgoing: boolean to define whether we collect incoming or outgoing traffic
83                               True = incoming, False = outgoing
84     """
85     # Maps timestamps to frequencies of packets
86     packetsize = dict()
87     with open(filepath) as jf:
88         # Read JSON.
89         # data becomes reference to root JSON object (or in our case json array)
90         data = json.load(jf)
91         # Loop through json objects in data
92         # Each entry is a pcap entry (request/response (packet) and associated metadata)
93         for p in data:
94             # p is a JSON object, not an index
95             layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
96             # Get timestamp
97             frame = layers.get(JSON_KEY_FRAME, None)
98             datetime = frame.get(JSON_KEY_FRAME_TIME, None)
99             length = frame.get(JSON_KEY_FRAME_LENGTH, None)
100             # Get into the Ethernet address part
101             eth = layers.get(JSON_KEY_ETH, None)
102             # Skip any non DNS traffic
103             if eth is None:
104                 print "[ WARNING: Packet has no ethernet address! ]"
105                 continue
106             # Get source and destination MAC addresses
107             src = eth.get(JSON_KEY_ETH_SRC, None)
108             dst = eth.get(JSON_KEY_ETH_DST, None)
109             # Get just the time part
110             datetimeobj = parser.parse(datetime)
111             timestr = str(datetimeobj.time())
112             print str(timestr) + " - src:" + str(src) + " - dest:" + str(dst)
113             # Get and count the traffic for the specified MAC address
114             if incomingoutgoing:           
115                 if dst == macaddress:
116                     # Put the time frequency in the dictionary
117                     packetsize[timestr] = length
118             else:
119                 if src == macaddress:
120                     # Put the time frequency in the dictionary
121                     packetsize[timestr] = length
122
123     return packetsize
124
125
126 if __name__ == '__main__':
127     main()
128