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