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