1 package edu.uci.iotproject;
3 import static edu.uci.iotproject.analysis.UserAction.Type;
5 import edu.uci.iotproject.analysis.*;
6 import edu.uci.iotproject.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;
16 import java.io.EOFException;
17 import java.net.UnknownHostException;
18 import java.time.Duration;
19 import java.time.Instant;
21 import java.util.concurrent.TimeoutException;
22 import java.util.stream.Collectors;
23 import java.util.stream.Stream;
26 * This is a system that reads PCAP files to compare
27 * patterns of DNS hostnames, packet sequences, and packet
28 * lengths with training data to determine certain events
29 * or actions for smart home devices.
31 * @author Janus Varmarken
32 * @author Rahmadi Trimananda (rtrimana@uci.edu)
35 public class SignatureGenerator {
38 public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
39 // -------------------------------------------------------------------------------------------------------------
40 // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
41 // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
42 // which traffic is to be extracted:
43 String path = "/scratch/July-2018"; // Rahmadi
44 // String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
45 boolean verbose = true;
46 final String onPairsPath = "/scratch/July-2018/on.txt";
47 final String offPairsPath = "/scratch/July-2018/off.txt";
49 // 1) D-Link July 26 experiment
50 // final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
51 // final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
52 // final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
53 // final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
55 // final String inputPcapFile = path + "/2018-10/dlink-plug/dlink-plug.wlan1.local.pcap";
56 // final String outputPcapFile = path + "/2018-10/dlink-plug/dlink-plug-processed.pcap";
57 // final String triggerTimesFile = path + "/2018-10/dlink-plug/dlink-plug-oct-17-2018.timestamps";
58 // final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
59 // TODO: EXPERIMENT - November 7, 2018
60 // final String inputPcapFile = path + "/experimental_result/standalone/dlink-plug/wlan1/dlink-plug.wlan1.local.pcap";
61 // final String outputPcapFile = path + "/experimental_result/standalone/dlink-plug/wlan1/dlink-plug-processed.pcap";
62 // final String triggerTimesFile = path + "/experimental_result/standalone/dlink-plug/timestamps/dlink-plug-nov-7-2018.timestamps";
63 // final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
64 //// final String deviceIp = "192.168.1.246"; // .246 == phone; .199 == dlink plug?
66 // 2) TP-Link July 25 experiment
67 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
68 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
69 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
70 // final String deviceIp = "192.168.1.159";
72 // final String inputPcapFile = path + "/2018-10/tplink-plug/tplink-plug.wlan1.local.pcap";
73 // final String outputPcapFile = path + "/2018-10/tplink-plug/tplink-plug-processed.pcap";
74 // final String triggerTimesFile = path + "/2018-10/tplink-plug/tplink-plug-oct-17-2018.timestamps";
75 // final String deviceIp = "192.168.1.159"; // .246 == phone; .159 == tplink plug
76 // TODO: EXPERIMENT - November 8, 2018
77 // final String inputPcapFile = path + "/experimental_result/standalone/tplink-plug/wlan1/tplink-plug.wlan1.local.pcap";
78 // final String outputPcapFile = path + "/experimental_result/standalone/tplink-plug/wlan1/tplink-plug-processed.pcap";
79 // final String triggerTimesFile = path + "/experimental_result/standalone/tplink-plug/timestamps/tplink-plug-nov-8-2018.timestamps";
80 // final String deviceIp = "192.168.1.159"; // .246 == phone; .159 == tplink plug
81 //// final String deviceIp = "192.168.1.246"; // .246 == phone; .159 == tplink plug
83 // 2b) TP-Link July 25 experiment TRUNCATED:
84 // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
85 // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
86 // final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
87 // final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
88 // final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
89 // final String deviceIp = "192.168.1.159";
91 // 3) SmartThings Plug July 25 experiment
92 // final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
93 // final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
94 // final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
95 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
97 // final String inputPcapFile = path + "/2018-10/st-plug/st-plug.wlan1.local.pcap";
98 // final String outputPcapFile = path + "/2018-10/st-plug/st-plug-processed.pcap";
99 // final String triggerTimesFile = path + "/2018-10/st-plug/st-plug-oct-18-2018.timestamps";
100 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
101 // TODO: EXPERIMENT - November 12, 2018
102 // final String inputPcapFile = path + "/experimental_result/standalone/st-plug/wlan1/st-plug.wlan1.local.pcap";
103 // final String outputPcapFile = path + "/experimental_result/standalone/st-plug/wlan1/st-plug-processed.pcap";
104 //// final String inputPcapFile = path + "/experimental_result/standalone/st-plug/eth1/st-plug.eth1.local.pcap";
105 //// final String outputPcapFile = path + "/experimental_result/standalone/st-plug/eth1/st-plug-processed.pcap";
106 // final String triggerTimesFile = path + "/experimental_result/standalone/st-plug/timestamps/st-plug-nov-12-2018.timestamps";
107 //// final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
108 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
110 // 4) Wemo July 30 experiment
111 // final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
112 // final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
113 // final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
114 // final String deviceIp = "192.168.1.145"; // .246 == phone; .145 == WeMo
115 // TODO: EXPERIMENT - November 20, 2018
116 // final String inputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug.wlan1.local.pcap";
117 // final String outputPcapFile = path + "/experimental_result/standalone/wemo-plug/wlan1/wemo-plug-processed.pcap";
118 // final String triggerTimesFile = path + "/experimental_result/standalone/wemo-plug/timestamps/wemo-plug-nov-20-2018.timestamps";
119 //// final String deviceIp = "192.168.1.145"; // .246 == phone; .145 == WeMo
120 // final String deviceIp = "192.168.1.246"; // .246 == phone; .145 == WeMo
122 // 5) Wemo Insight July 31 experiment
123 // final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
124 // final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
125 // final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
126 // final String deviceIp = "192.168.1.135";
127 // TODO: EXPERIMENT - November 21, 2018
128 // final String inputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug.wlan1.local.pcap";
129 // final String outputPcapFile = path + "/experimental_result/standalone/wemo-insight-plug/wlan1/wemo-insight-plug-processed.pcap";
130 // final String triggerTimesFile = path + "/experimental_result/standalone/wemo-insight-plug/timestamps/wemo-insight-plug-nov-21-2018.timestamps";
131 //// final String deviceIp = "192.168.1.145"; // .246 == phone; .135 == WeMo Insight
132 // final String deviceIp = "192.168.1.246"; // .246 == phone; .135 == WeMo Insight
134 // 6) TP-Link Bulb August 1 experiment
135 // final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
136 // final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
137 // final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
138 // final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
139 // TODO: EXPERIMENT - November 16, 2018
140 // final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb.wlan1.local.pcap";
141 // final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/wlan1/tplink-bulb-processed.pcap";
142 //// final String inputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb.eth1.local.pcap";
143 //// final String outputPcapFile = path + "/experimental_result/standalone/tplink-bulb/eth0/tplink-bulb-processed.pcap";
144 // final String triggerTimesFile = path + "/experimental_result/standalone/tplink-bulb/timestamps/tplink-bulb-nov-16-2018.timestamps";
145 //// final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == TP-Link bulb
146 // final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == TP-Link bulb
148 // 7) Kwikset Doorlock August 6 experiment
149 // final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
150 //// final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
151 // final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
152 //// final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
153 // final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-8hr-data-oct-11-2018.timestamps";
154 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
155 // TODO: EXPERIMENT - November 10, 2018
156 // final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock.wlan1.local.pcap";
157 // final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/wlan1/kwikset-doorlock-processed.pcap";
158 //// final String inputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock.eth1.local.pcap";
159 //// final String outputPcapFile = path + "/experimental_result/standalone/kwikset-doorlock/eth1/kwikset-doorlock-processed.pcap";
160 // final String triggerTimesFile = path + "/experimental_result/standalone/kwikset-doorlock/timestamps/kwikset-doorlock-nov-10-2018.timestamps";
161 //// final String deviceIp = "192.168.1.142"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
162 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
164 // September 12, 2018 - includes both wlan1 and eth1 interfaces
165 // final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
166 // //final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.eth1.local.pcap";
167 // final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3-processed.pcap";
168 // final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-sept-12-2018.timestamps";
169 // final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
171 // 8) Hue Bulb August 7 experiment
172 // final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
173 // final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
174 // final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
175 // final String deviceIp = "192.168.1.246";
176 // October 30 experiment
177 // final String inputPcapFile = path + "/2018-10/hue-bulb/hue-bulb.wlan1.local.pcap";
178 // final String outputPcapFile = path + "/2018-10/hue-bulb/hue-bulb-processed.pcap";
179 // final String triggerTimesFile = path + "/2018-10/hue-bulb/hue-bulb-oct-30-2018.timestamps";
180 // final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
181 // TODO: EXPERIMENT - November 19, 2018
182 // final String inputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb.wlan1.local.pcap";
183 // final String outputPcapFile = path + "/experimental_result/standalone/hue-bulb/wlan1/hue-bulb-processed.pcap";
184 // final String triggerTimesFile = path + "/experimental_result/standalone/hue-bulb/timestamps/hue-bulb-nov-19-2018.timestamps";
185 //// final String deviceIp = "192.168.1.100"; // .246 == phone; .100 == Hue hub
186 // final String deviceIp = "192.168.1.246"; // .246 == phone; .100 == Hue hub
188 // 9) Lifx Bulb August 8 experiment
189 // final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
190 // final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
191 // final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
192 // final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
194 // final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
195 // final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
196 // final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-oct-18-2018.timestamps";
197 // final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
199 // final String inputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb.wlan1.local.pcap";
200 // final String outputPcapFile = path + "/2018-10/lifx-bulb/lifx-bulb-processed.pcap";
201 // final String triggerTimesFile = path + "/2018-10/lifx-bulb/lifx-bulb-nov-1-2018.timestamps";
202 // final String deviceIp = "192.168.1.231"; // .246 == phone; .231 == Lifx
204 // 10) Amcrest Camera August 9 experiment
205 // final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
206 // final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
207 // final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
208 // final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
210 // 11) Arlo Camera August 10 experiment
211 // final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
212 // final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
213 // final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
214 // final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
215 // TODO: EXPERIMENT - November 13, 2018
216 // final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera.wlan1.local.pcap";
217 // final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/wlan1/arlo-camera-processed.pcap";
218 //// final String inputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera.eth1.local.pcap";
219 //// final String outputPcapFile = path + "/experimental_result/standalone/arlo-camera/eth0/arlo-camera-processed.pcap";
220 // final String triggerTimesFile = path + "/experimental_result/standalone/arlo-camera/timestamps/arlo-camera-nov-13-2018.timestamps";
221 //// final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
222 // final String deviceIp = "192.168.1.246"; // .246 == phone; .140 == camera
224 // 12) Blossom sprinkler August 13 experiment
225 // final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
226 // final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
227 // final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
228 // final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
230 // final String inputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler.wlan1.local.pcap";
231 // final String outputPcapFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-processed.pcap";
232 // final String triggerTimesFile = path + "/2018-10/blossom-sprinkler/blossom-sprinkler-nov-2-2018.timestamps";
233 // final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
234 // January 9, 11, 13, 14
235 // final String inputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler.wlan1.local.pcap";
236 // final String outputPcapFile = path + "/experimental_result/standalone/blossom-sprinkler/wlan1/blossom-sprinkler-processed.pcap";
237 // final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-14-2019.timestamps";
238 //// final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-11-2019.timestamps";
239 // final String deviceIp = "192.168.1.246"; // .246 == phone; .229 == sprinkler
240 //// final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
242 // // 13) DLink siren August 14 experiment
243 // final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
244 // //final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
245 // final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
246 // final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-oct-12-2018.timestamps";
247 // //final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
248 // //final String triggerTimesFile = path + "/actual/timestamps/dlink-siren-8hr-data-oct-10-2018.timestamps";
249 // final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
250 // TODO: EXPERIMENT - November 9, 2018
251 // final String inputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren.wlan1.local.pcap";
252 // final String outputPcapFile = path + "/experimental_result/standalone/dlink-siren/wlan1/dlink-siren-processed.pcap";
253 // final String triggerTimesFile = path + "/experimental_result/standalone/dlink-siren/timestamps/dlink-siren-nov-9-2018.timestamps";
254 //// final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
255 // final String deviceIp = "192.168.1.246"; // .246 == phone; .183 == siren
257 // 14) Nest thermostat August 15 experiment
258 // final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
259 // final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
260 // final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
261 // final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
262 // // TODO: EXPERIMENT - November 14, 2018
263 final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat.wlan1.local.pcap";
264 final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/wlan1/nest-thermostat-processed.pcap";
265 // final String inputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat.eth1.local.pcap";
266 // final String outputPcapFile = path + "/experimental_result/standalone/nest-thermostat/eth0/nest-thermostat-processed.pcap";
267 final String triggerTimesFile = path + "/experimental_result/standalone/nest-thermostat/timestamps/nest-thermostat-nov-15-2018.timestamps";
268 // final String deviceIp = "192.168.1.127"; // .246 == phone; .127 == Nest thermostat
269 final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
271 // 15) Alexa August 16 experiment
272 // final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
273 // final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
274 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
275 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
277 // final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
278 // final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
279 // final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
280 // final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
283 // final String inputPcapFile = path + "/2018-08/noise/noise.eth1.pcap";
284 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
285 // final String triggerTimesFile = path + "/2018-08/noise/noise-sept-17-2018.timestamps";
286 // final String deviceIp = "192.168.1.142"; // .142 == SmartThings Hub; .199 == dlink plug; .183 == siren
287 // September 26 - D-Link noise
288 // final String inputPcapFile = path + "/2018-08/noise/noise.dlink.wlan1.pcap";
289 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
290 // final String triggerTimesFile = path + "/2018-08/noise/dlink-noise-sept-26-2018.timestamps";
291 // final String deviceIp = "192.168.1.183"; // .199 == dlink plug; .183 == siren
292 // September 27 - Kwikset noise
293 // final String inputPcapFile = path + "/2018-08/noise/noise.kwikset.eth1.pcap";
294 // final String outputPcapFile = path + "/2018-08/noise/noise-processed.pcap";
295 // final String triggerTimesFile = path + "/2018-08/noise/kwikset-doorlock-noise-sept-27-2018.timestamps";
296 // final String deviceIp = "192.168.1.142"; // .142 == SmartThings Hub;
298 // TODO: The below part is just for 15-second time sensitivity experiment
299 // TODO: The below part is just for 15-second time sensitivity experiment
300 // TODO: The below part is just for 15-second time sensitivity experiment
302 // final String triggerTimesFile = path + "/experimental_result/standalone/dlink-plug/timestamps/dlink-plug-nov-7-2018.timestamps";
303 //// final String onSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-onSignature-phone-side.sig";
304 //// final String offSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-offSignature-phone-side.sig";
305 // final String onSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-onSignature-device-side.sig";
306 // final String offSignatureFile = path + "/experimental_result/standalone/dlink-plug/signatures/dlink-plug-offSignature-device-side.sig";
308 // final String triggerTimesFile = path + "/experimental_result/standalone/tplink-plug/timestamps/tplink-plug-nov-8-2018.timestamps";
309 ////// final String onSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-onSignature-phone-side.sig";
310 ////// final String offSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-offSignature-phone-side.sig";
311 //// final String onSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-onSignature-device-side-outbound.sig";
312 //// final String offSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-offSignature-device-side-outbound.sig";
313 // final String onSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-onSignature-device-side.sig";
314 // final String offSignatureFile = path + "/experimental_result/standalone/tplink-plug/signatures/tplink-plug-offSignature-device-side.sig";
317 // final String triggerTimesFile = path + "/experimental_result/standalone/dlink-siren/timestamps/dlink-siren-nov-9-2018.timestamps";
318 // final String onSignatureFile = path + "/experimental_result/standalone/dlink-siren/signatures/dlink-siren-onSignature-phone-side.sig";
319 // final String offSignatureFile = path + "/experimental_result/standalone/dlink-siren/signatures/dlink-siren-offSignature-phone-side.sig";
321 // final String triggerTimesFile = path + "/experimental_result/standalone/kwikset-doorlock/timestamps/kwikset-doorlock-nov-10-2018.timestamps";
322 // final String onSignatureFile = path + "/experimental_result/standalone/kwikset-doorlock/signatures/kwikset-doorlock-onSignature-phone-side.sig";
323 // final String offSignatureFile = path + "/experimental_result/standalone/kwikset-doorlock/signatures/kwikset-doorlock-offSignature-phone-side.sig";
325 // final String triggerTimesFile = path + "/experimental_result/standalone/st-plug/timestamps/st-plug-nov-12-2018.timestamps";
326 // final String onSignatureFile = path + "/experimental_result/standalone/st-plug/signatures/st-plug-onSignature-phone-side.sig";
327 // final String offSignatureFile = path + "/experimental_result/standalone/st-plug/signatures/st-plug-offSignature-phone-side.sig";
329 // final String triggerTimesFile = path + "/experimental_result/standalone/arlo-camera/timestamps/arlo-camera-nov-13-2018.timestamps";
330 // final String onSignatureFile = path + "/experimental_result/standalone/arlo-camera/signatures/arlo-camera-onSignature-phone-side.sig";
331 // final String offSignatureFile = path + "/experimental_result/standalone/arlo-camera/signatures/arlo-camera-offSignature-phone-side.sig";
333 // final String triggerTimesFile = path + "/experimental_result/standalone/nest-thermostat/timestamps/nest-thermostat-nov-15-2018.timestamps";
334 // final String onSignatureFile = path + "/experimental_result/standalone/nest-thermostat/signatures/nest-thermostat-onSignature-phone-side.sig";
335 // final String offSignatureFile = path + "/experimental_result/standalone/nest-thermostat/signatures/nest-thermostat-offSignature-phone-side.sig";
337 // final String triggerTimesFile = path + "/experimental_result/standalone/blossom-sprinkler/timestamps/blossom-sprinkler-standalone-jan-14-2019.timestamps";
338 // final String onSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-onSignature-device-side.sig";
339 // final String offSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-offSignature-device-side.sig";
340 // final String onSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-onSignature-phone-side.sig";
341 // final String offSignatureFile = path + "/experimental_result/standalone/blossom-sprinkler/signatures/blossom-sprinkler-offSignature-phone-side.sig";
343 // final String triggerTimesFile = path + "/experimental_result/standalone/tplink-bulb/timestamps/tplink-bulb-nov-16-2018.timestamps";
344 // final String onSignatureFile = path + "/experimental_result/standalone/tplink-bulb/signatures/tplink-bulb-onSignature-phone-side.sig";
345 // final String offSignatureFile = path + "/experimental_result/standalone/tplink-bulb/signatures/tplink-bulb-offSignature-phone-side.sig";
347 // final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
348 // final String onSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-onSignature-phone-side.sig";
349 // final String offSignatureFile = path + "/training/hue-bulb/signatures/hue-bulb-offSignature-phone-side.sig";
351 // final String triggerTimesFile = path + "/experimental_result/standalone/wemo-plug/timestamps/wemo-plug-nov-20-2018.timestamps";
352 // final String onSignatureFile = path + "/experimental_result/standalone/wemo-plug/signatures/wemo-plug-onSignature-phone-side.sig";
353 // final String offSignatureFile = path + "/experimental_result/standalone/wemo-plug/signatures/wemo-plug-offSignature-phone-side.sig";
355 // final String triggerTimesFile = path + "/experimental_result/standalone/wemo-insight-plug/timestamps/wemo-insight-plug-nov-21-2018.timestamps";
356 // final String onSignatureFile = path + "/experimental_result/standalone/wemo-insight-plug/signatures/wemo-insight-plug-onSignature-phone-side.sig";
357 // final String offSignatureFile = path + "/experimental_result/standalone/wemo-insight-plug/signatures/wemo-insight-plug-offSignature-phone-side.sig";
360 // TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
361 // List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
363 // System.out.println("ON signature file in use is " + onSignatureFile);
364 // System.out.println("OFF signature file in use is " + offSignatureFile);
366 // List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
367 // List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
369 // List<Instant> signatureTimestamps = new ArrayList<>();
370 // // Load ON signature last packet's timestamp
371 // // Get the last only
372 // List<List<PcapPacket>> lastListOn = onSignature.get(onSignature.size()-1);
373 // for (List<PcapPacket> list : lastListOn) {
374 // // Get timestamp Instant from the last packet
375 // int lastPacketIndex = list.size()-1;
376 // signatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
378 // // Load OFF signature last packet's timestamp
379 // // Get the last only
380 // List<List<PcapPacket>> lastListOff = offSignature.get(offSignature.size()-1);
381 // for (List<PcapPacket> list : lastListOff) {
382 // // Get timestamp Instant from the last packet
383 // int lastPacketIndex = list.size()-1;
384 // signatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
386 // // Sort the timestamps
387 // signatureTimestamps.sort((p1, p2) -> {
388 // return p1.compareTo(p2);
391 // Iterator<Instant> iterTrig = triggerTimes.iterator();
392 // Iterator<Instant> iterSign = signatureTimestamps.iterator();
393 // System.out.println("Trigger to Last Packet:");
394 // while (iterTrig.hasNext() && iterSign.hasNext()) {
395 // Instant trigInst = (Instant) iterTrig.next();
396 // Instant signInst = (Instant) iterSign.next();
397 // Duration dur = Duration.between(trigInst, signInst);
398 // long duration = dur.toMillis();
399 // // Check duration --- should be below 15 seconds
400 // if (duration >= 0 && duration <= 15000) {
401 // System.out.println(dur.toMillis());
402 // } else if (duration > 15000) {
403 // while (duration > 15000) { // that means we have to move to the next trigger
404 // trigInst = (Instant) iterTrig.next();
405 // dur = Duration.between(trigInst, signInst);
406 // duration = dur.toMillis();
408 // System.out.println(dur.toMillis());
409 // } else { // below 0 / negative --- that means we have to move to the next signature
410 // while (duration < 0) { // that means we have to move to the next trigger
411 // signInst = (Instant) iterSign.next();
412 // dur = Duration.between(trigInst, signInst);
413 // duration = dur.toMillis();
415 // System.out.println(dur.toMillis());
420 // // ==========================================================================
421 // List<Instant> firstSignatureTimestamps = new ArrayList<>();
422 // List<Instant> lastSignatureTimestamps = new ArrayList<>();
423 // List<List<PcapPacket>> firstListOnSign = onSignature.get(0);
424 // List<List<PcapPacket>> lastListOnSign = onSignature.get(onSignature.size()-1);
425 // // Load ON signature first and last packet's timestamps
426 // for (List<PcapPacket> list : firstListOnSign) {
427 // // Get timestamp Instant from the last packet
428 // firstSignatureTimestamps.add(list.get(0).getTimestamp());
430 // for (List<PcapPacket> list : lastListOnSign) {
431 // // Get timestamp Instant from the last packet
432 // int lastPacketIndex = list.size()-1;
433 // lastSignatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
436 // List<List<PcapPacket>> firstListOffSign = offSignature.get(0);
437 // List<List<PcapPacket>> lastListOffSign = offSignature.get(offSignature.size()-1);
438 // // Load OFF signature first and last packet's timestamps
439 // for (List<PcapPacket> list : firstListOffSign) {
440 // // Get timestamp Instant from the last packet
441 // firstSignatureTimestamps.add(list.get(0).getTimestamp());
443 // for (List<PcapPacket> list : lastListOffSign) {
444 // // Get timestamp Instant from the last packet
445 // int lastPacketIndex = list.size()-1;
446 // lastSignatureTimestamps.add(list.get(lastPacketIndex).getTimestamp());
448 // // Sort the timestamps
449 // firstSignatureTimestamps.sort((p1, p2) -> {
450 // return p1.compareTo(p2);
452 // // Sort the timestamps
453 // lastSignatureTimestamps.sort((p1, p2) -> {
454 // return p1.compareTo(p2);
457 // Iterator<Instant> iterFirst = firstSignatureTimestamps.iterator();
458 // Iterator<Instant> iterLast = lastSignatureTimestamps.iterator();
459 // System.out.println("First to Last Packet:");
460 // while (iterFirst.hasNext() && iterLast.hasNext()) {
461 // Instant firstInst = (Instant) iterFirst.next();
462 // Instant lastInst = (Instant) iterLast.next();
463 // Duration dur = Duration.between(firstInst, lastInst);
464 // long duration = dur.toMillis();
465 // // Check duration --- should be below 15 seconds
466 // if (duration >= 0 && duration <= 15000) {
467 // System.out.println(dur.toMillis());
468 // } else if (duration > 15000) {
469 // while (duration > 15000) { // that means we have to move to the next trigger
470 // firstInst = (Instant) iterFirst.next();
471 // dur = Duration.between(firstInst, lastInst);
472 // duration = dur.toMillis();
474 // System.out.println(dur.toMillis());
475 // } else { // below 0 / negative --- that means we have to move to the next signature
476 // while (duration < 0) { // that means we have to move to the next trigger
477 // lastInst = (Instant) iterLast.next();
478 // dur = Duration.between(firstInst, lastInst);
479 // duration = dur.toMillis();
481 // System.out.println(dur.toMillis());
483 // if (duration > 8000) {
488 // TODO: The above part is just for 15-second time sensitivity experiment
489 // TODO: The above part is just for 15-second time sensitivity experiment
490 // TODO: The above part is just for 15-second time sensitivity experiment
495 TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
496 List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
497 // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
498 List<UserAction> userActions = new ArrayList<>();
499 for (int i = 0; i < triggerTimes.size(); i++) {
500 userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
502 TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
503 final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
504 DnsMap dnsMap = new DnsMap();
505 TcpReassembler tcpReassembler = new TcpReassembler();
506 TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
507 tte.performExtraction(pkt -> {
510 } catch (NotOpenException e) {
513 }, dnsMap, tcpReassembler, trafficLabeler);
517 if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
518 // Sanity/debug check
519 throw new AssertionError(String.format("mismatch between packet count in %s and %s",
520 TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
523 // Extract all conversations present in the filtered trace.
524 List<Conversation> allConversations = tcpReassembler.getTcpConversations();
525 // Group conversations by hostname.
526 Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
527 System.out.println("Grouped conversations by hostname.");
528 // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
529 final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
530 convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
531 System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
532 // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
533 // sequence of packets of some specific lengths).
534 final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
535 convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
536 System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
537 // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
538 final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
539 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
540 System.out.println("Counted frequencies of packet pairs per hostname");
541 // For each user action, reassemble the set of TCP connections occurring shortly after
542 final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
543 final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
544 System.out.println("Reassembled TCP conversations occurring shortly after each user event");
549 * NOTE: no need to generate these more complex on/off maps that also contain mappings from hostname and
550 * sequence identifiers as we do not care about hostnames and sequences during clustering.
551 * We can simply use the UserAction->List<Conversation> map to generate ON/OFF groupings of conversations.
554 // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
555 Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
556 // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
557 Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
558 userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
559 Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
560 hostnameToConvs.forEach((host, convs) -> {
561 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
562 groupConversationsByPacketSequence(convs, verbose);
563 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
564 newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
573 // System.out.println("==== ON ====");
574 // // Print out all the pairs into a file for ON events
575 // File fileOnEvents = new File(onPairsPath);
576 // PrintWriter pwOn = null;
578 // pwOn = new PrintWriter(fileOnEvents);
579 // } catch(Exception ex) {
580 // ex.printStackTrace();
582 // for(Map.Entry<String, Map<String, List<Conversation>>> entry : ons.entrySet()) {
583 // Map<String, List<Conversation>> seqsToConvs = entry.getValue();
584 // for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
585 // List<Conversation> listConv = entryConv.getValue();
586 // // Just get the first Conversation because all Conversations in this group
587 // // should have the same pairs of Application Data.
588 // for(Conversation conv : listConv) {
589 // // Process only if it is a TLS packet
590 // if (conv.isTls()) {
591 // List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
592 // for(PcapPacketPair pair: tlsAppDataList) {
593 // System.out.println(PrintUtils.toCsv(pair, dnsMap));
594 // pwOn.println(PrintUtils.toCsv(pair, dnsMap));
596 // } else { // Non-TLS conversations
597 // List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
598 // for(PcapPacketPair pair: packetList) {
599 // System.out.println(PrintUtils.toCsv(pair, dnsMap));
600 // pwOn.println(PrintUtils.toCsv(pair, dnsMap));
608 // System.out.println("==== OFF ====");
609 // // Print out all the pairs into a file for ON events
610 // File fileOffEvents = new File(offPairsPath);
611 // PrintWriter pwOff = null;
613 // pwOff = new PrintWriter(fileOffEvents);
614 // } catch(Exception ex) {
615 // ex.printStackTrace();
617 // for(Map.Entry<String, Map<String, List<Conversation>>> entry : offs.entrySet()) {
618 // Map<String, List<Conversation>> seqsToConvs = entry.getValue();
619 // for(Map.Entry<String, List<Conversation>> entryConv : seqsToConvs.entrySet()) {
620 // List<Conversation> listConv = entryConv.getValue();
621 // // Just get the first Conversation because all Conversations in this group
622 // // should have the same pairs of Application Data.
623 // for(Conversation conv : listConv) {
624 // // Process only if it is a TLS packet
625 // if (conv.isTls()) {
626 // List<PcapPacketPair> tlsAppDataList = TcpConversationUtils.extractTlsAppDataPacketPairs(conv);
627 // for(PcapPacketPair pair: tlsAppDataList) {
628 // System.out.println(PrintUtils.toCsv(pair, dnsMap));
629 // pwOff.println(PrintUtils.toCsv(pair, dnsMap));
631 // } else { // Non-TLS conversations
632 // List<PcapPacketPair> packetList = TcpConversationUtils.extractPacketPairs(conv);
633 // for (PcapPacketPair pair : packetList) {
634 // System.out.println(PrintUtils.toCsv(pair, dnsMap));
635 // pwOff.println(PrintUtils.toCsv(pair, dnsMap));
644 // ================================================ CLUSTERING ================================================
645 // Note: no need to use the more convoluted on/off maps; can simply use the UserAction->List<Conversation> map
646 // when don't care about hostnames and sequences (see comment earlier).
647 List<Conversation> onConversations = userActionToConversations.entrySet().stream().
648 filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
649 map(e -> e.getValue()). // no longer interested in the UserActions
650 flatMap(List::stream). // flatten List<List<T>> to a List<T>
651 collect(Collectors.toList());
652 List<Conversation> offConversations = userActionToConversations.entrySet().stream().
653 filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
654 map(e -> e.getValue()).
655 flatMap(List::stream).
656 collect(Collectors.toList());
657 //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
659 List<PcapPacketPair> onPairs = onConversations.stream().
660 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
661 TcpConversationUtils.extractPacketPairs(c)).
662 flatMap(List::stream). // flatten List<List<>> to List<>
663 collect(Collectors.toList());
664 List<PcapPacketPair> offPairs = offConversations.stream().
665 map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
666 TcpConversationUtils.extractPacketPairs(c)).
667 flatMap(List::stream). // flatten List<List<>> to List<>
668 collect(Collectors.toList());
669 // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
670 Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
671 // Perform clustering on conversation logged as part of all ON events.
672 DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 45);
673 // DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(2, 2);
674 //DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(10.0, 10);
675 List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
676 // Perform clustering on conversation logged as part of all OFF events.
677 DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 45);
678 // DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10, 2);
679 //DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(10.0, 10);
680 List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
681 // Sort the conversations as reference
682 List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
684 System.out.println("========================================");
685 System.out.println(" Clustering results for ON ");
686 System.out.println(" Number of clusters: " + onClusters.size());
688 List<List<List<PcapPacket>>> ppListOfListReadOn = new ArrayList<>();
689 List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
690 for (Cluster<PcapPacketPair> c : onClusters) {
691 System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
692 System.out.print(PrintUtils.toSummaryString(c));
693 if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
694 //if(c.getPoints().size() > 25) {
696 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
697 //TODO: DO EPSILON ANALYSIS HERE!!!
699 ppListOfListListOn.add(ppListOfList);
702 // TODO: Merging test
703 ppListOfListListOn = PcapPacketUtils.mergeSignatures(ppListOfListListOn, sortedAllConversation);
704 // TODO: Need to remove sequence 550 567 for Blossom phone side since it is not a good signature (overlap)!
705 // PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 1);
706 // TODO: Need to remove sequence 69 296 for Blossom device side since it is not a good signature (overlap)!
707 // PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 2);
708 // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
709 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 2);
710 // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
711 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
712 // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
713 // TODO: This sequence actually belongs to the local communication between the plug and the phone
714 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOn, 0);
715 ppListOfListListOn = PcapPacketUtils.sortSignatures(ppListOfListListOn);
716 PcapPacketUtils.printSignatures(ppListOfListListOn);
718 System.out.println("========================================");
719 System.out.println(" Clustering results for OFF ");
720 System.out.println(" Number of clusters: " + offClusters.size());
722 List<List<List<PcapPacket>>> ppListOfListReadOff = new ArrayList<>();
723 List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
724 for (Cluster<PcapPacketPair> c : offClusters) {
725 System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
726 System.out.print(PrintUtils.toSummaryString(c));
727 if(c.getPoints().size() > 45 && c.getPoints().size() < 55) {
728 //if(c.getPoints().size() > 25) {
730 List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
731 //TODO: DO EPSILON ANALYSIS HERE!!!
733 ppListOfListListOff.add(ppListOfList);
736 // TODO: Merging test
737 ppListOfListListOff = PcapPacketUtils.mergeSignatures(ppListOfListListOff, sortedAllConversation);
738 // TODO: Need to remove sequence 69 296 for Blossom device side since it is not a good signature (overlap)!
739 // PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 3);
740 // TODO: Need to remove sequence number 1 for Nest Thermostat since it is not a good signature!
741 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
742 // TODO: Need to remove sequence number 0 for Arlo Camera since it is not a good signature!
743 // PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 1);
744 // TODO: Need to remove sequence number 2 for ST plug since it is not a good signature!
745 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 2);
746 // TODO: Need to remove sequence number 0 for TP-Link plug since it is not a good signature!
747 // TODO: This sequence actually belongs to the local communication between the plug and the phone
748 //PcapPacketUtils.removeSequenceFromSignature(ppListOfListListOff, 0);
749 ppListOfListListOff = PcapPacketUtils.sortSignatures(ppListOfListListOff);
750 PcapPacketUtils.printSignatures(ppListOfListListOff);
753 // Printing signatures into files
754 PrintUtils.serializeSignatureIntoFile("./onSignature.sig", ppListOfListListOn);
755 ppListOfListReadOn = PrintUtils.deserializeSignatureFromFile("./onSignature.sig");
756 PrintUtils.serializeSignatureIntoFile("./offSignature.sig", ppListOfListListOff);
757 ppListOfListReadOff = PrintUtils.deserializeSignatureFromFile("./offSignature.sig");
758 System.out.println("========================================");
759 // ============================================================================================================
761 // // TODO: This part is just for DBSCAN sensitivity experiment
762 // // TODO: This part is just for DBSCAN sensitivity experiment
763 // // TODO: This part is just for DBSCAN sensitivity experiment
764 // // TODO: This part is just for DBSCAN sensitivity experiment
765 // // TODO: This part is just for DBSCAN sensitivity experiment
766 // List<Conversation> onConversations = userActionToConversations.entrySet().stream().
767 // filter(e -> e.getKey().getType() == Type.TOGGLE_ON). // drop all OFF events from stream
768 // map(e -> e.getValue()). // no longer interested in the UserActions
769 // flatMap(List::stream). // flatten List<List<T>> to a List<T>
770 // collect(Collectors.toList());
771 // List<Conversation> offConversations = userActionToConversations.entrySet().stream().
772 // filter(e -> e.getKey().getType() == Type.TOGGLE_OFF).
773 // map(e -> e.getValue()).
774 // flatMap(List::stream).
775 // collect(Collectors.toList());
776 // //Collections.sort(onConversations, (c1, c2) -> c1.getPackets().)
778 // List<PcapPacketPair> onPairs = onConversations.stream().
779 // map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
780 // TcpConversationUtils.extractPacketPairs(c)).
781 // flatMap(List::stream). // flatten List<List<>> to List<>
782 // collect(Collectors.toList());
783 // List<PcapPacketPair> offPairs = offConversations.stream().
784 // map(c -> c.isTls() ? TcpConversationUtils.extractTlsAppDataPacketPairs(c) :
785 // TcpConversationUtils.extractPacketPairs(c)).
786 // flatMap(List::stream). // flatten List<List<>> to List<>
787 // collect(Collectors.toList());
788 // // Note: need to update the DnsMap of all PcapPacketPairs if we want to use the IP/hostname-sensitive distance.
789 // Stream.concat(Stream.of(onPairs), Stream.of(offPairs)).flatMap(List::stream).forEach(p -> p.setDnsMap(dnsMap));
791 // double eps = 10; // loop from eps 1-10
792 // int minPts = 50; // loop from minPts 30-50
793 // for(int epsCount = 7; epsCount <= eps; epsCount++) {
794 // for(int minPtsCount = 30; minPtsCount <= minPts; minPtsCount++) {
795 // System.out.println("Eps: " + epsCount + " --- minPts: " + minPtsCount);
796 // DBSCANClusterer<PcapPacketPair> onClusterer = new DBSCANClusterer<>(epsCount, minPtsCount);
797 // DBSCANClusterer<PcapPacketPair> offClusterer = new DBSCANClusterer<>(epsCount, minPtsCount);
798 // List<Cluster<PcapPacketPair>> onClusters = onClusterer.cluster(onPairs);
799 // List<Cluster<PcapPacketPair>> offClusters = offClusterer.cluster(offPairs);
800 // // Sort the conversations as reference
801 // List<Conversation> sortedAllConversation = TcpConversationUtils.sortConversationList(allConversations);
802 // // Output clusters
803 // System.out.println("========================================");
804 // System.out.println(" Clustering results for ON ");
805 // System.out.println(" Number of clusters: " + onClusters.size());
807 // List<List<List<PcapPacket>>> ppListOfListListOn = new ArrayList<>();
808 // for (Cluster<PcapPacketPair> c : onClusters) {
809 // System.out.println(String.format("<<< Cluster #%02d (%03d points) >>>", ++count, c.getPoints().size()));
810 //// System.out.print(PrintUtils.toSummaryString(c));
811 // if (c.getPoints().size() > 45 && c.getPoints().size() < 55) {
812 //// if(c.getPoints().size() > 25) {
814 // List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
815 // ppListOfListListOn.add(ppListOfList);
818 // PcapPacketUtils.printSignatures(ppListOfListListOn);
820 // System.out.println("========================================");
821 // System.out.println(" Clustering results for OFF ");
822 // System.out.println(" Number of clusters: " + offClusters.size());
824 // List<List<List<PcapPacket>>> ppListOfListListOff = new ArrayList<>();
825 // for (Cluster<PcapPacketPair> c : offClusters) {
826 // System.out.println(String.format("<<< Cluster #%03d (%06d points) >>>", ++count, c.getPoints().size()));
827 //// System.out.print(PrintUtils.toSummaryString(c));
828 // if (c.getPoints().size() > 45 && c.getPoints().size() < 55) {
829 // //if(c.getPoints().size() > 25) {
831 // List<List<PcapPacket>> ppListOfList = PcapPacketUtils.clusterToListOfPcapPackets(c);
832 // ppListOfListListOff.add(ppListOfList);
835 // PcapPacketUtils.printSignatures(ppListOfListListOff);
836 // System.out.println();
837 // System.out.println();
838 // System.out.println();
839 // // ============================================================================================================
844 // // ================================================================================================
845 // // <<< Some work-in-progress/explorative code that extracts a "representative" sequence >>>
847 // // Currently need to know relevant hostname in advance :(
848 // String hostname = "events.tplinkra.com";
849 //// String hostname = "rfe-us-west-1.dch.dlink.com";
850 // // Conversations with 'hostname' for ON events.
851 // List<Conversation> onsForHostname = new ArrayList<>();
852 // // Conversations with 'hostname' for OFF events.
853 // List<Conversation> offsForHostname = new ArrayList<>();
854 // // "Unwrap" sequence groupings in ons/offs maps.
855 // ons.get(hostname).forEach((k,v) -> onsForHostname.addAll(v));
856 // offs.get(hostname).forEach((k,v) -> offsForHostname.addAll(v));
859 // Map<String, List<Conversation>> onsForHostnameGroupedByTlsAppDataSequence = TcpConversationUtils.groupConversationsByTlsApplicationDataPacketSequence(onsForHostname);
862 // // Extract representative sequence for ON and OFF by providing the list of conversations with
863 // // 'hostname' observed for each event type (the training data).
864 // SequenceExtraction seqExtraction = new SequenceExtraction();
865 //// ExtractedSequence extractedSequenceForOn = seqExtraction.extract(onsForHostname);
866 //// ExtractedSequence extractedSequenceForOff = seqExtraction.extract(offsForHostname);
868 // ExtractedSequence extractedSequenceForOn = seqExtraction.extractByTlsAppData(onsForHostname);
869 // ExtractedSequence extractedSequenceForOff = seqExtraction.extractByTlsAppData(offsForHostname);
871 // // Let's check how many ONs align with OFFs and vice versa (that is, how many times an event is incorrectly
873 // int onsLabeledAsOff = 0;
874 // Integer[] representativeOnSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOn.getRepresentativeSequence());
875 // Integer[] representativeOffSeq = TcpConversationUtils.getPacketLengthSequence(extractedSequenceForOff.getRepresentativeSequence());
876 // SequenceAlignment<Integer> seqAlg = seqExtraction.getAlignmentAlgorithm();
877 // for (Conversation c : onsForHostname) {
878 // Integer[] onSeq = TcpConversationUtils.getPacketLengthSequence(c);
879 // if (seqAlg.calculateAlignment(representativeOffSeq, onSeq) <= extractedSequenceForOff.getMaxAlignmentCost()) {
880 // onsLabeledAsOff++;
883 // int offsLabeledAsOn = 0;
884 // for (Conversation c : offsForHostname) {
885 // Integer[] offSeq = TcpConversationUtils.getPacketLengthSequence(c);
886 // if (seqAlg.calculateAlignment(representativeOnSeq, offSeq) <= extractedSequenceForOn.getMaxAlignmentCost()) {
887 // offsLabeledAsOn++;
890 // System.out.println("");
891 // // ================================================================================================
894 // // -------------------------------------------------------------------------------------------------------------
895 // // -------------------------------------------------------------------------------------------------------------
899 * Check if there is any overlap between the signature stored in this class and another signature.
901 * 1) If both signatures do not have any range, then we need to do conservative checking (return true).
902 * 2) If both signatures have the same number of packets/packet lengths, then we check the range; if the
903 * numbers of packets/packet lengths are different then we assume that there is no overlap.
904 * 3) If there is any range in the signatures, then we need to check for overlap.
905 * 4) If there is overlap for every packet/packet length, then we return false (range-based checking); otherwise,
906 * true (conservative checking).
908 * @param otherSignature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
909 * for overlaps with the signature stored in this class.
910 * @return A boolean that is true if there is an overlap; false otherwise.
912 // public boolean isConservativeChecking(List<List<List<PcapPacket>>> otherSignature) {
914 // // Get the ranges of the two signatures
915 // List<List<List<PcapPacket>>> signatureRanges = getSequenceRanges(mSignature);
916 // List<List<List<PcapPacket>>> otherSignatureRanges = getSequenceRanges(otherSignature);
917 // if (!isRangeBased(signatureRanges) && !isRangeBased(otherSignatureRanges)) {
918 // // Conservative checking when there is no range
920 // } else if(signatureRanges.size() != otherSignatureRanges.size()) {
921 // // The two signatures have different numbers of packets/packet lengths
924 // // There is range; check if there is overlap
925 // return checkOverlap(signatureRanges, otherSignatureRanges);
930 * Check for overlap since we have range in at least one of the signatures.
931 * Overlap is only true when all ranges overlap. We need to check in order.
933 // private boolean checkOverlap(List<List<List<PcapPacket>>> signatureRanges,
934 // List<List<List<PcapPacket>>> otherSignatureRanges) {
936 // for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
937 // // Lower bound of the range is in index 0
938 // // Upper bound of the range is in index 1
939 // int sequenceSetIndex = signatureRanges.indexOf(listListPcapPacket);
940 // List<PcapPacket> minSequenceSignature = listListPcapPacket.get(0);
941 // List<PcapPacket> maxSequenceSignature = listListPcapPacket.get(1);
942 // for(PcapPacket pcapPacket : minSequenceSignature) {
943 // // Get the lower and upper bounds of the current signature
944 // int packetIndex = minSequenceSignature.indexOf(pcapPacket);
945 // int lowerBound = pcapPacket.length();
946 // int upperBound = maxSequenceSignature.get(packetIndex).length();
947 // // Check for range overlap in the other signature!
948 // // Check the packet/packet length at the same position
949 // List<PcapPacket> minSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(0);
950 // List<PcapPacket> maxSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(1);
951 // int lowerBoundOther = minSequenceSignatureOther.get(packetIndex).length();
952 // int upperBoundOther = maxSequenceSignatureOther.get(packetIndex).length();
953 // if (!(lowerBoundOther <= lowerBound && lowerBound <= upperBoundOther) &&
954 // !(lowerBoundOther <= upperBound && upperBound <= upperBoundOther)) {
964 // * Check and see if there is any range in the signatures
966 // private boolean isRangeBased(List<List<List<PcapPacket>>> signatureRanges) {
968 // for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
969 // // Lower bound of the range is in index 0
970 // // Upper bound of the range is in index 1
971 // List<PcapPacket> minSequence = listListPcapPacket.get(0);
972 // List<PcapPacket> maxSequence = listListPcapPacket.get(1);
973 // for(PcapPacket pcapPacket : minSequence) {
974 // int index = minSequence.indexOf(pcapPacket);
975 // if (pcapPacket.length() != maxSequence.get(index).length()) {
976 // // If there is any packet length that differs in the minSequence
977 // // and maxSequence, then it is range-based
986 // /* Find the sequence with the minimum packet lengths.
987 // * The second-layer list should contain the minimum sequence for element 0 and maximum sequence for element 1.
989 // private List<List<List<PcapPacket>>> getSequenceRanges(List<List<List<PcapPacket>>> signature) {
991 // // Start from the first index
992 // List<List<List<PcapPacket>>> rangeBasedSequence = new ArrayList<>();
993 // for (List<List<PcapPacket>> listListPcapPacket : signature) {
994 // List<List<PcapPacket>> minMaxSequence = new ArrayList<>();
995 // // Both searches start from index 0
996 // List<PcapPacket> minSequence = new ArrayList<>(listListPcapPacket.get(0));
997 // List<PcapPacket> maxSequence = new ArrayList<>(listListPcapPacket.get(0));
998 // for (List<PcapPacket> listPcapPacket : listListPcapPacket) {
999 // for (PcapPacket pcapPacket : listPcapPacket) {
1000 // int index = listPcapPacket.indexOf(pcapPacket);
1001 // // Set the new minimum if length at the index is minimum
1002 // if (pcapPacket.length() < minSequence.get(index).length()) {
1003 // minSequence.set(index, pcapPacket);
1005 // // Set the new maximum if length at the index is maximum
1006 // if (pcapPacket.length() > maxSequence.get(index).length()) {
1007 // maxSequence.set(index, pcapPacket);
1011 // // minSequence as element 0 and maxSequence as element 1
1012 // minMaxSequence.add(minSequence);
1013 // minMaxSequence.add(maxSequence);
1014 // rangeBasedSequence.add(minMaxSequence);
1017 // return rangeBasedSequence;
1022 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
1023 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159