1 package edu.uci.iotproject;
4 import org.pcap4j.core.*;
5 import org.pcap4j.packet.*;
6 import org.pcap4j.packet.DnsPacket;
7 import org.pcap4j.packet.namednumber.DnsResourceRecordType;
9 import java.io.EOFException;
10 import java.net.Inet4Address;
11 import java.net.UnknownHostException;
13 import java.util.concurrent.TimeoutException;
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.
21 * @author Janus Varmarken
22 * @author Rahmadi Trimananda (rtrimana@uci.edu)
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())));
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
43 private static List<DnsPacket> extractDnsAnswerPackets(String pcapFileName) throws PcapNativeException, NotOpenException, TimeoutException {
46 handle = Pcaps.openOffline(pcapFileName, PcapHandle.TimestampPrecision.NANO);
47 } catch (PcapNativeException pne) {
48 handle = Pcaps.openOffline(pcapFileName);
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<>();
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);
62 } catch (EOFException eof) {
63 // (Note have to resort to EOFException as handle.getStats().getNumPacketsCaptured() only works on Windows)
67 System.out.println(String.format("Found %d DNS answers", result.size()));
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.
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.
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)) {
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");
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; });
112 // * Private class properties
114 // private Pcap pcap;
115 // private List<Pcap.Packet> listPacket;
116 // private Map<String, String> mapIPAddressToHostname;
119 // * Private class constants
121 // private static final int DNS_PORT = 53;
126 // * @param file name of the analyzed PCAP file
128 // public Main(String file) throws IOException {
130 // pcap = Pcap.fromFile(file);
131 // listPacket = pcap.packets();
132 // mapIPAddressToHostname = new HashMap<String, String>();
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.
145 // private void mapHostnamesToIPAddresses() {
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();
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());
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 + ".";
182 // break; // We are assuming that there is only one query
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 + ".";
201 // mapIPAddressToHostname.put(strAnswer, strDomainName);
208 // System.out.println();
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());
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"));
220 // /*private String cloudIPAddress(String hostName) {
221 // if (hostName.equals("events.tplinkra.com"))
222 // return "205.251.203.26";
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) {
231 // // No difference, output "Complete match"
232 // // If difference, output <Packet no, deviation from expected> for each packet
236 // public static void main(String[] args) {
237 // System.out.println("it works");
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";
243 // Main main = new Main(file);
244 // main.mapHostnamesToIPAddresses();
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(".");
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(".");
270 // System.out.println("\n");
276 // } catch (Exception e) {
277 // e.printStackTrace();