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.pcap4j.core.*;
12 import org.pcap4j.packet.namednumber.DataLinkType;
14 import java.io.EOFException;
16 import java.io.PrintWriter;
17 import java.net.UnknownHostException;
18 import java.time.Instant;
20 import java.util.concurrent.TimeoutException;
23 * This is a system that reads PCAP files to compare
24 * patterns of DNS hostnames, packet sequences, and packet
25 * lengths with training data to determine certain events
26 * or actions for smart home devices.
28 * @author Janus Varmarken
29 * @author Rahmadi Trimananda (rtrimana@uci.edu)
35 public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
36 // -------------------------------------------------------------------------------------------------------------
37 // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
38 // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
39 // which traffic is to be extracted:
40 String path = "/scratch/July-2018"; // Rahmadi
41 // String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
42 boolean verbose = true;
43 final String onPairsPath = "/scratch/July-2018/on.txt";
44 final String offPairsPath = "/scratch/July-2018/off.txt";
46 // 1) D-Link July 26 experiment
47 // final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
48 // final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
49 // final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
50 // final String deviceIp = "192.168.1.246"; // .246 == phone; .199 == dlink plug?
52 // 2) TP-Link July 25 experiment
53 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
54 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
55 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
56 // final String deviceIp = "192.168.1.159";
58 // 2b) TP-Link July 25 experiment TRUNCATED:
59 // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
60 // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
61 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
62 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
63 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
64 // final String deviceIp = "192.168.1.159";
66 // 3) SmartThings Plug July 25 experiment
67 // final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
68 // final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
69 // final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
70 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
72 // 4) Wemo July 30 experiment
73 // final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
74 // final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
75 // final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
76 // final String deviceIp = "192.168.1.145";
78 // 5) Wemo Insight July 31 experiment
79 // final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
80 // final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
81 // final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
82 // final String deviceIp = "192.168.1.135";
84 // 6) TP-Link Bulb August 1 experiment
85 // final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
86 // final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
87 // final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
88 // final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
90 // 7) Kwikset Doorlock August 6 experiment
91 // final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
92 // final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
93 // final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
94 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
95 // September 12, 2018 - includes both wlan1 and eth1 interfaces
96 //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
97 // final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
98 // final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
99 // final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
100 // final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
103 // 8) Hue Bulb August 7 experiment
104 // final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
105 // final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
106 // final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
107 // final String deviceIp = "192.168.1.246";
109 // 9) Lifx Bulb August 8 experiment
110 // final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
111 // final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
112 // final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
113 // final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
115 // 10) Amcrest Camera August 9 experiment
116 // final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
117 // final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
118 // final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
119 // final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
121 // 11) Arlo Camera August 10 experiment
122 // final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
123 // final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
124 // final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
125 // final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
127 // 12) Blossom sprinkler August 13 experiment
128 // final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
129 // final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
130 // final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
131 // final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
133 // // 13) DLink siren August 14 experiment
134 // final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
135 // final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
136 // final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
137 // final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
139 // 14) Nest thermostat August 15 experiment
140 // final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
141 // final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
142 // final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
143 // final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
145 // 15) Alexa August 16 experiment
146 // final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
147 // final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
148 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
149 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
151 // final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
152 // final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
153 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
154 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
157 final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
158 final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
159 final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
160 final String deviceIp = "192.168.1.142"; // .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
162 TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
163 List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
164 // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
165 List<UserAction> userActions = new ArrayList<>();
166 for (int i = 0; i < triggerTimes.size(); i++) {
167 userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
169 TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
170 final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
171 DnsMap dnsMap = new DnsMap();
172 TcpReassembler tcpReassembler = new TcpReassembler();
173 TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
174 tte.performExtraction(pkt -> {
177 } catch (NotOpenException e) {
180 }, dnsMap, tcpReassembler, trafficLabeler);
184 if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
185 // Sanity/debug check
186 throw new AssertionError(String.format("mismatch between packet count in %s and %s",
187 TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
190 // Extract all conversations present in the filtered trace.
191 List<Conversation> allConversations = tcpReassembler.getTcpConversations();
192 // Group conversations by hostname.
193 Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
194 System.out.println("Grouped conversations by hostname.");
195 // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
196 final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
197 convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
198 System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
199 // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
200 // sequence of packets of some specific lengths).
201 final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
202 convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
203 System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
204 // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
205 final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
206 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
207 System.out.println("Counted frequencies of packet pairs per hostname");
208 // For each user action, reassemble the set of TCP connections occurring shortly after
209 final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
210 final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
211 System.out.println("Reassembled TCP conversations occurring shortly after each user event");
215 // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
216 Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
217 // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
218 Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
219 userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
220 Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
221 hostnameToConvs.forEach((host, convs) -> {
222 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
223 groupConversationsByPacketSequence(convs, verbose);
224 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
225 newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
235 System.out.println("==== ON ====");
236 // Print out all the pairs into a file for ON events
237 File fileOnEvents = new File(onPairsPath);
238 PrintWriter pwOn = null;
240 pwOn = new PrintWriter(fileOnEvents);
241 } catch(Exception ex) {
242 ex.printStackTrace();
244 for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
245 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
246 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
247 List<Conversation> listConv = entryConv.getValue();
248 // Just get the first Conversation because all Conversations in this group
249 // should have the same pairs of Application Data.
250 for(Conversation conv : listConv) {
251 // Process only if it is a TLS packet
253 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
254 for(PcapPacketPair pair: tlsAppDataList) {
255 System.out.println(PrintUtils.toCsv(pair, dnsMap));
256 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
258 } else { // Non-TLS conversations
259 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
260 for(PcapPacketPair pair: packetList) {
261 System.out.println(PrintUtils.toCsv(pair, dnsMap));
262 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
270 System.out.println("==== OFF ====");
271 // Print out all the pairs into a file for ON events
272 File fileOffEvents = new File(offPairsPath);
273 PrintWriter pwOff = null;
275 pwOff = new PrintWriter(fileOffEvents);
276 } catch(Exception ex) {
277 ex.printStackTrace();
279 for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
280 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
281 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
282 List<Conversation> listConv = entryConv.getValue();
283 // Just get the first Conversation because all Conversations in this group
284 // should have the same pairs of Application Data.
285 for(Conversation conv : listConv) {
286 // Process only if it is a TLS packet
288 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
289 for(PcapPacketPair pair: tlsAppDataList) {
290 System.out.println(PrintUtils.toCsv(pair, dnsMap));
291 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
293 } else { // Non-TLS conversations
294 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
295 for (PcapPacketPair pair : packetList) {
296 System.out.println(PrintUtils.toCsv(pair, dnsMap));
297 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
306 // // ================================================================================================
307 // // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
309 // // Currently need to know relevant hostname in advance :(
310 // String hostname = "events.tplinkra.com";
311 //// String hostname = "rfe-us-west-1.dch.dlink.com";
312 // // Conversations with 'hostname' for ON events.
313 // List<Conversation> onsForHostname = new ArrayList<>();
314 // // Conversations with 'hostname' for OFF events.
315 // List<Conversation> offsForHostname = new ArrayList<>();
316 // // "Unwrap" sequence groupings in ons/offs maps.
317 // ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
318 // offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
321 // Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
324 // // Extract representative sequence for ON and OFF by providing the list of conversations with
325 // // 'hostname' observed for each event type (the training data).
326 // SequenceExtraction seqExtraction = new SequenceExtraction();
327 //// ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
328 //// ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
330 // ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
331 // ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
333 // // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
335 // int onsLabeledAsOff = 0;
336 // Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
337 // Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
338 // SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
339 // for (Conversation c : onsForHostname) {
340 // Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
341 // if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
342 // onsLabeledAsOff++;
345 // int offsLabeledAsOn = 0;
346 // for (Conversation c : offsForHostname) {
347 // Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
348 // if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
349 // offsLabeledAsOn++;
352 // System.out.println("");
353 // // ================================================================================================
356 // // -------------------------------------------------------------------------------------------------------------
357 // // -------------------------------------------------------------------------------------------------------------
363 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
364 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159