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.PrintUtils;
11 import org.apache.commons.math3.stat.clustering.Cluster;
12 import org.apache.commons.math3.stat.clustering.DBSCANClusterer;
13 import org.pcap4j.core.*;
14 import org.pcap4j.packet.namednumber.DataLinkType;
16 import java.io.EOFException;
18 import java.io.PrintWriter;
19 import java.net.UnknownHostException;
20 import java.time.Instant;
22 import java.util.concurrent.TimeoutException;
23 import java.util.stream.Collectors;
24 import java.util.stream.Stream;
27 * This is a system that reads PCAP files to compare
28 * patterns of DNS hostnames, packet sequences, and packet
29 * lengths with training data to determine certain events
30 * or actions for smart home devices.
32 * @author Janus Varmarken
33 * @author Rahmadi Trimananda (rtrimana@uci.edu)
39 public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
40 // -------------------------------------------------------------------------------------------------------------
41 // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
42 // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
43 // which traffic is to be extracted:
44 // String path = "/scratch/July-2018"; // Rahmadi
45 String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
46 boolean verbose = true;
47 final String onPairsPath = "/scratch/July-2018/on.txt";
48 final String offPairsPath = "/scratch/July-2018/off.txt";
50 // 1) D-Link July 26 experiment
51 // final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
52 // final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
53 // final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
54 // final String deviceIp = "192.168.1.246"; // .246 == phone; .199 == dlink plug?
56 // 2) TP-Link July 25 experiment
57 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
58 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
59 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
60 // final String deviceIp = "192.168.1.159";
62 // 2b) TP-Link July 25 experiment TRUNCATED:
63 // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
64 // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
65 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
66 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
67 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
68 // final String deviceIp = "192.168.1.159";
70 // 3) SmartThings Plug July 25 experiment
71 // final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
72 // final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
73 // final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
74 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
76 // 4) Wemo July 30 experiment
77 // final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
78 // final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
79 // final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
80 // final String deviceIp = "192.168.1.145";
82 // 5) Wemo Insight July 31 experiment
83 // final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
84 // final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
85 // final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
86 // final String deviceIp = "192.168.1.135";
88 // 6) TP-Link Bulb August 1 experiment
89 // final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
90 // final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
91 // final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
92 // final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
94 // 7) Kwikset Doorlock August 6 experiment
95 // final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
96 // final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
97 // final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
98 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
100 // 8) Hue Bulb August 7 experiment
101 // final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
102 // final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
103 // final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
104 // final String deviceIp = "192.168.1.246";
106 // 9) Lifx Bulb August 8 experiment
107 // final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
108 // final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
109 // final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
110 // final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
112 // 10) Amcrest Camera August 9 experiment
113 // final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
114 // final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
115 // final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
116 // final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
118 // 11) Arlo Camera August 10 experiment
119 // final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
120 // final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
121 // final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
122 // final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
124 // 12) Blossom sprinkler August 13 experiment
125 // final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
126 // final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
127 // final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
128 // final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
130 // // 13) DLink siren August 14 experiment
131 final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
132 final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
133 final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
134 final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
136 // 14) Nest thermostat August 15 experiment
137 // final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
138 // final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
139 // final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
140 // final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
142 // 15) Alexa August 16 experiment
143 // final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
144 // final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
145 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
146 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
148 // final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
149 // final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
150 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
151 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
153 TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
154 List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
155 // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
156 List<UserAction> userActions = new ArrayList<>();
157 for (int i = 0; i < triggerTimes.size(); i++) {
158 userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
160 TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
161 final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
162 DnsMap dnsMap = new DnsMap();
163 TcpReassembler tcpReassembler = new TcpReassembler();
164 TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
165 tte.performExtraction(pkt -> {
168 } catch (NotOpenException e) {
171 }, dnsMap, tcpReassembler, trafficLabeler);
175 if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
176 // Sanity/debug check
177 throw new AssertionError(String.format("mismatch between packet count in %s and %s",
178 TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
181 // Extract all conversations present in the filtered trace.
182 List<Conversation> allConversations = tcpReassembler.getTcpConversations();
183 // Group conversations by hostname.
184 Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
185 System.out.println("Grouped conversations by hostname.");
186 // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
187 final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
188 convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
189 System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
190 // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
191 // sequence of packets of some specific lengths).
192 final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
193 convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
194 System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
195 // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
196 final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
197 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
198 System.out.println("Counted frequencies of packet pairs per hostname");
199 // For each user action, reassemble the set of TCP connections occurring shortly after
200 final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
201 final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
202 System.out.println("Reassembled TCP conversations occurring shortly after each user event");
207 * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
208 * sequence identifiers as we do not care about hostnames and sequences during clustering.
209 * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
212 // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
213 Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
214 // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
215 Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
216 userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
217 Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
218 hostnameToConvs.forEach((host, convs) -> {
219 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
220 groupConversationsByPacketSequence(convs, verbose);
221 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
222 newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
232 // ================================================ CLUSTERING ================================================
233 // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
234 // when don't care about hostnames and sequences (see comment earlier).
235 List<Conversation> onConversations = userActionToConversations.entrySet().stream().
236 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
237 map(e -> e.getValue()). // no longer interested in the UserActions
238 flatMap(List::stream). // flatten List<List<T>> to a List<T>
239 collect(Collectors.toList());
240 List<Conversation> offConversations = userActionToConversations.entrySet().stream().
241 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
242 map(e -> e.getValue()).
243 flatMap(List::stream).
244 collect(Collectors.toList());
245 List<PcapPacketPair> onPairs = onConversations.stream().
246 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
247 TcpConversationUtils.extractPacketPairs(c)).
248 flatMap(List::stream). // flatten List<List<>> to List<>
249 collect(Collectors.toList());
250 List<PcapPacketPair> offPairs = offConversations.stream().
251 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
252 TcpConversationUtils.extractPacketPairs(c)).
253 flatMap(List::stream). // flatten List<List<>> to List<>
254 collect(Collectors.toList());
255 // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
256 Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
257 // Perform clustering on conversation logged as part of all ON events.
258 DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 5);
259 List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
260 // Perform clustering on conversation logged as part of all OFF events.
261 DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 5);
262 List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
264 System.out.println("========================================");
265 System.out.println(" Clustering results for ON ");
266 System.out.println(" Number of clusters: " + onClusters.size());
268 for (Cluster<PcapPacketPair> c : onClusters) {
269 System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
270 System.out.print(PrintUtils.toSummaryString(c));
272 System.out.println("========================================");
273 System.out.println(" Clustering results for OFF ");
274 System.out.println(" Number of clusters: " + offClusters.size());
276 for (Cluster<PcapPacketPair> c : offClusters) {
277 System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
278 System.out.print(PrintUtils.toSummaryString(c));
280 System.out.println("========================================");
281 // ============================================================================================================
284 System.out.println("==== ON ====");
285 // Print out all the pairs into a file for ON events
286 File fileOnEvents = new File(onPairsPath);
287 PrintWriter pwOn = null;
289 pwOn = new PrintWriter(fileOnEvents);
290 } catch(Exception ex) {
291 ex.printStackTrace();
293 for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
294 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
295 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
296 List<Conversation> listConv = entryConv.getValue();
297 // Just get the first Conversation because all Conversations in this group
298 // should have the same pairs of Application Data.
299 for(Conversation conv : listConv) {
300 // Process only if it is a TLS packet
302 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
303 for(PcapPacketPair pair: tlsAppDataList) {
304 System.out.println(PrintUtils.toCsv(pair, dnsMap));
305 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
307 } else { // Non-TLS conversations
308 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
309 for(PcapPacketPair pair: packetList) {
310 System.out.println(PrintUtils.toCsv(pair, dnsMap));
311 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
319 System.out.println("==== OFF ====");
320 // Print out all the pairs into a file for ON events
321 File fileOffEvents = new File(offPairsPath);
322 PrintWriter pwOff = null;
324 pwOff = new PrintWriter(fileOffEvents);
325 } catch(Exception ex) {
326 ex.printStackTrace();
328 for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
329 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
330 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
331 List<Conversation> listConv = entryConv.getValue();
332 // Just get the first Conversation because all Conversations in this group
333 // should have the same pairs of Application Data.
334 for(Conversation conv : listConv) {
335 // Process only if it is a TLS packet
337 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
338 for(PcapPacketPair pair: tlsAppDataList) {
339 System.out.println(PrintUtils.toCsv(pair, dnsMap));
340 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
342 } else { // Non-TLS conversations
343 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
344 for (PcapPacketPair pair : packetList) {
345 System.out.println(PrintUtils.toCsv(pair, dnsMap));
346 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
355 // // ================================================================================================
356 // // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
358 // // Currently need to know relevant hostname in advance :(
359 // String hostname = "events.tplinkra.com";
360 //// String hostname = "rfe-us-west-1.dch.dlink.com";
361 // // Conversations with 'hostname' for ON events.
362 // List<Conversation> onsForHostname = new ArrayList<>();
363 // // Conversations with 'hostname' for OFF events.
364 // List<Conversation> offsForHostname = new ArrayList<>();
365 // // "Unwrap" sequence groupings in ons/offs maps.
366 // ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
367 // offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
370 // Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
373 // // Extract representative sequence for ON and OFF by providing the list of conversations with
374 // // 'hostname' observed for each event type (the training data).
375 // SequenceExtraction seqExtraction = new SequenceExtraction();
376 //// ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
377 //// ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
379 // ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
380 // ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
382 // // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
384 // int onsLabeledAsOff = 0;
385 // Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
386 // Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
387 // SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
388 // for (Conversation c : onsForHostname) {
389 // Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
390 // if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
391 // onsLabeledAsOff++;
394 // int offsLabeledAsOn = 0;
395 // for (Conversation c : offsForHostname) {
396 // Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
397 // if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
398 // offsLabeledAsOn++;
401 // System.out.println("");
402 // // ================================================================================================
405 // // -------------------------------------------------------------------------------------------------------------
406 // // -------------------------------------------------------------------------------------------------------------
412 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
413 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159