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