1 package edu.uci.iotproject.detection.layer3;
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.io.PcapHandleReader;
8 import edu.uci.iotproject.io.PrintWriterUtils;
9 import edu.uci.iotproject.util.PcapPacketUtils;
10 import edu.uci.iotproject.util.PrintUtils;
11 import org.apache.commons.math3.distribution.AbstractRealDistribution;
12 import org.apache.commons.math3.distribution.NormalDistribution;
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;
24 import java.time.ZoneId;
25 import java.time.format.DateTimeFormatter;
26 import java.time.format.FormatStyle;
28 import java.util.function.Consumer;
31 * Detects an event signature that spans one or multiple TCP connections.
33 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
34 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
36 public class Layer3SignatureDetector implements PacketListener, ClusterMatcherObserver {
39 * If set to {@code true}, output written to the results file is also dumped to standard out.
41 private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
46 private static String ROUTER_WAN_IP = "128.195.205.105";
48 public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
49 if (args.length < 8) {
50 String errMsg = String.format("Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile resultsFile" +
51 "\n inputPcapFile: the target of the detection" +
52 "\n onAnalysisFile: the file that contains the ON clusters analysis" +
53 "\n offAnalysisFile: the file that contains the OFF clusters analysis" +
54 "\n onSignatureFile: the file that contains the ON signature to search for" +
55 "\n offSignatureFile: the file that contains the OFF signature to search for" +
56 "\n resultsFile: where to write the results of the detection" +
57 "\n signatureDuration: the maximum duration of signature detection" +
58 "\n epsilon: the epsilon value for the DBSCAN algorithm",
59 Layer3SignatureDetector.class.getSimpleName());
60 System.out.println(errMsg);
63 final String pcapFile = args[0];
64 final String onClusterAnalysisFile = args[1];
65 final String offClusterAnalysisFile = args[2];
66 final String onSignatureFile = args[3];
67 final String offSignatureFile = args[4];
68 final String resultsFile = args[5];
69 final int signatureDuration = Integer.parseInt(args[6]);
70 final double eps = Double.parseDouble(args[7]);
72 // Prepare file outputter.
73 File outputFile = new File(resultsFile);
74 outputFile.getParentFile().mkdirs();
75 final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
76 // Include metadata as comments at the top
77 PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
78 PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
79 PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
80 PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
81 PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
82 PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
83 resultsWriter.flush();
86 List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
87 List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
88 // Load signature analyses
89 List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
90 List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
92 // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
93 // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
94 // TODO: STRICT MATCHING
95 // Check if we should use range-based matching
96 boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
97 boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
98 // Update the signature with ranges if it is range-based
99 if (isRangeBasedForOn) {
100 onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
102 if (isRangeBasedForOff) {
103 offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
106 Layer3SignatureDetector onDetector = new Layer3SignatureDetector(onSignature, ROUTER_WAN_IP,
107 signatureDuration, isRangeBasedForOn, eps);
108 Layer3SignatureDetector offDetector = new Layer3SignatureDetector(offSignature, ROUTER_WAN_IP,
109 signatureDuration, isRangeBasedForOff, eps);
111 final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
112 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
114 // Outputs information about a detected event to std.out
115 final Consumer<UserAction> outputter = ua -> {
116 String eventDescription;
117 switch (ua.getType()) {
119 eventDescription = "ON";
122 eventDescription = "OFF";
125 throw new AssertionError("unhandled event type");
127 // TODO: Uncomment the following if we want the old style print-out messages
128 // String output = String.format("%s",
129 // dateTimeFormatter.format(ua.getTimestamp()));
130 // System.out.println(output);
131 PrintWriterUtils.println(ua, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
134 // Let's create observers that construct a UserAction representing the detected event.
135 final List<UserAction> detectedEvents = new ArrayList<>();
136 onDetector.addObserver((searched, match) -> {
137 PcapPacket firstPkt = match.get(0).get(0);
138 UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp());
139 detectedEvents.add(event);
141 offDetector.addObserver((searched, match) -> {
142 PcapPacket firstPkt = match.get(0).get(0);
143 UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp());
144 //PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
145 detectedEvents.add(event);
150 handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
151 } catch (PcapNativeException pne) {
152 handle = Pcaps.openOffline(pcapFile);
154 PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
155 reader.readFromHandle();
157 // TODO: need a better way of triggering detection than this...
158 if (isRangeBasedForOn) {
159 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
161 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
163 if (isRangeBasedForOff) {
164 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
166 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
169 // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
171 Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
173 // Output the detected events
174 detectedEvents.forEach(outputter);
176 String resultOn = "Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
177 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
178 String resultOff = "Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
179 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
180 PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
181 PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
183 // Flush output to results file and close it.
184 resultsWriter.flush();
185 resultsWriter.close();
186 // TODO: Temporary clean up until we clean the pipeline
187 // List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
188 // cleanedDetectedEvents.forEach(outputter);
192 * The signature that this {@link Layer3SignatureDetector} is searching for.
194 private final List<List<List<PcapPacket>>> mSignature;
197 * The {@link Layer3ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
200 private final List<Layer3ClusterMatcher> mClusterMatchers;
203 * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
204 * found by the {@link Layer3ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
205 * have yet to be included in a signature detected by this {@link Layer3SignatureDetector} (a signature can be encompassed
206 * of multiple packet sequences occurring shortly after one another on multiple connections).
208 private final List<List<PcapPacket>>[] pendingMatches;
211 * Maps a {@link Layer3ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
213 private final Map<Layer3ClusterMatcher, Integer> mClusterMatcherIds;
215 private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
217 private int mInclusionTimeMillis;
220 * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
221 * that appear multiple times.
222 * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
225 * @param listUserAction A {@link List} of {@code UserAction}.
228 public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
230 // Iterate and check for duplicates (check timestamps)
231 Set<Long> epochSecondSet = new HashSet<>();
232 // Create a target list for cleaned up list
233 List<UserAction> listUserActionClean = new ArrayList<>();
234 for(UserAction userAction : listUserAction) {
235 // Don't insert if any duplicate is found
236 if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
237 listUserActionClean.add(userAction);
238 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
241 return listUserActionClean;
244 public Layer3SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp,
245 int inclusionTimeMillis, boolean isRangeBased, double eps) {
246 // note: doesn't protect inner lists from changes :'(
247 mSignature = Collections.unmodifiableList(searchedSignature);
248 // Generate corresponding/appropriate ClusterMatchers based on the provided signature
249 List<Layer3ClusterMatcher> clusterMatchers = new ArrayList<>();
250 for (List<List<PcapPacket>> cluster : mSignature) {
251 clusterMatchers.add(new Layer3ClusterMatcher(cluster, routerWanIp, isRangeBased, eps, this));
253 mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
256 pendingMatches = new List[mClusterMatchers.size()];
257 for (int i = 0; i < pendingMatches.length; i++) {
258 pendingMatches[i] = new ArrayList<>();
260 Map<Layer3ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
261 for (int i = 0; i < mClusterMatchers.size(); i++) {
262 clusterMatcherIds.put(mClusterMatchers.get(i), i);
264 mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
265 mInclusionTimeMillis =
266 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
269 public void addObserver(SignatureDetectionObserver observer) {
270 mObservers.add(observer);
273 public boolean removeObserver(SignatureDetectionObserver observer) {
274 return mObservers.remove(observer);
278 public void gotPacket(PcapPacket packet) {
279 // simply delegate packet reception to all ClusterMatchers.
280 mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
284 public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
285 // Add the match at the corresponding index
286 pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
287 checkSignatureMatch();
290 private void checkSignatureMatch() {
291 // << Graph-based approach using Balint's idea. >>
292 // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
294 // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
295 if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
297 final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
298 new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
299 // Add a vertex for each match found by all ClusterMatchers
300 // And maintain an array to keep track of what cluster matcher each vertex corresponds to
301 final List<Vertex>[] vertices = new List[pendingMatches.length];
302 for (int i = 0; i < pendingMatches.length; i++) {
303 vertices[i] = new ArrayList<>();
304 for (List<PcapPacket> sequence : pendingMatches[i]) {
305 Vertex v = new Vertex(sequence);
306 vertices[i].add(v); // retain reference for later when we are to add edges
307 graph.addVertex(v); // add to vertex to graph
310 // Add dummy source and sink vertices to facilitate search.
311 final Vertex source = new Vertex(null);
312 final Vertex sink = new Vertex(null);
313 graph.addVertex(source);
314 graph.addVertex(sink);
315 // The source is connected to all vertices that wrap the sequences detected by Layer3ClusterMatcher at index 0.
316 // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
317 for (Vertex v : vertices[0]) {
318 DefaultWeightedEdge edge = graph.addEdge(source, v);
319 graph.setEdgeWeight(edge, 0.0);
321 // Similarly, all vertices that wrap the sequences detected by the last Layer3ClusterMatcher of the signature
322 // are connected to the sink node.
323 for (Vertex v : vertices[vertices.length-1]) {
324 DefaultWeightedEdge edge = graph.addEdge(v, sink);
325 graph.setEdgeWeight(edge, 0.0);
327 // Now link sequences detected by Layer3ClusterMatcher at index i to sequences detected by Layer3ClusterMatcher at index
328 // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
329 for (int i = 0; i < vertices.length; i++) {
331 if (j < vertices.length) {
332 for (Vertex iv : vertices[i]) {
333 PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
334 for (Vertex jv : vertices[j]) {
335 PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
336 if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
337 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
338 // The weight is the duration of the i'th sequence plus the duration between the i'th
339 // and i+1'th sequence.
340 Duration d = Duration.
341 between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
342 // Unfortunately weights are double values, so must convert from long to double.
343 // TODO: need nano second precision? If so, use d.toNanos().
344 // TODO: risk of overflow when converting from long to double..?
345 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
347 // Alternative version if we cannot assume that sequences are ordered by timestamp:
348 // if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
349 // .getTimestamp().isBefore(jv.sequence.stream().min(
350 // Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
357 // Graph construction complete, run shortest-path to find a (potential) signature match.
358 DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
359 GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
360 if (shortestPath != null) {
361 // The total weight is the duration between the first packet of the first sequence and the last packet
362 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
363 // the signature to span. For now we just use the inclusion window we defined for training purposes.
364 // Note however, that we must convert back from double to long as the weight is stored as a double in
366 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
367 // There's a signature match!
368 // Extract the match from the vertices
369 List<List<PcapPacket>> signatureMatch = new ArrayList<>();
370 for(Vertex v : shortestPath.getVertexList()) {
371 if (v == source || v == sink) {
372 // Skip the dummy source and sink nodes.
375 signatureMatch.add(v.sequence);
376 // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
377 // the sequence we've "consumed" for index i of the matched signature is also at index i in
378 // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
379 // another signature match in a later call.
380 pendingMatches[signatureMatch.size()-1].remove(v.sequence);
382 // Declare success: notify observers
383 mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
384 Collections.unmodifiableList(signatureMatch)));
391 * Used for registering for notifications of signatures detected by a {@link Layer3SignatureDetector}.
393 interface SignatureDetectionObserver {
396 * Invoked when the {@link Layer3SignatureDetector} detects the presence of a signature in the traffic that it's
398 * @param searchedSignature The signature that the {@link Layer3SignatureDetector} reporting the match is searching
400 * @param matchingTraffic The actual traffic trace that matches the searched signature.
402 void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
403 List<List<PcapPacket>> matchingTraffic);
407 * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
408 * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
409 * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
410 * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
411 * recognize two lists that contain the same items--from a value and not reference point of view--as the same
412 * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
415 private static class Vertex {
416 private final List<PcapPacket> sequence;
417 private Vertex(List<PcapPacket> wrappedSequence) {
418 sequence = wrappedSequence;