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