Kaitai parser half baked; there seems to be a problem with the parsing of DNS packets...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3 import io.kaitai.struct.ByteBufferKaitaiStream;
4 import io.kaitai.struct.KaitaiStruct;
5 import io.kaitai.struct.KaitaiStream;
6 import java.io.IOException;
7 import java.util.Iterator;
8 import java.util.ArrayList;
9 import java.util.List;
10 import java.util.HashMap;
11 import java.util.Map;
12
13 /**
14  * This is a system that reads PCAP files to compare
15  * patterns of DNS hostnames, packet sequences, and packet
16  * lengths with training data to determine certain events
17  * or actions for smart home devices.
18  *
19  * @author Janus Varmarken
20  * @author Rahmadi Trimananda (rtrimana@uci.edu)
21  * @version 0.1
22  */
23 public class Main {
24
25
26     /** 
27      * Private class properties
28      */
29     private Pcap pcap;
30     private List<Pcap.Packet> listPacket;
31     private Map<String, String> mapIPAddressToHostname;
32
33     /** 
34      * Private class constants
35      */
36     private static final int DNS_PORT = 53;
37
38     /** 
39      * Constructor
40      *
41      * @param   file    name of the analyzed PCAP file
42      */
43     public Main(String file) throws IOException {
44
45         pcap = Pcap.fromFile(file);
46         listPacket = pcap.packets();
47         mapIPAddressToHostname = new HashMap<String, String>();
48     }
49
50
51     /** 
52      * Private method that maps DNS hostnames to their
53      * respected IP addresses. This method iterates
54      * through the List<Pcap.Packet>, gets DNS packets,
55      * and gets the IP addresses associated with them.
56      */
57     private void mapHostnamesToIPAddresses() {
58
59         int counter = 1;
60         for(Pcap.Packet packet : listPacket) {
61             System.out.print("# " + counter++);
62             // Check the packet type
63             if (packet._root().hdr().network() == Pcap.Linktype.ETHERNET) {
64                 EthernetFrame ethFrame = (EthernetFrame) packet.body();
65                 if (ethFrame.etherType() == EthernetFrame.EtherTypeEnum.IPV4) {
66                     Ipv4Packet ip4Packet = (Ipv4Packet) ethFrame.body();
67
68                     System.out.print(" - Protocol: " + ip4Packet.protocol());                   
69                     if (ip4Packet.protocol() == Ipv4Packet.ProtocolEnum.UDP) {
70                         // DNS is UDP port 53
71                         UdpDatagram udpData = (UdpDatagram) ip4Packet.body();
72                         System.out.print(" - Source Port: " + udpData.srcPort());
73                         System.out.print(" - Dest Port: " + udpData.dstPort());
74                         
75                         // Source port 53 means this is DNS response
76                         if (udpData.srcPort() == DNS_PORT) {
77                             KaitaiStream dnsStream = new ByteBufferKaitaiStream(udpData.body());
78                             DnsPacket dnsPacket = new DnsPacket(dnsStream);
79                             ArrayList<DnsPacket.Query> queries = dnsPacket.queries();
80                             ArrayList<DnsPacket.Answer> answers = dnsPacket.answers();
81                             String strDomainName = new String();
82                             for(DnsPacket.Query query : queries) {
83                                 System.out.print(" - Queries: ");
84                                 DnsPacket.DomainName domainName = query.name();
85                                 ArrayList<DnsPacket.Label> labels = domainName.name();
86                                 for(int i = 0; i < labels.size(); i++) {
87                                     System.out.print(labels.get(i).name());
88                                     strDomainName = strDomainName + labels.get(i).name();
89                                     if(i < labels.size()-2) {
90                                         System.out.print(".");
91                                         strDomainName = strDomainName + ".";
92                                     }
93                                 }
94                                 break;  // We are assuming that there is only one query
95                             }
96                             System.out.print(" - Answers " + answers.size());
97                             for(DnsPacket.Answer answer : answers) {
98                                 System.out.print(" - TypeType: " + answer.type());
99                                 System.out.print(" - ClassType: " + answer.answerClass());
100                                 System.out.print("\n - Answers: ");
101                                 DnsPacket.Address address = answer.address();
102                                 if (answer.type() == DnsPacket.TypeType.A) {
103                                     String strAnswer = new String();
104                                     ArrayList<Integer> ipList = address.ip();
105                                     for(int i = 0; i < ipList.size(); i++) {
106                                         System.out.print(ipList.get(i));
107                                         strAnswer = strAnswer + Integer.toString(ipList.get(i));
108                                         if(i < ipList.size()-1) {
109                                             System.out.print(".");
110                                             strAnswer = strAnswer + ".";
111                                         }
112                                     }
113                                     mapIPAddressToHostname.put(strAnswer, strDomainName);
114                                 }
115                             }
116                         }
117                     }
118                 }
119             }
120             System.out.println();
121         }
122 //        for(Map.Entry<String, String> entry : mapIPAddressToHostname.entrySet()) {
123 //            if (entry.getValue().equals("devs.tplinkcloud.com")) {
124 //                System.out.println(entry.getKey() + " - " + entry.getValue());
125 //            }
126 //        }
127         System.out.println("Total map size: " + mapIPAddressToHostname.size());
128         System.out.println("Answer for 13.33.41.8: " + mapIPAddressToHostname.get("13.33.41.8"));
129         System.out.println("Answer for 34.226.240.125: " + mapIPAddressToHostname.get("34.226.240.125"));
130     }
131
132     /*private String cloudIPAddress(String hostName) {
133         if (hostName.equals("events.tplinkra.com"))
134             return "205.251.203.26";
135         else
136             return null;
137     }*/
138
139     // TODO move to separate class
140     // Add parameter that is the trace to be analyzed (most like the pcap library's representation of a flow)
141     public String findPattern(Map<String, List<Integer>> hostnameToPacketLengths, String smartPlugIp) {
142
143         // No difference, output "Complete match"
144         // If difference, output <Packet no, deviation from expected> for each packet
145         return null;
146     }
147     
148     public static void main(String[] args) {
149         System.out.println("it works");
150         
151         //String file = "/home/rtrimana/pcap_processing/smart_home_traffic/Code/Projects/SmartPlugDetector/pcap/wlan1.local.dns.pcap";
152         String file = "/home/rtrimana/pcap_processing/smart_home_traffic/Code/Projects/SmartPlugDetector/pcap/wlan1.remote.dns.pcap";
153         
154         try {
155             Main main = new Main(file);
156             main.mapHostnamesToIPAddresses();
157
158             /*Pcap data = Pcap.fromFile(file);
159             List<Pcap.Packet> listPacket = data.packets();
160             System.out.println("Number of packets: " + listPacket.size());
161             System.out.println("===================");
162             for(Pcap.Packet packet : listPacket) {
163                 if (packet._root().hdr().network() == Pcap.Linktype.ETHERNET) {
164                     EthernetFrame eFrame = (EthernetFrame) packet.body();
165                     if (eFrame.etherType() == EthernetFrame.EtherTypeEnum.IPV4) {
166                         Ipv4Packet ip4Packet = (Ipv4Packet) eFrame.body();
167                         byte[] srcIp = ip4Packet.srcIpAddr();
168                         byte[] dstIp = ip4Packet.dstIpAddr();
169                         System.out.println("Byte length source: " + srcIp.length + " Byte length dest: " + dstIp.length);
170                         System.out.print("Source: ");
171                         for(int i = 0; i < srcIp.length; i++) {
172                             System.out.print(Byte.toUnsignedInt(srcIp[i]));
173                             if(i < srcIp.length-1)
174                                 System.out.print(".");
175                         }
176                         System.out.print(" - Dest: ");
177                         for(int i = 0; i < dstIp.length; i++) {
178                             System.out.print(Byte.toUnsignedInt(dstIp[i]));
179                             if(i < dstIp.length-1)
180                                 System.out.print(".");
181                             else
182                                 System.out.println("\n");
183                         }
184                     }
185                 }
186             }*/
187             
188         } catch (Exception e) {
189             e.printStackTrace();
190         }
191     }
192 }