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