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