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