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.199"; // .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!)
96 // 8) Hue Bulb August 7 experiment
97 // final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
98 // final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
99 // final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
100 // final String deviceIp = "192.168.1.246";
102 // 9) Lifx Bulb August 8 experiment
103 // final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
104 // final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
105 // final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
106 // final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
108 // 10) Amcrest Camera August 9 experiment
109 // final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
110 // final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
111 // final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
112 // final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
114 // 11) Arlo Camera August 10 experiment
115 // final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
116 // final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
117 // final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
118 // final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
120 // 12) Blossom sprinkler August 13 experiment
121 // final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
122 // final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
123 // final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
124 // final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
126 // 13) DLink siren August 14 experiment
127 final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
128 final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
129 final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
130 final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
132 // 14) Nest thermostat August 15 experiment
133 // final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
134 // final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
135 // final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
136 // final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
138 // 15) Alexa August 16 experiment
139 // final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
140 // final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
141 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
142 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
144 // final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
145 // final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
146 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
147 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
149 TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
150 List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
151 // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
152 List<UserAction> userActions = new ArrayList<>();
153 for (int i = 0; i < triggerTimes.size(); i++) {
154 userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
156 TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
157 final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
158 DnsMap dnsMap = new DnsMap();
159 TcpReassembler tcpReassembler = new TcpReassembler();
160 TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
161 tte.performExtraction(pkt -> {
164 } catch (NotOpenException e) {
167 }, dnsMap, tcpReassembler, trafficLabeler);
171 if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
172 // Sanity/debug check
173 throw new AssertionError(String.format("mismatch between packet count in %s and %s",
174 TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
177 // Extract all conversations present in the filtered trace.
178 List<Conversation> allConversations = tcpReassembler.getTcpConversations();
179 // Group conversations by hostname.
180 Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
181 System.out.println("Grouped conversations by hostname.");
182 // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
183 final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
184 convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
185 System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
186 // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
187 // sequence of packets of some specific lengths).
188 final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
189 convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
190 System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
191 // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
192 final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
193 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
194 System.out.println("Counted frequencies of packet pairs per hostname");
195 // For each user action, reassemble the set of TCP connections occurring shortly after
196 final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
197 final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
198 System.out.println("Reassembled TCP conversations occurring shortly after each user event");
202 // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
203 Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
204 // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
205 Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
206 userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
207 Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
208 hostnameToConvs.forEach((host, convs) -> {
209 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
210 groupConversationsByPacketSequence(convs, verbose);
211 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
212 newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
222 System.out.println("==== ON ====");
223 // Print out all the pairs into a file for ON events
224 File fileOnEvents = new File(onPairsPath);
225 PrintWriter pwOn = null;
227 pwOn = new PrintWriter(fileOnEvents);
228 } catch(Exception ex) {
229 ex.printStackTrace();
231 for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
232 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
233 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
234 List<Conversation> listConv = entryConv.getValue();
235 // Just get the first Conversation because all Conversations in this group
236 // should have the same pairs of Application Data.
237 for(Conversation conv : listConv) {
238 // Process only if it is a TLS packet
240 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
241 for(PcapPacketPair pair: tlsAppDataList) {
242 System.out.println(PrintUtils.toCsv(pair, dnsMap));
243 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
245 } else { // Non-TLS conversations
246 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
247 for(PcapPacketPair pair: packetList) {
248 System.out.println(PrintUtils.toCsv(pair, dnsMap));
249 pwOn.println(PrintUtils.toCsv(pair, dnsMap));
257 System.out.println("==== OFF ====");
258 // Print out all the pairs into a file for ON events
259 File fileOffEvents = new File(offPairsPath);
260 PrintWriter pwOff = null;
262 pwOff = new PrintWriter(fileOffEvents);
263 } catch(Exception ex) {
264 ex.printStackTrace();
266 for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
267 Map<String, List<Conversation>> seqsToConvs = entry.getValue();
268 for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
269 List<Conversation> listConv = entryConv.getValue();
270 // Just get the first Conversation because all Conversations in this group
271 // should have the same pairs of Application Data.
272 for(Conversation conv : listConv) {
273 // Process only if it is a TLS packet
275 List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
276 for(PcapPacketPair pair: tlsAppDataList) {
277 System.out.println(PrintUtils.toCsv(pair, dnsMap));
278 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
280 } else { // Non-TLS conversations
281 List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
282 for (PcapPacketPair pair : packetList) {
283 System.out.println(PrintUtils.toCsv(pair, dnsMap));
284 pwOff.println(PrintUtils.toCsv(pair, dnsMap));
293 // // ================================================================================================
294 // // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
296 // // Currently need to know relevant hostname in advance :(
297 // String hostname = "events.tplinkra.com";
298 //// String hostname = "rfe-us-west-1.dch.dlink.com";
299 // // Conversations with 'hostname' for ON events.
300 // List<Conversation> onsForHostname = new ArrayList<>();
301 // // Conversations with 'hostname' for OFF events.
302 // List<Conversation> offsForHostname = new ArrayList<>();
303 // // "Unwrap" sequence groupings in ons/offs maps.
304 // ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
305 // offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
308 // Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
311 // // Extract representative sequence for ON and OFF by providing the list of conversations with
312 // // 'hostname' observed for each event type (the training data).
313 // SequenceExtraction seqExtraction = new SequenceExtraction();
314 //// ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
315 //// ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
317 // ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
318 // ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
320 // // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
322 // int onsLabeledAsOff = 0;
323 // Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
324 // Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
325 // SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
326 // for (Conversation c : onsForHostname) {
327 // Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
328 // if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
329 // onsLabeledAsOff++;
332 // int offsLabeledAsOn = 0;
333 // for (Conversation c : offsForHostname) {
334 // Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
335 // if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
336 // offsLabeledAsOn++;
339 // System.out.println("");
340 // // ================================================================================================
343 // // -------------------------------------------------------------------------------------------------------------
344 // // -------------------------------------------------------------------------------------------------------------
350 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
351 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159