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