1 package edu.uci.iotproject.detection.layer2;
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.*;
21 import java.io.FileWriter;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.time.Duration;
26 import java.util.function.Function;
27 import java.util.regex.Pattern;
30 * Performs layer 2 signature detection.
32 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
33 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
35 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
38 * If set to {@code true}, output written to the results file is also dumped to standard out.
40 private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
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());
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);
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]);
90 final String pcapFile = args[0];
91 final String onSignatureFile = args[1];
92 final String offSignatureFile = args[2];
93 final String resultsFile = args[3];
94 final int signatureDuration = Integer.parseInt(args[4]);
96 // Parse optional parameters.
97 List<Function<Layer2Flow, Boolean>> onSignatureMacFilters = null, offSignatureMacFilters = null;
98 final int optParamsStartIdx = 7;
99 if (args.length > optParamsStartIdx) {
100 for (int i = optParamsStartIdx; i < args.length; i++) {
101 if (args[i].equalsIgnoreCase("-onMacFilters")) {
102 // Next argument is the cluster-wise MAC filters (separated by semicolons).
103 onSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
104 } else if (args[i].equalsIgnoreCase("-offMacFilters")) {
105 // Next argument is the cluster-wise MAC filters (separated by semicolons).
106 offSignatureMacFilters = parseSignatureMacFilters(args[i+1]);
107 } else if (args[i].equalsIgnoreCase("-sout")) {
108 // Next argument is a boolean true/false literal.
109 DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[i+1]);
114 // Prepare file outputter.
115 File outputFile = new File(resultsFile);
116 outputFile.getParentFile().mkdirs();
117 final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
118 // Include metadata as comments at the top
119 PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
120 PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
121 // PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
122 // PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
123 PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
124 PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
125 resultsWriter.flush();
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 && isRangeBasedForOff) {
142 // onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
143 // offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
145 // TODO: WE DON'T DO RANGE-BASED FOR NOW BECAUSE THE RESULTS ARE TERRIBLE FOR LAYER 2 MATCHING
146 // TODO: THIS WOULD ONLY WORK FOR SIGNATURES LONGER THAN 2 PACKETS
147 boolean isRangeBasedForOn = false;
148 boolean isRangeBasedForOff = false;
149 Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
150 new Layer2SignatureDetector(onSignature, isRangeBasedForOn, eps) :
151 new Layer2SignatureDetector(onSignature, onSignatureMacFilters, signatureDuration, isRangeBasedForOn, eps);
152 Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
153 new Layer2SignatureDetector(offSignature, isRangeBasedForOff, eps) :
154 new Layer2SignatureDetector(offSignature, offSignatureMacFilters, signatureDuration, isRangeBasedForOff, eps);
155 onDetector.addObserver((signature, match) -> {
156 UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
157 PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
159 offDetector.addObserver((signature, match) -> {
160 UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
161 PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
164 // Load the PCAP file
167 handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
168 } catch (PcapNativeException pne) {
169 handle = Pcaps.openOffline(pcapFile);
171 PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
173 reader.readFromHandle();
175 // Flush output to results file and close it.
176 resultsWriter.flush();
177 resultsWriter.close();
181 * The signature that this {@link Layer2SignatureDetector} is searching for.
183 private final List<List<List<PcapPacket>>> mSignature;
186 * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
187 * up the the signature.
189 private final List<Layer2ClusterMatcher> mClusterMatchers;
192 * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
193 * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
194 * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
195 * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
197 private final List<List<PcapPacket>>[] mPendingMatches;
200 * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
202 private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
205 * In charge of reassembling layer 2 packet flows.
207 private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
209 private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
211 private int mInclusionTimeMillis;
213 public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, boolean isRangeBased, double eps) {
214 this(searchedSignature, null, 0, isRangeBased, eps);
217 public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, List<Function<Layer2Flow,
218 Boolean>> flowFilters, int inclusionTimeMillis, boolean isRangeBased, double eps) {
219 if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
220 throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster " +
221 "of the signature.");
223 mSignature = Collections.unmodifiableList(searchedSignature);
224 List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
225 for (int i = 0; i < mSignature.size(); i++) {
226 List<List<PcapPacket>> cluster = mSignature.get(i);
227 Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
228 new Layer2ClusterMatcher(cluster, isRangeBased, eps) :
229 new Layer2ClusterMatcher(cluster, flowFilters.get(i), isRangeBased, eps);
230 clusterMatcher.addObserver(this);
231 clusterMatchers.add(clusterMatcher);
233 mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
234 mPendingMatches = new List[mClusterMatchers.size()];
235 for (int i = 0; i < mPendingMatches.length; i++) {
236 mPendingMatches[i] = new ArrayList<>();
238 Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
239 for (int i = 0; i < mClusterMatchers.size(); i++) {
240 clusterMatcherIds.put(mClusterMatchers.get(i), i);
242 mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
243 // Register all cluster matchers to receive a notification whenever a new flow is encountered.
244 mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
245 mInclusionTimeMillis =
246 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
250 public void gotPacket(PcapPacket packet) {
251 // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
252 mFlowReassembler.gotPacket(packet);
256 public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
257 // TODO: a cluster matcher found a match
258 if (clusterMatcher instanceof Layer2ClusterMatcher) {
259 // Add the match at the corresponding index
260 mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
261 checkSignatureMatch();
265 public void addObserver(SignatureDetectorObserver observer) {
266 mObservers.add(observer);
269 public boolean removeObserver(SignatureDetectorObserver observer) {
270 return mObservers.remove(observer);
274 @SuppressWarnings("Duplicates")
275 private void checkSignatureMatch() {
276 // << Graph-based approach using Balint's idea. >>
277 // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
279 // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
280 if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
282 final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
283 new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
284 // Add a vertex for each match found by all cluster matchers.
285 // And maintain an array to keep track of what cluster matcher each vertex corresponds to
286 final List<Vertex>[] vertices = new List[mPendingMatches.length];
287 for (int i = 0; i < mPendingMatches.length; i++) {
288 vertices[i] = new ArrayList<>();
289 for (List<PcapPacket> sequence : mPendingMatches[i]) {
290 Vertex v = new Vertex(sequence);
291 vertices[i].add(v); // retain reference for later when we are to add edges
292 graph.addVertex(v); // add to vertex to graph
295 // Add dummy source and sink vertices to facilitate search.
296 final Vertex source = new Vertex(null);
297 final Vertex sink = new Vertex(null);
298 graph.addVertex(source);
299 graph.addVertex(sink);
300 // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
301 // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
302 for (Vertex v : vertices[0]) {
303 DefaultWeightedEdge edge = graph.addEdge(source, v);
304 graph.setEdgeWeight(edge, 0.0);
306 // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
307 // are connected to the sink node.
308 for (Vertex v : vertices[vertices.length-1]) {
309 DefaultWeightedEdge edge = graph.addEdge(v, sink);
310 graph.setEdgeWeight(edge, 0.0);
312 // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
313 // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
315 for (int i = 0; i < vertices.length; i++) {
317 if (j < vertices.length) {
318 for (Vertex iv : vertices[i]) {
319 PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
320 for (Vertex jv : vertices[j]) {
321 PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
322 if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
323 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
324 // The weight is the duration of the i'th sequence plus the duration between the i'th
325 // and i+1'th sequence.
326 Duration d = Duration.
327 between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
328 // Unfortunately weights are double values, so must convert from long to double.
329 // TODO: need nano second precision? If so, use d.toNanos().
330 // TODO: risk of overflow when converting from long to double..?
331 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
333 // Alternative version if we cannot assume that sequences are ordered by timestamp:
334 // if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
335 // .getTimestamp().isBefore(jv.sequence.stream().min(
336 // Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
343 // Graph construction complete, run shortest-path to find a (potential) signature match.
344 DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
345 GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
346 if (shortestPath != null) {
347 // The total weight is the duration between the first packet of the first sequence and the last packet
348 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
349 // the signature to span. For now we just use the inclusion window we defined for training purposes.
350 // Note however, that we must convert back from double to long as the weight is stored as a double in
352 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
353 // There's a signature match!
354 // Extract the match from the vertices
355 List<List<PcapPacket>> signatureMatch = new ArrayList<>();
356 for(Vertex v : shortestPath.getVertexList()) {
357 if (v == source || v == sink) {
358 // Skip the dummy source and sink nodes.
361 signatureMatch.add(v.sequence);
362 // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
363 // the sequence we've "consumed" for index i of the matched signature is also at index i in
364 // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
365 // another signature match in a later call.
366 mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
368 // Declare success: notify observers
369 mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
370 Collections.unmodifiableList(signatureMatch)));
377 * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
378 * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
379 * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
380 * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
381 * recognize two lists that contain the same items--from a value and not reference point of view--as the same
382 * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
385 private static class Vertex {
386 private final List<PcapPacket> sequence;
387 private Vertex(List<PcapPacket> wrappedSequence) {
388 sequence = wrappedSequence;