Reorganize code by creating a package for code that reassembles traffic flows at...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / util / PcapPacketUtils.java
1 package edu.uci.iotproject.util;
2
3 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
4 import edu.uci.iotproject.analysis.PcapPacketPair;
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
7 import org.apache.commons.math3.stat.clustering.Cluster;
8 import org.pcap4j.core.PcapPacket;
9 import org.pcap4j.packet.EthernetPacket;
10 import org.pcap4j.packet.IpV4Packet;
11 import org.pcap4j.packet.TcpPacket;
12 import org.pcap4j.util.MacAddress;
13
14 import java.util.*;
15
16 /**
17  * Utility methods for inspecting {@link PcapPacket} properties.
18  *
19  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
20  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
21  */
22 public final class PcapPacketUtils {
23
24     /**
25      * This is the threshold value for a signature's number of members
26      * If after a merging the number of members of a signature falls below this threshold, then we can boldly
27      * get rid of that signature.
28      */
29     private static final int SIGNATURE_MERGE_THRESHOLD = 5;
30
31
32     /**
33      * Gets the source address of the Ethernet part of {@code packet}.
34      * @param packet The packet for which the Ethernet source address is to be extracted.
35      * @return The source address of the Ethernet part of {@code packet}.
36      */
37     public static MacAddress getEthSrcAddr(PcapPacket packet) {
38         return getEthernetPacketOrThrow(packet).getHeader().getSrcAddr();
39     }
40
41     /**
42      * Gets the destination address of the Ethernet part of {@code packet}.
43      * @param packet The packet for which the Ethernet destination address is to be extracted.
44      * @return The destination address of the Ethernet part of {@code packet}.
45      */
46     public static MacAddress getEthDstAddr(PcapPacket packet) {
47         return getEthernetPacketOrThrow(packet).getHeader().getDstAddr();
48     }
49
50     /**
51      * Determines if a given {@link PcapPacket} wraps a {@link TcpPacket}.
52      * @param packet The {@link PcapPacket} to inspect.
53      * @return {@code true} if {@code packet} wraps a {@link TcpPacket}, {@code false} otherwise.
54      */
55     public static boolean isTcp(PcapPacket packet) {
56         return packet.get(TcpPacket.class) != null;
57     }
58
59     /**
60      * Gets the source IP (in decimal format) of an IPv4 packet.
61      * @param packet The packet for which the IPv4 source address is to be extracted.
62      * @return The decimal representation of the source IP of {@code packet} <em>iff</em> {@code packet} wraps an
63      *         {@link IpV4Packet}.
64      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
65      */
66     public static String getSourceIp(PcapPacket packet) {
67         return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().getHostAddress();
68     }
69
70     /**
71      * Gets the destination IP (in decimal format) of an IPv4 packet.
72      * @param packet The packet for which the IPv4 source address is to be extracted.
73      * @return The decimal representation of the destination IP of {@code packet} <em>iff</em> {@code packet} wraps an
74      *         {@link IpV4Packet}.
75      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
76      */
77     public static String getDestinationIp(PcapPacket packet) {
78         return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().getHostAddress();
79     }
80
81     /**
82      * Gets the source port of a TCP packet.
83      * @param packet The packet for which the source port is to be extracted.
84      * @return The source port of the {@link TcpPacket} encapsulated by {@code packet}.
85      * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
86      */
87     public static int getSourcePort(PcapPacket packet) {
88         TcpPacket tcpPacket = packet.get(TcpPacket.class);
89         if (tcpPacket == null) {
90             throw new IllegalArgumentException("not a TCP packet");
91         }
92         return tcpPacket.getHeader().getSrcPort().valueAsInt();
93     }
94
95     /**
96      * Gets the destination port of a TCP packet.
97      * @param packet The packet for which the destination port is to be extracted.
98      * @return The destination port of the {@link TcpPacket} encapsulated by {@code packet}.
99      * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
100      */
101     public static int getDestinationPort(PcapPacket packet) {
102         TcpPacket tcpPacket = packet.get(TcpPacket.class);
103         if (tcpPacket == null) {
104             throw new IllegalArgumentException("not a TCP packet");
105         }
106         return tcpPacket.getHeader().getDstPort().valueAsInt();
107     }
108
109     /**
110      * Helper method to determine if the given combination of IP and port matches the source of the given packet.
111      * @param packet The packet to check.
112      * @param ip The IP to look for in the ip.src field of {@code packet}.
113      * @param port The port to look for in the tcp.port field of {@code packet}.
114      * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
115      */
116     public static boolean isSource(PcapPacket packet, String ip, int port) {
117         IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
118         // For now we only support TCP flows.
119         TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
120         String ipSrc = ipPacket.getHeader().getSrcAddr().getHostAddress();
121         int srcPort = tcpPacket.getHeader().getSrcPort().valueAsInt();
122         return ipSrc.equals(ip) && srcPort == port;
123     }
124
125     /**
126      * Helper method to determine if the given combination of IP and port matches the destination of the given packet.
127      * @param packet The packet to check.
128      * @param ip The IP to look for in the ip.dst field of {@code packet}.
129      * @param port The port to look for in the tcp.dstport field of {@code packet}.
130      * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
131      */
132     public static boolean isDestination(PcapPacket packet, String ip, int port) {
133         IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
134         // For now we only support TCP flows.
135         TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
136         String ipDst = ipPacket.getHeader().getDstAddr().getHostAddress();
137         int dstPort = tcpPacket.getHeader().getDstPort().valueAsInt();
138         return ipDst.equals(ip) && dstPort == port;
139     }
140
141     /**
142      * Checks if the source IP address of the {@link IpV4Packet} contained in {@code packet} is a local address, i.e.,
143      * if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
144      * @param packet The packet for which the source IP address is to be examined.
145      * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the source IP address is a local IP
146      *         address, {@code false} otherwise.
147      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
148      */
149     public static boolean isSrcIpLocal(PcapPacket packet) {
150         return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().isSiteLocalAddress();
151     }
152
153     /**
154      * Checks if the destination IP address of the {@link IpV4Packet} contained in {@code packet} is a local address,
155      * i.e., if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
156      * @param packet The packet for which the destination IP address is to be examined.
157      * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the destination IP address is a local
158      *         IP address, {@code false} otherwise.
159      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
160      */
161     public static boolean isDstIpLocal(PcapPacket packet) {
162         return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().isSiteLocalAddress();
163     }
164
165     /**
166      * Checks if {@code packet} wraps a TCP packet that has the SYN flag set.
167      * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the SYN flag is set.
168      * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the SYN flag is set,
169      *         {@code false} otherwise.
170      */
171     public static boolean isSyn(PcapPacket packet) {
172         TcpPacket tcp = packet.get(TcpPacket.class);
173         return tcp != null && tcp.getHeader().getSyn();
174     }
175
176     /**
177      * Checks if {@code packet} wraps a TCP packet that has the ACK flag set.
178      * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the ACK flag is set.
179      * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the ACK flag is set,
180      *         {@code false} otherwise.
181      */
182     public static boolean isAck(PcapPacket packet) {
183         TcpPacket tcp = packet.get(TcpPacket.class);
184         return tcp != null && tcp.getHeader().getAck();
185     }
186
187     /**
188      * Transform a {@code Cluster} of {@code PcapPacketPair} objects into a {@code List} of {@code List} of
189      * {@code PcapPacket} objects.
190      * @param cluster A {@link Cluster} of {@link PcapPacketPair} objects that needs to be transformed.
191      * @return A {@link List} of {@link List} of {@link PcapPacket} objects as the result of the transformation.
192      */
193     public static List<List<PcapPacket>> clusterToListOfPcapPackets(Cluster<PcapPacketPair> cluster) {
194         List<List<PcapPacket>> ppListOfList = new ArrayList<>();
195         for (PcapPacketPair ppp: cluster.getPoints()) {
196             // Create a list of PcapPacket objects (list of two members).
197             List<PcapPacket> ppList = new ArrayList<>();
198             ppList.add(ppp.getFirst());
199             if(ppp.getSecond().isPresent())
200                 ppList.add(ppp.getSecond().get());
201             else
202                 ppList.add(null);
203             // Create a list of list of PcapPacket objects.
204             ppListOfList.add(ppList);
205         }
206         // Sort the list of lists based on the first packet's timestamp!
207         Collections.sort(ppListOfList, (p1, p2) -> p1.get(0).getTimestamp().compareTo(p2.get(0).getTimestamp()));
208         return ppListOfList;
209     }
210
211     /**
212      * Merge signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
213      * We cross-check these with {@code List} of {@code Conversation} objects to see
214      * if two {@code List} of {@code PcapPacket} objects actually belong to the same {@code Conversation}.
215      * @param signatures A {@link List} of {@link List} of {@link List} of
216      *          {@link PcapPacket} objects that needs to be checked and merged.
217      * @param conversations A {@link List} of {@link Conversation} objects as reference for merging.
218      * @return A {@link List} of {@link List} of {@link List} of
219      *          {@link PcapPacket} objects as the result of the merging.
220      */
221     public static List<List<List<PcapPacket>>>
222             mergeSignatures(List<List<List<PcapPacket>>> signatures, List<Conversation> conversations) {
223
224         // TODO: THIS IS NOT A DEEP COPY; IT BASICALLY CREATES A REFERENCE TO THE SAME LIST OBJECT
225         // List<List<List<PcapPacket>>> copySignatures = new ArrayList<>(signatures);
226         // Make a deep copy first.
227         List<List<List<PcapPacket>>> copySignatures = new ArrayList<>();
228         listDeepCopy(copySignatures, signatures);
229         // Traverse and look into the pairs of signatures.
230         for (int first = 0; first < signatures.size(); first++) {
231             List<List<PcapPacket>> firstList = signatures.get(first);
232             for (int second = first+1; second < signatures.size(); second++) {
233                 int maxSignatureEl = 0; // Number of maximum signature elements.
234                 List<List<PcapPacket>> secondList = signatures.get(second);
235                 int initialSecondListMembers = secondList.size();
236                 // Iterate over the signatures in the first list.
237                 for (List<PcapPacket> signature : firstList) {
238                     signature.removeIf(el -> el == null); // Clean up null elements.
239                     // Return the Conversation that the signature is part of.
240                     Conversation conv = TcpConversationUtils.returnConversation(signature, conversations);
241                     // Find the element of the second list that is a match for that Conversation.
242                     for (List<PcapPacket> ppList : secondList) {
243                         ppList.removeIf(el -> el == null); // Clean up null elements.
244                         // Check if they are part of a Conversation and are adjacent to the first signature.
245                         // If yes then merge into the first list.
246                         TcpConversationUtils.SignaturePosition position =
247                                 TcpConversationUtils.isPartOfConversationAndAdjacent(signature, ppList, conv);
248                         if (position == TcpConversationUtils.SignaturePosition.LEFT_ADJACENT) {
249                             // Merge to the left side of the first signature.
250                             ppList.addAll(signature);
251                             signature = ppList;
252                             maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
253                             secondList.remove(ppList); // Remove as we merge.
254                             break;
255                         } else if (position == TcpConversationUtils.SignaturePosition.RIGHT_ADJACENT) {
256                             // Merge to the right side of the first signature.
257                             signature.addAll(ppList);
258                             maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
259                             secondList.remove(ppList); // Remove as we merge.
260                             break;
261                         } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
262                     }
263                 }
264                 // Call it a successful merging if there are only less than 5 elements from the second list that
265                 // cannot be merged.
266                 if (secondList.size() < SIGNATURE_MERGE_THRESHOLD) {
267                     // Prune the unsuccessfully merged signatures (i.e., these will have size() < maxSignatureEl).
268                     final int maxNumOfEl = maxSignatureEl;
269                     // TODO: DOUBLE CHECK IF WE REALLY NEED TO PRUNE FAILED BINDINGS
270                     // TODO: SOMETIMES THE SEQUENCES ARE JUST INCOMPLETE
271                     // TODO: AND BOTH THE COMPLETE AND INCOMPLETE SEQUENCES ARE VALID SIGNATURES!
272                     firstList.removeIf(el -> el.size() < maxNumOfEl);
273                     // Remove the merged set of signatures when successful.
274                     signatures.remove(secondList);
275                 } else if (secondList.size() < initialSecondListMembers) {
276                     // If only some of the signatures from the second list are merged, this means UNSUCCESSFUL merging.
277                     // Return the original copy of the signatures object.
278                     return copySignatures;
279                 }
280             }
281         }
282         return signatures;
283     }
284
285     /**
286      * Deep copy to create an entirely new {@link List} of {@link List} of {@link List} of {@link PcapPacket} objects.
287      * @param destList A {@link List} of {@link List} of {@link List} of
288      *          {@link PcapPacket} objects that will be the final container of the deep copy
289      * @param sourceList A {@link List} of {@link List} of {@link List} of
290      *          {@link PcapPacket} objects that will be the source of the deep copy.
291      */
292     private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
293
294         for(List<List<PcapPacket>> llPcapPacket : sourceList) {
295             List<List<PcapPacket>> tmpListOfList = new ArrayList<>();
296             for(List<PcapPacket> lPcapPacket : llPcapPacket) {
297                 List<PcapPacket> tmpList = new ArrayList<>();
298                 for(PcapPacket pcapPacket : lPcapPacket) {
299                     tmpList.add(pcapPacket);
300                 }
301                 tmpListOfList.add(tmpList);
302             }
303             destList.add(tmpListOfList);
304         }
305     }
306
307     /**
308      * Sort the signatures in the {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
309      * The purpose of this is to sort the order of signatures in the signature list. For detection purposes, we need
310      * to know if one signature occurs earlier/later in time with respect to the other signatures for more confidence
311      * in detecting the occurrence of an event.
312      * @param signatures A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects that needs sorting.
313      *                   We assume that innermost {@code List} of {@code PcapPacket} objects have been sorted ascending
314      *                   by timestamps. By the time we use this method, we should have sorted it when calling the
315      *                   {@code clusterToListOfPcapPackets} method.
316      * @return A sorted {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
317      */
318     public static List<List<List<PcapPacket>>> sortSignatures(List<List<List<PcapPacket>>> signatures) {
319         // TODO: This is the simplest solution!!! Might not cover all corner cases.
320         // TODO: Sort the list of lists based on the first packet's timestamps!
321         //Collections.sort(signatures, (p1, p2) -> {
322         //    return p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
323         //});
324         // TODO: The following is a more complete solution that covers corner cases.
325         // Sort the list of lists based on one-to-one comparison between timestamps of signatures on both lists.
326         // This also takes into account the fact that the number of signatures in the two lists could be different.
327         // Additionally, this code forces the comparison between two signatures only if they occur in the
328         // INCLUSION_WINDOW_MILLIS window; otherwise, it tries to find the right pair of signatures in the time window.
329         Collections.sort(signatures, (p1, p2) -> {
330             int compare = 0;
331             int comparePrev = 0;
332             int count1 = 0;
333             int count2 = 0;
334             // Need to make sure that both are not out of bound!
335             while (count1 + 1 < p1.size() && count2 + 1 < p2.size()) {
336                 long timestamp1 = p1.get(count1).get(0).getTimestamp().toEpochMilli();
337                 long timestamp2 = p2.get(count2).get(0).getTimestamp().toEpochMilli();
338                 // The two timestamps have to be within a 15-second window!
339                 if (Math.abs(timestamp1 - timestamp2) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
340                     // If these two are within INCLUSION_WINDOW_MILLIS window then compare!
341                     compare = p1.get(count1).get(0).getTimestamp().compareTo(p2.get(count2).get(0).getTimestamp());
342                     if (comparePrev != 0) { // First time since it is 0
343                         if (Integer.signum(compare) != Integer.signum(comparePrev)) {
344                             // Throw an exception if the order of the two signatures is not consistent,
345                             // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
346 //                            throw new Error("For some reason, the order of signatures are not always consistent!" +
347 //                                    "Returning the original data structure of signatures...");
348                         }
349                     }
350                     comparePrev = compare;
351                     count1++;
352                     count2++;
353                 } else {
354                     // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
355                     // by incrementing one of them.
356                     if (timestamp1 < timestamp2)
357                         count1++;
358                     else
359                         count2++;
360                 }
361             }
362             return compare;
363         });
364         return signatures;
365     }
366
367     /**
368      * Gets the {@link IpV4Packet} contained in {@code packet}, or throws a {@link NullPointerException} if
369      * {@code packet} does not contain an {@link IpV4Packet}.
370      * @param packet A {@link PcapPacket} that is expected to contain an {@link IpV4Packet}.
371      * @return The {@link IpV4Packet} contained in {@code packet}.
372      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
373      */
374     private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
375         return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
376     }
377
378     /**
379      * Gets the {@link EthernetPacket} contained in {@code packet}, or throws a {@link NullPointerException} if
380      * {@code packet} does not contain an {@link EthernetPacket}.
381      * @param packet A {@link PcapPacket} that is expected to contain an {@link EthernetPacket}.
382      * @return The {@link EthernetPacket} contained in {@code packet}.
383      * @throws NullPointerException if {@code packet} does not encapsulate an {@link EthernetPacket}.
384      */
385     private static final EthernetPacket getEthernetPacketOrThrow(PcapPacket packet) {
386         return Objects.requireNonNull(packet.get(EthernetPacket.class), "not an Ethernet packet");
387     }
388
389     /**
390      * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
391      *
392      * @param signatures A {@link List} of {@link List} of {@link List} of
393      *          {@link PcapPacket} objects that needs to be printed.
394      */
395     public static void printSignatures(List<List<List<PcapPacket>>> signatures) {
396
397         // Iterate over the list of all clusters/sequences
398         int sequenceCounter = 0;
399         for(List<List<PcapPacket>> listListPcapPacket : signatures) {
400             // Iterate over every member of a cluster/sequence
401             System.out.print("====== SEQUENCE " + sequenceCounter++);
402             System.out.println(" - " + listListPcapPacket.size() + " MEMBERS ======");
403             for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
404                 // Print out packet lengths in a sequence
405                 int packetCounter = 0;
406                 for(PcapPacket pcapPacket : listPcapPacket) {
407                     if(pcapPacket != null) {
408                         System.out.print(pcapPacket.length());
409                     }
410                     if(packetCounter < listPcapPacket.size() - 1) {
411                         System.out.print(" ");  // Provide space if not last packet
412                     } else {
413                         System.out.println();      // Newline if last packet
414                     }
415                     packetCounter++;
416                 }
417             }
418         }
419     }
420
421     /**
422      * Remove a sequence in a signature object.
423      *
424      * @param signatures A {@link List} of {@link List} of {@link List} of
425      *          {@link PcapPacket} objects.
426      * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
427      *          {@link PcapPacket} objects.
428      */
429     public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
430
431         // Sequence index starts from 0
432         signatures.remove(sequenceIndex);
433     }
434 }