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