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