ba5ec7af70654b3b636f39f79b58847220445440
[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.PrintUtils;
13 import org.jgrapht.GraphPath;
14 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
15 import org.jgrapht.graph.DefaultWeightedEdge;
16 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
17 import org.pcap4j.core.*;
18
19 import java.io.File;
20 import java.io.FileWriter;
21 import java.io.IOException;
22 import java.io.PrintWriter;
23 import java.time.Duration;
24 import java.util.*;
25 import java.util.function.Function;
26 import java.util.regex.Pattern;
27
28 /**
29  * Performs layer 2 signature detection.
30  *
31  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
32  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
33  */
34 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
35
36     /**
37      * If set to {@code true}, output written to the results file is also dumped to standard out.
38      */
39     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
40
41     private static List<Function<Layer2Flow, Boolean>> parseSignatureMacFilters(String filtersString) {
42         List<Function<Layer2Flow, Boolean>> filters = new ArrayList<>();
43         String[] filterRegexes = filtersString.split(";");
44         for (String filterRegex : filterRegexes) {
45             final Pattern regex = Pattern.compile(filterRegex);
46             // Create a filter that includes all flows where one of the two MAC addresses match the regex.
47             filters.add(flow -> regex.matcher(flow.getEndpoint1().toString()).matches() || regex.matcher(flow.getEndpoint2().toString()).matches());
48         }
49         return filters;
50     }
51
52     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
53         // Parse required parameters.
54         if (args.length < 4) {
55             String errMsg = String.format("Usage: %s inputPcapFile onSignatureFile offSignatureFile resultsFile" +
56                             "\n  inputPcapFile: the target of the detection" +
57                             "\n  onSignatureFile: the file that contains the ON signature to search for" +
58                             "\n  offSignatureFile: the file that contains the OFF signature to search for" +
59                             "\n  resultsFile: where to write the results of the detection",
60                     Layer2SignatureDetector.class.getSimpleName());
61             System.out.println(errMsg);
62             String optParamsExplained = "Above are the required, positional arguments. In addition to these, the " +
63                     "following options and associated positional arguments may be used:\n" +
64                     "  '-onmacfilters <regex>;<regex>;...;<regex>' which specifies that sequence matching should ONLY" +
65                     " be performed on flows where the MAC of one of the two endpoints matches the given regex. Note " +
66                     "that you MUST specify a regex for each cluster of the signature. This is to facilitate more " +
67                     "aggressive filtering on parts of the signature (e.g., the communication that involves the " +
68                     "smart home device itself as one can drop all flows that do not include an endpoint with a MAC " +
69                     "that matches the vendor's prefix).\n" +
70                     "  '-offmacfilters <regex>;<regex>;...;<regex>' works exactly the same as onmacfilters, but " +
71                     "applies to the OFF signature instead of the ON signature.\n" +
72                     "  '-sout <boolean literal>' true/false literal indicating if output should also be printed to std out; default is true.";
73             System.out.println(optParamsExplained);
74             return;
75         }
76         final String pcapFile = args[0];
77         final String onSignatureFile = args[1];
78         final String offSignatureFile = args[2];
79         final String resultsFile = args[3];
80
81         // Parse optional parameters.
82         List<Function<Layer2Flow, Boolean>> onSignatureMacFilters = null, offSignatureMacFilters = null;
83         final int optParamsStartIdx = 4;
84         if (args.length > optParamsStartIdx) {
85             for (int i = optParamsStartIdx; i < args.length; i++) {
86                 if (args[i].equalsIgnoreCase("-onMacFilters")) {
87                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
88                     onSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
89                 } else if (args[i].equalsIgnoreCase("-offMacFilters")) {
90                     // Next argument is the cluster-wise MAC filters (separated by semicolons).
91                     offSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
92                 } else if (args[i].equalsIgnoreCase("-sout")) {
93                     // Next argument is a boolean true/false literal.
94                     DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[i+1]);
95                 }
96             }
97         }
98
99         // Prepare file outputter.
100         File outputFile = new File(resultsFile);
101         outputFile.getParentFile().mkdirs();
102         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
103         // Include metadata as comments at the top
104         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
105         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
106         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
107         PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
108         resultsWriter.flush();
109
110         // Create signature detectors and add observers that output their detected events.
111         List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
112         List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
113         Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
114                 new Layer2SignatureDetector(onSignature) : new Layer2SignatureDetector(onSignature, onSignatureMacFilters);
115         Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
116                 new Layer2SignatureDetector(offSignature) : new Layer2SignatureDetector(offSignature, offSignatureMacFilters);
117         onDetector.addObserver((signature, match) -> {
118             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
119             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
120         });
121         offDetector.addObserver((signature, match) -> {
122             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
123             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
124         });
125
126         // Load the PCAP file
127         PcapHandle handle;
128         try {
129             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
130         } catch (PcapNativeException pne) {
131             handle = Pcaps.openOffline(pcapFile);
132         }
133         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
134         // Parse the file
135         reader.readFromHandle();
136
137         // Flush output to results file and close it.
138         resultsWriter.flush();
139         resultsWriter.close();
140     }
141
142     /**
143      * The signature that this {@link Layer2SignatureDetector} is searching for.
144      */
145     private final List<List<List<PcapPacket>>> mSignature;
146
147     /**
148      * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
149      * up the the signature.
150      */
151     private final List<Layer2ClusterMatcher> mClusterMatchers;
152
153     /**
154      * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
155      * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
156      * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
157      * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
158      */
159     private final List<List<PcapPacket>>[] mPendingMatches;
160
161     /**
162      * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
163      */
164     private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
165
166     /**
167      * In charge of reassembling layer 2 packet flows.
168      */
169     private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
170
171     private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
172
173     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature) {
174         this(searchedSignature, null);
175     }
176
177     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, List<Function<Layer2Flow, Boolean>> flowFilters) {
178         if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
179             throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster of the signature.");
180         }
181         mSignature = Collections.unmodifiableList(searchedSignature);
182         List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
183         for (int i = 0; i < mSignature.size(); i++) {
184             List<List<PcapPacket>> cluster = mSignature.get(i);
185             Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
186                     new Layer2ClusterMatcher(cluster) : new Layer2ClusterMatcher(cluster, flowFilters.get(i));
187             clusterMatcher.addObserver(this);
188             clusterMatchers.add(clusterMatcher);
189         }
190         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
191         mPendingMatches = new List[mClusterMatchers.size()];
192         for (int i = 0; i < mPendingMatches.length; i++) {
193             mPendingMatches[i] = new ArrayList<>();
194         }
195         Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
196         for (int i = 0; i < mClusterMatchers.size(); i++) {
197             clusterMatcherIds.put(mClusterMatchers.get(i), i);
198         }
199         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
200         // Register all cluster matchers to receive a notification whenever a new flow is encountered.
201         mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
202     }
203
204     @Override
205     public void gotPacket(PcapPacket packet) {
206         // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
207         mFlowReassembler.gotPacket(packet);
208     }
209
210     @Override
211     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
212         // TODO: a cluster matcher found a match
213         if (clusterMatcher instanceof Layer2ClusterMatcher) {
214             // Add the match at the corresponding index
215             mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
216             checkSignatureMatch();
217         }
218     }
219
220     public void addObserver(SignatureDetectorObserver observer) {
221         mObservers.add(observer);
222     }
223
224     public boolean removeObserver(SignatureDetectorObserver observer) {
225         return mObservers.remove(observer);
226     }
227
228
229     @SuppressWarnings("Duplicates")
230     private void checkSignatureMatch() {
231         // << Graph-based approach using Balint's idea. >>
232         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
233
234         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
235         if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
236             // Construct the DAG
237             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
238                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
239             // Add a vertex for each match found by all cluster matchers.
240             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
241             final List<Vertex>[] vertices = new List[mPendingMatches.length];
242             for (int i = 0; i < mPendingMatches.length; i++) {
243                 vertices[i] = new ArrayList<>();
244                 for (List<PcapPacket> sequence : mPendingMatches[i]) {
245                     Vertex v = new Vertex(sequence);
246                     vertices[i].add(v); // retain reference for later when we are to add edges
247                     graph.addVertex(v); // add to vertex to graph
248                 }
249             }
250             // Add dummy source and sink vertices to facilitate search.
251             final Vertex source = new Vertex(null);
252             final Vertex sink = new Vertex(null);
253             graph.addVertex(source);
254             graph.addVertex(sink);
255             // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
256             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
257             for (Vertex v : vertices[0]) {
258                 DefaultWeightedEdge edge = graph.addEdge(source, v);
259                 graph.setEdgeWeight(edge, 0.0);
260             }
261             // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
262             // are connected to the sink node.
263             for (Vertex v : vertices[vertices.length-1]) {
264                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
265                 graph.setEdgeWeight(edge, 0.0);
266             }
267             // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
268             // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
269             // the former).
270             for (int i = 0; i < vertices.length; i++) {
271                 int j = i + 1;
272                 if (j < vertices.length) {
273                     for (Vertex iv : vertices[i]) {
274                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
275                         for (Vertex jv : vertices[j]) {
276                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
277                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
278                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
279                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
280                                 // and i+1'th sequence.
281                                 Duration d = Duration.
282                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
283                                 // Unfortunately weights are double values, so must convert from long to double.
284                                 // TODO: need nano second precision? If so, use d.toNanos().
285                                 // TODO: risk of overflow when converting from long to double..?
286                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
287                             }
288                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
289 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
290 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
291 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
292 //
293 //                            }
294                         }
295                     }
296                 }
297             }
298             // Graph construction complete, run shortest-path to find a (potential) signature match.
299             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
300             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
301             if (shortestPath != null) {
302                 // The total weight is the duration between the first packet of the first sequence and the last packet
303                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
304                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
305                 // Note however, that we must convert back from double to long as the weight is stored as a double in
306                 // JGraphT's API.
307                 if (((long)shortestPath.getWeight()) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
308                     // There's a signature match!
309                     // Extract the match from the vertices
310                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
311                     for(Vertex v : shortestPath.getVertexList()) {
312                         if (v == source || v == sink) {
313                             // Skip the dummy source and sink nodes.
314                             continue;
315                         }
316                         signatureMatch.add(v.sequence);
317                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
318                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
319                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
320                         // another signature match in a later call.
321                         mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
322                     }
323                     // Declare success: notify observers
324                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
325                             Collections.unmodifiableList(signatureMatch)));
326                 }
327             }
328         }
329     }
330
331     /**
332      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
333      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
334      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
335      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
336      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
337      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
338      * appropriate.
339      */
340     private static class Vertex {
341         private final List<PcapPacket> sequence;
342         private Vertex(List<PcapPacket> wrappedSequence) {
343             sequence = wrappedSequence;
344         }
345     }
346 }