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