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