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 < 7) {
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 Layer3SignatureDetector.class.getSimpleName());
59 System.out.println(errMsg);
62 final String pcapFile = args[0];
63 final String onClusterAnalysisFile = args[1];
64 final String offClusterAnalysisFile = args[2];
65 final String onSignatureFile = args[3];
66 final String offSignatureFile = args[4];
67 final String resultsFile = args[5];
68 final int signatureDuration = Integer.parseInt(args[6]);
70 // Prepare file outputter.
71 File outputFile = new File(resultsFile);
72 outputFile.getParentFile().mkdirs();
73 final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
74 // Include metadata as comments at the top
75 PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
76 PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
77 PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
78 PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
79 PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
80 PrintWriterUtils.println("# - offSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
81 resultsWriter.flush();
84 // TODO: This would be specified through command line option
87 List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
88 List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
89 // Load signature analyses
90 List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
91 List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
93 // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
94 // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
95 // TODO: STRICT MATCHING
96 // Check if we should use range-based matching
97 boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
98 boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
99 // Update the signature with ranges if it is range-based
100 if (isRangeBasedForOn && isRangeBasedForOff) {
101 onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
102 offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
106 Layer3SignatureDetector onDetector = new Layer3SignatureDetector(onSignature, ROUTER_WAN_IP,
107 0, isRangeBasedForOn, eps);
108 Layer3SignatureDetector offDetector = new Layer3SignatureDetector(offSignature, ROUTER_WAN_IP,
109 0, 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);
133 // Let's create observers that construct a UserAction representing the detected event.
134 final List<UserAction> detectedEvents = new ArrayList<>();
135 onDetector.addObserver((searched, match) -> {
136 PcapPacket firstPkt = match.get(0).get(0);
137 UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp());
138 PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
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 && isRangeBasedForOff) {
159 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
160 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
162 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
163 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
166 // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
168 Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
170 // Output the detected events
171 detectedEvents.forEach(outputter);
173 System.out.println("Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
174 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count());
175 System.out.println("Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
176 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count());
178 // Flush output to results file and close it.
179 resultsWriter.flush();
180 resultsWriter.close();
181 // TODO: Temporary clean up until we clean the pipeline
182 // List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
183 // cleanedDetectedEvents.forEach(outputter);
187 * The signature that this {@link Layer3SignatureDetector} is searching for.
189 private final List<List<List<PcapPacket>>> mSignature;
192 * The {@link Layer3ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
195 private final List<Layer3ClusterMatcher> mClusterMatchers;
198 * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
199 * found by the {@link Layer3ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
200 * have yet to be included in a signature detected by this {@link Layer3SignatureDetector} (a signature can be encompassed
201 * of multiple packet sequences occurring shortly after one another on multiple connections).
203 private final List<List<PcapPacket>>[] pendingMatches;
206 * Maps a {@link Layer3ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
208 private final Map<Layer3ClusterMatcher, Integer> mClusterMatcherIds;
210 private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
212 private int mInclusionTimeMillis;
215 * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
216 * that appear multiple times.
217 * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
220 * @param listUserAction A {@link List} of {@code UserAction}.
223 public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
225 // Iterate and check for duplicates (check timestamps)
226 Set<Long> epochSecondSet = new HashSet<>();
227 // Create a target list for cleaned up list
228 List<UserAction> listUserActionClean = new ArrayList<>();
229 for(UserAction userAction : listUserAction) {
230 // Don't insert if any duplicate is found
231 if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
232 listUserActionClean.add(userAction);
233 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
236 return listUserActionClean;
239 public Layer3SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp,
240 int inclusionTimeMillis, boolean isRangeBased, double eps) {
241 // note: doesn't protect inner lists from changes :'(
242 mSignature = Collections.unmodifiableList(searchedSignature);
243 // Generate corresponding/appropriate ClusterMatchers based on the provided signature
244 List<Layer3ClusterMatcher> clusterMatchers = new ArrayList<>();
245 for (List<List<PcapPacket>> cluster : mSignature) {
246 clusterMatchers.add(new Layer3ClusterMatcher(cluster, routerWanIp, isRangeBased, eps, this));
248 mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
251 pendingMatches = new List[mClusterMatchers.size()];
252 for (int i = 0; i < pendingMatches.length; i++) {
253 pendingMatches[i] = new ArrayList<>();
255 Map<Layer3ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
256 for (int i = 0; i < mClusterMatchers.size(); i++) {
257 clusterMatcherIds.put(mClusterMatchers.get(i), i);
259 mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
260 mInclusionTimeMillis =
261 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
264 public void addObserver(SignatureDetectionObserver observer) {
265 mObservers.add(observer);
268 public boolean removeObserver(SignatureDetectionObserver observer) {
269 return mObservers.remove(observer);
273 public void gotPacket(PcapPacket packet) {
274 // simply delegate packet reception to all ClusterMatchers.
275 mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
279 public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
280 // Add the match at the corresponding index
281 pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
282 checkSignatureMatch();
285 private void checkSignatureMatch() {
286 // << Graph-based approach using Balint's idea. >>
287 // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
289 // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
290 if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
292 final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
293 new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
294 // Add a vertex for each match found by all ClusterMatchers
295 // And maintain an array to keep track of what cluster matcher each vertex corresponds to
296 final List<Vertex>[] vertices = new List[pendingMatches.length];
297 for (int i = 0; i < pendingMatches.length; i++) {
298 vertices[i] = new ArrayList<>();
299 for (List<PcapPacket> sequence : pendingMatches[i]) {
300 Vertex v = new Vertex(sequence);
301 vertices[i].add(v); // retain reference for later when we are to add edges
302 graph.addVertex(v); // add to vertex to graph
305 // Add dummy source and sink vertices to facilitate search.
306 final Vertex source = new Vertex(null);
307 final Vertex sink = new Vertex(null);
308 graph.addVertex(source);
309 graph.addVertex(sink);
310 // The source is connected to all vertices that wrap the sequences detected by Layer3ClusterMatcher at index 0.
311 // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
312 for (Vertex v : vertices[0]) {
313 DefaultWeightedEdge edge = graph.addEdge(source, v);
314 graph.setEdgeWeight(edge, 0.0);
316 // Similarly, all vertices that wrap the sequences detected by the last Layer3ClusterMatcher of the signature
317 // are connected to the sink node.
318 for (Vertex v : vertices[vertices.length-1]) {
319 DefaultWeightedEdge edge = graph.addEdge(v, sink);
320 graph.setEdgeWeight(edge, 0.0);
322 // Now link sequences detected by Layer3ClusterMatcher at index i to sequences detected by Layer3ClusterMatcher at index
323 // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
324 for (int i = 0; i < vertices.length; i++) {
326 if (j < vertices.length) {
327 for (Vertex iv : vertices[i]) {
328 PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
329 for (Vertex jv : vertices[j]) {
330 PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
331 if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
332 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
333 // The weight is the duration of the i'th sequence plus the duration between the i'th
334 // and i+1'th sequence.
335 Duration d = Duration.
336 between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
337 // Unfortunately weights are double values, so must convert from long to double.
338 // TODO: need nano second precision? If so, use d.toNanos().
339 // TODO: risk of overflow when converting from long to double..?
340 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
342 // Alternative version if we cannot assume that sequences are ordered by timestamp:
343 // if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
344 // .getTimestamp().isBefore(jv.sequence.stream().min(
345 // Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
352 // Graph construction complete, run shortest-path to find a (potential) signature match.
353 DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
354 GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
355 if (shortestPath != null) {
356 // The total weight is the duration between the first packet of the first sequence and the last packet
357 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
358 // the signature to span. For now we just use the inclusion window we defined for training purposes.
359 // Note however, that we must convert back from double to long as the weight is stored as a double in
361 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
362 // There's a signature match!
363 // Extract the match from the vertices
364 List<List<PcapPacket>> signatureMatch = new ArrayList<>();
365 for(Vertex v : shortestPath.getVertexList()) {
366 if (v == source || v == sink) {
367 // Skip the dummy source and sink nodes.
370 signatureMatch.add(v.sequence);
371 // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
372 // the sequence we've "consumed" for index i of the matched signature is also at index i in
373 // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
374 // another signature match in a later call.
375 pendingMatches[signatureMatch.size()-1].remove(v.sequence);
377 // Declare success: notify observers
378 mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
379 Collections.unmodifiableList(signatureMatch)));
386 * Used for registering for notifications of signatures detected by a {@link Layer3SignatureDetector}.
388 interface SignatureDetectionObserver {
391 * Invoked when the {@link Layer3SignatureDetector} detects the presence of a signature in the traffic that it's
393 * @param searchedSignature The signature that the {@link Layer3SignatureDetector} reporting the match is searching
395 * @param matchingTraffic The actual traffic trace that matches the searched signature.
397 void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
398 List<List<PcapPacket>> matchingTraffic);
402 * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
403 * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
404 * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
405 * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
406 * recognize two lists that contain the same items--from a value and not reference point of view--as the same
407 * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
410 private static class Vertex {
411 private final List<PcapPacket> sequence;
412 private Vertex(List<PcapPacket> wrappedSequence) {
413 sequence = wrappedSequence;