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