Adding copyright signature.
[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("SPECTO version 1.0\n" +
51                             "Copyright (C) 2018-2019 Janus Varmarken and Rahmadi Trimananda.\n" +
52                             "University of California, Irvine.\n" +
53                             "All rights reserved.\n\n" +
54                             "Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile resultsFile" +
55                             "\n  inputPcapFile: the target of the detection" +
56                             "\n  onAnalysisFile: the file that contains the ON clusters analysis" +
57                             "\n  offAnalysisFile: the file that contains the OFF clusters analysis" +
58                             "\n  onSignatureFile: the file that contains the ON signature to search for" +
59                             "\n  offSignatureFile: the file that contains the OFF signature to search for" +
60                             "\n  resultsFile: where to write the results of the detection" +
61                             "\n  signatureDuration: the maximum duration of signature detection" +
62                             "\n  epsilon: the epsilon value for the DBSCAN algorithm",
63                     Layer3SignatureDetector.class.getSimpleName());
64             System.out.println(errMsg);
65             return;
66         }
67         final String pcapFile = args[0];
68         final String onClusterAnalysisFile = args[1];
69         final String offClusterAnalysisFile = args[2];
70         final String onSignatureFile = args[3];
71         final String offSignatureFile = args[4];
72         final String resultsFile = args[5];
73         // TODO: THIS IS TEMPORARILY SET TO DEFAULT SIGNATURE DURATION
74         // TODO: WE DO NOT WANT TO BE TOO STRICT AT THIS POINT SINCE LAYER 3 ALREADY APPLIES BACK-TO-BACK REQUIREMENT
75         // TODO: FOR PACKETS IN A SIGNATURE
76 //        final int signatureDuration = Integer.parseInt(args[6]);
77         final int signatureDuration = TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS;
78         final double eps = Double.parseDouble(args[7]);
79
80         // Prepare file outputter.
81         File outputFile = new File(resultsFile);
82         outputFile.getParentFile().mkdirs();
83         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
84         // Include metadata as comments at the top
85         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
86         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
87         PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
88         PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
89         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
90         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
91         resultsWriter.flush();
92
93         // Load signatures
94         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
95         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
96         // Load signature analyses
97         List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
98         List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
99
100         // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
101         // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
102         // TODO: STRICT MATCHING
103         // Check if we should use range-based matching
104         boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
105         boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
106         // Update the signature with ranges if it is range-based
107         if (isRangeBasedForOn) {
108             onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
109         }
110         if (isRangeBasedForOff) {
111             offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
112         }
113         // WAN
114         Layer3SignatureDetector onDetector = new Layer3SignatureDetector(onSignature, ROUTER_WAN_IP,
115                 signatureDuration, isRangeBasedForOn, eps);
116         Layer3SignatureDetector offDetector = new Layer3SignatureDetector(offSignature, ROUTER_WAN_IP,
117                 signatureDuration, isRangeBasedForOff, eps);
118
119         final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
120                 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
121
122         // Outputs information about a detected event to std.out
123         final Consumer<UserAction> outputter = ua -> {
124             String eventDescription;
125             switch (ua.getType()) {
126                 case TOGGLE_ON:
127                     eventDescription = "ON";
128                     break;
129                 case TOGGLE_OFF:
130                     eventDescription = "OFF";
131                     break;
132                 default:
133                     throw new AssertionError("unhandled event type");
134             }
135             // TODO: Uncomment the following if we want the old style print-out messages
136             // String output = String.format("%s",
137             // dateTimeFormatter.format(ua.getTimestamp()));
138             // System.out.println(output);
139             PrintWriterUtils.println(ua, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
140         };
141
142         // Let's create observers that construct a UserAction representing the detected event.
143         final List<UserAction> detectedEvents = new ArrayList<>();
144         onDetector.addObserver((searched, match) -> {
145             PcapPacket firstPkt = match.get(0).get(0);
146             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp());
147             detectedEvents.add(event);
148         });
149         offDetector.addObserver((searched, match) -> {
150             PcapPacket firstPkt = match.get(0).get(0);
151             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp());
152             //PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
153             detectedEvents.add(event);
154         });
155
156         PcapHandle handle;
157         try {
158             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
159         } catch (PcapNativeException pne) {
160             handle = Pcaps.openOffline(pcapFile);
161         }
162         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
163         reader.readFromHandle();
164
165         // TODO: need a better way of triggering detection than this...
166         if (isRangeBasedForOn) {
167             onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
168         } else {
169             onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
170         }
171         if (isRangeBasedForOff) {
172             offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
173         } else {
174             offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
175         }
176
177         // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
178         // times file.
179         Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
180
181         // Output the detected events
182         detectedEvents.forEach(outputter);
183
184         String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
185                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
186         String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
187                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
188         PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
189         PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
190
191         // Flush output to results file and close it.
192         resultsWriter.flush();
193         resultsWriter.close();
194         // TODO: Temporary clean up until we clean the pipeline
195 //      List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
196 //      cleanedDetectedEvents.forEach(outputter);
197     }
198
199     /**
200      * The signature that this {@link Layer3SignatureDetector} is searching for.
201      */
202     private final List<List<List<PcapPacket>>> mSignature;
203
204     /**
205      * The {@link Layer3ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
206      * the signature.
207      */
208     private final List<Layer3ClusterMatcher> mClusterMatchers;
209
210     /**
211      * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
212      * found by the {@link Layer3ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
213      * have yet to be included in a signature detected by this {@link Layer3SignatureDetector} (a signature can be encompassed
214      * of multiple packet sequences occurring shortly after one another on multiple connections).
215      */
216     private final List<List<PcapPacket>>[] pendingMatches;
217
218     /**
219      * Maps a {@link Layer3ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
220      */
221     private final Map<Layer3ClusterMatcher, Integer> mClusterMatcherIds;
222
223     private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
224
225     private int mInclusionTimeMillis;
226
227     /**
228      * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
229      * that appear multiple times.
230      * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
231      * TODO:    the pipeline
232      *
233      * @param listUserAction A {@link List} of {@code UserAction}.
234      *
235      */
236     public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
237
238         // Iterate and check for duplicates (check timestamps)
239         Set<Long> epochSecondSet = new HashSet<>();
240         // Create a target list for cleaned up list
241         List<UserAction> listUserActionClean = new ArrayList<>();
242         for(UserAction userAction : listUserAction) {
243             // Don't insert if any duplicate is found
244             if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
245                 listUserActionClean.add(userAction);
246                 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
247             }
248         }
249         return listUserActionClean;
250     }
251
252     public Layer3SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp,
253                              int inclusionTimeMillis, boolean isRangeBased, double eps) {
254         // note: doesn't protect inner lists from changes :'(
255         mSignature = Collections.unmodifiableList(searchedSignature);
256         // Generate corresponding/appropriate ClusterMatchers based on the provided signature
257         List<Layer3ClusterMatcher> clusterMatchers = new ArrayList<>();
258         for (List<List<PcapPacket>> cluster : mSignature) {
259             clusterMatchers.add(new Layer3ClusterMatcher(cluster, routerWanIp, inclusionTimeMillis,
260                     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 }