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