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