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 * TODO: The following was the router address for EH (Networking Lab)
47 * private static String ROUTER_WAN_IP = "128.195.205.105";
49 private static String ROUTER_WAN_IP = "128.195.55.242";
51 public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
52 String errMsg = String.format("SPECTO version 1.0\n" +
53 "Copyright (C) 2018-2019 Janus Varmarken and Rahmadi Trimananda.\n" +
54 "University of California, Irvine.\n" +
55 "All rights reserved.\n\n" +
56 "Usage: %s inputPcapFile onAnalysisFile offAnalysisFile onSignatureFile offSignatureFile resultsFile" +
57 "\n inputPcapFile: the target of the detection" +
58 "\n onAnalysisFile: the file that contains the ON clusters analysis" +
59 "\n offAnalysisFile: the file that contains the OFF clusters analysis" +
60 "\n onSignatureFile: the file that contains the ON signature to search for" +
61 "\n offSignatureFile: the file that contains the OFF signature to search for" +
62 "\n resultsFile: where to write the results of the detection" +
63 "\n signatureDuration: the maximum duration of signature detection" +
64 "\n epsilon: the epsilon value for the DBSCAN algorithm\n" +
65 "\n Additional options (add '-r' before the following two parameters):" +
66 "\n delta: delta for relaxed matching" +
67 "\n packetId: packet number in the sequence" +
68 "\n (could be more than one packet whose matching is relaxed, " +
69 "\n e.g., 0,1 for packets 0 and 1)",
70 Layer3SignatureDetector.class.getSimpleName());
71 if (args.length < 8) {
72 System.out.println(errMsg);
75 final String pcapFile = args[0];
76 final String onClusterAnalysisFile = args[1];
77 final String offClusterAnalysisFile = args[2];
78 final String onSignatureFile = args[3];
79 final String offSignatureFile = args[4];
80 final String resultsFile = args[5];
81 // TODO: THIS IS TEMPORARILY SET TO DEFAULT SIGNATURE DURATION
82 // TODO: WE DO NOT WANT TO BE TOO STRICT AT THIS POINT SINCE LAYER 3 ALREADY APPLIES BACK-TO-BACK REQUIREMENT
83 // TODO: FOR PACKETS IN A SIGNATURE
84 // final int signatureDuration = Integer.parseInt(args[6]);
85 final int signatureDuration = TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS;
86 final double eps = Double.parseDouble(args[7]);
87 // Additional feature---relaxed matching
89 final Set<Integer> packetSet = new HashSet<>();
90 if (args.length == 11 && args[8].equals("-r")) {
91 delta = Integer.parseInt(args[9]);
92 StringTokenizer stringTokenizerOff = new StringTokenizer(args[10], ",");
93 // Add the list of packet IDs
94 while(stringTokenizerOff.hasMoreTokens()) {
95 int id = Integer.parseInt(stringTokenizerOff.nextToken());
99 // Prepare file outputter.
100 File outputFile = new File(resultsFile);
101 outputFile.getParentFile().mkdirs();
102 final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
103 // Include metadata as comments at the top
104 PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
105 PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
106 PrintWriterUtils.println("# - onAnalysisFile: " + onClusterAnalysisFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
107 PrintWriterUtils.println("# - offAnalysisFile: " + offClusterAnalysisFile, 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();
113 List<List<List<PcapPacket>>> onSignature = PrintUtils.deserializeFromFile(onSignatureFile);
114 List<List<List<PcapPacket>>> offSignature = PrintUtils.deserializeFromFile(offSignatureFile);
115 // Load signature analyses
116 List<List<List<PcapPacket>>> onClusterAnalysis = PrintUtils.deserializeFromFile(onClusterAnalysisFile);
117 List<List<List<PcapPacket>>> offClusterAnalysis = PrintUtils.deserializeFromFile(offClusterAnalysisFile);
119 // TODO: FOR NOW WE DECIDE PER SIGNATURE AND THEN WE OR THE BOOLEANS
120 // TODO: SINCE WE ONLY HAVE 2 SIGNATURES FOR NOW (ON AND OFF), THEN IT IS USUALLY EITHER RANGE-BASED OR
121 // TODO: STRICT MATCHING
122 // Check if we should use range-based matching
123 boolean isRangeBasedForOn = PcapPacketUtils.isRangeBasedMatching(onSignature, eps, offSignature);
124 boolean isRangeBasedForOff = PcapPacketUtils.isRangeBasedMatching(offSignature, eps, onSignature);
125 // Update the signature with ranges if it is range-based
126 if (isRangeBasedForOn) {
127 onSignature = PcapPacketUtils.useRangeBasedMatching(onSignature, onClusterAnalysis);
129 if (isRangeBasedForOff) {
130 offSignature = PcapPacketUtils.useRangeBasedMatching(offSignature, offClusterAnalysis);
133 Layer3SignatureDetector onDetector = new Layer3SignatureDetector(onSignature, ROUTER_WAN_IP,
134 signatureDuration, isRangeBasedForOn, eps, delta, packetSet);
135 Layer3SignatureDetector offDetector = new Layer3SignatureDetector(offSignature, ROUTER_WAN_IP,
136 signatureDuration, isRangeBasedForOff, eps, delta, packetSet);
138 final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).
139 withLocale(Locale.US).withZone(ZoneId.of("America/Los_Angeles"));
141 // Outputs information about a detected event to std.out
142 final Consumer<UserAction> outputter = ua -> {
143 String eventDescription;
144 switch (ua.getType()) {
146 eventDescription = "ON";
149 eventDescription = "OFF";
152 throw new AssertionError("unhandled event type");
154 // TODO: Uncomment the following if we want the old style print-out messages
155 // String output = String.format("%s",
156 // dateTimeFormatter.format(ua.getTimestamp()));
157 // System.out.println(output);
158 PrintWriterUtils.println(ua, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
161 // Let's create observers that construct a UserAction representing the detected event.
162 final List<UserAction> detectedEvents = new ArrayList<>();
163 onDetector.addObserver((searched, match) -> {
164 PcapPacket firstPkt = match.get(0).get(0);
165 UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, firstPkt.getTimestamp());
166 detectedEvents.add(event);
168 offDetector.addObserver((searched, match) -> {
169 PcapPacket firstPkt = match.get(0).get(0);
170 UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, firstPkt.getTimestamp());
171 //PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
172 detectedEvents.add(event);
177 handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
178 } catch (PcapNativeException pne) {
179 handle = Pcaps.openOffline(pcapFile);
181 PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
182 reader.readFromHandle();
184 // TODO: need a better way of triggering detection than this...
185 if (isRangeBasedForOn) {
186 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
188 onDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
190 if (isRangeBasedForOff) {
191 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionRangeBased());
193 offDetector.mClusterMatchers.forEach(cm -> cm.performDetectionConservative());
196 // Sort the list of detected events by timestamp to make it easier to compare it line-by-line with the trigger
198 Collections.sort(detectedEvents, Comparator.comparing(UserAction::getTimestamp));
200 // Output the detected events
201 detectedEvents.forEach(outputter);
203 String resultOn = "# Number of detected events of type " + UserAction.Type.TOGGLE_ON + ": " +
204 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_ON).count();
205 String resultOff = "# Number of detected events of type " + UserAction.Type.TOGGLE_OFF + ": " +
206 detectedEvents.stream().filter(ua -> ua.getType() == UserAction.Type.TOGGLE_OFF).count();
207 PrintWriterUtils.println(resultOn, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
208 PrintWriterUtils.println(resultOff, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
210 // Flush output to results file and close it.
211 resultsWriter.flush();
212 resultsWriter.close();
213 // TODO: Temporary clean up until we clean the pipeline
214 // List<UserAction> cleanedDetectedEvents = SignatureDetector.removeDuplicates(detectedEvents);
215 // cleanedDetectedEvents.forEach(outputter);
219 * The signature that this {@link Layer3SignatureDetector} is searching for.
221 private final List<List<List<PcapPacket>>> mSignature;
224 * The {@link Layer3ClusterMatcher}s in charge of detecting each individual sequence of packets that together make up the
227 private final List<Layer3ClusterMatcher> mClusterMatchers;
230 * For each {@code i} ({@code i >= 0 && i < pendingMatches.length}), {@code pendingMatches[i]} holds the matches
231 * found by the {@link Layer3ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed", i.e.,
232 * have yet to be included in a signature detected by this {@link Layer3SignatureDetector} (a signature can be encompassed
233 * of multiple packet sequences occurring shortly after one another on multiple connections).
235 private final List<List<PcapPacket>>[] pendingMatches;
238 * Maps a {@link Layer3ClusterMatcher} to its corresponding index in {@link #pendingMatches}.
240 private final Map<Layer3ClusterMatcher, Integer> mClusterMatcherIds;
242 private final List<SignatureDetectionObserver> mObservers = new ArrayList<>();
244 private int mInclusionTimeMillis;
247 * Remove duplicates in {@code List} of {@code UserAction} objects. We need to clean this up for user actions
248 * that appear multiple times.
249 * TODO: This static method is probably just for temporary and we could get rid of this after we clean up
252 * @param listUserAction A {@link List} of {@code UserAction}.
255 public static List<UserAction> removeDuplicates(List<UserAction> listUserAction) {
257 // Iterate and check for duplicates (check timestamps)
258 Set<Long> epochSecondSet = new HashSet<>();
259 // Create a target list for cleaned up list
260 List<UserAction> listUserActionClean = new ArrayList<>();
261 for(UserAction userAction : listUserAction) {
262 // Don't insert if any duplicate is found
263 if(!epochSecondSet.contains(userAction.getTimestamp().getEpochSecond())) {
264 listUserActionClean.add(userAction);
265 epochSecondSet.add(userAction.getTimestamp().getEpochSecond());
268 return listUserActionClean;
271 public Layer3SignatureDetector(List<List<List<PcapPacket>>> searchedSignature, String routerWanIp,
272 int inclusionTimeMillis, boolean isRangeBased, double eps,
273 int delta, Set<Integer> packetSet) {
274 // note: doesn't protect inner lists from changes :'(
275 mSignature = Collections.unmodifiableList(searchedSignature);
276 // Generate corresponding/appropriate ClusterMatchers based on the provided signature
277 List<Layer3ClusterMatcher> clusterMatchers = new ArrayList<>();
278 for (List<List<PcapPacket>> cluster : mSignature) {
279 clusterMatchers.add(new Layer3ClusterMatcher(cluster, routerWanIp, inclusionTimeMillis,
280 isRangeBased, eps, delta, packetSet, this));
282 mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
285 pendingMatches = new List[mClusterMatchers.size()];
286 for (int i = 0; i < pendingMatches.length; i++) {
287 pendingMatches[i] = new ArrayList<>();
289 Map<Layer3ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
290 for (int i = 0; i < mClusterMatchers.size(); i++) {
291 clusterMatcherIds.put(mClusterMatchers.get(i), i);
293 mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
294 mInclusionTimeMillis =
295 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
298 public void addObserver(SignatureDetectionObserver observer) {
299 mObservers.add(observer);
302 public boolean removeObserver(SignatureDetectionObserver observer) {
303 return mObservers.remove(observer);
307 public void gotPacket(PcapPacket packet) {
308 // simply delegate packet reception to all ClusterMatchers.
309 mClusterMatchers.forEach(cm -> cm.gotPacket(packet));
313 public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
314 // Add the match at the corresponding index
315 pendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
316 checkSignatureMatch();
319 private void checkSignatureMatch() {
320 // << Graph-based approach using Balint's idea. >>
321 // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
323 // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
324 if (Arrays.stream(pendingMatches).noneMatch(l -> l.isEmpty())) {
326 final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
327 new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
328 // Add a vertex for each match found by all ClusterMatchers
329 // And maintain an array to keep track of what cluster matcher each vertex corresponds to
330 final List<Vertex>[] vertices = new List[pendingMatches.length];
331 for (int i = 0; i < pendingMatches.length; i++) {
332 vertices[i] = new ArrayList<>();
333 for (List<PcapPacket> sequence : pendingMatches[i]) {
334 Vertex v = new Vertex(sequence);
335 vertices[i].add(v); // retain reference for later when we are to add edges
336 graph.addVertex(v); // add to vertex to graph
339 // Add dummy source and sink vertices to facilitate search.
340 final Vertex source = new Vertex(null);
341 final Vertex sink = new Vertex(null);
342 graph.addVertex(source);
343 graph.addVertex(sink);
344 // The source is connected to all vertices that wrap the sequences detected by Layer3ClusterMatcher at index 0.
345 // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
346 for (Vertex v : vertices[0]) {
347 DefaultWeightedEdge edge = graph.addEdge(source, v);
348 graph.setEdgeWeight(edge, 0.0);
350 // Similarly, all vertices that wrap the sequences detected by the last Layer3ClusterMatcher of the signature
351 // are connected to the sink node.
352 for (Vertex v : vertices[vertices.length-1]) {
353 DefaultWeightedEdge edge = graph.addEdge(v, sink);
354 graph.setEdgeWeight(edge, 0.0);
356 // Now link sequences detected by Layer3ClusterMatcher at index i to sequences detected by Layer3ClusterMatcher at index
357 // i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than the former).
358 for (int i = 0; i < vertices.length; i++) {
360 if (j < vertices.length) {
361 for (Vertex iv : vertices[i]) {
362 PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
363 for (Vertex jv : vertices[j]) {
364 PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
365 if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
366 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
367 // The weight is the duration of the i'th sequence plus the duration between the i'th
368 // and i+1'th sequence.
369 Duration d = Duration.
370 between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
371 // Unfortunately weights are double values, so must convert from long to double.
372 // TODO: need nano second precision? If so, use d.toNanos().
373 // TODO: risk of overflow when converting from long to double..?
374 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
376 // Alternative version if we cannot assume that sequences are ordered by timestamp:
377 // if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
378 // .getTimestamp().isBefore(jv.sequence.stream().min(
379 // Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
386 // Graph construction complete, run shortest-path to find a (potential) signature match.
387 DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
388 GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
389 if (shortestPath != null) {
390 // The total weight is the duration between the first packet of the first sequence and the last packet
391 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
392 // the signature to span. For now we just use the inclusion window we defined for training purposes.
393 // Note however, that we must convert back from double to long as the weight is stored as a double in
395 if (((long)shortestPath.getWeight()) < mInclusionTimeMillis) {
396 // There's a signature match!
397 // Extract the match from the vertices
398 List<List<PcapPacket>> signatureMatch = new ArrayList<>();
399 for(Vertex v : shortestPath.getVertexList()) {
400 if (v == source || v == sink) {
401 // Skip the dummy source and sink nodes.
404 signatureMatch.add(v.sequence);
405 // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
406 // the sequence we've "consumed" for index i of the matched signature is also at index i in
407 // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
408 // another signature match in a later call.
409 pendingMatches[signatureMatch.size()-1].remove(v.sequence);
411 // Declare success: notify observers
412 mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
413 Collections.unmodifiableList(signatureMatch)));
420 * Used for registering for notifications of signatures detected by a {@link Layer3SignatureDetector}.
422 interface SignatureDetectionObserver {
425 * Invoked when the {@link Layer3SignatureDetector} detects the presence of a signature in the traffic that it's
427 * @param searchedSignature The signature that the {@link Layer3SignatureDetector} reporting the match is searching
429 * @param matchingTraffic The actual traffic trace that matches the searched signature.
431 void onSignatureDetected(List<List<List<PcapPacket>>> searchedSignature,
432 List<List<PcapPacket>> matchingTraffic);
436 * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
437 * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
438 * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
439 * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
440 * recognize two lists that contain the same items--from a value and not reference point of view--as the same
441 * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
444 private static class Vertex {
445 private final List<PcapPacket> sequence;
446 private Vertex(List<PcapPacket> wrappedSequence) {
447 sequence = wrappedSequence;