e81fd95e3477519f42599846987a1ed4a0e9e7ca
[pingpong.git] / parse_dns.py
1 #!/usr/bin/python
2
3 """
4 Script that takes a file (output by wireshark/tshark, in JSON format) with DNS traffic
5 and constructs a map (dictionary) in which a hostname points to a set that contains the
6 IP addresses that is associated with that hostname.
7 """
8
9 import sys
10 import json
11 from collections import defaultdict
12 from decimal import *
13
14 ROUTER_MAC = "b0:b9:8a:73:69:8e"
15
16 JSON_KEY_SOURCE = "_source"
17 JSON_KEY_LAYERS = "layers"
18 JSON_KEY_DNS = "dns"
19 JSON_KEY_QUERIES = "Queries"
20 JSON_KEY_ANSWERS = "Answers"
21 JSON_KEY_DNS_RESP_TYPE = "dns.resp.type"
22 JSON_KEY_DNS_A = "dns.a" # Key for retrieving IP. 'a' for type A DNS record.
23 JSON_KEY_DNS_RESP_NAME = "dns.resp.name"
24 JSON_KEY_DNS_CNAME = "dns.cname"
25 JSON_KEY_ETH = "eth"
26 JSON_KEY_ETH_DST = "eth.dst"
27 JSON_KEY_FRAME = "frame"
28 JSON_KEY_FRAME_TIME_EPOCH = "frame.time_epoch"
29
30 def main():
31         if len(sys.argv) < 2:
32                 print "Usage: python", sys.argv[0], "input_file"
33                 return
34         mac_to_ddm = parse_json_dns(sys.argv[1])
35         for mac in mac_to_ddm:
36                 ddm = mac_to_ddm[mac]
37                 ddm.print_mappings()
38         # maps_tuple = parse_json_dns(sys.argv[1])
39         
40         # # print hostname to ip map
41         # hn_ip_map = maps_tuple[0]
42         # for hn in hn_ip_map.keys():
43         #       print "====================================================================="
44         #       print hn, "maps to:"
45         #       for ip in hn_ip_map[hn]:
46         #               print "    -", ip
47         # print "====================================================================="
48         
49         # print " "
50
51         # # print ip to hostname map
52         # ip_hn_map = maps_tuple[1]
53         # for ip in ip_hn_map.keys():
54         #       print "====================================================================="
55         #       print ip, "maps to:"
56         #       for hn in ip_hn_map[ip]:
57         #               print "    -", hn
58         # print "====================================================================="
59
60 class DeviceDNSMap:
61         def __init__(self, mac_address):
62                 # MAC address of device
63                 self.mac = mac_address
64                 # Maps an external IP to a list of (timestamp,hostname) tuples.
65                 # Entries in the list should be interpreted as follows:
66                 # the timestamp indicates WHEN this device mapped the given ip (key in dict) to the hostname.
67                 self.ip_mappings = defaultdict(list)
68
69         def hostname_for_ip_at_time(self, ip, timestamp):
70                 # Does device have a mapping for the given IP?
71                 if not ip in self.ip_mappings:
72                         return None
73                 if not self.ip_mappings[ip]:
74                         # If list of (timestamp,hostname) tuples is empty, there is no mapping to report.
75                         return None
76                 # Best fit mapping: the mapping immediately BEFORE timestamp parameter.
77                 # Start with random pick (element 0).
78                 best_fit = self.ip_mappings[ip][0]
79                 for t in self.ip_mappings[ip]:
80                         # t is a (timestamp,hostname) tuple
81                         if t[0] < timestamp and t[0] > best_fit[0]:
82                                 # t is a better fit if it happened BEFORE the input timestamp
83                                 # and is LATER than the current best_fit
84                                 best_fit = t
85                 return best_fit
86
87         def add_mapping(self, ip, timestamp_hostname_tuple):
88                 self.ip_mappings[ip].append(timestamp_hostname_tuple)
89
90         def print_mappings(self):
91                 count = 0
92                 print "### Mappings for MAC = ", self.mac, "###"
93                 for ip in self.ip_mappings:
94                         print "--- IP ", ip, " maps to: ---"
95                         for t in self.ip_mappings[ip]:
96                                 print t[1], "at epoch time =", t[0]
97                                 count += 1
98                 print "### Total of", count, "mappings for", self.mac, "###"
99
100         # --------------------------------------------------------------------------
101         # Define eq and hash such that instances of the class can be used as keys in dictionaries.
102         # Equality is based on MAC as a MAC uniquely identifies the device.
103         def __eq__(self, another):
104                 return hasattr(another, 'mac') and self.mac == another.mac
105         def __hash__(self):
106                 return hash(self.data)
107         # --------------------------------------------------------------------------
108
109
110 def parse_json_dns(file_path):
111         # Our end output: dictionary of MAC addresses with DeviceDNSMaps as values.
112         # Each DeviceDNSMap contains DNS lookups performed by the device with the corresponding MAC.
113         result = defaultdict()
114         with open(file_path) as jf:
115                 # Read JSON.
116         # data becomes reference to root JSON object (or in our case json array)
117                 data = json.load(jf)
118                 # Loop through json objects in data
119                 # Each entry is a pcap entry (request/response (packet) and associated metadata)
120                 for p in data:
121                         # p is a JSON object, not an index
122                         # Drill down to DNS part: _source->layers->dns
123                         layers = p[JSON_KEY_SOURCE][JSON_KEY_LAYERS]
124                         dns = layers.get(JSON_KEY_DNS, None)
125                         # Skip any non DNS traffic
126                         if dns is None:
127                                 print "[ WARNING: Non DNS traffic ]"
128                                 continue
129                         # We only care about DNS responses as these also contain a copy of the query that they answer
130                         answers = dns.get(JSON_KEY_ANSWERS, None)
131                         if answers is None:
132                                 continue
133                         ## Now that we know that it is an answer, the queries should also be available.
134                         queries = dns.get(JSON_KEY_QUERIES)
135                         if len(queries.keys()) > 1:
136                                 # Unclear if script will behave correctly for DNS lookups with multiple queries
137                                 print "[ WARNING: Multi query DNS lookup ]"
138                         # Get ethernet information for identifying the device performing the DNS lookup.
139                         eth = layers.get(JSON_KEY_ETH, None)
140                         if eth is None:
141                                 print "[ WARNING: eth data not found ]"
142                                 continue
143                         # As this is a response to a DNS query, the IoT device is the destination.
144                         # Get the device MAC of that device.
145                         device_mac = eth.get(JSON_KEY_ETH_DST, None)
146                         if device_mac is None:
147                                 print "[ WARNING: eth.dst data not found ]"
148                                 continue
149                         # Get the router's timestamp for this packet
150                         # so that we can mark when the DNS mapping occurred
151                         timestamp = Decimal(layers[JSON_KEY_FRAME][JSON_KEY_FRAME_TIME_EPOCH])
152                         for ak in answers.keys():
153                                 a = answers[ak]
154                                 # We are looking for type A records as these are the ones that contain the IP.
155                                 # Type A == type 1
156                                 if a[JSON_KEY_DNS_RESP_TYPE] == "1":
157                                         # get the IP
158                                         ip = a[JSON_KEY_DNS_A]
159                                         # The answer may be the canonical name.
160                                         # Now trace back the answer stack, looking for any higher level aliases.
161                                         hostname = find_alias_hostname(answers, a[JSON_KEY_DNS_RESP_NAME])
162                                         # Create the tuple that indicates WHEN the ip to hostname mapping occurred
163                                         timestamp_hostname_tuple = (timestamp,hostname)
164                                         if device_mac in result:
165                                                 # If we already have DNS data for the device with this MAC:
166                                                 # Add the mapping to the DeviceDNSMap that is already present in the dict.
167                                                 result[device_mac].add_mapping(ip, timestamp_hostname_tuple)
168                                         else:
169                                                 # No DNS data for this device yet:
170                                                 # Create a new DeviceDNSMap, add the mapping, and at it to the dict.
171                                                 ddm = DeviceDNSMap(device_mac)
172                                                 ddm.add_mapping(ip, timestamp_hostname_tuple)
173                                                 result[device_mac] = ddm
174         return result
175
176 # Recursively traverse set of answers trying to find the top most alias for a canonical name
177 def find_alias_hostname(answers, hostname):
178         for ak in answers.keys():
179                 a = answers[ak]
180                 cname = a.get(JSON_KEY_DNS_CNAME, None)
181                 # We only care about type=CNAME records
182                 if cname is None:
183                         continue
184                 if cname == hostname:
185                         # Located the right answer, perform recursive search for higher level aliases.
186                         return find_alias_hostname(answers, a[JSON_KEY_DNS_RESP_NAME])
187         return hostname
188
189 if __name__ == '__main__':
190         main()
191
192 # ================================================================================================
193 # Notes/brainstorming how to do ip to host mappings.
194
195 # Maps IPs to hostnames. Uses a dictionary of dictionaries.
196 # IP lookup in the outer dictionary returns a dictionary that has hostnames as keys.
197 # Looking up a hostname in the inner dictionary returns a set of timestamps.
198 # Each timestamp indicate the time at which the IP<->hostname mapping was determined by a DNS query.
199 # Note that the keyset of the inner dictionary will be of size 1 in most cases.
200 # When this is the case, the value (the set of timestamps) can be ignored.
201 # The values are only relevant when one IP maps to more than 1 hostname.
202 # When this the case, the timestamps must be considered to find the most recent mapping.
203 # ip_host_mappings = defaultdict(defaultdict(set))
204
205 # ================================================================================================