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