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