f67a8326d87b12c8be16b3566ba8b41efbdc6144
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / SignatureDetector.java
1 package edu.uci.iotproject.detection;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.analysis.UserAction;
5 import edu.uci.iotproject.io.PcapHandleReader;
6 import edu.uci.iotproject.util.PrintUtils;
7 import org.jgrapht.GraphPath;
8 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
9 import org.jgrapht.graph.DefaultWeightedEdge;
10 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
11 import org.pcap4j.core.*;
12
13 import java.time.Duration;
14 import java.time.Instant;
15 import java.time.ZoneId;
16 import java.time.format.DateTimeFormatter;
17 import java.time.format.FormatStyle;
18 import java.util.*;
19 import java.util.function.Consumer;
20
21 /**
22  * Detects an event signature that spans one or multiple TCP connections.
23  *
24  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
25  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
26  */
27 public class SignatureDetector implements PacketListener, ClusterMatcher.ClusterMatchObserver {
28
29     // Test client
30     public static void main(String[] args) throws PcapNativeException, NotOpenException {
31         String path = "/scratch/July-2018"; // Rahmadi
32         //String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
33
34         // No activity test
35         //final String inputPcapFile = path + "/evaluation/no-activity/no-activity.wlan1.pcap";
36
37         // D-Link Siren experiment
38 //        final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.data.wlan1.pcap";
39 //        final String inputPcapFile = path + "/evaluation/dlink-siren/dlink-siren.eth0.local.pcap";
40         // D-Link Siren DEVICE signatures
41 //        final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-device.sig";
42 //        final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-device.sig";
43         // D-Link Siren PHONE signatures
44 //        final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-phone.sig";
45 //        final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-phone.sig";
46
47         // Kwikset Doorlock Sep 12 experiment
48 //        final String inputPcapFile = path + "/evaluation/kwikset-doorlock/kwikset-doorlock.data.wlan1.pcap";
49 //        //final String inputPcapFile = path + "/evaluation/kwikset-doorlock/kwikset-doorlock.data.eth0.pcap";
50 ////        // Kwikset Doorlock PHONE signatures
51 //        final String onSignatureFile = path + "/2018-08/kwikset-doorlock/onSignature-Kwikset-Doorlock-phone-new.sig";
52 //        final String offSignatureFile = path + "/2018-08/kwikset-doorlock/offSignature-Kwikset-Doorlock-phone-new.sig";
53
54         // D-Link Plug experiment
55         //final String inputPcapFile = path + "/evaluation/dlink/dlink-plug.data.wlan1.pcap";
56 //        final String inputPcapFile = path + "/evaluation/dlink/dlink-plug.data.eth0.pcap";
57
58         // D-Link Plug DEVICE signatures
59 //        final String onSignatureFile = path + "/2018-07/dlink/onSignature-DLink-Plug-device.sig";
60 //        final String offSignatureFile = path + "/2018-07/dlink/offSignature-DLink-Plug-device.sig";
61         // D-Link Plug PHONE signatures
62 //        final String onSignatureFile = path + "/2018-07/dlink/onSignature-DLink-Plug-phone.sig";
63 //        final String offSignatureFile = path + "/2018-07/dlink/offSignature-DLink-Plug-phone.sig";
64
65
66         // TODO: The following are tests for signatures against training data
67         /*
68         // D-Link Plug experiment
69         final String inputPcapFile = path + "/training/dlink-plug/wlan1/dlink-plug.wlan1.local.pcap";
70         // D-Link Plug DEVICE signatures
71         final String onSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-onSignature-device-side.sig";
72         final String offSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-offSignature-device-side.sig";
73         // D-Link Plug PHONE signatures
74         //final String onSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-onSignature-phone-side.sig";
75         //final String offSignatureFile = path + "/training/dlink-plug/signatures/dlink-plug-offSignature-phone-side.sig";
76         */
77
78         /*
79         // TP-Link Plug experiment
80         final String inputPcapFile = path + "/training/tplink-plug/wlan1/tplink-plug.wlan1.local.pcap";
81         // TP-Link Plug DEVICE signatures
82         //final String onSignatureFile = path + "/training/tplink-plug/signatures/tplink-plug-onSignature-device-side.sig";
83         //final String offSignatureFile = path + "/training/tplink-plug/signatures/tplink-plug-offSignature-device-side.sig";
84         */
85
86         // Arlo camera experiment
87 //        final String inputPcapFile = path + "/training/arlo-camera/wlan1/arlo-camera.wlan1.local.pcap";
88 //        // TP-Link Plug DEVICE signatures
89 //        final String onSignatureFile = path + "/training/arlo-camera/signatures/arlo-camera-onSignature-phone-side.sig";
90 //        final String offSignatureFile = path + "/training/arlo-camera/signatures/arlo-camera-offSignature-phone-side.sig";
91
92         // Amazon Alexa experiment
93         final String inputPcapFile = path + "/training/amazon-alexa/wlan1/alexa2.wlan1.local.pcap";
94         // TP-Link Plug DEVICE signatures
95         final String onSignatureFile = path + "/training/amazon-alexa/signatures/amazon-alexa-onSignature-device-side.sig";
96         final String offSignatureFile = path + "/training/amazon-alexa/signatures/amazon-alexa-offSignature-device-side.sig";
97
98         // SmartThings Plug experiment
99 //        final String inputPcapFile = path + "/training/st-plug/wlan1/st-plug.wlan1.local.pcap";
100         // TP-Link Plug DEVICE signatures
101         //final String onSignatureFile = path + "/training/st-plug/signatures/st-plug-onSignature-device-side.sig";
102         //final String offSignatureFile = path + "/training/st-plug/signatures/st-plug-offSignature-device-side.sig";
103         // TP-Link Plug PHONE signatures
104 //        final String onSignatureFile = path + "/training/st-plug/signatures/st-plug-onSignature-phone-side.sig";
105 //        final String offSignatureFile = path + "/training/st-plug/signatures/st-plug-offSignature-phone-side.sig";
106
107
108         /*
109         // Kwikset Doorlock Sep 12 experiment
110         final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset3.wlan1.local.pcap";
111         // Kwikset Doorlock PHONE signatures
112         final String onSignatureFile = path + "/2018-08/kwikset-doorlock/onSignature-Kwikset-Doorlock-phone.sig";
113         final String offSignatureFile = path + "/2018-08/kwikset-doorlock/offSignature-Kwikset-Doorlock-phone.sig";
114         */
115
116         /*
117         // D-Link Siren experiment
118         final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
119         // D-Link Siren DEVICE signatures
120         //final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-device.sig";
121         //final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-device.sig";
122         // D-Link Siren PHONE signatures
123         final String onSignatureFile = path + "/2018-08/dlink-siren/onSignature-DLink-Siren-phone.sig";
124         final String offSignatureFile = path + "/2018-08/dlink-siren/offSignature-DLink-Siren-phone.sig";
125         */
126
127         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
128         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
129
130         // LAN
131 //        SignatureDetector onDetector = new SignatureDetector(onSignature, null);
132 //        SignatureDetector offDetector = new SignatureDetector(offSignature, null);
133         // WAN
134         SignatureDetector onDetector = new SignatureDetector(onSignature, "128.195.205.105");
135         SignatureDetector offDetector = new SignatureDetector(offSignature, "128.195.205.105");
136
137         final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
138                 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
139
140         // Outputs information about a detected event to std.out
141         final Consumer<UserAction> outputter = ua -> {
142             String eventDescription;
143             switch (ua.getType()) {
144                 case TOGGLE_ON:
145                     eventDescription = "ON";
146                     break;
147                 case TOGGLE_OFF:
148                     eventDescription = "OFF";
149                     break;
150                 default:
151                     throw new AssertionError("unhandled event type");
152             }
153             //String output = String.format("[ !!! %s SIGNATURE DETECTED at %s !!! ]",
154             //      eventDescription, dateTimeFormatter.format(ua.getTimestamp()));
155             String output = String.format("%s",
156                     dateTimeFormatter.format(ua.getTimestamp()));
157             System.out.println(output);
158         };
159
160         // Let's create observers that construct a UserAction representing the detected event.
161         final List<UserAction> detectedEvents = new ArrayList<>();
162         onDetector.addObserver((searched, match) -> {
163             PcapPacket firstPkt = match.get(0).get(0);
164             detectedEvents.add(new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp()));
165         });
166         offDetector.addObserver((searched, match) -> {
167             PcapPacket firstPkt = match.get(0).get(0);
168             detectedEvents.add(new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp()));
169         });
170
171         PcapHandle handle;
172         try {
173             handle = Pcaps.openOffline(inputPcapFile, PcapHandle.TimestampPrecision.NANO);
174         } catch (PcapNativeException pne) {
175             handle = Pcaps.openOffline(inputPcapFile);
176         }
177         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
178         reader.readFromHandle();
179
180         // TODO: need a better way of triggering detection than this...
181         onDetector.mClusterMatchers.forEach(cm -> cm.performDetection());
182         offDetector.mClusterMatchers.forEach(cm -> cm.performDetection());
183
184         // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
185         // times file.
186         Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
187
188
189         // Output the detected events
190         //detectedEvents.forEach(outputter);
191
192         // TODO: Temporary clean up until we clean the pipeline
193         List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
194         cleanedDetectedEvents.forEach(outputter);
195     }
196
197     /**
198      * The signature that this {@link SignatureDetector} is searching for.
199      */
200     private final List<List<List<PcapPacket>>> mSignature;
201
202     /**
203      * The {@link ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
204      * the signature.
205      */
206     private final List<ClusterMatcher> mClusterMatchers;
207
208     /**
209      * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
210      * found by the {@link ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
211      * have yet to be included in a signature detected by this {@link SignatureDetector} (a signature can be encompassed
212      * of multiple packet sequences occurring shortly after one another on multiple connections).
213      */
214     private final List<List<PcapPacket>>[] pendingMatches;
215
216     /**
217      * Maps a {@link ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
218      */
219     private final Map<ClusterMatcher, Integer> mClusterMatcherIds;
220
221     private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
222
223     /**
224      * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
225      * that appear multiple times.
226      * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
227      * TODO:    the pipeline
228      *
229      * @param listUserAction A {@link List} of {@code UserAction}.
230      *
231      */
232     public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
233
234         // Iterate and check for duplicates (check timestamps)
235         Set<Long> epochSecondSet = new HashSet<>();
236         // Create a target list for cleaned up list
237         List<UserAction> listUserActionClean = new ArrayList<>();
238         for(UserAction userAction : listUserAction) {
239             // Don't insert if any duplicate is found
240             if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
241                 listUserActionClean.add(userAction);
242                 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
243             }
244         }
245         return listUserActionClean;
246     }
247
248     public SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp) {
249         // note: doesn't protect inner lists from changes :'(
250         mSignature = Collections.unmodifiableList(searchedSignature);
251         // Generate corresponding/appropriate ClusterMatchers based on the provided signature
252         List<ClusterMatcher> clusterMatchers = new ArrayList<>();
253         for (List<List<PcapPacket>> cluster : mSignature) {
254             clusterMatchers.add(new ClusterMatcher(cluster, routerWanIp, this));
255         }
256         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
257
258         // < exploratory >
259         pendingMatches = new List[mClusterMatchers.size()];
260         for (int i = 0; i < pendingMatches.length; i++) {
261             pendingMatches[i] = new ArrayList<>();
262         }
263         Map<ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
264         for (int i = 0; i < mClusterMatchers.size(); i++) {
265             clusterMatcherIds.put(mClusterMatchers.get(i), i);
266         }
267         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
268     }
269
270     public void addObserver(SignatureDetectionObserver observer) {
271         mObservers.add(observer);
272     }
273
274     public boolean removeObserver(SignatureDetectionObserver observer) {
275         return mObservers.remove(observer);
276     }
277
278     @Override
279     public void gotPacket(PcapPacket packet) {
280         // simply delegate packet reception to all ClusterMatchers.
281         mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
282     }
283
284     @Override
285     public void onMatch(ClusterMatcher clusterMatcher, List<PcapPacket> match) {
286         // Add the match at the corresponding index
287         pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
288         checkSignatureMatch();
289     }
290
291     private void checkSignatureMatch() {
292         // << Graph-based approach using Balint's idea. >>
293         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
294
295         // There cannot be a signature match until each ClusterMatcher has found a match of its respective sequence.
296         if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
297             // Construct the DAG
298             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
299                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
300             // Add a vertex for each match found by all ClusterMatchers
301             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
302             final List<Vertex>[] vertices = new List[pendingMatches.length];
303             for (int i = 0; i < pendingMatches.length; i++) {
304                 vertices[i] = new ArrayList<>();
305                 for (List<PcapPacket> sequence : pendingMatches[i]) {
306                     Vertex v = new Vertex(sequence);
307                     vertices[i].add(v); // retain reference for later when we are to add edges
308                     graph.addVertex(v); // add to vertex to graph
309                 }
310             }
311             // Add dummy source and sink vertices to facilitate search.
312             final Vertex source = new Vertex(null);
313             final Vertex sink = new Vertex(null);
314             graph.addVertex(source);
315             graph.addVertex(sink);
316             // The source is connected to all vertices that wrap the sequences detected by ClusterMatcher at index 0.
317             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
318             for (Vertex v : vertices[0]) {
319                 DefaultWeightedEdge edge = graph.addEdge(source, v);
320                 graph.setEdgeWeight(edge, 0.0);
321             }
322             // Similarly, all vertices that wrap the sequences detected by the last ClusterMatcher of the signature
323             // are connected to the sink node.
324             for (Vertex v : vertices[vertices.length-1]) {
325                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
326                 graph.setEdgeWeight(edge, 0.0);
327             }
328             // Now link sequences detected by ClusterMatcher at index i to sequences detected by ClusterMatcher at index
329             // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
330             for (int i = 0; i < vertices.length; i++) {
331                 int j = i + 1;
332                 if (j < vertices.length) {
333                     for (Vertex iv : vertices[i]) {
334                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
335                         for (Vertex jv : vertices[j]) {
336                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
337                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
338                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
339                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
340                                 // and i+1'th sequence.
341                                 Duration d = Duration.
342                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
343                                 // Unfortunately weights are double values, so must convert from long to double.
344                                 // TODO: need nano second precision? If so, use d.toNanos().
345                                 // TODO: risk of overflow when converting from long to double..?
346                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
347                             }
348                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
349 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
350 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
351 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
352 //
353 //                            }
354                         }
355                     }
356                 }
357             }
358             // Graph construction complete, run shortest-path to find a (potential) signature match.
359             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
360             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
361             if (shortestPath != null) {
362                 // The total weight is the duration between the first packet of the first sequence and the last packet
363                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
364                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
365                 // Note however, that we must convert back from double to long as the weight is stored as a double in
366                 // JGraphT's API.
367                 if (((long)shortestPath.getWeight()) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
368                     // There's a signature match!
369                     // Extract the match from the vertices
370                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
371                     for(Vertex v : shortestPath.getVertexList()) {
372                         if (v == source || v == sink) {
373                             // Skip the dummy source and sink nodes.
374                             continue;
375                         }
376                         signatureMatch.add(v.sequence);
377                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
378                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
379                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
380                         // another signature match in a later call.
381                         pendingMatches[signatureMatch.size()-1].remove(v.sequence);
382                     }
383                     // Declare success: notify observers
384                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
385                             Collections.unmodifiableList(signatureMatch)));
386                 }
387             }
388         }
389     }
390
391     /**
392      * Used for registering for notifications of signatures detected by a {@link SignatureDetector}.
393      */
394     interface SignatureDetectionObserver {
395
396         /**
397          * Invoked when the {@link SignatureDetector} detects the presence of a signature in the traffic that it's
398          * examining.
399          * @param searchedSignature The signature that the {@link SignatureDetector} reporting the match is searching
400          *                          for.
401          * @param matchingTraffic The actual traffic trace that matches the searched signature.
402          */
403         void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
404                                  List<List<PcapPacket>> matchingTraffic);
405     }
406
407     /**
408      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
409      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
410      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
411      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
412      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
413      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
414      * appropriate.
415      */
416     private static class Vertex {
417         private final List<PcapPacket> sequence;
418         private Vertex(List<PcapPacket> wrappedSequence) {
419             sequence = wrappedSequence;
420         }
421     }
422 }