Converted IP to hostname map from Map<String,List<String>> to Map<String,Set<String...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3
4 import org.pcap4j.core.*;
5 import org.pcap4j.packet.*;
6 import org.pcap4j.packet.DnsPacket;
7 import org.pcap4j.packet.namednumber.DnsResourceRecordType;
8
9 import java.io.EOFException;
10 import java.net.Inet4Address;
11 import java.net.UnknownHostException;
12 import java.util.*;
13 import java.util.concurrent.TimeoutException;
14
15 /**
16  * This is a system that reads PCAP files to compare
17  * patterns of DNS hostnames, packet sequences, and packet
18  * lengths with training data to determine certain events
19  * or actions for smart home devices.
20  *
21  * @author Janus Varmarken
22  * @author Rahmadi Trimananda (rtrimana@uci.edu)
23  * @version 0.1
24  */
25 public class Main {
26
27
28     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
29         final String fileName = "/users/varmarken/Desktop/wlan1.local.dns.pcap";
30         List<DnsPacket> dnsPackets = extractDnsAnswerPackets(fileName);
31         Map<String, Set<String>> ipToHostnameMap = constructIpToHostnameMap(dnsPackets);
32         ipToHostnameMap.forEach((k,v) -> System.out.println(String.format("%s => %s", k, v.toString())));
33     }
34
35     /**
36      * Opens a PCAP file and extracts all DNS reply packets with non-empty answer sections.
37      * @param pcapFileName The name of the PCAP file.
38      * @return A list of DNS reply packets.
39      * @throws PcapNativeException
40      * @throws NotOpenException
41      * @throws TimeoutException
42      */
43     private static List<DnsPacket> extractDnsAnswerPackets(String pcapFileName) throws PcapNativeException, NotOpenException, TimeoutException {
44         PcapHandle handle;
45         try {
46             handle = Pcaps.openOffline(pcapFileName, PcapHandle.TimestampPrecision.NANO);
47         } catch (PcapNativeException pne) {
48             handle = Pcaps.openOffline(pcapFileName);
49         }
50         // Apparently BPFs don't support "dns" protocol filter, so have to filter by port.
51         handle.setFilter("port 53", BpfProgram.BpfCompileMode.OPTIMIZE);
52         ArrayList<DnsPacket> result = new ArrayList<>();
53         try {
54             Packet packet;
55             while ((packet = handle.getNextPacketEx()) != null) {
56                 DnsPacket dnsPacket = packet.get(DnsPacket.class);
57                 // We only care about DNS answers.
58                 if (dnsPacket != null && dnsPacket.getHeader().getAnswers().size() != 0) {
59                     result.add(dnsPacket);
60                 }
61             }
62         } catch (EOFException eof) {
63             // (Note have to resort to EOFException as handle.getStats().getNumPacketsCaptured() only works on Windows)
64             // Clean up.
65             handle.close();
66         }
67         System.out.println(String.format("Found %d DNS answers", result.size()));
68         return result;
69     }
70
71     /**
72      * Based on the information found in a list of DNS replies, this method constructs a {@link Map} that maps from an
73      * IP to a {@link Set} of hostnames associated with that IP.
74      *
75      * @param dnsPackets A list of DNS <em>reply</em> packets.
76      * @return A {@link Map} that maps from an IP to a {@link Set} of hostnames associated with that IP
77      * @throws UnknownHostException If an IP found in a {@code DnsPacket} is of incorrect length.
78      */
79     private static Map<String, Set<String>> constructIpToHostnameMap(List<DnsPacket> dnsPackets) throws UnknownHostException {
80         HashMap<String, Set<String>> result = new HashMap<>();
81         for(DnsPacket dnsPacket : dnsPackets) {
82             // The hostname that this DNS reply provides answers for.
83             // TODO: safe to assume only one question?
84             String hostname = dnsPacket.getHeader().getQuestions().get(0).getQName().getName();
85             for(DnsResourceRecord answer : dnsPacket.getHeader().getAnswers()) {
86                 // We only care about type A records
87                 if (!answer.getDataType().equals(DnsResourceRecordType.A)) {
88                     continue;
89                 }
90                 // Sanity check. For some reason the hostname appears to be the empty string in the answer .
91                 // We hence have to assume that all answers correspond to a single question that holds the hostname as part of its object tree.
92                 // Therefore, if there are more questions in one query-reply exchange, we are in trouble.
93                 if (!answer.getName().getName().equals("") && !answer.getName().getName().equals(hostname)) {
94                     throw new RuntimeException("[DNS parser] mismatch between hostname in question and hostname in answer");
95                 }
96                 // The IP in byte representation.
97                 byte[] ipBytes = answer.getRData().getRawData();
98                 // Convert to string representation.
99                 String ip = Inet4Address.getByAddress(ipBytes).getHostAddress();
100                 HashSet<String> hostnameSet = new HashSet<>();
101                 hostnameSet.add(hostname);
102                 // Update or insert depending on presence of key:
103                 // Concat the existing set and the new set if ip already present as key,
104                 // otherwise add an entry for ip pointing to new set.
105                 result.merge(ip, hostnameSet, (v1, v2) -> { v1.addAll(v2); return v1; });
106             }
107         }
108         return result;
109     }
110
111 //    /**
112 //     * Private class properties
113 //     */
114 //    private Pcap pcap;
115 //    private List<Pcap.Packet> listPacket;
116 //    private Map<String, String> mapIPAddressToHostname;
117 //
118 //    /**
119 //     * Private class constants
120 //     */
121 //    private static final int DNS_PORT = 53;
122 //
123 //    /**
124 //     * Constructor
125 //     *
126 //     * @param   file    name of the analyzed PCAP file
127 //     */
128 //    public Main(String file) throws IOException {
129 //
130 //        pcap = Pcap.fromFile(file);
131 //        listPacket = pcap.packets();
132 //        mapIPAddressToHostname = new HashMap<String, String>();
133 //    }
134 //
135 //
136 //
137 //
138 //
139 //    /**
140 //     * Private method that maps DNS hostnames to their
141 //     * respected IP addresses. This method iterates
142 //     * through the List<Pcap.Packet>, gets DNS packets,
143 //     * and gets the IP addresses associated with them.
144 //     */
145 //    private void mapHostnamesToIPAddresses() {
146 //
147 //        int counter = 1;
148 //        for(Pcap.Packet packet : listPacket) {
149 //            System.out.print("# " + counter++);
150 //            // Check the packet type
151 //            if (packet._root().hdr().network() == Pcap.Linktype.ETHERNET) {
152 //                EthernetFrame ethFrame = (EthernetFrame) packet.body();
153 //                if (ethFrame.etherType() == EthernetFrame.EtherTypeEnum.IPV4) {
154 //                    Ipv4Packet ip4Packet = (Ipv4Packet) ethFrame.body();
155 //
156 //                    System.out.print(" - Protocol: " + ip4Packet.protocol());
157 //                    if (ip4Packet.protocol() == Ipv4Packet.ProtocolEnum.UDP) {
158 //                        // DNS is UDP port 53
159 //                        UdpDatagram udpData = (UdpDatagram) ip4Packet.body();
160 //                        System.out.print(" - Source Port: " + udpData.srcPort());
161 //                        System.out.print(" - Dest Port: " + udpData.dstPort());
162 //
163 //                        // Source port 53 means this is DNS response
164 //                        if (udpData.srcPort() == DNS_PORT) {
165 //                            KaitaiStream dnsStream = new ByteBufferKaitaiStream(udpData.body());
166 //                            DnsPacket dnsPacket = new DnsPacket(dnsStream);
167 //                            ArrayList<DnsPacket.Query> queries = dnsPacket.queries();
168 //                            ArrayList<DnsPacket.Answer> answers = dnsPacket.answers();
169 //                            String strDomainName = new String();
170 //                            for(DnsPacket.Query query : queries) {
171 //                                System.out.print(" - Queries: ");
172 //                                DnsPacket.DomainName domainName = query.name();
173 //                                ArrayList<DnsPacket.Label> labels = domainName.name();
174 //                                for(int i = 0; i < labels.size(); i++) {
175 //                                    System.out.print(labels.get(i).name());
176 //                                    strDomainName = strDomainName + labels.get(i).name();
177 //                                    if(i < labels.size()-2) {
178 //                                        System.out.print(".");
179 //                                        strDomainName = strDomainName + ".";
180 //                                    }
181 //                                }
182 //                                break;  // We are assuming that there is only one query
183 //                            }
184 //                            System.out.print(" - Answers " + answers.size());
185 //                            for(DnsPacket.Answer answer : answers) {
186 //                                System.out.print(" - TypeType: " + answer.type());
187 //                                System.out.print(" - ClassType: " + answer.answerClass());
188 //                                System.out.print("\n - Answers: ");
189 //                                DnsPacket.Address address = answer.address();
190 //                                if (answer.type() == DnsPacket.TypeType.A) {
191 //                                    String strAnswer = new String();
192 //                                    ArrayList<Integer> ipList = address.ip();
193 //                                    for(int i = 0; i < ipList.size(); i++) {
194 //                                        System.out.print(ipList.get(i));
195 //                                        strAnswer = strAnswer + Integer.toString(ipList.get(i));
196 //                                        if(i < ipList.size()-1) {
197 //                                            System.out.print(".");
198 //                                            strAnswer = strAnswer + ".";
199 //                                        }
200 //                                    }
201 //                                    mapIPAddressToHostname.put(strAnswer, strDomainName);
202 //                                }
203 //                            }
204 //                        }
205 //                    }
206 //                }
207 //            }
208 //            System.out.println();
209 //        }
210 ////        for(Map.Entry<String, String> entry : mapIPAddressToHostname.entrySet()) {
211 ////            if (entry.getValue().equals("devs.tplinkcloud.com")) {
212 ////                System.out.println(entry.getKey() + " - " + entry.getValue());
213 ////            }
214 ////        }
215 //        System.out.println("Total map size: " + mapIPAddressToHostname.size());
216 //        System.out.println("Answer for 13.33.41.8: " + mapIPAddressToHostname.get("13.33.41.8"));
217 //        System.out.println("Answer for 34.226.240.125: " + mapIPAddressToHostname.get("34.226.240.125"));
218 //    }
219 //
220 //    /*private String cloudIPAddress(String hostName) {
221 //        if (hostName.equals("events.tplinkra.com"))
222 //            return "205.251.203.26";
223 //        else
224 //            return null;
225 //    }*/
226 //
227 //    // TODO move to separate class
228 //    // Add parameter that is the trace to be analyzed (most like the pcap library's representation of a flow)
229 //    public String findPattern(Map<String, List<Integer>> hostnameToPacketLengths, String smartPlugIp) {
230 //
231 //        // No difference, output "Complete match"
232 //        // If difference, output <Packet no, deviation from expected> for each packet
233 //        return null;
234 //    }
235 //
236 //    public static void main(String[] args) {
237 //        System.out.println("it works");
238 //
239 //        //String file = "/home/rtrimana/pcap_processing/smart_home_traffic/Code/Projects/SmartPlugDetector/pcap/wlan1.local.dns.pcap";
240 //        String file = "/home/rtrimana/pcap_processing/smart_home_traffic/Code/Projects/SmartPlugDetector/pcap/wlan1.remote.dns.pcap";
241 //
242 //        try {
243 //            Main main = new Main(file);
244 //            main.mapHostnamesToIPAddresses();
245 //
246 //            /*Pcap data = Pcap.fromFile(file);
247 //            List<Pcap.Packet> listPacket = data.packets();
248 //            System.out.println("Number of packets: " + listPacket.size());
249 //            System.out.println("===================");
250 //            for(Pcap.Packet packet : listPacket) {
251 //                if (packet._root().hdr().network() == Pcap.Linktype.ETHERNET) {
252 //                    EthernetFrame eFrame = (EthernetFrame) packet.body();
253 //                    if (eFrame.etherType() == EthernetFrame.EtherTypeEnum.IPV4) {
254 //                        Ipv4Packet ip4Packet = (Ipv4Packet) eFrame.body();
255 //                        byte[] srcIp = ip4Packet.srcIpAddr();
256 //                        byte[] dstIp = ip4Packet.dstIpAddr();
257 //                        System.out.println("Byte length source: " + srcIp.length + " Byte length dest: " + dstIp.length);
258 //                        System.out.print("Source: ");
259 //                        for(int i = 0; i < srcIp.length; i++) {
260 //                            System.out.print(Byte.toUnsignedInt(srcIp[i]));
261 //                            if(i < srcIp.length-1)
262 //                                System.out.print(".");
263 //                        }
264 //                        System.out.print(" - Dest: ");
265 //                        for(int i = 0; i < dstIp.length; i++) {
266 //                            System.out.print(Byte.toUnsignedInt(dstIp[i]));
267 //                            if(i < dstIp.length-1)
268 //                                System.out.print(".");
269 //                            else
270 //                                System.out.println("\n");
271 //                        }
272 //                    }
273 //                }
274 //            }*/
275 //
276 //        } catch (Exception e) {
277 //            e.printStackTrace();
278 //        }
279 //    }
280 }