Adding a method to delete a bad sequence in a signature after we test the produced...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / ClusterMatcher.java
1 package edu.uci.iotproject.detection;
2
3 import edu.uci.iotproject.Conversation;
4 import edu.uci.iotproject.TcpReassembler;
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.io.PcapHandleReader;
7 import edu.uci.iotproject.util.PrintUtils;
8 import org.pcap4j.core.*;
9
10 import java.time.ZoneId;
11 import java.util.*;
12 import java.util.stream.Collectors;
13
14 import static edu.uci.iotproject.util.PcapPacketUtils.*;
15
16 /**
17  * Searches a traffic trace for sequences of packets "belong to" a given cluster (in other words, attempts to classify
18  * traffic as pertaining to a given cluster).
19  *
20  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
21  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
22  */
23 public class ClusterMatcher implements PacketListener {
24
25     // Test client
26     public static void main(String[] args) throws PcapNativeException, NotOpenException {
27
28 //        String path = "/scratch/July-2018"; // Rahmadi
29         String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
30         final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
31         final String signatureFile = path + "/2018-07/dlink/offSignature1.sig";
32
33         List<List<PcapPacket>> signature = PrintUtils.deserializeClustersFromFile(signatureFile);
34         ClusterMatcher clusterMatcher = new ClusterMatcher(signature, null,
35                 (sig, match) -> System.out.println(
36                         String.format("[ !!! SIGNATURE DETECTED AT %s !!! ]",
37                                 match.get(0).getTimestamp().atZone(ZoneId.of("America/Los_Angeles")))
38                 )
39         );
40
41         PcapHandle handle;
42         try {
43             handle = Pcaps.openOffline(inputPcapFile, PcapHandle.TimestampPrecision.NANO);
44         } catch (PcapNativeException pne) {
45             handle = Pcaps.openOffline(inputPcapFile);
46         }
47         PcapHandleReader reader = new PcapHandleReader(handle, p -> true, clusterMatcher);
48         reader.readFromHandle();
49         clusterMatcher.performDetection();
50     }
51
52     /**
53      * The cluster that describes the sequence of packets that this {@link ClusterMatcher} is trying to detect in the
54      * observed traffic.
55      */
56     private final List<List<PcapPacket>> mCluster;
57
58     /**
59      * The ordered directions of packets in the sequences that make up {@link #mCluster}.
60      */
61     private final Conversation.Direction[] mClusterMemberDirections;
62
63     /**
64      * For reassembling the observed traffic into TCP connections.
65      */
66     private final TcpReassembler mTcpReassembler = new TcpReassembler();
67
68     /**
69      * IP of the router's WAN port (if analyzed traffic is captured at the ISP's point of view).
70      */
71     private final String mRouterWanIp;
72
73     private final ClusterMatchObserver[] mObservers;
74
75     /**
76      * Create a {@link ClusterMatcher}.
77      * @param cluster The cluster that traffic is matched against.
78      * @param routerWanIp The router's WAN IP if examining traffic captured at the ISP's point of view (used for
79      *                    determining the direction of packets).
80      * @param detectionObservers Client code that wants to get notified whenever the {@link ClusterMatcher} detects that
81      *                          (a subset of) the examined traffic is similar to the traffic that makes up
82      *                          {@code cluster}, i.e., when the examined traffic is classified as pertaining to
83      *                          {@code cluster}.
84      */
85     public ClusterMatcher(List<List<PcapPacket>> cluster, String routerWanIp, ClusterMatchObserver... detectionObservers) {
86         mCluster = Collections.unmodifiableList(Objects.requireNonNull(cluster, "cluster cannot be null"));
87         mObservers = Objects.requireNonNull(detectionObservers, "detectionObservers cannot be null");
88         if (mCluster.isEmpty() || mCluster.stream().anyMatch(inner -> inner.isEmpty())) {
89             throw new IllegalArgumentException("cluster is empty (or contains an empty inner List)");
90         }
91         if (mObservers.length == 0) {
92             throw new IllegalArgumentException("no detectionObservers provided");
93         }
94         mRouterWanIp = routerWanIp;
95         // Build the cluster members' direction sequence.
96         // Note: assumes that the provided cluster was captured within the local network (routerWanIp is set to null).
97         mClusterMemberDirections = getPacketDirections(mCluster.get(0), null);
98         /*
99          * Enforce restriction on cluster members: all representatives must exhibit the same direction pattern and
100          * contain the same number of packets. Note that this is a somewhat heavy operation, so it may be disabled later
101          * on in favor of performance. However, it is only run once (at instantiation), so the overhead may be warranted
102          * in order to ensure correctness, especially during the development/debugging phase.
103          */
104         if (mCluster.stream().
105                 anyMatch(inner -> !Arrays.equals(mClusterMemberDirections, getPacketDirections(inner, null)))) {
106             throw new IllegalArgumentException(
107                     "cluster members must contain the same number of packets and exhibit the same packet direction " +
108                             "pattern"
109             );
110         }
111     }
112
113     @Override
114     public void gotPacket(PcapPacket packet) {
115         // Present packet to TCP reassembler so that it can be mapped to a connection (if it is a TCP packet).
116         mTcpReassembler.gotPacket(packet);
117     }
118
119     /**
120      * Get the cluster that describes the packet sequence that this {@link ClusterMatcher} is searching for.
121      * @return the cluster that describes the packet sequence that this {@link ClusterMatcher} is searching for.
122      */
123     public List<List<PcapPacket>> getCluster() {
124         return mCluster;
125     }
126
127     public void performDetection() {
128         /*
129          * Let's start out simple by building a version that only works for signatures that do not span across multiple
130          * TCP conversations...
131          */
132         for (Conversation c : mTcpReassembler.getTcpConversations()) {
133             if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
134                 // Skip empty conversations.
135                 continue;
136             }
137             for (List<PcapPacket> signatureSequence : mCluster) {
138                 if (isTlsSequence(signatureSequence) != c.isTls()) {
139                     // We consider it a mismatch if one is a TLS application data sequence and the other is not.
140                     continue;
141                 }
142                 // Fetch set of packets to examine based on TLS or not.
143                 List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
144                 /*
145                  * Note: we embed the attempt to detect the signature sequence in a loop in order to capture those cases
146                  * where the same signature sequence appears multiple times in one Conversation.
147                  *
148                  * Note: as the cluster can be made up of identical sequences, we must keep track of whether we detected
149                  * a match and, if so, break the inner for-each loop in order to prevent raising an alarm for each
150                  * cluster-member (prevent duplicate detections of the same event). However, a negative side-effect of
151                  * this is that, in doing so, we will also skip searching for subsequent different cluster members in
152                  * the current conversation if the current cluster member is a match.
153                  *
154                  * Note: since we expect all sequences that together make up the signature to exhibit the same direction
155                  * pattern, we can simply pass the precomputed direction array for the signature sequence so that it
156                  * won't have to be recomputed internally in each call to findSubsequenceInSequence().
157                  */
158                 Optional<List<PcapPacket>> match;
159                 boolean matchFound = false;
160                 while ((match = findSubsequenceInSequence(signatureSequence, cPkts, mClusterMemberDirections, null)).
161                         isPresent()) {
162                     matchFound = true;
163                     List<PcapPacket> matchSeq = match.get();
164                     // Notify observers about the match.
165                     Arrays.stream(mObservers).forEach(o -> o.onMatch(ClusterMatcher.this, matchSeq));
166                     /*
167                      * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
168                      * signature sequence.
169                      */
170                     int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size()-1));
171                     // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
172                     cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
173                 }
174                 if (matchFound) {
175                     // Break inner for-each loop in order to avoid duplicate detection of same event (see comment above)
176                     break;
177                 }
178             }
179             /*
180              * TODO:
181              * if no item in cluster matches, also perform a distance-based matching to cover those cases where we did
182              * not manage to capture every single mutation of the sequence during training.
183              *
184              * Need to compute average/centroid of cluster to do so...? Compute within-cluster variance, then check if
185              * distance between input conversation and cluster average/centroid is smaller than or equal to the computed
186              * variance?
187              */
188         }
189     }
190
191     /**
192      * Checks if {@code sequence} is a sequence of TLS packets. Note: the current implementation relies on inspection
193      * of the port numbers when deciding between TLS vs. non-TLS. Therefore, only the first packet of {@code sequence}
194      * is examined as it is assumed that all packets in {@code sequence} pertain to the same {@link Conversation} and
195      * hence share the same set of two src/dst port numbers (albeit possibly alternating between which one is the src
196      * and which one is the dst, as packets in {@code sequence} may be in alternating directions).
197      * @param sequence The sequence of packets for which it is to be determined if it is a sequence of TLS packets or
198      *                 non-TLS packets.
199      * @return {@code true} if {@code sequence} is a sequence of TLS packets, {@code false} otherwise.
200      */
201     private boolean isTlsSequence(List<PcapPacket> sequence) {
202         // NOTE: Assumes ALL packets in sequence pertain to the same TCP connection!
203         PcapPacket firstPkt = sequence.get(0);
204         int srcPort = getSourcePort(firstPkt);
205         int dstPort = getDestinationPort(firstPkt);
206         return TcpConversationUtils.isTlsPort(srcPort) || TcpConversationUtils.isTlsPort(dstPort);
207     }
208
209     /**
210      * Examine if a given sequence of packets ({@code sequence}) contains a given shorter sequence of packets
211      * ({@code subsequence}). Note: the current implementation actually searches for a substring as it does not allow
212      * for interleaving packets in {@code sequence} that are not in {@code subsequence}; for example, if
213      * {@code subsequence} consists of packet lengths [2, 3, 5] and {@code sequence} consists of  packet lengths
214      * [2, 3, 4, 5], the result will be that there is no match (because of the interleaving 4). If we are to allow
215      * interleaving packets, we need a modified version of
216      * <a href="https://stackoverflow.com/a/20545604/1214974">this</a>.
217      *
218      * @param subsequence The sequence to search for.
219      * @param sequence The sequence to search.
220      * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
221      *                              {@code subsequenceDirections[i]} is the direction of the packet returned by
222      *                              {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
223      *                              internally compute the packet directions.
224      * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
225      *                           {@code sequenceDirections[i]} is the direction of the packet returned by
226      *                           {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
227      *                           compute the packet directions.
228      *
229      * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
230      *         {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
231      */
232     private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> subsequence,
233                                                                  List<PcapPacket> sequence,
234                                                                  Conversation.Direction[] subsequenceDirections,
235                                                                  Conversation.Direction[] sequenceDirections) {
236         if (sequence.size() < subsequence.size()) {
237             // If subsequence is longer, it cannot be contained in sequence.
238             return Optional.empty();
239         }
240         if (isTlsSequence(subsequence) != isTlsSequence(sequence)) {
241             // We consider it a mismatch if one is a TLS application data sequence and the other is not.
242             return Optional.empty();
243         }
244         // If packet directions have not been precomputed by calling code, we need to construct them.
245         if (subsequenceDirections == null) {
246             subsequenceDirections = getPacketDirections(subsequence, mRouterWanIp);
247         }
248         if (sequenceDirections == null) {
249             sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
250         }
251         int subseqIdx = 0;
252         int seqIdx = 0;
253         while (seqIdx < sequence.size()) {
254             PcapPacket subseqPkt = subsequence.get(subseqIdx);
255             PcapPacket seqPkt = sequence.get(seqIdx);
256             // We only have a match if packet lengths and directions match.
257             if (subseqPkt.getOriginalLength() == seqPkt.getOriginalLength() &&
258                     subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
259                 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
260                 subseqIdx++;
261                 seqIdx++;
262                 if (subseqIdx == subsequence.size()) {
263                     // We managed to match the entire subsequence in sequence.
264                     // Return the sublist of sequence that matches subsequence.
265                     /*
266                      * TODO:
267                      * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
268                      * for live traces!
269                      */
270                     return Optional.of(sequence.subList(seqIdx - subsequence.size(), seqIdx));
271                 }
272             } else {
273                 // Mismatch.
274                 if (subseqIdx > 0) {
275                     /*
276                      * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
277                      * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
278                      * leave seqIdx untouched.
279                      */
280                     subseqIdx = 0;
281                 } else {
282                     /*
283                      * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
284                      * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
285                      * sequence.
286                      */
287                     seqIdx++;
288                 }
289             }
290         }
291         return Optional.empty();
292     }
293
294     /**
295      * Given a {@code List<PcapPacket>}, generate a {@code Conversation.Direction[]} such that each entry in the
296      * resulting {@code Conversation.Direction[]} specifies the direction of the {@link PcapPacket} at the corresponding
297      * index in the input list.
298      * @param packets The list of packets for which to construct a corresponding array of packet directions.
299      * @param routerWanIp The IP of the router's WAN port. This is used for determining the direction of packets when
300      *                    the traffic is captured just outside the local network (at the ISP side of the router). Set to
301      *                    {@code null} if {@code packets} stem from traffic captured within the local network.
302      * @return A {@code Conversation.Direction[]} specifying the direction of the {@link PcapPacket} at the
303      *         corresponding index in {@code packets}.
304      */
305     private static Conversation.Direction[] getPacketDirections(List<PcapPacket> packets, String routerWanIp) {
306         Conversation.Direction[] directions = new Conversation.Direction[packets.size()];
307         for (int i = 0; i < packets.size(); i++) {
308             PcapPacket pkt = packets.get(i);
309             if (getSourceIp(pkt).equals(getDestinationIp(pkt))) {
310                 // Sanity check: we shouldn't be processing loopback traffic
311                 throw new AssertionError("loopback traffic detected");
312             }
313             if (isSrcIpLocal(pkt) || getSourceIp(pkt).equals(routerWanIp)) {
314                 directions[i] = Conversation.Direction.CLIENT_TO_SERVER;
315             } else if (isDstIpLocal(pkt) || getDestinationIp(pkt).equals(routerWanIp)) {
316                 directions[i] = Conversation.Direction.SERVER_TO_CLIENT;
317             } else {
318                 throw new IllegalArgumentException("no local IP or router WAN port IP found, can't detect direction");
319             }
320         }
321         return directions;
322     }
323
324     /**
325      * Interface used by client code to register for receiving a notification whenever the {@link ClusterMatcher}
326      * detects traffic that is similar to the traffic that makes up the cluster returned by
327      * {@link ClusterMatcher#getCluster()}.
328      */
329     interface ClusterMatchObserver {
330         /**
331          * Callback that is invoked whenever a sequence that is similar to a sequence associated with the cluster (i.e.,
332          * a sequence is a member of the cluster) is detected in the traffic that the associated {@link ClusterMatcher}
333          * observes.
334          * @param clusterMatcher The {@link ClusterMatcher} that detected a match (classified traffic as pertaining to
335          *                       its associated cluster).
336          * @param match The traffic that was deemed to match the cluster associated with {@code clusterMatcher}.
337          */
338         void onMatch(ClusterMatcher clusterMatcher, List<PcapPacket> match);
339     }
340
341 }