Update DetectionResultsAnalyzer to also print results to a file. Convert Layer2Signat...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2SignatureDetector.java
1 package edu.uci.iotproject.detection.layer2;
2
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.Layer2FlowReassembler;
11 import edu.uci.iotproject.util.PrintUtils;
12 import org.jgrapht.GraphPath;
13 import org.jgrapht.alg.shortestpath.DijkstraShortestPath;
14 import org.jgrapht.graph.DefaultWeightedEdge;
15 import org.jgrapht.graph.SimpleDirectedWeightedGraph;
16 import org.pcap4j.core.*;
17
18 import java.io.File;
19 import java.io.FileWriter;
20 import java.io.IOException;
21 import java.io.PrintWriter;
22 import java.time.Duration;
23 import java.util.*;
24
25 /**
26  * Performs layer 2 signature detection.
27  *
28  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
29  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
30  */
31 public class Layer2SignatureDetector implements PacketListener, ClusterMatcherObserver {
32
33     /**
34      * If set to {@code true}, output written to the results file is also dumped to standard out.
35      */
36     private static boolean DUPLICATE_OUTPUT_TO_STD_OUT = true;
37
38     public static void main(String[] args) throws PcapNativeException, NotOpenException, IOException {
39         if (args.length < 4) {
40             String errMsg = String.format("Usage: %s inputPcapFile onSignatureFile offSignatureFile resultsFile [stdOut]" +
41                             "\n - inputPcapFile: the target of the detection" +
42                             "\n - onSignatureFile: the file that contains the ON signature to search for" +
43                             "\n - offSignatureFile: the file that contains the OFF signature to search for" +
44                             "\n - resultsFile: where to write the results of the detection" +
45                             "\n - stdOut: optional true/false literal indicating if output should also be printed to std out; default is true",
46                     Layer2SignatureDetector.class.getSimpleName());
47             System.out.println(errMsg);
48             return;
49         }
50         final String pcapFile = args[0];
51         final String onSignatureFile = args[1];
52         final String offSignatureFile = args[2];
53         final String resultsFile = args[3];
54         if (args.length == 5) {
55             DUPLICATE_OUTPUT_TO_STD_OUT = Boolean.parseBoolean(args[4]);
56         }
57
58         // Prepare file outputter.
59         File outputFile = new File(resultsFile);
60         outputFile.getParentFile().mkdirs();
61         final PrintWriter resultsWriter = new PrintWriter(new FileWriter(outputFile));
62         // Include metadata as comments at the top
63         PrintWriterUtils.println("# Detection results for:", resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
64         PrintWriterUtils.println("# - inputPcapFile: " + pcapFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
65         PrintWriterUtils.println("# - onSignatureFile: " + onSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
66         PrintWriterUtils.println("# - onSignatureFile: " + offSignatureFile, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
67         resultsWriter.flush();
68
69         // Create signature detectors and add observers that output their detected events.
70         Layer2SignatureDetector onDetector = new Layer2SignatureDetector(PrintUtils.deserializeSignatureFromFile(onSignatureFile));
71         Layer2SignatureDetector offDetector = new Layer2SignatureDetector(PrintUtils.deserializeSignatureFromFile(offSignatureFile));
72         onDetector.addObserver((signature, match) -> {
73             UserAction event = new UserAction(UserAction.Type.TOGGLE_ON, match.get(0).get(0).getTimestamp());
74             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
75         });
76         offDetector.addObserver((signature, match) -> {
77             UserAction event = new UserAction(UserAction.Type.TOGGLE_OFF, match.get(0).get(0).getTimestamp());
78             PrintWriterUtils.println(event, resultsWriter, DUPLICATE_OUTPUT_TO_STD_OUT);
79         });
80
81         // Load the PCAP file
82         PcapHandle handle;
83         try {
84             handle = Pcaps.openOffline(pcapFile, PcapHandle.TimestampPrecision.NANO);
85         } catch (PcapNativeException pne) {
86             handle = Pcaps.openOffline(pcapFile);
87         }
88         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, onDetector, offDetector);
89         // Parse the file
90         reader.readFromHandle();
91
92         // Flush output to results file and close it.
93         resultsWriter.flush();
94         resultsWriter.close();
95     }
96
97     /**
98      * The signature that this {@link Layer2SignatureDetector} is searching for.
99      */
100     private final List<List<List<PcapPacket>>> mSignature;
101
102     /**
103      * The {@link Layer2ClusterMatcher}s in charge of detecting each individual sequence of packets that together make
104      * up the the signature.
105      */
106     private final List<Layer2ClusterMatcher> mClusterMatchers;
107
108     /**
109      * For each {@code i} ({@code i >= 0 && i < mPendingMatches.length}), {@code mPendingMatches[i]} holds the matches
110      * found by the {@link Layer2ClusterMatcher} at {@code mClusterMatchers.get(i)} that have yet to be "consumed",
111      * i.e., have yet to be included in a signature detected by this {@link Layer2SignatureDetector} (a signature can
112      * be encompassed of multiple packet sequences occurring shortly after one another on multiple connections).
113      */
114     private final List<List<PcapPacket>>[] mPendingMatches;
115
116     /**
117      * Maps a {@link Layer2ClusterMatcher} to its corresponding index in {@link #mPendingMatches}.
118      */
119     private final Map<Layer2ClusterMatcher, Integer> mClusterMatcherIds;
120
121     /**
122      * In charge of reassembling layer 2 packet flows.
123      */
124     private final Layer2FlowReassembler mFlowReassembler = new Layer2FlowReassembler();
125
126     private final List<SignatureDetectorObserver> mObservers = new ArrayList<>();
127
128     public Layer2SignatureDetector(List<List<List<PcapPacket>>> searchedSignature) {
129         mSignature = Collections.unmodifiableList(searchedSignature);
130         List<Layer2ClusterMatcher> clusterMatchers = new ArrayList<>();
131         for (List<List<PcapPacket>> cluster : mSignature) {
132             Layer2ClusterMatcher clusterMatcher = new Layer2ClusterMatcher(cluster);
133             clusterMatcher.addObserver(this);
134             clusterMatchers.add(clusterMatcher);
135         }
136         mClusterMatchers = Collections.unmodifiableList(clusterMatchers);
137         mPendingMatches = new List[mClusterMatchers.size()];
138         for (int i = 0; i < mPendingMatches.length; i++) {
139             mPendingMatches[i] = new ArrayList<>();
140         }
141         Map<Layer2ClusterMatcher, Integer> clusterMatcherIds = new HashMap<>();
142         for (int i = 0; i < mClusterMatchers.size(); i++) {
143             clusterMatcherIds.put(mClusterMatchers.get(i), i);
144         }
145         mClusterMatcherIds = Collections.unmodifiableMap(clusterMatcherIds);
146         // Register all cluster matchers to receive a notification whenever a new flow is encountered.
147         mClusterMatchers.forEach(cm -> mFlowReassembler.addObserver(cm));
148     }
149
150
151     @Override
152     public void gotPacket(PcapPacket packet) {
153         // Forward packet processing to the flow reassembler that in turn notifies the cluster matchers as appropriate
154         mFlowReassembler.gotPacket(packet);
155     }
156
157     @Override
158     public void onMatch(AbstractClusterMatcher clusterMatcher, List<PcapPacket> match) {
159         // TODO: a cluster matcher found a match
160         if (clusterMatcher instanceof Layer2ClusterMatcher) {
161             // Add the match at the corresponding index
162             mPendingMatches[mClusterMatcherIds.get(clusterMatcher)].add(match);
163             checkSignatureMatch();
164         }
165     }
166
167     public void addObserver(SignatureDetectorObserver observer) {
168         mObservers.add(observer);
169     }
170
171     public boolean removeObserver(SignatureDetectorObserver observer) {
172         return mObservers.remove(observer);
173     }
174
175
176     @SuppressWarnings("Duplicates")
177     private void checkSignatureMatch() {
178         // << Graph-based approach using Balint's idea. >>
179         // This implementation assumes that the packets in the inner lists (the sequences) are ordered by asc timestamp.
180
181         // There cannot be a signature match until each Layer3ClusterMatcher has found a match of its respective sequence.
182         if (Arrays.stream(mPendingMatches).noneMatch(l -> l.isEmpty())) {
183             // Construct the DAG
184             final SimpleDirectedWeightedGraph<Vertex, DefaultWeightedEdge> graph =
185                     new SimpleDirectedWeightedGraph<>(DefaultWeightedEdge.class);
186             // Add a vertex for each match found by all cluster matchers.
187             // And maintain an array to keep track of what cluster matcher each vertex corresponds to
188             final List<Vertex>[] vertices = new List[mPendingMatches.length];
189             for (int i = 0; i < mPendingMatches.length; i++) {
190                 vertices[i] = new ArrayList<>();
191                 for (List<PcapPacket> sequence : mPendingMatches[i]) {
192                     Vertex v = new Vertex(sequence);
193                     vertices[i].add(v); // retain reference for later when we are to add edges
194                     graph.addVertex(v); // add to vertex to graph
195                 }
196             }
197             // Add dummy source and sink vertices to facilitate search.
198             final Vertex source = new Vertex(null);
199             final Vertex sink = new Vertex(null);
200             graph.addVertex(source);
201             graph.addVertex(sink);
202             // The source is connected to all vertices that wrap the sequences detected by cluster matcher at index 0.
203             // Note: zero cost edges as this is just a dummy link to facilitate search from a common start node.
204             for (Vertex v : vertices[0]) {
205                 DefaultWeightedEdge edge = graph.addEdge(source, v);
206                 graph.setEdgeWeight(edge, 0.0);
207             }
208             // Similarly, all vertices that wrap the sequences detected by the last cluster matcher of the signature
209             // are connected to the sink node.
210             for (Vertex v : vertices[vertices.length-1]) {
211                 DefaultWeightedEdge edge = graph.addEdge(v, sink);
212                 graph.setEdgeWeight(edge, 0.0);
213             }
214             // Now link sequences detected by the cluster matcher at index i to sequences detected by the cluster
215             // matcher at index i+1 if they obey the timestamp constraint (i.e., that the latter is later in time than
216             // the former).
217             for (int i = 0; i < vertices.length; i++) {
218                 int j = i + 1;
219                 if (j < vertices.length) {
220                     for (Vertex iv : vertices[i]) {
221                         PcapPacket ivLast = iv.sequence.get(iv.sequence.size()-1);
222                         for (Vertex jv : vertices[j]) {
223                             PcapPacket jvFirst = jv.sequence.get(jv.sequence.size()-1);
224                             if (ivLast.getTimestamp().isBefore(jvFirst.getTimestamp())) {
225                                 DefaultWeightedEdge edge = graph.addEdge(iv, jv);
226                                 // The weight is the duration of the i'th sequence plus the duration between the i'th
227                                 // and i+1'th sequence.
228                                 Duration d = Duration.
229                                         between(iv.sequence.get(0).getTimestamp(), jvFirst.getTimestamp());
230                                 // Unfortunately weights are double values, so must convert from long to double.
231                                 // TODO: need nano second precision? If so, use d.toNanos().
232                                 // TODO: risk of overflow when converting from long to double..?
233                                 graph.setEdgeWeight(edge, Long.valueOf(d.toMillis()).doubleValue());
234                             }
235                             // Alternative version if we cannot assume that sequences are ordered by timestamp:
236 //                            if (iv.sequence.stream().max(Comparator.comparing(PcapPacket::getTimestamp)).get()
237 //                                    .getTimestamp().isBefore(jv.sequence.stream().min(
238 //                                            Comparator.comparing(PcapPacket::getTimestamp)).get().getTimestamp())) {
239 //
240 //                            }
241                         }
242                     }
243                 }
244             }
245             // Graph construction complete, run shortest-path to find a (potential) signature match.
246             DijkstraShortestPath<Vertex, DefaultWeightedEdge> dijkstra = new DijkstraShortestPath<>(graph);
247             GraphPath<Vertex, DefaultWeightedEdge> shortestPath = dijkstra.getPath(source, sink);
248             if (shortestPath != null) {
249                 // The total weight is the duration between the first packet of the first sequence and the last packet
250                 // of the last sequence, so we simply have to compare the weight against the timeframe that we allow
251                 // the signature to span. For now we just use the inclusion window we defined for training purposes.
252                 // Note however, that we must convert back from double to long as the weight is stored as a double in
253                 // JGraphT's API.
254                 if (((long)shortestPath.getWeight()) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
255                     // There's a signature match!
256                     // Extract the match from the vertices
257                     List<List<PcapPacket>> signatureMatch = new ArrayList<>();
258                     for(Vertex v : shortestPath.getVertexList()) {
259                         if (v == source || v == sink) {
260                             // Skip the dummy source and sink nodes.
261                             continue;
262                         }
263                         signatureMatch.add(v.sequence);
264                         // As there is a one-to-one correspondence between vertices[] and pendingMatches[], we know that
265                         // the sequence we've "consumed" for index i of the matched signature is also at index i in
266                         // pendingMatches. We must remove it from pendingMatches so that we don't use it to construct
267                         // another signature match in a later call.
268                         mPendingMatches[signatureMatch.size()-1].remove(v.sequence);
269                     }
270                     // Declare success: notify observers
271                     mObservers.forEach(obs -> obs.onSignatureDetected(mSignature,
272                             Collections.unmodifiableList(signatureMatch)));
273                 }
274             }
275         }
276     }
277
278     /**
279      * Encapsulates a {@code List<PcapPacket>} so as to allow the list to be used as a vertex in a graph while avoiding
280      * the expensive {@link AbstractList#equals(Object)} calls when adding vertices to the graph.
281      * Using this wrapper makes the incurred {@code equals(Object)} calls delegate to {@link Object#equals(Object)}
282      * instead of {@link AbstractList#equals(Object)}. The net effect is a faster implementation, but the graph will not
283      * recognize two lists that contain the same items--from a value and not reference point of view--as the same
284      * vertex. However, this is fine for our purposes -- in fact restricting it to reference equality seems more
285      * appropriate.
286      */
287     private static class Vertex {
288         private final List<PcapPacket> sequence;
289         private Vertex(List<PcapPacket> wrappedSequence) {
290             sequence = wrappedSequence;
291         }
292     }
293 }