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 / layer2 / Layer2SignatureDetector.java
1 package edu.uci.iotproject.detection.layer2;
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.detection.SignatureDetectorObserver;
8 import edu.uci.iotproject.io.PcapHandleReader;
9 import edu.uci.iotproject.io.PrintWriterUtils;
10 import edu.uci.iotproject.trafficreassembly.layer2.Layer2Flow;
11 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassembler;
12 import edu.uci.iotproject.util.PcapPacketUtils;
13 import edu.uci.iotproject.util.PrintUtils;
14 import org.jgrapht.GraphPath;
15 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
16 import org.jgrapht.graph.DefaultWeightedEdge;
17 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
18 import org.pcap4j.core.*;
19
20 import java.io.File;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.time.Duration;
25 import java.util.*;
26 import java.util.function.Function;
27 import java.util.regex.Pattern;
28
29 /**
30  * Performs layer 2 signature detection.
31  *
32  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
33  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
34  */
35 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
36
37     /**
38      * If set to {@code true}, output written to the results file is also dumped to standard out.
39      */
40     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
41
42     private static List<Function<Layer2Flow, Boolean>> parseSignatureMacFilters(String filtersString) {
43         List<Function<Layer2Flow, Boolean>> filters = new ArrayList<>();
44         String[] filterRegexes = filtersString.split(";");
45         for (String filterRegex : filterRegexes) {
46             final Pattern regex = Pattern.compile(filterRegex);
47             // Create a filter that includes all flows where one of the two MAC addresses match the regex.
48             filters.add(flow -> regex.matcher(flow.getEndpoint1().toString()).matches() || regex.matcher(flow.getEndpoint2().toString()).matches());
49         }
50         return filters;
51     }
52
53     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
54         // Parse required parameters.
55         if (args.length < 8) {
56             String errMsg = String.format("Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile resultsFile" +
57                             "\n  inputPcapFile: the target of the detection" +
58                             "\n  onAnalysisFile: the file that contains the ON clusters analysis" +
59                             "\n  offAnalysisFile: the file that contains the OFF clusters analysis" +
60                             "\n  onSignatureFile: the file that contains the ON signature to search for" +
61                             "\n  offSignatureFile: the file that contains the OFF signature to search for" +
62                             "\n  resultsFile: where to write the results of the detection" +
63                             "\n  signatureDuration: the maximum duration of signature detection",
64                     Layer2SignatureDetector.class.getSimpleName());
65             System.out.println(errMsg);
66             String optParamsExplained = "Above are the required, positional arguments. In addition to these, the " +
67                     "following options and associated positional arguments may be used:\n" +
68                     "  '-onmacfilters <regex>;<regex>;...;<regex>' which specifies that sequence matching should ONLY" +
69                     " be performed on flows where the MAC of one of the two endpoints matches the given regex. Note " +
70                     "that you MUST specify a regex for each cluster of the signature. This is to facilitate more " +
71                     "aggressive filtering on parts of the signature (e.g., the communication that involves the " +
72                     "smart home device itself as one can drop all flows that do not include an endpoint with a MAC " +
73                     "that matches the vendor's prefix).\n" +
74                     "  '-offmacfilters <regex>;<regex>;...;<regex>' works exactly the same as onmacfilters, but " +
75                     "applies to the OFF signature instead of the ON signature.\n" +
76                     "  '-sout <boolean literal>' true/false literal indicating if output should also be printed to std out; default is true.";
77             System.out.println(optParamsExplained);
78             return;
79         }
80         // TODO: We could take 7 inputs if we decided to use the cluster analyses.
81         final String pcapFile = args[0];
82         final String onClusterAnalysisFile = args[1];
83         final String offClusterAnalysisFile = args[2];
84         final String onSignatureFile = args[3];
85         final String offSignatureFile = args[4];
86         final String resultsFile = args[5];
87         final int signatureDuration = Integer.parseInt(args[6]);
88         final double eps = Double.parseDouble(args[7]);
89
90         // Parse optional parameters.
91         List<Function<Layer2Flow, Boolean>> onSignatureMacFilters = null, offSignatureMacFilters = null;
92         final int optParamsStartIdx = 7;
93         if (args.length > optParamsStartIdx) {
94             for (int i = optParamsStartIdx; i < args.length; i++) {
95                 if (args[i].equalsIgnoreCase("-onMacFilters")) {
96                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
97                     onSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
98                 } else if (args[i].equalsIgnoreCase("-offMacFilters")) {
99                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
100                     offSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
101                 } else if (args[i].equalsIgnoreCase("-sout")) {
102                     // Next argument is a boolean true/false literal.
103                     DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[i+1]);
104                 }
105             }
106         }
107
108         // Prepare file outputter.
109         File outputFile = new File(resultsFile);
110         outputFile.getParentFile().mkdirs();
111         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
112         // Include metadata as comments at the top
113         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
114         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
115         PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
116         PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
117         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
118         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
119         resultsWriter.flush();
120
121         // Create signature detectors and add observers that output their detected events.
122         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
123         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
124         // Load signature analyses
125         List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
126         List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
127         // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
128         // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
129         // TODO: STRICT MATCHING
130         // Check if we should use range-based matching
131         boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
132         boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
133         // TODO: WE DON'T DO RANGE-BASED FOR NOW BECAUSE THE RESULTS ARE TERRIBLE FOR LAYER 2 MATCHING
134         // TODO: THIS WOULD ONLY WORK FOR SIGNATURES LONGER THAN 2 PACKETS
135 //        boolean isRangeBasedForOn = false;
136 //        boolean isRangeBasedForOff = false;
137         // Update the signature with ranges if it is range-based
138         if (isRangeBasedForOn) {
139             onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
140         }
141         if (isRangeBasedForOff) {
142             offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
143         }
144         Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
145                 new Layer2SignatureDetector(onSignature, signatureDuration, isRangeBasedForOn, eps) :
146                 new Layer2SignatureDetector(onSignature, onSignatureMacFilters, signatureDuration, isRangeBasedForOn, eps);
147         Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
148                 new Layer2SignatureDetector(offSignature, signatureDuration, isRangeBasedForOff, eps) :
149                 new Layer2SignatureDetector(offSignature, offSignatureMacFilters, signatureDuration, isRangeBasedForOff, eps);
150         final List<UserAction> detectedEvents = new ArrayList<>();
151         onDetector.addObserver((signature, match) -> {
152             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
153             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
154             detectedEvents.add(event);
155         });
156         offDetector.addObserver((signature, match) -> {
157             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
158             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
159             detectedEvents.add(event);
160         });
161
162         // Load the PCAP file
163         PcapHandle handle;
164         try {
165             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
166         } catch (PcapNativeException pne) {
167             handle = Pcaps.openOffline(pcapFile);
168         }
169         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
170         // Parse the file
171         reader.readFromHandle();
172
173         String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
174                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
175         String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
176                 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
177         PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
178         PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
179
180         // Flush output to results file and close it.
181         resultsWriter.flush();
182         resultsWriter.close();
183     }
184
185     /**
186      * The signature that this {@link Layer2SignatureDetector} is searching for.
187      */
188     private final List<List<List<PcapPacket>>> mSignature;
189
190     /**
191      * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
192      * up the the signature.
193      */
194     private final List<Layer2ClusterMatcher> mClusterMatchers;
195
196     /**
197      * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
198      * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
199      * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
200      * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
201      */
202     private final List<List<PcapPacket>>[] mPendingMatches;
203
204     /**
205      * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
206      */
207     private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
208
209     /**
210      * In charge of reassembling layer 2 packet flows.
211      */
212     private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
213
214     private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
215
216     private int mInclusionTimeMillis;
217
218     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, int signatureDuration, boolean isRangeBased, double eps) {
219         this(searchedSignature, null, signatureDuration, isRangeBased, eps);
220     }
221
222     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, List<Function<Layer2Flow,
223             Boolean>> flowFilters, int inclusionTimeMillis, boolean isRangeBased, double eps) {
224         if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
225             throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster " +
226                     "of the signature.");
227         }
228         mSignature = Collections.unmodifiableList(searchedSignature);
229         List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
230         for (int i = 0; i < mSignature.size(); i++) {
231             List<List<PcapPacket>> cluster = mSignature.get(i);
232             Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
233                     new Layer2ClusterMatcher(cluster, inclusionTimeMillis, isRangeBased, eps) :
234                     new Layer2ClusterMatcher(cluster, flowFilters.get(i), inclusionTimeMillis, isRangeBased, eps);
235             clusterMatcher.addObserver(this);
236             clusterMatchers.add(clusterMatcher);
237         }
238         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
239         mPendingMatches = new List[mClusterMatchers.size()];
240         for (int i = 0; i < mPendingMatches.length; i++) {
241             mPendingMatches[i] = new ArrayList<>();
242         }
243         Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
244         for (int i = 0; i < mClusterMatchers.size(); i++) {
245             clusterMatcherIds.put(mClusterMatchers.get(i), i);
246         }
247         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
248         // Register all cluster matchers to receive a notification whenever a new flow is encountered.
249         mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
250         mInclusionTimeMillis =
251                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
252     }
253
254     @Override
255     public void gotPacket(PcapPacket packet) {
256         // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
257         mFlowReassembler.gotPacket(packet);
258     }
259
260     @Override
261     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
262         // TODO: a cluster matcher found a match
263         if (clusterMatcher instanceof Layer2ClusterMatcher) {
264             // Add the match at the corresponding index
265             mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
266             checkSignatureMatch();
267         }
268     }
269
270     public void addObserver(SignatureDetectorObserver observer) {
271         mObservers.add(observer);
272     }
273
274     public boolean removeObserver(SignatureDetectorObserver observer) {
275         return mObservers.remove(observer);
276     }
277
278
279     @SuppressWarnings("Duplicates")
280     private void checkSignatureMatch() {
281         // << Graph-based approach using Balint's idea. >>
282         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
283
284         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
285         if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
286             // Construct the DAG
287             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
288                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
289             // Add a vertex for each match found by all cluster matchers.
290             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
291             final List<Vertex>[] vertices = new List[mPendingMatches.length];
292             for (int i = 0; i < mPendingMatches.length; i++) {
293                 vertices[i] = new ArrayList<>();
294                 for (List<PcapPacket> sequence : mPendingMatches[i]) {
295                     Vertex v = new Vertex(sequence);
296                     vertices[i].add(v); // retain reference for later when we are to add edges
297                     graph.addVertex(v); // add to vertex to graph
298                 }
299             }
300             // Add dummy source and sink vertices to facilitate search.
301             final Vertex source = new Vertex(null);
302             final Vertex sink = new Vertex(null);
303             graph.addVertex(source);
304             graph.addVertex(sink);
305             // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
306             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
307             for (Vertex v : vertices[0]) {
308                 DefaultWeightedEdge edge = graph.addEdge(source, v);
309                 graph.setEdgeWeight(edge, 0.0);
310             }
311             // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
312             // are connected to the sink node.
313             for (Vertex v : vertices[vertices.length-1]) {
314                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
315                 graph.setEdgeWeight(edge, 0.0);
316             }
317             // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
318             // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
319             // the former).
320             for (int i = 0; i < vertices.length; i++) {
321                 int j = i + 1;
322                 if (j < vertices.length) {
323                     for (Vertex iv : vertices[i]) {
324                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
325                         for (Vertex jv : vertices[j]) {
326                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
327                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
328                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
329                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
330                                 // and i+1'th sequence.
331                                 Duration d = Duration.
332                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
333                                 // Unfortunately weights are double values, so must convert from long to double.
334                                 // TODO: need nano second precision? If so, use d.toNanos().
335                                 // TODO: risk of overflow when converting from long to double..?
336                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
337                             }
338                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
339 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
340 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
341 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
342 //
343 //                            }
344                         }
345                     }
346                 }
347             }
348             // Graph construction complete, run shortest-path to find a (potential) signature match.
349             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
350             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
351             if (shortestPath != null) {
352                 // The total weight is the duration between the first packet of the first sequence and the last packet
353                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
354                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
355                 // Note however, that we must convert back from double to long as the weight is stored as a double in
356                 // JGraphT's API.
357                 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
358                     // There's a signature match!
359                     // Extract the match from the vertices
360                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
361                     for(Vertex v : shortestPath.getVertexList()) {
362                         if (v == source || v == sink) {
363                             // Skip the dummy source and sink nodes.
364                             continue;
365                         }
366                         signatureMatch.add(v.sequence);
367                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
368                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
369                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
370                         // another signature match in a later call.
371                         mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
372                     }
373                     // Declare success: notify observers
374                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
375                             Collections.unmodifiableList(signatureMatch)));
376                 }
377             }
378         }
379     }
380
381     /**
382      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
383      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
384      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
385      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
386      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
387      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
388      * appropriate.
389      */
390     private static class Vertex {
391         private final List<PcapPacket> sequence;
392         private Vertex(List<PcapPacket> wrappedSequence) {
393             sequence = wrappedSequence;
394         }
395     }
396 }