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.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.*;
20 import java.io.FileWriter;
21 import java.io.IOException;
22 import java.io.PrintWriter;
23 import java.time.Duration;
25 import java.util.function.Function;
26 import java.util.regex.Pattern;
29 * Performs layer 2 signature detection.
31 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
32 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
34 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
37 * If set to {@code true}, output written to the results file is also dumped to standard out.
39 private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
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());
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);
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]);
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]);
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();
112 // Create signature detectors and add observers that output their detected events.
113 List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeSignatureFromFile(onSignatureFile);
114 List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeSignatureFromFile(offSignatureFile);
115 Layer2SignatureDetector onDetector = onSignatureMacFilters == null ?
116 new Layer2SignatureDetector(onSignature) : new Layer2SignatureDetector(onSignature, onSignatureMacFilters, signatureDuration);
117 Layer2SignatureDetector offDetector = offSignatureMacFilters == null ?
118 new Layer2SignatureDetector(offSignature) : new Layer2SignatureDetector(offSignature, offSignatureMacFilters, signatureDuration);
119 onDetector.addObserver((signature, match) -> {
120 UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
121 PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
123 offDetector.addObserver((signature, match) -> {
124 UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
125 PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
128 // Load the PCAP file
131 handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
132 } catch (PcapNativeException pne) {
133 handle = Pcaps.openOffline(pcapFile);
135 PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
137 reader.readFromHandle();
139 // Flush output to results file and close it.
140 resultsWriter.flush();
141 resultsWriter.close();
145 * The signature that this {@link Layer2SignatureDetector} is searching for.
147 private final List<List<List<PcapPacket>>> mSignature;
150 * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
151 * up the the signature.
153 private final List<Layer2ClusterMatcher> mClusterMatchers;
156 * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
157 * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
158 * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
159 * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
161 private final List<List<PcapPacket>>[] mPendingMatches;
164 * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
166 private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
169 * In charge of reassembling layer 2 packet flows.
171 private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
173 private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
175 private int mInclusionTimeMillis;
177 public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature) {
178 this(searchedSignature, null, 0);
181 public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, List<Function<Layer2Flow, Boolean>> flowFilters, int inclusionTimeMillis) {
182 if (flowFilters != null && flowFilters.size() != searchedSignature.size()) {
183 throw new IllegalArgumentException("If flow filters are used, there must be a flow filter for each cluster of the signature.");
185 mSignature = Collections.unmodifiableList(searchedSignature);
186 List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
187 for (int i = 0; i < mSignature.size(); i++) {
188 List<List<PcapPacket>> cluster = mSignature.get(i);
189 Layer2ClusterMatcher clusterMatcher = flowFilters == null ?
190 new Layer2ClusterMatcher(cluster) : new Layer2ClusterMatcher(cluster, flowFilters.get(i));
191 clusterMatcher.addObserver(this);
192 clusterMatchers.add(clusterMatcher);
194 mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
195 mPendingMatches = new List[mClusterMatchers.size()];
196 for (int i = 0; i < mPendingMatches.length; i++) {
197 mPendingMatches[i] = new ArrayList<>();
199 Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
200 for (int i = 0; i < mClusterMatchers.size(); i++) {
201 clusterMatcherIds.put(mClusterMatchers.get(i), i);
203 mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
204 // Register all cluster matchers to receive a notification whenever a new flow is encountered.
205 mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
206 mInclusionTimeMillis =
207 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
211 public void gotPacket(PcapPacket packet) {
212 // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
213 mFlowReassembler.gotPacket(packet);
217 public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
218 // TODO: a cluster matcher found a match
219 if (clusterMatcher instanceof Layer2ClusterMatcher) {
220 // Add the match at the corresponding index
221 mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
222 checkSignatureMatch();
226 public void addObserver(SignatureDetectorObserver observer) {
227 mObservers.add(observer);
230 public boolean removeObserver(SignatureDetectorObserver observer) {
231 return mObservers.remove(observer);
235 @SuppressWarnings("Duplicates")
236 private void checkSignatureMatch() {
237 // << Graph-based approach using Balint's idea. >>
238 // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
240 // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
241 if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
243 final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
244 new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
245 // Add a vertex for each match found by all cluster matchers.
246 // And maintain an array to keep track of what cluster matcher each vertex corresponds to
247 final List<Vertex>[] vertices = new List[mPendingMatches.length];
248 for (int i = 0; i < mPendingMatches.length; i++) {
249 vertices[i] = new ArrayList<>();
250 for (List<PcapPacket> sequence : mPendingMatches[i]) {
251 Vertex v = new Vertex(sequence);
252 vertices[i].add(v); // retain reference for later when we are to add edges
253 graph.addVertex(v); // add to vertex to graph
256 // Add dummy source and sink vertices to facilitate search.
257 final Vertex source = new Vertex(null);
258 final Vertex sink = new Vertex(null);
259 graph.addVertex(source);
260 graph.addVertex(sink);
261 // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
262 // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
263 for (Vertex v : vertices[0]) {
264 DefaultWeightedEdge edge = graph.addEdge(source, v);
265 graph.setEdgeWeight(edge, 0.0);
267 // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
268 // are connected to the sink node.
269 for (Vertex v : vertices[vertices.length-1]) {
270 DefaultWeightedEdge edge = graph.addEdge(v, sink);
271 graph.setEdgeWeight(edge, 0.0);
273 // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
274 // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
276 for (int i = 0; i < vertices.length; i++) {
278 if (j < vertices.length) {
279 for (Vertex iv : vertices[i]) {
280 PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
281 for (Vertex jv : vertices[j]) {
282 PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
283 if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
284 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
285 // The weight is the duration of the i'th sequence plus the duration between the i'th
286 // and i+1'th sequence.
287 Duration d = Duration.
288 between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
289 // Unfortunately weights are double values, so must convert from long to double.
290 // TODO: need nano second precision? If so, use d.toNanos().
291 // TODO: risk of overflow when converting from long to double..?
292 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
294 // Alternative version if we cannot assume that sequences are ordered by timestamp:
295 // if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
296 // .getTimestamp().isBefore(jv.sequence.stream().min(
297 // Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
304 // Graph construction complete, run shortest-path to find a (potential) signature match.
305 DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
306 GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
307 if (shortestPath != null) {
308 // The total weight is the duration between the first packet of the first sequence and the last packet
309 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
310 // the signature to span. For now we just use the inclusion window we defined for training purposes.
311 // Note however, that we must convert back from double to long as the weight is stored as a double in
313 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
314 // There's a signature match!
315 // Extract the match from the vertices
316 List<List<PcapPacket>> signatureMatch = new ArrayList<>();
317 for(Vertex v : shortestPath.getVertexList()) {
318 if (v == source || v == sink) {
319 // Skip the dummy source and sink nodes.
322 signatureMatch.add(v.sequence);
323 // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
324 // the sequence we've "consumed" for index i of the matched signature is also at index i in
325 // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
326 // another signature match in a later call.
327 mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
329 // Declare success: notify observers
330 mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
331 Collections.unmodifiableList(signatureMatch)));
338 * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
339 * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
340 * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
341 * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
342 * recognize two lists that contain the same items--from a value and not reference point of view--as the same
343 * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
346 private static class Vertex {
347 private final List<PcapPacket> sequence;
348 private Vertex(List<PcapPacket> wrappedSequence) {
349 sequence = wrappedSequence;