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