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