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