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