5b184d2857780a28ad04cf437b59880d25689425
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3 import static edu.uci.iotproject.analysis.UserAction.Type;
4
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;
16
17 import java.io.EOFException;
18 import java.io.File;
19 import java.io.PrintWriter;
20 import java.net.UnknownHostException;
21 import java.time.Instant;
22 import java.util.*;
23 import java.util.concurrent.TimeoutException;
24 import java.util.stream.Collectors;
25 import java.util.stream.Stream;
26
27 /**
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.
32  *
33  * @author Janus Varmarken
34  * @author Rahmadi Trimananda (rtrimana@uci.edu)
35  * @version 0.1
36  */
37 public class Main {
38
39
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";
50
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?
56           // Actual training
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?
67
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";
73           // Actual training
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
84
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";
92
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!)
98         // October 18
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!)
111
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
117         // TODO: EXPERIMENT - November 20, 2018
118 //        final String inputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug.wlan1.local.pcap";
119 //        final String outputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug-processed.pcap";
120 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-plug/timestamps/wemo-plug-nov-20-2018.timestamps";
121 ////        final String deviceIp = "192.168.1.145"; // .246 == phone; .145 == WeMo
122 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .145 == WeMo
123
124         // 5) Wemo Insight July 31 experiment
125 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
126 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
127 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
128 //        final String deviceIp = "192.168.1.135";
129         // TODO: EXPERIMENT - November 21, 2018
130 //        final String inputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug.wlan1.local.pcap";
131 //        final String outputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug-processed.pcap";
132 //        final String triggerTimesFile = path + "/experimental_result/standalone/wemo-insight-plug/timestamps/wemo-insight-plug-nov-21-2018.timestamps";
133 ////        final String deviceIp = "192.168.1.145"; // .246 == phone; .135 == WeMo Insight
134 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .135 == WeMo Insight
135
136         // 6) TP-Link Bulb August 1 experiment
137 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
138 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
139 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
140 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
141         // TODO: EXPERIMENT - November 16, 2018
142 //        final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb.wlan1.local.pcap";
143 //        final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb-processed.pcap";
144 ////        final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb.eth1.local.pcap";
145 ////        final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb-processed.pcap";
146 //        final String triggerTimesFile = path + "/experimental_result/standalone/tplink-bulb/timestamps/tplink-bulb-nov-16-2018.timestamps";
147 ////        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
148 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
149
150         // 7) Kwikset Doorlock August 6 experiment
151 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
152 ////        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
153 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
154 ////        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
155 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-8hr-data-oct-11-2018.timestamps";
156 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
157         // TODO: EXPERIMENT - November 10, 2018
158 //        final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock.wlan1.local.pcap";
159 //        final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock-processed.pcap";
160 ////        final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock.eth1.local.pcap";
161 ////        final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock-processed.pcap";
162 //        final String triggerTimesFile = path + "/experimental_result/standalone/kwikset-doorlock/timestamps/kwikset-doorlock-nov-10-2018.timestamps";
163 ////        final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
164 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
165
166         // September 12, 2018 - includes both wlan1 and eth1 interfaces
167 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
168 //        //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
169 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
170 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
171 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
172
173         // 8) Hue Bulb August 7 experiment
174 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
175 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
176 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
177 //        final String deviceIp = "192.168.1.246";
178         // October 30 experiment
179 //        final String inputPcapFile = path + "/2018-10/hue-bulb/hue-bulb.wlan1.local.pcap";
180 //        final String outputPcapFile = path + "/2018-10/hue-bulb/hue-bulb-processed.pcap";
181 //        final String triggerTimesFile = path + "/2018-10/hue-bulb/hue-bulb-oct-30-2018.timestamps";
182 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
183         // TODO: EXPERIMENT - November 19, 2018
184 //        final String inputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb.wlan1.local.pcap";
185 //        final String outputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb-processed.pcap";
186 //        final String triggerTimesFile = path + "/experimental_result/standalone/hue-bulb/timestamps/hue-bulb-nov-19-2018.timestamps";
187 //        final String deviceIp = "192.168.1.100"; // .246 == phone; .100 == Hue hub
188 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
189
190         // 9) Lifx Bulb August 8 experiment
191 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
192 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
193 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
194 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
195         // October 18
196 //        final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
197 //        final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
198 //        final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-oct-18-2018.timestamps";
199 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
200         // November 1
201 //        final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
202 //        final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
203 //        final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-nov-1-2018.timestamps";
204 //        final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
205
206         // 10) Amcrest Camera August 9 experiment
207 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
208 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
209 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
210 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
211
212         // 11) Arlo Camera August 10 experiment
213 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
214 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
215 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
216 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
217         // TODO: EXPERIMENT - November 13, 2018
218 //        final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera.wlan1.local.pcap";
219 //        final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera-processed.pcap";
220 ////        final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera.eth1.local.pcap";
221 ////        final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera-processed.pcap";
222 //        final String triggerTimesFile = path + "/experimental_result/standalone/arlo-camera/timestamps/arlo-camera-nov-13-2018.timestamps";
223 ////        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
224 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
225
226         // 12) Blossom sprinkler August 13 experiment
227 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
228 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
229 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
230 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
231 //        // 2 November
232 //        final String inputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler.wlan1.local.pcap";
233 //        final String outputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-processed.pcap";
234 //        final String triggerTimesFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-nov-2-2018.timestamps";
235 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
236         // January 9, 11
237         final String inputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler.wlan1.local.pcap";
238         final String outputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler-processed.pcap";
239         final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-9-2019.timestamps";
240 //        final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-11-2019.timestamps";
241         final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
242
243 //        // 13) DLink siren August 14 experiment
244 //        final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
245 //        //final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
246 //        final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
247 //        final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-oct-12-2018.timestamps";
248 //        //final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
249 //        //final String triggerTimesFile = path + "/actual/timestamps/dlink-siren-8hr-data-oct-10-2018.timestamps";
250 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
251         // TODO: EXPERIMENT - November 9, 2018
252 //        final String inputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren.wlan1.local.pcap";
253 //        final String outputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren-processed.pcap";
254 //        final String triggerTimesFile = path + "/experimental_result/standalone/dlink-siren/timestamps/dlink-siren-nov-9-2018.timestamps";
255 //        final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
256 ////        final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
257
258         // 14) Nest thermostat August 15 experiment
259 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
260 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
261 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
262 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
263         // TODO: EXPERIMENT - November 14, 2018
264 //        final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat.wlan1.local.pcap";
265 //        final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat-processed.pcap";
266 ////        final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat.eth1.local.pcap";
267 ////        final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat-processed.pcap";
268 //        final String triggerTimesFile = path + "/experimental_result/standalone/nest-thermostat/timestamps/nest-thermostat-nov-15-2018.timestamps";
269 ////        final String deviceIp = "192.168.1.127"; // .246 == phone; .127 == Nest thermostat
270 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
271
272         // 15) Alexa August 16 experiment
273 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
274 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
275 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
276 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
277         // August 17
278 //        final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
279 //        final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
280 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
281 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
282
283         // September 17
284 //        final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
285 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
286 //        final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
287 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
288         // September 26 - D-Link noise
289 //        final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
290 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
291 //        final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
292 //        final String deviceIp = "192.168.1.183"; //  .199 == dlink plug; .183 == siren
293         // September 27 - Kwikset noise
294 //        final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
295 //        final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
296 //        final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
297 //        final String deviceIp = "192.168.1.142"; //  .142 == SmartThings Hub;
298
299         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
300         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
301         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
302         List<UserAction> userActions = new ArrayList<>();
303         for (int i = 0; i < triggerTimes.size(); i++) {
304             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
305         }
306         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
307         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
308         DnsMap dnsMap = new DnsMap();
309         TcpReassembler tcpReassembler = new TcpReassembler();
310         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
311         tte.performExtraction(pkt -> {
312             try {
313                 outputter.dump(pkt);
314             } catch (NotOpenException e) {
315                 e.printStackTrace();
316             }
317         }, dnsMap, tcpReassembler, trafficLabeler);
318         outputter.flush();
319         outputter.close();
320
321         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
322             // Sanity/debug check
323             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
324                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
325         }
326
327         // Extract all conversations present in the filtered trace.
328         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
329         // Group conversations by hostname.
330         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
331         System.out.println("Grouped conversations by hostname.");
332         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
333         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
334         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
335         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
336         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
337         // sequence of packets of some specific lengths).
338         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
339         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
340         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
341         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
342         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
343                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
344         System.out.println("Counted frequencies of packet pairs per hostname");
345         // For each user action, reassemble the set of TCP connections occurring shortly after
346         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
347         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
348         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
349
350
351
352         /*
353          * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
354          * sequence identifiers as we do not care about hostnames and sequences during clustering.
355          * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
356          */
357
358 //        // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
359 //        Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
360 //        // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
361 //        Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
362 //        userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
363 //            Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
364 //            hostnameToConvs.forEach((host, convs) -> {
365 //                Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
366 //                        groupConversationsByPacketSequence(convs, verbose);
367 //                outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
368 //                    newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
369 //                        list1.addAll(list2);
370 //                        return list1;
371 //                    }));
372 //                    return oldMap;
373 //                });
374 //            });
375 //        });
376 //
377 //        System.out.println("==== ON ====");
378 //        // Print out all the pairs into a file for ON events
379 //        File fileOnEvents = new File(onPairsPath);
380 //        PrintWriter pwOn = null;
381 //        try {
382 //            pwOn = new PrintWriter(fileOnEvents);
383 //        } catch(Exception ex) {
384 //            ex.printStackTrace();
385 //        }
386 //        for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
387 //            Map<String, List<Conversation>> seqsToConvs = entry.getValue();
388 //            for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
389 //                List<Conversation> listConv = entryConv.getValue();
390 //                // Just get the first Conversation because all Conversations in this group
391 //                // should have the same pairs of Application Data.
392 //                for(Conversation conv : listConv) {
393 //                    // Process only if it is a TLS packet
394 //                    if (conv.isTls()) {
395 //                        List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
396 //                        for(PcapPacketPair pair: tlsAppDataList) {
397 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
398 //                            pwOn.println(PrintUtils.toCsv(pair, dnsMap));
399 //                        }
400 //                    } else { // Non-TLS conversations
401 //                        List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
402 //                        for(PcapPacketPair pair: packetList) {
403 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
404 //                            pwOn.println(PrintUtils.toCsv(pair, dnsMap));
405 //                        }
406 //                    }
407 //                }
408 //            }
409 //        }
410 //        pwOn.close();
411 //
412 //        System.out.println("==== OFF ====");
413 //        // Print out all the pairs into a file for ON events
414 //        File fileOffEvents = new File(offPairsPath);
415 //        PrintWriter pwOff = null;
416 //        try {
417 //            pwOff = new PrintWriter(fileOffEvents);
418 //        } catch(Exception ex) {
419 //            ex.printStackTrace();
420 //        }
421 //        for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
422 //            Map<String, List<Conversation>> seqsToConvs = entry.getValue();
423 //            for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
424 //                List<Conversation> listConv = entryConv.getValue();
425 //                // Just get the first Conversation because all Conversations in this group
426 //                // should have the same pairs of Application Data.
427 //                for(Conversation conv : listConv) {
428 //                    // Process only if it is a TLS packet
429 //                    if (conv.isTls()) {
430 //                        List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
431 //                        for(PcapPacketPair pair: tlsAppDataList) {
432 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
433 //                            pwOff.println(PrintUtils.toCsv(pair, dnsMap));
434 //                        }
435 //                    } else { // Non-TLS conversations
436 //                        List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
437 //                        for (PcapPacketPair pair : packetList) {
438 //                            System.out.println(PrintUtils.toCsv(pair, dnsMap));
439 //                            pwOff.println(PrintUtils.toCsv(pair, dnsMap));
440 //                        }
441 //                    }
442 //                }
443 //            }
444 //        }
445 //        pwOff.close();
446
447
448         // ================================================ CLUSTERING ================================================
449         // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
450         // when don't care about hostnames and sequences (see comment earlier).
451         List<Conversation> onConversations = userActionToConversations.entrySet().stream().
452                 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
453                 map(e -> e.getValue()). // no longer interested in the UserActions
454                 flatMap(List::stream). // flatten List<List<T>> to a List<T>
455                 collect(Collectors.toList());
456         List<Conversation> offConversations = userActionToConversations.entrySet().stream().
457                 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
458                 map(e -> e.getValue()).
459                 flatMap(List::stream).
460                 collect(Collectors.toList());
461         //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
462
463         List<PcapPacketPair> onPairs = onConversations.stream().
464                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
465                         TcpConversationUtils.extractPacketPairs(c)).
466                 flatMap(List::stream). // flatten List<List<>> to List<>
467                 collect(Collectors.toList());
468         List<PcapPacketPair> offPairs = offConversations.stream().
469                 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
470                         TcpConversationUtils.extractPacketPairs(c)).
471                 flatMap(List::stream). // flatten List<List<>> to List<>
472                 collect(Collectors.toList());
473         // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
474         Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
475         // Perform clustering on conversation logged as part of all ON events.
476         DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
477         //DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(7.0, 45);
478         //DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 10);
479         List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
480         // Perform clustering on conversation logged as part of all OFF events.
481         DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
482         //DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(7.0, 45);
483         //DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 10);
484         List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
485         // Sort the conversations as reference
486         List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
487         // Output clusters
488         System.out.println("========================================");
489         System.out.println("       Clustering results for ON        ");
490         System.out.println("       Number of clusters: " + onClusters.size());
491         int count = 0;
492         List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
493         List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
494         for (Cluster<PcapPacketPair> c : onClusters) {
495             System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
496             System.out.print(PrintUtils.toSummaryString(c));
497             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
498             //if(c.getPoints().size() > 25) {
499                 // Print to file
500                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
501                 ppListOfListListOn.add(ppListOfList);
502             }
503         }
504         // TODO: Merging test
505         ppListOfListListOn = PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
506         ppListOfListListOn = PcapPacketUtils.sortSignatures(ppListOfListListOn);
507         // TODO: Need to remove sequence numbers 0,1 for Blossom phone side since it is not a good signature!
508         PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
509         PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 1);
510         // TODO: Need to remove sequence numbers 0 for Blossom device side since it is not a good signature!
511 //        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
512 //        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
513         // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
514         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 2);
515         // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
516         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
517         // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
518         // TODO: This sequence actually belongs to the local communication between the plug and the phone
519         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
520         PcapPacketUtils.printSignatures(ppListOfListListOn);
521         //count = 0;
522         /*for (List<List<PcapPacket>> ll : ppListOfListListOn) {
523             PrintUtils.serializeClustersIntoFile("./onSignature" + ++count + ".sig", ll);
524             ppListOfListReadOn.add(PrintUtils.deserializeClustersFromFile("./onSignature" + count + ".sig"));
525         }*/
526         PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
527         ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
528
529         System.out.println("========================================");
530         System.out.println("       Clustering results for OFF       ");
531         System.out.println("       Number of clusters: " + offClusters.size());
532         count = 0;
533         List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
534         List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
535         for (Cluster<PcapPacketPair> c : offClusters) {
536             System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
537             System.out.print(PrintUtils.toSummaryString(c));
538             if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
539             //if(c.getPoints().size() > 25) {
540                 // Print to file
541                 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
542                 ppListOfListListOff.add(ppListOfList);
543             }
544         }
545         // TODO: Merging test
546         ppListOfListListOff = PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
547         ppListOfListListOff = PcapPacketUtils.sortSignatures(ppListOfListListOff);
548         // TODO: Need to remove sequence numbers 0,2 for Blossom device side since it is not a good signature!
549 //        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 0);
550 //        PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 0);
551         // TODO: Need to remove sequence number 1 for Nest Thermostat since it is not a good signature!
552         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
553         // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
554         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
555         // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
556         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 2);
557         // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
558         // TODO: This sequence actually belongs to the local communication between the plug and the phone
559         //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 0);
560         PcapPacketUtils.printSignatures(ppListOfListListOff);
561         //count = 0;
562         /*for (List<List<PcapPacket>> ll : ppListOfListListOff) {
563             PrintUtils.serializeClustersIntoFile("./offSignature" + ++count + ".sig", ll);
564             ppListOfListReadOff.add(PrintUtils.deserializeClustersFromFile("./offSignature" + count + ".sig"));
565         }*/
566         PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
567         ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
568         System.out.println("========================================");
569         // ============================================================================================================
570
571
572 //        // ================================================================================================
573 //        // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
574 //        //
575 //        // Currently need to know relevant hostname in advance :(
576 //        String hostname = "events.tplinkra.com";
577 ////        String hostname = "rfe-us-west-1.dch.dlink.com";
578 //        // Conversations with 'hostname' for ON events.
579 //        List<Conversation> onsForHostname = new ArrayList<>();
580 //        // Conversations with 'hostname' for OFF events.
581 //        List<Conversation> offsForHostname = new ArrayList<>();
582 //        // "Unwrap" sequence groupings in ons/offs maps.
583 //        ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
584 //        offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
585 //
586 //
587 //        Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
588 //
589 //
590 //        // Extract representative sequence for ON and OFF by providing the list of conversations with
591 //        // 'hostname' observed for each event type (the training data).
592 //        SequenceExtraction seqExtraction = new SequenceExtraction();
593 ////        ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
594 ////        ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
595 //
596 //        ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
597 //        ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
598 //
599 //        // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
600 //        // labeled).
601 //        int onsLabeledAsOff = 0;
602 //        Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
603 //        Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
604 //        SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
605 //        for (Conversation c : onsForHostname) {
606 //            Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
607 //            if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
608 //                onsLabeledAsOff++;
609 //            }
610 //        }
611 //        int offsLabeledAsOn = 0;
612 //        for (Conversation c : offsForHostname) {
613 //            Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
614 //            if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
615 //                offsLabeledAsOn++;
616 //            }
617 //        }
618 //        System.out.println("");
619 //        // ================================================================================================
620 //
621 //
622 //        // -------------------------------------------------------------------------------------------------------------
623 //        // -------------------------------------------------------------------------------------------------------------
624     }
625
626 }
627
628
629 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
630 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159