cc3a128329a824f94f6fb105b6b79cc49059378f
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2SignatureDetector.java
1 package edu.uci.iotproject.detection.layer2;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.analysis.UserAction;
5 import edu.uci.iotproject.detection.AbstractClusterMatcher;
6 import edu.uci.iotproject.detection.ClusterMatcherObserver;
7 import edu.uci.iotproject.detection.SignatureDetectorObserver;
8 import edu.uci.iotproject.io.PcapHandleReader;
9 import edu.uci.iotproject.io.PrintWriterUtils;
10 import edu.uci.iotproject.trafficreassembly.layer2.Layer2Flow;
11 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassembler;
12 import edu.uci.iotproject.util.PcapPacketUtils;
13 import edu.uci.iotproject.util.PrintUtils;
14 import org.jgrapht.GraphPath;
15 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
16 import org.jgrapht.graph.DefaultWeightedEdge;
17 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
18 import org.pcap4j.core.*;
19
20 import java.io.File;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.time.Duration;
25 import java.util.*;
26 import java.util.function.Function;
27 import java.util.regex.Pattern;
28
29 /**
30  * Performs layer 2 signature detection.
31  *
32  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
33  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
34  */
35 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
36
37     /**
38      * If set to {@code true}, output written to the results file is also dumped to standard out.
39      */
40     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
41
42     /**
43      * Router's MAC.
44      * This is only useful for the filter for direction when it is a WAN signature (Phone-Cloud or Device-Cloud).
45      * Phone-Device signatures do not have router MAC address in it.
46      */
47     // TODO: MAKE THESE INPUT PARAMETERS
48     private static String TRAINING_ROUTER_WLAN_MAC = "b0:b9:8a:73:69:8e";
49     private static String ROUTER_WLAN_MAC = "00:c1:b1:14:eb:31";
50     //private static String TRAINING_ROUTER_WLAN_MAC = null;
51     //private static String ROUTER_WLAN_MAC = null;
52
53     private static List<Function<Layer2Flow, Boolean>> parseSignatureMacFilters(String filtersString) {
54         List<Function<Layer2Flow, Boolean>> filters = new ArrayList<>();
55         String[] filterRegexes = filtersString.split(";");
56         for (String filterRegex : filterRegexes) {
57             final Pattern regex = Pattern.compile(filterRegex);
58             // Create a filter that includes all flows where one of the two MAC addresses match the regex.
59             filters.add(flow -> regex.matcher(flow.getEndpoint1().toString()).matches() || regex.matcher(flow.getEndpoint2().toString()).matches());
60         }
61         return filters;
62     }
63
64     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
65         // Parse required parameters.
66         if (args.length < 10) {
67             String errMsg = String.format("SPECTO version 1.0\n" +
68                             "Copyright (C) 2018-2019 Janus Varmarken and Rahmadi Trimananda.\n" +
69                             "University of California, Irvine.\n" +
70                             "All rights reserved.\n\n" +
71                             "Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile " +
72                             "resultsFile signatureDuration eps onMaxSkippedPackets offMaxSkippedPackets" +
73                             "\n  inputPcapFile: the target of the detection" +
74                             "\n  onAnalysisFile: the file that contains the ON clusters analysis" +
75                             "\n  offAnalysisFile: the file that contains the OFF clusters analysis" +
76                             "\n  onSignatureFile: the file that contains the ON signature to search for" +
77                             "\n  offSignatureFile: the file that contains the OFF signature to search for" +
78                             "\n  resultsFile: where to write the results of the detection" +
79                             "\n  signatureDuration: the maximum duration of signature detection" +
80                             "\n  eps: the epsilon value for the DBSCAN algorithm" +
81                             "\n  onMaxSkippedPackets: the maximum duration of ON signature detection (put -1 if not used)" +
82                             "\n  offMaxSkippedPackets: the maximum duration of OFF signature detection (put -1 if not used)",
83                     Layer2SignatureDetector.class.getSimpleName());
84             System.out.println(errMsg);
85             String optParamsExplained = "Above are the required, positional arguments. In addition to these, the " +
86                     "following options and associated positional arguments may be used:\n" +
87                     "  '-onmacfilters <regex>;<regex>;...;<regex>' which specifies that sequence matching should ONLY" +
88                     " be performed on flows where the MAC of one of the two endpoints matches the given regex. Note " +
89                     "that you MUST specify a regex for each cluster of the signature. This is to facilitate more " +
90                     "aggressive filtering on parts of the signature (e.g., the communication that involves the " +
91                     "smart home device itself as one can drop all flows that do not include an endpoint with a MAC " +
92                     "that matches the vendor's prefix).\n" +
93                     "  '-offmacfilters <regex>;<regex>;...;<regex>' works exactly the same as onmacfilters, but " +
94                     "applies to the OFF signature instead of the ON signature.\n" +
95                     "  '-sout <boolean literal>' true/false literal indicating if output should also be printed to std out; default is true.";
96             System.out.println(optParamsExplained);
97             return;
98         }
99         final String pcapFile = args[0];
100         final String onClusterAnalysisFile = args[1];
101         final String offClusterAnalysisFile = args[2];
102         final String onSignatureFile = args[3];
103         final String offSignatureFile = args[4];
104         final String resultsFile = args[5];
105         final int signatureDuration = Integer.parseInt(args[6]);
106         final double eps = Double.parseDouble(args[7]);
107         final int onMaxSkippedPackets = Integer.parseInt(args[8]);
108         final int offMaxSkippedPackets = Integer.parseInt(args[9]);
109
110         // Parse optional parameters.
111         List<Function<Layer2Flow, Boolean>> onSignatureMacFilters = null, offSignatureMacFilters = null;
112         final int optParamsStartIdx = 7;
113         if (args.length > optParamsStartIdx) {
114             for (int i = optParamsStartIdx; i < args.length; i++) {
115                 if (args[i].equalsIgnoreCase("-onMacFilters")) {
116                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
117                     onSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
118                 } else if (args[i].equalsIgnoreCase("-offMacFilters")) {
119                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
120                     offSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
121                 } else if (args[i].equalsIgnoreCase("-sout")) {
122                     // Next argument is a boolean true/false literal.
123                     DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[i+1]);
124                 }
125             }
126         }
127
128         // Prepare file outputter.
129         File outputFile = new File(resultsFile);
130         outputFile.getParentFile().mkdirs();
131         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
132         // Include metadata as comments at the top
133         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
134         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
135         PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
136         PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
137         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
138         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
139         resultsWriter.flush();
140
141         // Create signature detectors and add observers that output their detected events.
142         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
143         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
144         // Load signature analyses
145         List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
146         List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
147         // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
148         // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
149         // TODO: STRICT MATCHING
150         // Check if we should use range-based matching
151         boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
152         boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
153         // TODO: WE DON'T DO RANGE-BASED FOR NOW BECAUSE THE RESULTS ARE TERRIBLE FOR LAYER 2 MATCHING
154         // TODO: THIS WOULD ONLY WORK FOR SIGNATURES LONGER THAN 2 PACKETS
155 //        boolean isRangeBasedForOn = false;
156 //        boolean isRangeBasedForOff = false;
157         // Update the signature with ranges if it is range-based
158         if (isRangeBasedForOn) {
159             onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
160         }
161         if (isRangeBasedForOff) {
162             offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
163         }
164         Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
165                 new Layer2SignatureDetector(onSignature, TRAINING_ROUTER_WLAN_MAC, ROUTER_WLAN_MAC, signatureDuration,
166                         isRangeBasedForOn, eps, onMaxSkippedPackets) :
167                 new Layer2SignatureDetector(onSignature, TRAINING_ROUTER_WLAN_MAC, ROUTER_WLAN_MAC,
168                         onSignatureMacFilters, signatureDuration, isRangeBasedForOn, eps, onMaxSkippedPackets);
169         Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
170                 new Layer2SignatureDetector(offSignature, TRAINING_ROUTER_WLAN_MAC, ROUTER_WLAN_MAC, signatureDuration,
171                         isRangeBasedForOff, eps, offMaxSkippedPackets) :
172                 new Layer2SignatureDetector(offSignature, TRAINING_ROUTER_WLAN_MAC, ROUTER_WLAN_MAC, offSignatureMacFilters,
173                         signatureDuration, isRangeBasedForOff, eps, offMaxSkippedPackets);
174         final List<UserAction> detectedEvents = new ArrayList<>();
175         onDetector.addObserver((signature, match) -> {
176             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
177             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
178             detectedEvents.add(event);
179         });
180         offDetector.addObserver((signature, match) -> {
181             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
182             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
183             detectedEvents.add(event);
184         });
185
186         // Load the PCAP file
187         PcapHandle handle;
188         try {
189             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
190         } catch (PcapNativeException pne) {
191             handle = Pcaps.openOffline(pcapFile);
192         }
193         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
194         // Parse the file
195         reader.readFromHandle();
196
197         String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
198                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
199         String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
200                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
201         String onMaximumSkippedPackets = "# Maximum number of skipped packets in ON signature " +
202                 Integer.toString(onDetector.getMaxSkippedPackets());
203         String offMaximumSkippedPackets = "# Maximum number of skipped packets in OFF signature " +
204                 Integer.toString(offDetector.getMaxSkippedPackets());
205         PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
206         PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
207         PrintWriterUtils.println(onMaximumSkippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
208         // TODO: We do not use the feature for now because it is essentially the same as signature duration.
209         //for(Integer skippedPackets : onDetector.getSkippedPackets()) {
210         //    PrintWriterUtils.println(skippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
211         //}
212         PrintWriterUtils.println(offMaximumSkippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
213         //for(Integer skippedPackets : offDetector.getSkippedPackets()) {
214         //    PrintWriterUtils.println(skippedPackets, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
215         //}
216         // Flush output to results file and close it.
217         resultsWriter.flush();
218         resultsWriter.close();
219     }
220
221     /**
222      * The signature that this {@link Layer2SignatureDetector} is searching for.
223      */
224     private final List<List<List<PcapPacket>>> mSignature;
225
226     /**
227      * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
228      * up the the signature.
229      */
230     private final List<Layer2ClusterMatcher> mClusterMatchers;
231
232     /**
233      * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
234      * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
235      * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
236      * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
237      */
238     private final List<List<PcapPacket>>[] mPendingMatches;
239
240     /**
241      * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
242      */
243     private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
244
245     /**
246      * In charge of reassembling layer 2 packet flows.
247      */
248     private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
249
250     private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
251
252     private int mInclusionTimeMillis;
253
254     /**
255      * Skipped-packet analysis.
256      */
257     private int mMaxSkippedPackets;
258     private List<Integer> mSkippedPackets;
259
260
261
262     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String trainingRouterWlanMac,
263                                    String routerWlanMac, int signatureDuration, boolean isRangeBased, double eps,
264                                    int limitSkippedPackets) {
265         this(searchedSignature, trainingRouterWlanMac, routerWlanMac, null, signatureDuration, isRangeBased,
266                 eps, limitSkippedPackets);
267     }
268
269     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String trainingRouterWlanMac,
270                                    String routerWlanMac, List<Function<Layer2Flow, Boolean>> flowFilters,
271                                    int inclusionTimeMillis, boolean isRangeBased, double eps, int limitSkippedPackets) {
272         if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
273             throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster " +
274                     "of the signature.");
275         }
276         mSignature = Collections.unmodifiableList(searchedSignature);
277         List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
278         for (int i = 0; i < mSignature.size(); i++) {
279             List<List<PcapPacket>> cluster = mSignature.get(i);
280             Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
281                     new Layer2ClusterMatcher(cluster, trainingRouterWlanMac, routerWlanMac, inclusionTimeMillis,
282                             isRangeBased, eps, limitSkippedPackets) :
283                     new Layer2ClusterMatcher(cluster, trainingRouterWlanMac, routerWlanMac, flowFilters.get(i),
284                             inclusionTimeMillis, isRangeBased, eps, limitSkippedPackets);
285             clusterMatcher.addObserver(this);
286             clusterMatchers.add(clusterMatcher);
287         }
288         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
289         mPendingMatches = new List[mClusterMatchers.size()];
290         for (int i = 0; i < mPendingMatches.length; i++) {
291             mPendingMatches[i] = new ArrayList<>();
292         }
293         Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
294         for (int i = 0; i < mClusterMatchers.size(); i++) {
295             clusterMatcherIds.put(mClusterMatchers.get(i), i);
296         }
297         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
298         // Register all cluster matchers to receive a notification whenever a new flow is encountered.
299         mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
300         mInclusionTimeMillis =
301                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
302         mMaxSkippedPackets = 0;
303         mSkippedPackets = new ArrayList<>();
304     }
305
306     public int getMaxSkippedPackets() {
307         return mMaxSkippedPackets;
308     }
309
310     public List<Integer> getSkippedPackets() {
311         for (Layer2ClusterMatcher matcher : mClusterMatchers) {
312             mSkippedPackets.addAll(matcher.getSkippedPackets());
313         }
314         return mSkippedPackets;
315     }
316
317     @Override
318     public void gotPacket(PcapPacket packet) {
319         // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
320         mFlowReassembler.gotPacket(packet);
321     }
322
323     @Override
324     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
325         // TODO: a cluster matcher found a match
326         if (clusterMatcher instanceof Layer2ClusterMatcher) {
327             // Add the match at the corresponding index
328             mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
329             checkSignatureMatch();
330             // Update maximum number of skipped packets
331             if (mMaxSkippedPackets < ((Layer2ClusterMatcher) clusterMatcher).getMaxSkippedPackets()) {
332                 mMaxSkippedPackets = ((Layer2ClusterMatcher) clusterMatcher).getMaxSkippedPackets();
333             }
334         }
335     }
336
337     public void addObserver(SignatureDetectorObserver observer) {
338         mObservers.add(observer);
339     }
340
341     public boolean removeObserver(SignatureDetectorObserver observer) {
342         return mObservers.remove(observer);
343     }
344
345
346     @SuppressWarnings("Duplicates")
347     private void checkSignatureMatch() {
348         // << Graph-based approach using Balint's idea. >>
349         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
350
351         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
352         if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
353             // Construct the DAG
354             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
355                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
356             // Add a vertex for each match found by all cluster matchers.
357             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
358             final List<Vertex>[] vertices = new List[mPendingMatches.length];
359             for (int i = 0; i < mPendingMatches.length; i++) {
360                 vertices[i] = new ArrayList<>();
361                 for (List<PcapPacket> sequence : mPendingMatches[i]) {
362                     Vertex v = new Vertex(sequence);
363                     vertices[i].add(v); // retain reference for later when we are to add edges
364                     graph.addVertex(v); // add to vertex to graph
365                 }
366             }
367             // Add dummy source and sink vertices to facilitate search.
368             final Vertex source = new Vertex(null);
369             final Vertex sink = new Vertex(null);
370             graph.addVertex(source);
371             graph.addVertex(sink);
372             // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
373             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
374             for (Vertex v : vertices[0]) {
375                 DefaultWeightedEdge edge = graph.addEdge(source, v);
376                 graph.setEdgeWeight(edge, 0.0);
377             }
378             // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
379             // are connected to the sink node.
380             for (Vertex v : vertices[vertices.length-1]) {
381                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
382                 graph.setEdgeWeight(edge, 0.0);
383             }
384             // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
385             // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
386             // the former).
387             for (int i = 0; i < vertices.length; i++) {
388                 int j = i + 1;
389                 if (j < vertices.length) {
390                     for (Vertex iv : vertices[i]) {
391                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
392                         for (Vertex jv : vertices[j]) {
393                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
394                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
395                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
396                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
397                                 // and i+1'th sequence.
398                                 Duration d = Duration.
399                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
400                                 // Unfortunately weights are double values, so must convert from long to double.
401                                 // TODO: need nano second precision? If so, use d.toNanos().
402                                 // TODO: risk of overflow when converting from long to double..?
403                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
404                             }
405                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
406 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
407 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
408 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
409 //
410 //                            }
411                         }
412                     }
413                 }
414             }
415             // Graph construction complete, run shortest-path to find a (potential) signature match.
416             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
417             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
418             if (shortestPath != null) {
419                 // The total weight is the duration between the first packet of the first sequence and the last packet
420                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
421                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
422                 // Note however, that we must convert back from double to long as the weight is stored as a double in
423                 // JGraphT's API.
424                 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
425                     // There's a signature match!
426                     // Extract the match from the vertices
427                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
428                     for(Vertex v : shortestPath.getVertexList()) {
429                         if (v == source || v == sink) {
430                             // Skip the dummy source and sink nodes.
431                             continue;
432                         }
433                         signatureMatch.add(v.sequence);
434                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
435                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
436                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
437                         // another signature match in a later call.
438                         mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
439                     }
440                     // Declare success: notify observers
441                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
442                             Collections.unmodifiableList(signatureMatch)));
443                 }
444             }
445         }
446     }
447
448     /**
449      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
450      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
451      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
452      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
453      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
454      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
455      * appropriate.
456      */
457     private static class Vertex {
458         private final List<PcapPacket> sequence;
459         private Vertex(List<PcapPacket> wrappedSequence) {
460             sequence = wrappedSequence;
461         }
462     }
463 }