1 package edu.uci.iotproject;
3 import static edu.uci.iotproject.analysis.UserAction.Type;
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;
17 import java.io.EOFException;
19 import java.io.PrintWriter;
20 import java.net.UnknownHostException;
21 import java.time.Instant;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
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.
33 * @author Janus Varmarken
34 * @author Rahmadi Trimananda (rtrimana@uci.edu)
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";
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?
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?
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";
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
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";
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!)
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!)
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
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";
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
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!)
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!)
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
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
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
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
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
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
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
170 // final String inputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler.wlan1.local.pcap";
171 // final String outputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-processed.pcap";
172 // final String triggerTimesFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-nov-2-2018.timestamps";
173 // final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
175 // // 13) DLink siren August 14 experiment
176 // final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
177 // //final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
178 // final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
179 // final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-oct-12-2018.timestamps";
180 // //final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
181 // //final String triggerTimesFile = path + "/actual/timestamps/dlink-siren-8hr-data-oct-10-2018.timestamps";
182 // final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
184 // 14) Nest thermostat August 15 experiment
185 final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
186 final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
187 final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
188 final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
190 // 15) Alexa August 16 experiment
191 // final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
192 // final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
193 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
194 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
196 // final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
197 // final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
198 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
199 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
202 // final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
203 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
204 // final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
205 // final String deviceIp = "192.168.1.142"; // .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
206 // September 26 - D-Link noise
207 // final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
208 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
209 // final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
210 // final String deviceIp = "192.168.1.183"; // .199 == dlink plug; .183 == siren
211 // September 27 - Kwikset noise
212 // final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
213 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
214 // final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
215 // final String deviceIp = "192.168.1.142"; // .142 == SmartThings Hub;
217 TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
218 List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
219 // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
220 List<UserAction> userActions = new ArrayList<>();
221 for (int i = 0; i < triggerTimes.size(); i++) {
222 userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
224 TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
225 final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
226 DnsMap dnsMap = new DnsMap();
227 TcpReassembler tcpReassembler = new TcpReassembler();
228 TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
229 tte.performExtraction(pkt -> {
232 } catch (NotOpenException e) {
235 }, dnsMap, tcpReassembler, trafficLabeler);
239 if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
240 // Sanity/debug check
241 throw new AssertionError(String.format("mismatch between packet count in %s and %s",
242 TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
245 // Extract all conversations present in the filtered trace.
246 List<Conversation> allConversations = tcpReassembler.getTcpConversations();
247 // Group conversations by hostname.
248 Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
249 System.out.println("Grouped conversations by hostname.");
250 // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
251 final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
252 convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
253 System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
254 // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
255 // sequence of packets of some specific lengths).
256 final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
257 convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
258 System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
259 // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
260 final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
261 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
262 System.out.println("Counted frequencies of packet pairs per hostname");
263 // For each user action, reassemble the set of TCP connections occurring shortly after
264 final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
265 final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
266 System.out.println("Reassembled TCP conversations occurring shortly after each user event");
271 * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
272 * sequence identifiers as we do not care about hostnames and sequences during clustering.
273 * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
276 // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
277 Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
278 // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
279 Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
280 userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
281 Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
282 hostnameToConvs.forEach((host, convs) -> {
283 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
284 groupConversationsByPacketSequence(convs, verbose);
285 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
286 newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
296 // ================================================ CLUSTERING ================================================
297 // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
298 // when don't care about hostnames and sequences (see comment earlier).
299 List<Conversation> onConversations = userActionToConversations.entrySet().stream().
300 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
301 map(e -> e.getValue()). // no longer interested in the UserActions
302 flatMap(List::stream). // flatten List<List<T>> to a List<T>
303 collect(Collectors.toList());
304 List<Conversation> offConversations = userActionToConversations.entrySet().stream().
305 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
306 map(e -> e.getValue()).
307 flatMap(List::stream).
308 collect(Collectors.toList());
309 //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
311 List<PcapPacketPair> onPairs = onConversations.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 List<PcapPacketPair> offPairs = offConversations.stream().
317 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
318 TcpConversationUtils.extractPacketPairs(c)).
319 flatMap(List::stream). // flatten List<List<>> to List<>
320 collect(Collectors.toList());
321 // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
322 Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
323 // Perform clustering on conversation logged as part of all ON events.
324 DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
325 List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
326 // Perform clustering on conversation logged as part of all OFF events.
327 DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
328 List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
329 // Sort the conversations as reference
330 List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
332 System.out.println("========================================");
333 System.out.println(" Clustering results for ON ");
334 System.out.println(" Number of clusters: " + onClusters.size());
336 List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
337 List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
338 for (Cluster<PcapPacketPair> c : onClusters) {
339 System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
340 System.out.print(PrintUtils.toSummaryString(c));
341 if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
343 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
344 ppListOfListListOn.add(ppListOfList);
347 // TODO: Merging test
348 ppListOfListListOn = PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
349 ppListOfListListOn = PcapPacketUtils.sortSignatures(ppListOfListListOn);
350 PcapPacketUtils.printSignatures(ppListOfListListOn);
352 /*for (List<List<PcapPacket>> ll : ppListOfListListOn) {
353 PrintUtils.serializeClustersIntoFile("./onSignature" + ++count + ".sig", ll);
354 ppListOfListReadOn.add(PrintUtils.deserializeClustersFromFile("./onSignature" + count + ".sig"));
356 PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
357 ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
359 System.out.println("========================================");
360 System.out.println(" Clustering results for OFF ");
361 System.out.println(" Number of clusters: " + offClusters.size());
363 List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
364 List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
365 for (Cluster<PcapPacketPair> c : offClusters) {
366 System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
367 System.out.print(PrintUtils.toSummaryString(c));
368 if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
370 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
371 ppListOfListListOff.add(ppListOfList);
374 // TODO: Merging test
375 ppListOfListListOff = PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
376 ppListOfListListOff = PcapPacketUtils.sortSignatures(ppListOfListListOff);
377 // TODO: Need to remove sequence number 1 for Nest Thermostat since it is not a good signature!
378 PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
379 PcapPacketUtils.printSignatures(ppListOfListListOff);
381 /*for (List<List<PcapPacket>> ll : ppListOfListListOff) {
382 PrintUtils.serializeClustersIntoFile("./offSignature" + ++count + ".sig", ll);
383 ppListOfListReadOff.add(PrintUtils.deserializeClustersFromFile("./offSignature" + count + ".sig"));
385 PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
386 ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
387 System.out.println("========================================");
388 // ============================================================================================================
391 System.out.println("==== ON ====");
392 // Print out all the pairs into a file for ON events
393 File fileOnEvents = new File(onPairsPath);
394 PrintWriter pwOn = null;
396 pwOn = new PrintWriter(fileOnEvents);
397 } catch(Exception ex) {
398 ex.printStackTrace();
400 for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
401 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
402 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
403 List<Conversation> listConv = entryConv.getValue();
404 // Just get the first Conversation because all Conversations in this group
405 // should have the same pairs of Application Data.
406 for(Conversation conv : listConv) {
407 // Process only if it is a TLS packet
409 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
410 for(PcapPacketPair pair: tlsAppDataList) {
411 System.out.println(PrintUtils.toCsv(pair, dnsMap));
412 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
414 } else { // Non-TLS conversations
415 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
416 for(PcapPacketPair pair: packetList) {
417 System.out.println(PrintUtils.toCsv(pair, dnsMap));
418 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
426 System.out.println("==== OFF ====");
427 // Print out all the pairs into a file for ON events
428 File fileOffEvents = new File(offPairsPath);
429 PrintWriter pwOff = null;
431 pwOff = new PrintWriter(fileOffEvents);
432 } catch(Exception ex) {
433 ex.printStackTrace();
435 for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
436 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
437 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
438 List<Conversation> listConv = entryConv.getValue();
439 // Just get the first Conversation because all Conversations in this group
440 // should have the same pairs of Application Data.
441 for(Conversation conv : listConv) {
442 // Process only if it is a TLS packet
444 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
445 for(PcapPacketPair pair: tlsAppDataList) {
446 System.out.println(PrintUtils.toCsv(pair, dnsMap));
447 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
449 } else { // Non-TLS conversations
450 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
451 for (PcapPacketPair pair : packetList) {
452 System.out.println(PrintUtils.toCsv(pair, dnsMap));
453 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
462 // // ================================================================================================
463 // // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
465 // // Currently need to know relevant hostname in advance :(
466 // String hostname = "events.tplinkra.com";
467 //// String hostname = "rfe-us-west-1.dch.dlink.com";
468 // // Conversations with 'hostname' for ON events.
469 // List<Conversation> onsForHostname = new ArrayList<>();
470 // // Conversations with 'hostname' for OFF events.
471 // List<Conversation> offsForHostname = new ArrayList<>();
472 // // "Unwrap" sequence groupings in ons/offs maps.
473 // ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
474 // offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
477 // Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
480 // // Extract representative sequence for ON and OFF by providing the list of conversations with
481 // // 'hostname' observed for each event type (the training data).
482 // SequenceExtraction seqExtraction = new SequenceExtraction();
483 //// ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
484 //// ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
486 // ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
487 // ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
489 // // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
491 // int onsLabeledAsOff = 0;
492 // Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
493 // Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
494 // SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
495 // for (Conversation c : onsForHostname) {
496 // Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
497 // if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
498 // onsLabeledAsOff++;
501 // int offsLabeledAsOn = 0;
502 // for (Conversation c : offsForHostname) {
503 // Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
504 // if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
505 // offsLabeledAsOn++;
508 // System.out.println("");
509 // // ================================================================================================
512 // // -------------------------------------------------------------------------------------------------------------
513 // // -------------------------------------------------------------------------------------------------------------
519 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
520 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159