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