Temporary fix for router's IP as client for WAN trace and paths for new tests for...
[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.*;
6 import edu.uci.iotproject.comparison.seqalignment.ExtractedSequence;
7 import edu.uci.iotproject.comparison.seqalignment.SequenceAlignment;
8 import edu.uci.iotproject.comparison.seqalignment.SequenceExtraction;
9 import edu.uci.iotproject.io.TriggerTimesFileReader;
10 import edu.uci.iotproject.util.PcapPacketUtils;
11 import edu.uci.iotproject.util.PrintUtils;
12 import org.apache.commons.math3.stat.clustering.Cluster;
13 import org.apache.commons.math3.stat.clustering.DBSCANClusterer;
14 import org.pcap4j.core.*;
15 import org.pcap4j.packet.namednumber.DataLinkType;
16
17 import java.io.EOFException;
18 import java.io.File;
19 import java.io.PrintWriter;
20 import java.net.UnknownHostException;
21 import java.time.Instant;
22 import java.util.*;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26
27 /**
28  * This is a system that reads PCAP files to compare
29  * patterns of DNS hostnames, packet sequences, and packet
30  * lengths with training data to determine certain events
31  * or actions for smart home devices.
32  *
33  * @author Janus Varmarken
34  * @author Rahmadi Trimananda (rtrimana@uci.edu)
35  * @version 0.1
36  */
37 public class Main {
38
39
40     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
41         // -------------------------------------------------------------------------------------------------------------
42         // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
43         // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
44         // which traffic is to be extracted:
45         String path = "/scratch/July-2018"; // Rahmadi
46 //        String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
47         boolean verbose = true;
48         final String onPairsPath = "/scratch/July-2018/on.txt";
49         final String offPairsPath = "/scratch/July-2018/off.txt";
50
51         // 1) D-Link July 26 experiment
52 //        final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
53 //        final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
54 //        final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
55 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
56           // Actual training
57 //        final String inputPcapFile = path + "/2018-10/dlink-plug/dlink-plug.wlan1.local.pcap";
58 //        final String outputPcapFile = path + "/2018-10/dlink-plug/dlink-plug-processed.pcap";
59 //        final String triggerTimesFile = path + "/2018-10/dlink-plug/dlink-plug-oct-17-2018.timestamps";
60 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
61
62         // 2) TP-Link July 25 experiment
63 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
64 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
65 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
66 //        final String deviceIp = "192.168.1.159";
67           // Actual training
68 //        final String inputPcapFile = path + "/2018-10/tplink-plug/tplink-plug.wlan1.local.pcap";
69 //        final String outputPcapFile = path + "/2018-10/tplink-plug/tplink-plug-processed.pcap";
70 //        final String triggerTimesFile = path + "/2018-10/tplink-plug/tplink-plug-oct-17-2018.timestamps";
71 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .159 == tplink plug
72
73         // 2b) TP-Link July 25 experiment TRUNCATED:
74         // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
75         // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
76 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
77 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
78 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
79 //        final String deviceIp = "192.168.1.159";
80
81         // 3) SmartThings Plug July 25 experiment
82 //        final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
83 //        final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
84 //        final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
85 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
86         // October 18
87 //        final String inputPcapFile = path + "/2018-10/st-plug/st-plug.wlan1.local.pcap";
88 //        final String outputPcapFile = path + "/2018-10/st-plug/st-plug-processed.pcap";
89 //        final String triggerTimesFile = path + "/2018-10/st-plug/st-plug-oct-18-2018.timestamps";
90 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
91
92         // 4) Wemo July 30 experiment
93 //        final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
94 //        final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
95 //        final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
96 //        final String deviceIp = "192.168.1.145";  // .246 == phone; .145 == WeMo
97
98         // 5) Wemo Insight July 31 experiment
99 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
100 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
101 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
102 //        final String deviceIp = "192.168.1.135";
103
104         // 6) TP-Link Bulb August 1 experiment
105 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
106 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
107 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
108 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
109
110         // 7) Kwikset Doorlock August 6 experiment
111 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
112 ////        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
113 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
114 ////        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
115 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-8hr-data-oct-11-2018.timestamps";
116 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
117
118         // September 12, 2018 - includes both wlan1 and eth1 interfaces
119 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
120 //        //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
121 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
122 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
123 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
124
125         // 8) Hue Bulb August 7 experiment
126 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
127 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
128 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
129 //        final String deviceIp = "192.168.1.246";
130         // October 30 experiment
131 //        final String inputPcapFile = path + "/2018-10/hue-bulb/hue-bulb.wlan1.local.pcap";
132 //        final String outputPcapFile = path + "/2018-10/hue-bulb/hue-bulb-processed.pcap";
133 //        final String triggerTimesFile = path + "/2018-10/hue-bulb/hue-bulb-oct-30-2018.timestamps";
134 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
135
136         // 9) Lifx Bulb August 8 experiment
137 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
138 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
139 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
140 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
141         // October 18
142 //        final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
143 //        final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
144 //        final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-oct-18-2018.timestamps";
145 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
146         // November 1
147         final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
148         final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
149         final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-nov-1-2018.timestamps";
150         final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
151
152         // 10) Amcrest Camera August 9 experiment
153 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
154 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
155 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
156 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
157
158         // 11) Arlo Camera August 10 experiment
159 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
160 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
161 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
162 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
163
164         // 12) Blossom sprinkler August 13 experiment
165 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
166 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
167 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
168 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
169
170 //        // 13) DLink siren August 14 experiment
171 //        final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
172 //        //final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
173 //        final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
174 //        final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-oct-12-2018.timestamps";
175 //        //final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
176 //        //final String triggerTimesFile = path + "/actual/timestamps/dlink-siren-8hr-data-oct-10-2018.timestamps";
177 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
178
179         // 14) Nest thermostat August 15 experiment
180 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
181 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
182 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
183 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
184
185         // 15) Alexa August 16 experiment
186 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
187 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
188 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
189 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
190         // August 17
191 //        final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
192 //        final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
193 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
194 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
195
196         // September 17
197 //        final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
198 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
199 //        final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
200 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
201         // September 26 - D-Link noise
202 //        final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
203 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
204 //        final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
205 //        final String deviceIp = "192.168.1.183"; //  .199 == dlink plug; .183 == siren
206         // September 27 - Kwikset noise
207 //        final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
208 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
209 //        final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
210 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub;
211
212         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
213         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
214         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
215         List<UserAction> userActions = new ArrayList<>();
216         for (int i = 0; i < triggerTimes.size(); i++) {
217             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
218         }
219         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
220         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
221         DnsMap dnsMap = new DnsMap();
222         TcpReassembler tcpReassembler = new TcpReassembler();
223         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
224         tte.performExtraction(pkt -> {
225             try {
226                 outputter.dump(pkt);
227             } catch (NotOpenException e) {
228                 e.printStackTrace();
229             }
230         }, dnsMap, tcpReassembler, trafficLabeler);
231         outputter.flush();
232         outputter.close();
233
234         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
235             // Sanity/debug check
236             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
237                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
238         }
239
240         // Extract all conversations present in the filtered trace.
241         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
242         // Group conversations by hostname.
243         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
244         System.out.println("Grouped conversations by hostname.");
245         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
246         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
247         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
248         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
249         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
250         // sequence of packets of some specific lengths).
251         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
252         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
253         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
254         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
255         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
256                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
257         System.out.println("Counted frequencies of packet pairs per hostname");
258         // For each user action, reassemble the set of TCP connections occurring shortly after
259         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
260         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
261         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
262
263
264
265         /*
266          * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
267          * sequence identifiers as we do not care about hostnames and sequences during clustering.
268          * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
269          */
270         /*
271         // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
272         Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
273         // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
274         Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
275         userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
276             Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
277             hostnameToConvs.forEach((host, convs) -> {
278                 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
279                         groupConversationsByPacketSequence(convs, verbose);
280                 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
281                     newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
282                         list1.addAll(list2);
283                         return list1;
284                     }));
285                     return oldMap;
286                 });
287             });
288         });
289         */
290
291         // ================================================ CLUSTERING ================================================
292         // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
293         // when don't care about hostnames and sequences (see comment earlier).
294         List<Conversation> onConversations = userActionToConversations.entrySet().stream().
295                 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
296                 map(e -> e.getValue()). // no longer interested in the UserActions
297                 flatMap(List::stream). // flatten List<List<T>> to a List<T>
298                 collect(Collectors.toList());
299         List<Conversation> offConversations = userActionToConversations.entrySet().stream().
300                 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
301                 map(e -> e.getValue()).
302                 flatMap(List::stream).
303                 collect(Collectors.toList());
304         //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
305
306         List<PcapPacketPair> onPairs = onConversations.stream().
307                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
308                         TcpConversationUtils.extractPacketPairs(c)).
309                 flatMap(List::stream). // flatten List<List<>> to List<>
310                 collect(Collectors.toList());
311         List<PcapPacketPair> offPairs = offConversations.stream().
312                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
313                         TcpConversationUtils.extractPacketPairs(c)).
314                 flatMap(List::stream). // flatten List<List<>> to List<>
315                 collect(Collectors.toList());
316         // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
317         Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
318         // Perform clustering on conversation logged as part of all ON events.
319         DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
320         List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
321         // Perform clustering on conversation logged as part of all OFF events.
322         DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
323         List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
324         // Sort the conversations as reference
325         List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
326         // Output clusters
327         System.out.println("========================================");
328         System.out.println("       Clustering results for ON        ");
329         System.out.println("       Number of clusters: " + onClusters.size());
330         int count = 0;
331         List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
332         List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
333         for (Cluster<PcapPacketPair> c : onClusters) {
334             System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
335             System.out.print(PrintUtils.toSummaryString(c));
336             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
337                 // Print to file
338                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
339                 ppListOfListListOn.add(ppListOfList);
340             }
341         }
342         // TODO: Merging test
343         ppListOfListListOn = PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
344         ppListOfListListOn = PcapPacketUtils.sortSignatures(ppListOfListListOn);
345         PcapPacketUtils.printSignatures(ppListOfListListOn);
346         //count = 0;
347         /*for (List<List<PcapPacket>> ll : ppListOfListListOn) {
348             PrintUtils.serializeClustersIntoFile("./onSignature" + ++count + ".sig", ll);
349             ppListOfListReadOn.add(PrintUtils.deserializeClustersFromFile("./onSignature" + count + ".sig"));
350         }*/
351         PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
352         ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
353
354         System.out.println("========================================");
355         System.out.println("       Clustering results for OFF       ");
356         System.out.println("       Number of clusters: " + offClusters.size());
357         count = 0;
358         List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
359         List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
360         for (Cluster<PcapPacketPair> c : offClusters) {
361             System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
362             System.out.print(PrintUtils.toSummaryString(c));
363             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
364                 // Print to file
365                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
366                 ppListOfListListOff.add(ppListOfList);
367             }
368         }
369         // TODO: Merging test
370         ppListOfListListOff = PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
371         ppListOfListListOff = PcapPacketUtils.sortSignatures(ppListOfListListOff);
372         PcapPacketUtils.printSignatures(ppListOfListListOff);
373         //count = 0;
374         /*for (List<List<PcapPacket>> ll : ppListOfListListOff) {
375             PrintUtils.serializeClustersIntoFile("./offSignature" + ++count + ".sig", ll);
376             ppListOfListReadOff.add(PrintUtils.deserializeClustersFromFile("./offSignature" + count + ".sig"));
377         }*/
378         PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
379         ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
380         System.out.println("========================================");
381         // ============================================================================================================
382
383         /*
384         System.out.println("==== ON ====");
385         // Print out all the pairs into a file for ON events
386         File fileOnEvents = new File(onPairsPath);
387         PrintWriter pwOn = null;
388         try {
389
390
391             pwOn = new PrintWriter(fileOnEvents);
392         } catch(Exception ex) {
393             ex.printStackTrace();
394         }
395         for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
396             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
397             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
398                 List<Conversation> listConv = entryConv.getValue();
399                 // Just get the first Conversation because all Conversations in this group
400                 // should have the same pairs of Application Data.
401                 for(Conversation conv : listConv) {
402                     // Process only if it is a TLS packet
403                     if (conv.isTls()) {
404                         List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
405                         for(PcapPacketPair pair: tlsAppDataList) {
406                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
407                             pwOn.println(PrintUtils.toCsv(pair, dnsMap));
408                         }
409                     } else { // Non-TLS conversations
410                         List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
411                         for(PcapPacketPair pair: packetList) {
412                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
413                             pwOn.println(PrintUtils.toCsv(pair, dnsMap));
414                         }
415                     }
416                 }
417             }
418         }
419         pwOn.close();
420
421         System.out.println("==== OFF ====");
422         // Print out all the pairs into a file for ON events
423         File fileOffEvents = new File(offPairsPath);
424         PrintWriter pwOff = null;
425         try {
426             pwOff = new PrintWriter(fileOffEvents);
427         } catch(Exception ex) {
428             ex.printStackTrace();
429         }
430         for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
431             Map<String, List<Conversation>> seqsToConvs = entry.getValue();
432             for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
433                 List<Conversation> listConv = entryConv.getValue();
434                 // Just get the first Conversation because all Conversations in this group
435                 // should have the same pairs of Application Data.
436                 for(Conversation conv : listConv) {
437                     // Process only if it is a TLS packet
438                     if (conv.isTls()) {
439                         List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
440                         for(PcapPacketPair pair: tlsAppDataList) {
441                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
442                             pwOff.println(PrintUtils.toCsv(pair, dnsMap));
443                         }
444                     } else { // Non-TLS conversations
445                         List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
446                         for (PcapPacketPair pair : packetList) {
447                             System.out.println(PrintUtils.toCsv(pair, dnsMap));
448                             pwOff.println(PrintUtils.toCsv(pair, dnsMap));
449                         }
450                     }
451                 }
452             }
453         }
454         pwOff.close();
455         */
456
457 //        // ================================================================================================
458 //        // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
459 //        //
460 //        // Currently need to know relevant hostname in advance :(
461 //        String hostname = "events.tplinkra.com";
462 ////        String hostname = "rfe-us-west-1.dch.dlink.com";
463 //        // Conversations with 'hostname' for ON events.
464 //        List<Conversation> onsForHostname = new ArrayList<>();
465 //        // Conversations with 'hostname' for OFF events.
466 //        List<Conversation> offsForHostname = new ArrayList<>();
467 //        // "Unwrap" sequence groupings in ons/offs maps.
468 //        ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
469 //        offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
470 //
471 //
472 //        Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
473 //
474 //
475 //        // Extract representative sequence for ON and OFF by providing the list of conversations with
476 //        // 'hostname' observed for each event type (the training data).
477 //        SequenceExtraction seqExtraction = new SequenceExtraction();
478 ////        ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
479 ////        ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
480 //
481 //        ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
482 //        ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
483 //
484 //        // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
485 //        // labeled).
486 //        int onsLabeledAsOff = 0;
487 //        Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
488 //        Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
489 //        SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
490 //        for (Conversation c : onsForHostname) {
491 //            Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
492 //            if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
493 //                onsLabeledAsOff++;
494 //            }
495 //        }
496 //        int offsLabeledAsOn = 0;
497 //        for (Conversation c : offsForHostname) {
498 //            Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
499 //            if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
500 //                offsLabeledAsOn++;
501 //            }
502 //        }
503 //        System.out.println("");
504 //        // ================================================================================================
505 //
506 //
507 //        // -------------------------------------------------------------------------------------------------------------
508 //        // -------------------------------------------------------------------------------------------------------------
509     }
510
511 }
512
513
514 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
515 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159