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