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