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