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