Merging changes.
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3 import static edu.uci.iotproject.analysis.UserAction.Type;
4
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.analysis.TrafficLabeler;
7 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
8 import edu.uci.iotproject.analysis.UserAction;
9 import edu.uci.iotproject.comparison.seqalignment.ExtractedSequence;
10 import edu.uci.iotproject.comparison.seqalignment.SequenceAlignment;
11 import edu.uci.iotproject.comparison.seqalignment.SequenceExtraction;
12 import edu.uci.iotproject.io.TriggerTimesFileReader;
13 import org.pcap4j.core.*;
14 import org.pcap4j.packet.namednumber.DataLinkType;
15
16 import java.io.EOFException;
17 import java.io.File;
18 import java.io.PrintWriter;
19 import java.net.UnknownHostException;
20 import java.time.Instant;
21 import java.util.*;
22 import java.util.concurrent.TimeoutException;
23
24 /**
25  * This is a system that reads PCAP files to compare
26  * patterns of DNS hostnames, packet sequences, and packet
27  * lengths with training data to determine certain events
28  * or actions for smart home devices.
29  *
30  * @author Janus Varmarken
31  * @author Rahmadi Trimananda (rtrimana@uci.edu)
32  * @version 0.1
33  */
34 public class Main {
35
36
37     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
38         // -------------------------------------------------------------------------------------------------------------
39         // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
40         // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
41         // which traffic is to be extracted:
42 //        String path = "/scratch/July-2018"; // Rahmadi
43         String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
44         boolean verbose = true;
45         final String onPairsPath = "/scratch/July-2018/on.txt";
46         final String offPairsPath = "/scratch/July-2018/off.txt";
47
48         // 1) D-Link July 26 experiment
49 //        final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
50 //        final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
51 //        final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
52 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .199 == dlink plug?
53
54         // 2) TP-Link July 25 experiment
55         final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
56         final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
57         final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
58         final String deviceIp = "192.168.1.159";
59
60         // 2b) TP-Link July 25 experiment TRUNCATED:
61         // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
62         // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
63 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
64 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
65 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
66 //        final String deviceIp = "192.168.1.159";
67
68         // 3) SmartThings Plug July 25 experiment
69 //        final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
70 //        final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
71 //        final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
72 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
73
74         // 4) Wemo July 30 experiment
75 //        final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
76 //        final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
77 //        final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
78 //        final String deviceIp = "192.168.1.145";
79
80         // 5) Wemo Insight July 31 experiment
81 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
82 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
83 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
84 //        final String deviceIp = "192.168.1.135";
85
86         // 6) TP-Link Bulb August 1 experiment
87 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
88 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
89 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
90 //        final String deviceIp = "192.168.1.246";
91
92         // 7) Kwikset Doorlock August 6 experiment
93 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
94 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
95 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
96 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
97
98         // 8) Hue Bulb August 7 experiment
99 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
100 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
101 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
102 //        final String deviceIp = "192.168.1.246";
103
104         // 9) Lifx Bulb August 8 experiment
105 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
106 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
107 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
108 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
109
110         // 10) Amcrest Camera August 9 experiment
111 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
112 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
113 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
114 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
115
116         // 11) Arlo Camera August 10 experiment
117 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
118 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
119 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
120 //        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
121
122         // 12) Blossom sprinkler August 13 experiment
123 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
124 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
125 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
126 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
127
128         // 13) DLink siren August 14 experiment
129 //        final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
130 //        final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
131 //        final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
132 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
133
134         // 14) Nest thermostat August 15 experiment
135 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
136 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
137 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
138 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
139
140         // 15) Alexa August 16 experiment
141 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
142 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
143 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
144 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
145         // August 17
146 //        final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
147 //        final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
148 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
149 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
150
151         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
152         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
153         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
154         List<UserAction> userActions = new ArrayList<>();
155         for (int i = 0; i < triggerTimes.size(); i++) {
156             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
157         }
158         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
159         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
160         DnsMap dnsMap = new DnsMap();
161         TcpReassembler tcpReassembler = new TcpReassembler();
162         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
163         tte.performExtraction(pkt -> {
164             try {
165                 outputter.dump(pkt);
166             } catch (NotOpenException e) {
167                 e.printStackTrace();
168             }
169         }, dnsMap, tcpReassembler, trafficLabeler);
170         outputter.flush();
171         outputter.close();
172
173         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
174             // Sanity/debug check
175             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
176                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
177         }
178
179         // Extract all conversations present in the filtered trace.
180         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
181         // Group conversations by hostname.
182         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
183         System.out.println("Grouped conversations by hostname.");
184         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
185         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
186         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
187         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
188         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
189         // sequence of packets of some specific lengths).
190         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
191         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
192         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
193         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
194         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
195                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
196         System.out.println("Counted frequencies of packet pairs per hostname");
197         // For each user action, reassemble the set of TCP connections occurring shortly after
198         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
199         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
200         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
201
202
203
204         // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
205         Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
206         // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
207         Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
208         userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
209             Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
210             hostnameToConvs.forEach((host, convs) -> {
211                 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
212                         groupConversationsByPacketSequence(convs, verbose);
213                 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
214                     newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
215                         list1.addAll(list2);
216                         return list1;
217                     }));
218                     return oldMap;
219                 });
220             });
221         });
222
223
224         // Print out all the pairs into a file for ON events
225         File fileOnEvents = new File(onPairsPath);
226         PrintWriter pwOn = null;
227         try {
228             pwOn = new PrintWriter(fileOnEvents);
229         } catch(Exception ex) {
230             ex.printStackTrace();
231         }
232         for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
233             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
234             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
235                 List<Conversation> listConv = entryConv.getValue();
236                 // Just get the first Conversation because all Conversations in this group
237                 // should have the same pairs of Application Data.
238                 for(Conversation conv : listConv) {
239                     // Process only if it is a TLS packet
240                     if (conv.isTls()) {
241                         List<PcapPacket> tlsAppDataList = conv.getTlsApplicationDataPackets();
242                         // Loop and print out packets
243                         int count = 0;
244                         // The direction of the first packet
245                         Conversation.Direction firstDir = null;
246                         // The length of the first packet
247                         int firstLen = 0;
248                         for (PcapPacket pcap : tlsAppDataList) {
249                             boolean isPair = false;
250                             if (count % 2 == 0) {
251                                 firstDir = conv.getDirection(pcap);
252                                 firstLen = pcap.length();
253                             } else {// count%2 == 1
254                                 if(conv.getDirection(pcap) != firstDir) {
255                                     isPair = true;
256                                     pwOn.println(firstLen + ", " + pcap.length());
257                                     //System.out.println(firstDir + ", " + conv.getDirection(pcap));
258                                     //System.out.println(firstLen + ", " + pcap.length());
259                                 }
260                             }
261                             count++;
262                             // If we can't create a pair then just pad it with 0
263                             if (count == tlsAppDataList.size() && !isPair) {
264                                 pwOn.println(firstLen + ", 0");
265                             }
266                         }
267                     } else { // Non-TLS conversations
268                         List<PcapPacket> packetList = conv.getPackets();
269                         // Loop and print out packets
270                         int count = 0;
271                         // The direction of the first packet
272                         Conversation.Direction firstDir = null;
273                         // The length of the first packet
274                         int firstLen = 0;
275                         for (PcapPacket pcap : packetList) {
276                             System.out.println(pcap.length() + ", " + conv.getDirection(pcap));
277                             boolean isPair = false;
278                             if (count % 2 == 0) {
279                                 firstDir = conv.getDirection(pcap);
280                                 firstLen = pcap.length();
281                             } else {// count%2 == 1
282                                 if(conv.getDirection(pcap) != firstDir) {
283                                     isPair = true;
284                                     pwOn.println(firstLen + ", " + pcap.length());
285                                     //System.out.println(firstDir + ", " + conv.getDirection(pcap));
286                                     //System.out.println(firstLen + ", " + pcap.length());
287                                 }
288                             }
289                             count++;
290                             // If we can't create a pair then just pad it with 0
291                             if (count == packetList.size() && !isPair) {
292                                 pwOn.println(firstLen + ", 0");
293                             }
294                         }
295                     }
296                 }
297             }
298         }
299         pwOn.close();
300
301         // Print out all the pairs into a file for ON events
302         File fileOffEvents = new File(offPairsPath);
303         PrintWriter pwOff = null;
304         try {
305             pwOff = new PrintWriter(fileOffEvents);
306         } catch(Exception ex) {
307             ex.printStackTrace();
308         }
309         for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
310             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
311             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
312                 List<Conversation> listConv = entryConv.getValue();
313                 // Just get the first Conversation because all Conversations in this group
314                 // should have the same pairs of Application Data.
315                 for(Conversation conv : listConv) {
316                     // Process only if it is a TLS packet
317                     if (conv.isTls()) {
318                         List<PcapPacket> tlsAppDataList = conv.getTlsApplicationDataPackets();
319                         // Loop and print out packets
320                         int count = 0;
321                         // The direction of the first packet
322                         Conversation.Direction firstDir = null;
323                         // The length of the first packet
324                         int firstLen = 0;
325                         for (PcapPacket pcap : tlsAppDataList) {
326                             boolean isPair = false;
327                             if (count % 2 == 0) {
328                                 firstDir = conv.getDirection(pcap);
329                                 firstLen = pcap.length();
330                             } else {// count%2 == 1
331                                 if(conv.getDirection(pcap) != firstDir) {
332                                     isPair = true;
333                                     pwOff.println(firstLen + ", " + pcap.length());
334                                     System.out.println(firstDir + ", " + conv.getDirection(pcap));
335                                     System.out.println(firstLen + ", " + pcap.length());
336                                 }
337                             }
338                             count++;
339                             // If we can't create a pair then just pad it with 0
340                             if (count == tlsAppDataList.size() && !isPair) {
341                                 pwOff.println(firstLen + ", 0");
342                             }
343
344                         }
345                     } else { // Non-TLS conversations
346                         List<PcapPacket> packetList = conv.getPackets();
347                         // Loop and print out packets
348                         int count = 0;
349                         // The direction of the first packet
350                         Conversation.Direction firstDir = null;
351                         // The length of the first packet
352                         int firstLen = 0;
353                         for (PcapPacket pcap : packetList) {
354                             System.out.println(pcap.length() + ", " + conv.getDirection(pcap));
355                             boolean isPair = false;
356                             if (count % 2 == 0) {
357                                 firstDir = conv.getDirection(pcap);
358                                 firstLen = pcap.length();
359                             } else {// count%2 == 1
360                                 if(conv.getDirection(pcap) != firstDir) {
361                                     isPair = true;
362                                     pwOff.println(firstLen + ", " + pcap.length());
363                                     System.out.println(firstDir + ", " + conv.getDirection(pcap));
364                                     System.out.println(firstLen + ", " + pcap.length());
365                                 }
366                             }
367                             count++;
368                             // If we can't create a pair then just pad it with 0
369                             if (count == packetList.size() && !isPair) {
370                                 pwOff.println(firstLen + ", 0");
371                             }
372                         }
373                     }
374                 }
375             }
376         }
377         pwOff.close();
378
379
380         // ================================================================================================
381         // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
382         //
383         // Currently need to know relevant hostname in advance :(
384         String hostname = "events.tplinkra.com";
385 //        String hostname = "rfe-us-west-1.dch.dlink.com";
386         // Conversations with 'hostname' for ON events.
387         List<Conversation> onsForHostname = new ArrayList<>();
388         // Conversations with 'hostname' for OFF events.
389         List<Conversation> offsForHostname = new ArrayList<>();
390         // "Unwrap" sequence groupings in ons/offs maps.
391         ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
392         offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
393
394
395         Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
396
397
398         // Extract representative sequence for ON and OFF by providing the list of conversations with
399         // 'hostname' observed for each event type (the training data).
400         SequenceExtraction seqExtraction = new SequenceExtraction();
401 //        ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
402 //        ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
403
404         ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
405         ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
406
407         // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
408         // labeled).
409         int onsLabeledAsOff = 0;
410         Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
411         Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
412         SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
413         for (Conversation c : onsForHostname) {
414             Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
415             if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
416                 onsLabeledAsOff++;
417             }
418         }
419         int offsLabeledAsOn = 0;
420         for (Conversation c : offsForHostname) {
421             Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
422             if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
423                 offsLabeledAsOn++;
424             }
425         }
426         System.out.println("");
427         // ================================================================================================
428
429
430         // -------------------------------------------------------------------------------------------------------------
431         // -------------------------------------------------------------------------------------------------------------
432     }
433
434 }
435
436
437 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
438 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159