398ac1e948cdb1e1da3dce1bc47738683bddea5f
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer3 / Layer3ClusterMatcher.java
1 package edu.uci.iotproject.detection.layer3;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.detection.AbstractClusterMatcher;
5 import edu.uci.iotproject.detection.ClusterMatcherObserver;
6 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
7 import edu.uci.iotproject.trafficreassembly.layer3.TcpReassembler;
8 import edu.uci.iotproject.analysis.TcpConversationUtils;
9 import edu.uci.iotproject.io.PcapHandleReader;
10 import edu.uci.iotproject.util.PrintUtils;
11 import org.pcap4j.core.*;
12
13 import java.time.ZoneId;
14 import java.util.*;
15 import java.util.stream.Collectors;
16
17 import static edu.uci.iotproject.util.PcapPacketUtils.*;
18
19 /**
20  * Searches a traffic trace for sequences of packets "belong to" a given cluster (in other words, attempts to classify
21  * traffic as pertaining to a given cluster).
22  *
23  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
24  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
25  */
26 public class Layer3ClusterMatcher extends AbstractClusterMatcher implements PacketListener {
27
28     /**
29      * The ordered directions of packets in the sequences that make up {@link #mCluster}.
30      */
31     private final Conversation.Direction[] mClusterMemberDirections;
32
33     /**
34      * For reassembling the observed traffic into TCP connections.
35      */
36     private final TcpReassembler mTcpReassembler = new TcpReassembler();
37
38     /**
39      * IP of the router's WAN port (if analyzed traffic is captured at the ISP's point of view).
40      */
41     private final String mRouterWanIp;
42
43     /**
44      * Epsilon value used by the DBSCAN algorithm; it is used again for range-based matching here.
45      */
46     private final double mEps;
47
48     /**
49      * The packet inclusion time for signature.
50      */
51     private int mInclusionTimeMillis;
52
53     /**
54      * Create a {@link Layer3ClusterMatcher}.
55      * @param cluster The cluster that traffic is matched against.
56      * @param routerWanIp The router's WAN IP if examining traffic captured at the ISP's point of view (used for
57      *                    determining the direction of packets).
58      * @param inclusionTimeMillis The packet inclusion time for signature.
59      * @param isRangeBased The boolean that decides if it is range-based vs. strict matching.
60      * @param eps The epsilon value used in the DBSCAN algorithm.
61      * @param detectionObservers Client code that wants to get notified whenever the {@link Layer3ClusterMatcher} detects that
62      *                          (a subset of) the examined traffic is similar to the traffic that makes up
63      *                          {@code cluster}, i.e., when the examined traffic is classified as pertaining to
64      *                          {@code cluster}.
65      */
66     public Layer3ClusterMatcher(List<List<PcapPacket>> cluster, String routerWanIp, int inclusionTimeMillis,
67                                 boolean isRangeBased, double eps,
68                                 ClusterMatcherObserver... detectionObservers) {
69         super(cluster, isRangeBased);
70         Objects.requireNonNull(detectionObservers, "detectionObservers cannot be null");
71         for (ClusterMatcherObserver obs : detectionObservers) {
72             addObserver(obs);
73         }
74         // Build the cluster members' direction sequence.
75         // Note: assumes that the provided cluster was captured within the local network (routerWanIp is set to null).
76         mClusterMemberDirections = getPacketDirections(cluster.get(0), null);
77         /*
78          * Enforce restriction on cluster members: all representatives must exhibit the same direction pattern and
79          * contain the same number of packets. Note that this is a somewhat heavy operation, so it may be disabled later
80          * on in favor of performance. However, it is only run once (at instantiation), so the overhead may be warranted
81          * in order to ensure correctness, especially during the development/debugging phase.
82          */
83         if (!isRangeBased) {    // Only when it is not range-based
84             if (mCluster.stream().
85                     anyMatch(inner -> !Arrays.equals(mClusterMemberDirections, getPacketDirections(inner, null)))) {
86                 throw new IllegalArgumentException(
87                         "cluster members must contain the same number of packets and exhibit the same packet direction " +
88                                 "pattern"
89                 );
90             }
91         }
92         mEps = eps;
93         mRouterWanIp = routerWanIp;
94         mInclusionTimeMillis =
95                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
96     }
97
98     @Override
99     public void gotPacket(PcapPacket packet) {
100         // Present packet to TCP reassembler so that it can be mapped to a connection (if it is a TCP packet).
101         mTcpReassembler.gotPacket(packet);
102     }
103
104     /**
105      * Get the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
106      * @return the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
107      */
108     public List<List<PcapPacket>> getCluster() {
109         return mCluster;
110     }
111
112     public void performDetectionRangeBased() {
113         /*
114          * Let's start out simple by building a version that only works for signatures that do not span across multiple
115          * TCP conversations...
116          */
117         for (Conversation c : mTcpReassembler.getTcpConversations()) {
118             if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
119                 // Skip empty conversations.
120                 continue;
121             }
122             List<PcapPacket> lowerBound = mCluster.get(0);
123             List<PcapPacket> upperBound = mCluster.get(1);
124             if (isTlsSequence(lowerBound) != c.isTls() || isTlsSequence(upperBound) != c.isTls()) {
125                 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
126                 continue;
127             }
128             // Fetch set of packets to examine based on TLS or not.
129             List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
130             Optional<List<PcapPacket>> match;
131             while ((match = findSubsequenceInSequence(lowerBound, upperBound, cPkts, mClusterMemberDirections, null)).
132                     isPresent()) {
133                 List<PcapPacket> matchSeq = match.get();
134                 // Notify observers about the match.
135                 mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
136 //                if (!matchSeq.get(matchSeq.size()-1).getTimestamp().isAfter(matchSeq.get(0).getTimestamp().
137 //                        plusMillis(mInclusionTimeMillis))) {
138 //                    // Notify observers about the match.
139 //                    mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
140 //                }
141                 /*
142                  * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
143                  * signature sequence.
144                  */
145                 int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size() - 1));
146                 // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
147                 cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
148             }
149         }
150     }
151
152     public void performDetectionConservative() {
153         /*
154          * Let's start out simple by building a version that only works for signatures that do not span across multiple
155          * TCP conversations...
156          */
157         for (Conversation c : mTcpReassembler.getTcpConversations()) {
158             if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
159                 // Skip empty conversations.
160                 continue;
161             }
162             for (List<PcapPacket> signatureSequence : mCluster) {
163                 if (isTlsSequence(signatureSequence) != c.isTls()) {
164                     // We consider it a mismatch if one is a TLS application data sequence and the other is not.
165                     continue;
166                 }
167                 // Fetch set of packets to examine based on TLS or not.
168                 List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
169                 /*
170                  * Note: we embed the attempt to detect the signature sequence in a loop in order to capture those cases
171                  * where the same signature sequence appears multiple times in one Conversation.
172                  *
173                  * Note: since we expect all sequences that together make up the signature to exhibit the same direction
174                  * pattern, we can simply pass the precomputed direction array for the signature sequence so that it
175                  * won't have to be recomputed internally in each call to findSubsequenceInSequence().
176                  */
177                 Optional<List<PcapPacket>> match;
178                 while ((match = findSubsequenceInSequence(signatureSequence, cPkts, mClusterMemberDirections, null)).
179                         isPresent()) {
180                     List<PcapPacket> matchSeq = match.get();
181                     // Notify observers about the match.
182                     mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
183 //                    if (!matchSeq.get(matchSeq.size()-1).getTimestamp().isAfter(matchSeq.get(0).getTimestamp().
184 //                           plusMillis(mInclusionTimeMillis))) {
185 //                        // Notify observers about the match.
186 //                        mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
187 //                    }
188                     /*
189                      * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
190                      * signature sequence.
191                      */
192                     int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size() - 1));
193                     // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
194                     cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
195                 }
196             }
197
198             /*
199              * TODO:
200              * if no item in cluster matches, also perform a distance-based matching to cover those cases where we did
201              * not manage to capture every single mutation of the sequence during training.
202              *
203              * Need to compute average/centroid of cluster to do so...? Compute within-cluster variance, then check if
204              * distance between input conversation and cluster average/centroid is smaller than or equal to the computed
205              * variance?
206              */
207         }
208     }
209
210     /**
211      * Checks if {@code sequence} is a sequence of TLS packets. Note: the current implementation relies on inspection
212      * of the port numbers when deciding between TLS vs. non-TLS. Therefore, only the first packet of {@code sequence}
213      * is examined as it is assumed that all packets in {@code sequence} pertain to the same {@link Conversation} and
214      * hence share the same set of two src/dst port numbers (albeit possibly alternating between which one is the src
215      * and which one is the dst, as packets in {@code sequence} may be in alternating directions).
216      * @param sequence The sequence of packets for which it is to be determined if it is a sequence of TLS packets or
217      *                 non-TLS packets.
218      * @return {@code true} if {@code sequence} is a sequence of TLS packets, {@code false} otherwise.
219      */
220     private boolean isTlsSequence(List<PcapPacket> sequence) {
221         // NOTE: Assumes ALL packets in sequence pertain to the same TCP connection!
222         PcapPacket firstPkt = sequence.get(0);
223         int srcPort = getSourcePort(firstPkt);
224         int dstPort = getDestinationPort(firstPkt);
225         return TcpConversationUtils.isTlsPort(srcPort) || TcpConversationUtils.isTlsPort(dstPort);
226     }
227
228     /**
229      * Examine if a given sequence of packets ({@code sequence}) contains a given shorter sequence of packets
230      * ({@code subsequence}). Note: the current implementation actually searches for a substring as it does not allow
231      * for interleaving packets in {@code sequence} that are not in {@code subsequence}; for example, if
232      * {@code subsequence} consists of packet lengths [2, 3, 5] and {@code sequence} consists of  packet lengths
233      * [2, 3, 4, 5], the result will be that there is no match (because of the interleaving 4). If we are to allow
234      * interleaving packets, we need a modified version of
235      * <a href="https://stackoverflow.com/a/20545604/1214974">this</a>.
236      *
237      * @param subsequence The sequence to search for.
238      * @param sequence The sequence to search.
239      * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
240      *                              {@code subsequenceDirections[i]} is the direction of the packet returned by
241      *                              {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
242      *                              internally compute the packet directions.
243      * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
244      *                           {@code sequenceDirections[i]} is the direction of the packet returned by
245      *                           {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
246      *                           compute the packet directions.
247      *
248      * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
249      *         {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
250      */
251     private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> subsequence,
252                                                                  List<PcapPacket> sequence,
253                                                                  Conversation.Direction[] subsequenceDirections,
254                                                                  Conversation.Direction[] sequenceDirections) {
255         if (sequence.size() < subsequence.size()) {
256             // If subsequence is longer, it cannot be contained in sequence.
257             return Optional.empty();
258         }
259         if (isTlsSequence(subsequence) != isTlsSequence(sequence)) {
260             // We consider it a mismatch if one is a TLS application data sequence and the other is not.
261             return Optional.empty();
262         }
263         // If packet directions have not been precomputed by calling code, we need to construct them.
264         if (subsequenceDirections == null) {
265             subsequenceDirections = getPacketDirections(subsequence, mRouterWanIp);
266         }
267         if (sequenceDirections == null) {
268             sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
269         }
270         int subseqIdx = 0;
271         int seqIdx = 0;
272         while (seqIdx < sequence.size()) {
273             PcapPacket subseqPkt = subsequence.get(subseqIdx);
274             PcapPacket seqPkt = sequence.get(seqIdx);
275             // We only have a match if packet lengths and directions match.
276             if (subseqPkt.getOriginalLength() == seqPkt.getOriginalLength() &&
277                     subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
278                 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
279                 subseqIdx++;
280                 seqIdx++;
281                 if (subseqIdx == subsequence.size()) {
282                     // We managed to match the entire subsequence in sequence.
283                     // Return the sublist of sequence that matches subsequence.
284                     /*
285                      * TODO:
286                      * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
287                      * for live traces!
288                      */
289                     return Optional.of(sequence.subList(seqIdx - subsequence.size(), seqIdx));
290                 }
291             } else {
292                 // Mismatch.
293                 if (subseqIdx > 0) {
294                     /*
295                      * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
296                      * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
297                      * leave seqIdx untouched.
298                      */
299                     subseqIdx = 0;
300                 } else {
301                     /*
302                      * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
303                      * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
304                      * sequence.
305                      */
306                     seqIdx++;
307                 }
308             }
309         }
310         return Optional.empty();
311     }
312
313     /**
314      * Overloading the method {@code findSubsequenceInSequence} for range-based matching. Instead of a sequence,
315      * we have sequences of lower and upper bounds.
316      *
317      * @param lowerBound The lower bound of the sequence we search for.
318      * @param upperBound The upper bound of the sequence we search for.
319      * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
320      *                              {@code subsequenceDirections[i]} is the direction of the packet returned by
321      *                              {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
322      *                              internally compute the packet directions.
323      * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
324      *                           {@code sequenceDirections[i]} is the direction of the packet returned by
325      *                           {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
326      *                           compute the packet directions.
327      *
328      * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
329      *         {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
330      */
331     private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> lowerBound,
332                                                                  List<PcapPacket> upperBound,
333                                                                  List<PcapPacket> sequence,
334                                                                  Conversation.Direction[] subsequenceDirections,
335                                                                  Conversation.Direction[] sequenceDirections) {
336         // Just do the checks for either lower or upper bound!
337         // TODO: For now we use just the lower bound
338         if (sequence.size() < lowerBound.size()) {
339             // If subsequence is longer, it cannot be contained in sequence.
340             return Optional.empty();
341         }
342         if (isTlsSequence(lowerBound) != isTlsSequence(sequence)) {
343             // We consider it a mismatch if one is a TLS application data sequence and the other is not.
344             return Optional.empty();
345         }
346         // If packet directions have not been precomputed by calling code, we need to construct them.
347         if (subsequenceDirections == null) {
348             subsequenceDirections = getPacketDirections(lowerBound, mRouterWanIp);
349         }
350         if (sequenceDirections == null) {
351             sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
352         }
353         int subseqIdx = 0;
354         int seqIdx = 0;
355         while (seqIdx < sequence.size()) {
356             PcapPacket lowBndPkt = lowerBound.get(subseqIdx);
357             PcapPacket upBndPkt = upperBound.get(subseqIdx);
358             PcapPacket seqPkt = sequence.get(seqIdx);
359             // We only have a match if packet lengths and directions match.
360             // The packet lengths have to be in the range of [lowerBound - eps, upperBound+eps]
361             // We initialize the lower and upper bounds first
362             int epsLowerBound = lowBndPkt.length();
363             int epsUpperBound = upBndPkt.length();
364             // Do strict matching if the lower and upper bounds are the same length
365             // Do range matching with eps otherwise
366             if (epsLowerBound != epsUpperBound) {
367                 // TODO: Maybe we could do better here for the double to integer conversion?
368                 epsLowerBound = epsLowerBound - (int) mEps;
369                 epsUpperBound = epsUpperBound + (int) mEps;
370             }
371             if (epsLowerBound <= seqPkt.getOriginalLength() &&
372                     seqPkt.getOriginalLength() <= epsUpperBound &&
373                     subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
374                 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
375                 subseqIdx++;
376                 seqIdx++;
377                 if (subseqIdx == lowerBound.size()) {
378                     // We managed to match the entire subsequence in sequence.
379                     // Return the sublist of sequence that matches subsequence.
380                     /*
381                      * TODO:
382                      * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
383                      * for live traces!
384                      */
385                     return Optional.of(sequence.subList(seqIdx - lowerBound.size(), seqIdx));
386                 }
387             } else {
388                 // Mismatch.
389                 if (subseqIdx > 0) {
390                     /*
391                      * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
392                      * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
393                      * leave seqIdx untouched.
394                      */
395                     subseqIdx = 0;
396                 } else {
397                     /*
398                      * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
399                      * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
400                      * sequence.
401                      */
402                     seqIdx++;
403                 }
404             }
405         }
406         return Optional.empty();
407     }
408
409     /**
410      * Given a cluster, produces a pruned version of that cluster. In the pruned version, there are no duplicate cluster
411      * members. Two cluster members are considered identical if their packets lengths and packet directions are
412      * identical. The resulting pruned cluster is unmodifiable (this applies to both the outermost list as well as the
413      * nested lists) in order to preserve its integrity when exposed to external code (e.g., through
414      * {@link #getCluster()}).
415      *
416      * @param cluster A cluster to prune.
417      * @return The resulting pruned cluster.
418      */
419     @Override
420     protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster) {
421         List<List<PcapPacket>> prunedCluster = new ArrayList<>();
422         for (List<PcapPacket> originalClusterSeq : cluster) {
423             boolean alreadyPresent = false;
424             for (List<PcapPacket> prunedClusterSeq : prunedCluster) {
425                 Optional<List<PcapPacket>> duplicate = findSubsequenceInSequence(originalClusterSeq, prunedClusterSeq,
426                         mClusterMemberDirections, mClusterMemberDirections);
427                 if (duplicate.isPresent()) {
428                     alreadyPresent = true;
429                     break;
430                 }
431             }
432             if (!alreadyPresent) {
433                 prunedCluster.add(Collections.unmodifiableList(originalClusterSeq));
434             }
435         }
436         return Collections.unmodifiableList(prunedCluster);
437     }
438
439     /**
440      * Given a {@code List<PcapPacket>}, generate a {@code Conversation.Direction[]} such that each entry in the
441      * resulting {@code Conversation.Direction[]} specifies the direction of the {@link PcapPacket} at the corresponding
442      * index in the input list.
443      * @param packets The list of packets for which to construct a corresponding array of packet directions.
444      * @param routerWanIp The IP of the router's WAN port. This is used for determining the direction of packets when
445      *                    the traffic is captured just outside the local network (at the ISP side of the router). Set to
446      *                    {@code null} if {@code packets} stem from traffic captured within the local network.
447      * @return A {@code Conversation.Direction[]} specifying the direction of the {@link PcapPacket} at the
448      *         corresponding index in {@code packets}.
449      */
450     private static Conversation.Direction[] getPacketDirections(List<PcapPacket> packets, String routerWanIp) {
451         Conversation.Direction[] directions = new Conversation.Direction[packets.size()];
452         for (int i = 0; i < packets.size(); i++) {
453             PcapPacket pkt = packets.get(i);
454             if (getSourceIp(pkt).equals(getDestinationIp(pkt))) {
455                 // Sanity check: we shouldn't be processing loopback traffic
456                 throw new AssertionError("loopback traffic detected");
457             }
458             if (isSrcIpLocal(pkt) || getSourceIp(pkt).equals(routerWanIp)) {
459                 directions[i] = Conversation.Direction.CLIENT_TO_SERVER;
460             } else if (isDstIpLocal(pkt) || getDestinationIp(pkt).equals(routerWanIp)) {
461                 directions[i] = Conversation.Direction.SERVER_TO_CLIENT;
462             } else {
463                 //throw new IllegalArgumentException("no local IP or router WAN port IP found, can't detect direction");
464             }
465         }
466         return directions;
467     }
468
469 }