Implementing relaxed matching for layer 2 and layer 3.
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer3 / Layer3SignatureDetector.java
1 package edu.uci.iotproject.detection.layer3;
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.io.PcapHandleReader;
8 import edu.uci.iotproject.io.PrintWriterUtils;
9 import edu.uci.iotproject.util.PcapPacketUtils;
10 import edu.uci.iotproject.util.PrintUtils;
11 import org.apache.commons.math3.distribution.AbstractRealDistribution;
12 import org.apache.commons.math3.distribution.NormalDistribution;
13 import org.jgrapht.GraphPath;
14 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
15 import org.jgrapht.graph.DefaultWeightedEdge;
16 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
17 import org.pcap4j.core.*;
18
19 import java.io.File;
20 import java.io.FileWriter;
21 import java.io.IOException;
22 import java.io.PrintWriter;
23 import java.time.Duration;
24 import java.time.ZoneId;
25 import java.time.format.DateTimeFormatter;
26 import java.time.format.FormatStyle;
27 import java.util.*;
28 import java.util.function.Consumer;
29
30 /**
31  * Detects an event signature that spans one or multiple TCP connections.
32  *
33  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
34  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
35  */
36 public class Layer3SignatureDetector implements PacketListener, ClusterMatcherObserver {
37
38     /**
39      * If set to {@code true}, output written to the results file is also dumped to standard out.
40      */
41     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
42
43     /**
44      * Router's IP.
45      *
46      * TODO: The following was the router address for EH (Networking Lab)
47      * private static String ROUTER_WAN_IP = "128.195.205.105";
48      */
49     private static String ROUTER_WAN_IP = "128.195.55.242";
50
51     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
52         String errMsg = String.format("SPECTO version 1.0\n" +
53                         "Copyright (C) 2018-2019 Janus Varmarken and Rahmadi Trimananda.\n" +
54                         "University of California, Irvine.\n" +
55                         "All rights reserved.\n\n" +
56                         "Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile resultsFile" +
57                         "\n  inputPcapFile: the target of the detection" +
58                         "\n  onAnalysisFile: the file that contains the ON clusters analysis" +
59                         "\n  offAnalysisFile: the file that contains the OFF clusters analysis" +
60                         "\n  onSignatureFile: the file that contains the ON signature to search for" +
61                         "\n  offSignatureFile: the file that contains the OFF signature to search for" +
62                         "\n  resultsFile: where to write the results of the detection" +
63                         "\n  signatureDuration: the maximum duration of signature detection" +
64                         "\n  epsilon: the epsilon value for the DBSCAN algorithm\n" +
65                         "\n  Additional options (add '-r' before the following two parameters):" +
66                         "\n  delta: delta for relaxed matching" +
67                         "\n  packetId: packet number in the sequence" +
68                         "\n            (could be more than one packet whose matching is relaxed, " +
69                         "\n             e.g., 0,1 for packets 0 and 1)",
70                 Layer3SignatureDetector.class.getSimpleName());
71         if (args.length < 8) {
72             System.out.println(errMsg);
73             return;
74         }
75         final String pcapFile = args[0];
76         final String onClusterAnalysisFile = args[1];
77         final String offClusterAnalysisFile = args[2];
78         final String onSignatureFile = args[3];
79         final String offSignatureFile = args[4];
80         final String resultsFile = args[5];
81         // TODO: THIS IS TEMPORARILY SET TO DEFAULT SIGNATURE DURATION
82         // TODO: WE DO NOT WANT TO BE TOO STRICT AT THIS POINT SINCE LAYER 3 ALREADY APPLIES BACK-TO-BACK REQUIREMENT
83         // TODO: FOR PACKETS IN A SIGNATURE
84 //        final int signatureDuration = Integer.parseInt(args[6]);
85         final int signatureDuration = TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS;
86         final double eps = Double.parseDouble(args[7]);
87         // Additional feature---relaxed matching
88         int delta = 0;
89         final Set<Integer> packetSet = new HashSet<>();
90         if (args.length == 11 && args[8].equals("-r")) {
91             delta = Integer.parseInt(args[9]);
92             StringTokenizer stringTokenizerOff = new StringTokenizer(args[10], ",");
93             // Add the list of packet IDs
94             while(stringTokenizerOff.hasMoreTokens()) {
95                 int id = Integer.parseInt(stringTokenizerOff.nextToken());
96                 packetSet.add(id);
97             }
98         } else {
99             System.out.println(errMsg);
100             return;
101         }
102         // Prepare file outputter.
103         File outputFile = new File(resultsFile);
104         outputFile.getParentFile().mkdirs();
105         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
106         // Include metadata as comments at the top
107         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
108         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
109         PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
110         PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
111         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
112         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
113         resultsWriter.flush();
114
115         // Load signatures
116         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
117         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
118         // Load signature analyses
119         List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
120         List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
121
122         // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
123         // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
124         // TODO: STRICT MATCHING
125         // Check if we should use range-based matching
126         boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
127         boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
128         // Update the signature with ranges if it is range-based
129         if (isRangeBasedForOn) {
130             onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
131         }
132         if (isRangeBasedForOff) {
133             offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
134         }
135         // WAN
136         Layer3SignatureDetector onDetector = new Layer3SignatureDetector(onSignature, ROUTER_WAN_IP,
137                 signatureDuration, isRangeBasedForOn, eps, delta, packetSet);
138         Layer3SignatureDetector offDetector = new Layer3SignatureDetector(offSignature, ROUTER_WAN_IP,
139                 signatureDuration, isRangeBasedForOff, eps, delta, packetSet);
140
141         final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
142                 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
143
144         // Outputs information about a detected event to std.out
145         final Consumer<UserAction> outputter = ua -> {
146             String eventDescription;
147             switch (ua.getType()) {
148                 case TOGGLE_ON:
149                     eventDescription = "ON";
150                     break;
151                 case TOGGLE_OFF:
152                     eventDescription = "OFF";
153                     break;
154                 default:
155                     throw new AssertionError("unhandled event type");
156             }
157             // TODO: Uncomment the following if we want the old style print-out messages
158             // String output = String.format("%s",
159             // dateTimeFormatter.format(ua.getTimestamp()));
160             // System.out.println(output);
161             PrintWriterUtils.println(ua, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
162         };
163
164         // Let's create observers that construct a UserAction representing the detected event.
165         final List<UserAction> detectedEvents = new ArrayList<>();
166         onDetector.addObserver((searched, match) -> {
167             PcapPacket firstPkt = match.get(0).get(0);
168             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp());
169             detectedEvents.add(event);
170         });
171         offDetector.addObserver((searched, match) -> {
172             PcapPacket firstPkt = match.get(0).get(0);
173             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp());
174             //PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
175             detectedEvents.add(event);
176         });
177
178         PcapHandle handle;
179         try {
180             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
181         } catch (PcapNativeException pne) {
182             handle = Pcaps.openOffline(pcapFile);
183         }
184         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
185         reader.readFromHandle();
186
187         // TODO: need a better way of triggering detection than this...
188         if (isRangeBasedForOn) {
189             onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
190         } else {
191             onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
192         }
193         if (isRangeBasedForOff) {
194             offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
195         } else {
196             offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
197         }
198
199         // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
200         // times file.
201         Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
202
203         // Output the detected events
204         detectedEvents.forEach(outputter);
205
206         String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
207                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
208         String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
209                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
210         PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
211         PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
212
213         // Flush output to results file and close it.
214         resultsWriter.flush();
215         resultsWriter.close();
216         // TODO: Temporary clean up until we clean the pipeline
217 //      List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
218 //      cleanedDetectedEvents.forEach(outputter);
219     }
220
221     /**
222      * The signature that this {@link Layer3SignatureDetector} is searching for.
223      */
224     private final List<List<List<PcapPacket>>> mSignature;
225
226     /**
227      * The {@link Layer3ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
228      * the signature.
229      */
230     private final List<Layer3ClusterMatcher> mClusterMatchers;
231
232     /**
233      * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
234      * found by the {@link Layer3ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
235      * have yet to be included in a signature detected by this {@link Layer3SignatureDetector} (a signature can be encompassed
236      * of multiple packet sequences occurring shortly after one another on multiple connections).
237      */
238     private final List<List<PcapPacket>>[] pendingMatches;
239
240     /**
241      * Maps a {@link Layer3ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
242      */
243     private final Map<Layer3ClusterMatcher, Integer> mClusterMatcherIds;
244
245     private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
246
247     private int mInclusionTimeMillis;
248
249     /**
250      * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
251      * that appear multiple times.
252      * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
253      * TODO:    the pipeline
254      *
255      * @param listUserAction A {@link List} of {@code UserAction}.
256      *
257      */
258     public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
259
260         // Iterate and check for duplicates (check timestamps)
261         Set<Long> epochSecondSet = new HashSet<>();
262         // Create a target list for cleaned up list
263         List<UserAction> listUserActionClean = new ArrayList<>();
264         for(UserAction userAction : listUserAction) {
265             // Don't insert if any duplicate is found
266             if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
267                 listUserActionClean.add(userAction);
268                 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
269             }
270         }
271         return listUserActionClean;
272     }
273
274     public Layer3SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp,
275                                    int inclusionTimeMillis, boolean isRangeBased, double eps,
276                                    int delta, Set<Integer> packetSet) {
277         // note: doesn't protect inner lists from changes :'(
278         mSignature = Collections.unmodifiableList(searchedSignature);
279         // Generate corresponding/appropriate ClusterMatchers based on the provided signature
280         List<Layer3ClusterMatcher> clusterMatchers = new ArrayList<>();
281         for (List<List<PcapPacket>> cluster : mSignature) {
282             clusterMatchers.add(new Layer3ClusterMatcher(cluster, routerWanIp, inclusionTimeMillis,
283                     isRangeBased, eps, delta, packetSet, this));
284         }
285         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
286
287         // < exploratory >
288         pendingMatches = new List[mClusterMatchers.size()];
289         for (int i = 0; i < pendingMatches.length; i++) {
290             pendingMatches[i] = new ArrayList<>();
291         }
292         Map<Layer3ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
293         for (int i = 0; i < mClusterMatchers.size(); i++) {
294             clusterMatcherIds.put(mClusterMatchers.get(i), i);
295         }
296         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
297         mInclusionTimeMillis =
298                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
299     }
300
301     public void addObserver(SignatureDetectionObserver observer) {
302         mObservers.add(observer);
303     }
304
305     public boolean removeObserver(SignatureDetectionObserver observer) {
306         return mObservers.remove(observer);
307     }
308
309     @Override
310     public void gotPacket(PcapPacket packet) {
311         // simply delegate packet reception to all ClusterMatchers.
312         mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
313     }
314
315     @Override
316     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
317         // Add the match at the corresponding index
318         pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
319         checkSignatureMatch();
320     }
321
322     private void checkSignatureMatch() {
323         // << Graph-based approach using Balint's idea. >>
324         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
325
326         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
327         if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
328             // Construct the DAG
329             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
330                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
331             // Add a vertex for each match found by all ClusterMatchers
332             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
333             final List<Vertex>[] vertices = new List[pendingMatches.length];
334             for (int i = 0; i < pendingMatches.length; i++) {
335                 vertices[i] = new ArrayList<>();
336                 for (List<PcapPacket> sequence : pendingMatches[i]) {
337                     Vertex v = new Vertex(sequence);
338                     vertices[i].add(v); // retain reference for later when we are to add edges
339                     graph.addVertex(v); // add to vertex to graph
340                 }
341             }
342             // Add dummy source and sink vertices to facilitate search.
343             final Vertex source = new Vertex(null);
344             final Vertex sink = new Vertex(null);
345             graph.addVertex(source);
346             graph.addVertex(sink);
347             // The source is connected to all vertices that wrap the sequences detected by Layer3ClusterMatcher at index 0.
348             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
349             for (Vertex v : vertices[0]) {
350                 DefaultWeightedEdge edge = graph.addEdge(source, v);
351                 graph.setEdgeWeight(edge, 0.0);
352             }
353             // Similarly, all vertices that wrap the sequences detected by the last Layer3ClusterMatcher of the signature
354             // are connected to the sink node.
355             for (Vertex v : vertices[vertices.length-1]) {
356                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
357                 graph.setEdgeWeight(edge, 0.0);
358             }
359             // Now link sequences detected by Layer3ClusterMatcher at index i to sequences detected by Layer3ClusterMatcher at index
360             // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
361             for (int i = 0; i < vertices.length; i++) {
362                 int j = i + 1;
363                 if (j < vertices.length) {
364                     for (Vertex iv : vertices[i]) {
365                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
366                         for (Vertex jv : vertices[j]) {
367                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
368                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
369                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
370                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
371                                 // and i+1'th sequence.
372                                 Duration d = Duration.
373                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
374                                 // Unfortunately weights are double values, so must convert from long to double.
375                                 // TODO: need nano second precision? If so, use d.toNanos().
376                                 // TODO: risk of overflow when converting from long to double..?
377                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
378                             }
379                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
380 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
381 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
382 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
383 //
384 //                            }
385                         }
386                     }
387                 }
388             }
389             // Graph construction complete, run shortest-path to find a (potential) signature match.
390             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
391             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
392             if (shortestPath != null) {
393                 // The total weight is the duration between the first packet of the first sequence and the last packet
394                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
395                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
396                 // Note however, that we must convert back from double to long as the weight is stored as a double in
397                 // JGraphT's API.
398                 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
399                     // There's a signature match!
400                     // Extract the match from the vertices
401                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
402                     for(Vertex v : shortestPath.getVertexList()) {
403                         if (v == source || v == sink) {
404                             // Skip the dummy source and sink nodes.
405                             continue;
406                         }
407                         signatureMatch.add(v.sequence);
408                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
409                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
410                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
411                         // another signature match in a later call.
412                         pendingMatches[signatureMatch.size()-1].remove(v.sequence);
413                     }
414                     // Declare success: notify observers
415                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
416                             Collections.unmodifiableList(signatureMatch)));
417                 }
418             }
419         }
420     }
421
422     /**
423      * Used for registering for notifications of signatures detected by a {@link Layer3SignatureDetector}.
424      */
425     interface SignatureDetectionObserver {
426
427         /**
428          * Invoked when the {@link Layer3SignatureDetector} detects the presence of a signature in the traffic that it's
429          * examining.
430          * @param searchedSignature The signature that the {@link Layer3SignatureDetector} reporting the match is searching
431          *                          for.
432          * @param matchingTraffic The actual traffic trace that matches the searched signature.
433          */
434         void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
435                                  List<List<PcapPacket>> matchingTraffic);
436     }
437
438     /**
439      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
440      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
441      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
442      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
443      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
444      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
445      * appropriate.
446      */
447     private static class Vertex {
448         private final List<PcapPacket> sequence;
449         private Vertex(List<PcapPacket> wrappedSequence) {
450             sequence = wrappedSequence;
451         }
452     }
453 }