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