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