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