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