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