Completing the scripts with the latest devices and features.
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / util / PcapPacketUtils.java
1 package edu.uci.iotproject.util;
2
3 import edu.uci.iotproject.io.PrintWriterUtils;
4 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
5 import edu.uci.iotproject.analysis.PcapPacketPair;
6 import edu.uci.iotproject.analysis.TcpConversationUtils;
7 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
8 import org.apache.commons.math3.stat.clustering.Cluster;
9 import org.pcap4j.core.PcapPacket;
10 import org.pcap4j.packet.EthernetPacket;
11 import org.pcap4j.packet.IpV4Packet;
12 import org.pcap4j.packet.TcpPacket;
13 import org.pcap4j.util.MacAddress;
14
15 import java.io.PrintWriter;
16 import java.util.*;
17
18 /**
19  * Utility methods for inspecting {@link PcapPacket} properties.
20  *
21  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
22  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
23  */
24 public final class PcapPacketUtils {
25
26     /**
27      * This is the threshold value for a signature's number of members
28      * If after a merging the number of members of a signature falls below this threshold, then we can boldly
29      * get rid of that signature.
30      */
31     private static final int SIGNATURE_MERGE_THRESHOLD = 5;
32
33     /**
34      * This is an overlap counter (we consider overlaps between signatures if it happens more than once)
35      */
36     private static int mOverlapCounter = 0;
37
38
39     /**
40      * Gets the source address of the Ethernet part of {@code packet}.
41      * @param packet The packet for which the Ethernet source address is to be extracted.
42      * @return The source address of the Ethernet part of {@code packet}.
43      */
44     public static MacAddress getEthSrcAddr(PcapPacket packet) {
45         return getEthernetPacketOrThrow(packet).getHeader().getSrcAddr();
46     }
47
48     /**
49      * Gets the destination address of the Ethernet part of {@code packet}.
50      * @param packet The packet for which the Ethernet destination address is to be extracted.
51      * @return The destination address of the Ethernet part of {@code packet}.
52      */
53     public static MacAddress getEthDstAddr(PcapPacket packet) {
54         return getEthernetPacketOrThrow(packet).getHeader().getDstAddr();
55     }
56
57     /**
58      * Determines if a given {@link PcapPacket} wraps a {@link TcpPacket}.
59      * @param packet The {@link PcapPacket} to inspect.
60      * @return {@code true} if {@code packet} wraps a {@link TcpPacket}, {@code false} otherwise.
61      */
62     public static boolean isTcp(PcapPacket packet) {
63         return packet.get(TcpPacket.class) != null;
64     }
65
66     /**
67      * Gets the source IP (in decimal format) of an IPv4 packet.
68      * @param packet The packet for which the IPv4 source address is to be extracted.
69      * @return The decimal representation of the source IP of {@code packet} <em>iff</em> {@code packet} wraps an
70      *         {@link IpV4Packet}.
71      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
72      */
73     public static String getSourceIp(PcapPacket packet) {
74         return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().getHostAddress();
75     }
76
77     /**
78      * Gets the destination IP (in decimal format) of an IPv4 packet.
79      * @param packet The packet for which the IPv4 source address is to be extracted.
80      * @return The decimal representation of the destination IP of {@code packet} <em>iff</em> {@code packet} wraps an
81      *         {@link IpV4Packet}.
82      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
83      */
84     public static String getDestinationIp(PcapPacket packet) {
85         return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().getHostAddress();
86     }
87
88     /**
89      * Gets the source port of a TCP packet.
90      * @param packet The packet for which the source port is to be extracted.
91      * @return The source port of the {@link TcpPacket} encapsulated by {@code packet}.
92      * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
93      */
94     public static int getSourcePort(PcapPacket packet) {
95         TcpPacket tcpPacket = packet.get(TcpPacket.class);
96         if (tcpPacket == null) {
97             throw new IllegalArgumentException("not a TCP packet");
98         }
99         return tcpPacket.getHeader().getSrcPort().valueAsInt();
100     }
101
102     /**
103      * Gets the destination port of a TCP packet.
104      * @param packet The packet for which the destination port is to be extracted.
105      * @return The destination port of the {@link TcpPacket} encapsulated by {@code packet}.
106      * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
107      */
108     public static int getDestinationPort(PcapPacket packet) {
109         TcpPacket tcpPacket = packet.get(TcpPacket.class);
110         if (tcpPacket == null) {
111             throw new IllegalArgumentException("not a TCP packet");
112         }
113         return tcpPacket.getHeader().getDstPort().valueAsInt();
114     }
115
116     /**
117      * Helper method to determine if the given combination of IP and port matches the source of the given packet.
118      * @param packet The packet to check.
119      * @param ip The IP to look for in the ip.src field of {@code packet}.
120      * @param port The port to look for in the tcp.port field of {@code packet}.
121      * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
122      */
123     public static boolean isSource(PcapPacket packet,         String ip, int port) {
124         IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
125         // For now we only support TCP flows.
126         TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
127         String ipSrc = ipPacket.getHeader().getSrcAddr().getHostAddress();
128         int srcPort = tcpPacket.getHeader().getSrcPort().valueAsInt();
129         return ipSrc.equals(ip) && srcPort == port;
130     }
131
132     /**
133      * Helper method to determine if the given combination of IP and port matches the destination of the given packet.
134      * @param packet The packet to check.
135      * @param ip The IP to look for in the ip.dst field of {@code packet}.
136      * @param port The port to look for in the tcp.dstport field of {@code packet}.
137      * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
138      */
139     public static boolean isDestination(PcapPacket packet, String ip, int port) {
140         IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
141         // For now we only support TCP flows.
142         TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
143         String ipDst = ipPacket.getHeader().getDstAddr().getHostAddress();
144         int dstPort = tcpPacket.getHeader().getDstPort().valueAsInt();
145         return ipDst.equals(ip) && dstPort == port;
146     }
147
148     /**
149      * Checks if the source IP address of the {@link IpV4Packet} contained in {@code packet} is a local address, i.e.,
150      * if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
151      * @param packet The packet for which the source IP address is to be examined.
152      * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the source IP address is a local IP
153      *         address, {@code false} otherwise.
154      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
155      */
156     public static boolean isSrcIpLocal(PcapPacket packet) {
157         return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().isSiteLocalAddress();
158     }
159
160     /**
161      * Checks if the destination IP address of the {@link IpV4Packet} contained in {@code packet} is a local address,
162      * i.e., if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
163      * @param packet The packet for which the destination IP address is to be examined.
164      * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the destination IP address is a local
165      *         IP address, {@code false} otherwise.
166      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
167      */
168     public static boolean isDstIpLocal(PcapPacket packet) {
169         return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().isSiteLocalAddress();
170     }
171
172     /**
173      * Checks if {@code packet} wraps a TCP packet that has the SYN flag set.
174      * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the SYN flag is set.
175      * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the SYN flag is set,
176      *         {@code false} otherwise.
177      */
178     public static boolean isSyn(PcapPacket packet) {
179         TcpPacket tcp = packet.get(TcpPacket.class);
180         return tcp != null && tcp.getHeader().getSyn();
181     }
182
183     /**
184      * Checks if {@code packet} wraps a TCP packet th        at has the ACK flag set.
185      * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the ACK flag is set.
186      * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the ACK flag is set,
187      *         {@code false} otherwise.
188      */
189     public static boolean isAck(PcapPacket packet) {
190         TcpPacket tcp = packet.get(TcpPacket.class);
191         return tcp != null && tcp.getHeader().getAck();
192     }
193
194     /**
195      * Transform a {@code Cluster} of {@code PcapPacketPair} objects into a {@code List} of {@code List} of
196      * {@code PcapPacket} objects.
197      * @param cluster A {@link Cluster} of {@link PcapPacketPair} objects that needs to be transformed.
198      * @return A {@link List} of {@link List} of {@link PcapPacket} objects as the result of the transformation.
199      */
200     public static List<List<PcapPacket>> clusterToListOfPcapPackets(Cluster<PcapPacketPair> cluster) {
201         List<List<PcapPacket>> ppListOfList = new ArrayList<>();
202         for (PcapPacketPair ppp: cluster.getPoints()) {
203             // Create a list of PcapPacket objects (list of two members).
204             List<PcapPacket> ppList = new ArrayList<>();
205             ppList.add(ppp.getFirst());
206             if(ppp.getSecond().isPresent())
207                 ppList.add(ppp.getSecond().get());
208             else
209                 ppList.add(null);
210             // Create a list of list of PcapPacket objects.
211             ppListOfList.add(ppList);
212         }
213         // Sort the list of lists based on the first packet's timestamp!
214         Collections.sort(ppListOfList, (p1, p2) -> p1.        get(0).getTimestamp().compareTo(p2.get(0).getTimestamp()));
215         return ppListOfList;
216     }
217
218     /**
219      * Concatenate sequences in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
220      * We cross-check these with {@code List} of {@code Conversation} objects to see
221      * if two {@code List} of {@code PcapPacket} objects actually belong to the same {@code Conversation}.
222      * @param signatures A {@link List} of {@link List} of {@link List} of
223      *          {@link PcapPacket} objects that needs to be checked and concatenated.
224      * @param conversations A {@link List} of {@link Conversation} objects as reference for concatenation.
225      * @return A {@link List} of {@link List} of {@link List} of
226      *          {@link PcapPacket} objects as the result of the concatenation.
227      */
228     public static List<List<List<PcapPacket>>>
229             concatSequences(List<List<List<PcapPacket>>> signatures, List<Conversation> conversations) {
230
231         // TODO: THIS IS NOT A DEEP COPY; IT BASICALLY CREATES A REFERENCE TO THE SAME LIST OBJECT
232         // List<List<List<PcapPacket>>> copySignatures = new ArrayList<>(signatures);
233         // Make a deep copy first.
234         List<List<List<PcapPacket>>> copySignatures = new ArrayList<>();
235         listDeepCopy(copySignatures, signatures);
236         // Traverse and look into the pairs.
237         //for (int first = 0; first < signatures.size(); first++) {
238         int first = 0;
239         int signaturesSize = signatures.size();
240         while(first < signaturesSize) {
241 //            System.out.println("First: " + first + " Signatures: " + signatures.get(0).size());
242             List<List<PcapPacket>> firstList = signatures.get(first);
243             for (int second = first+1; second < signatures.size(); second++) {
244                 int maxSignatureEl = 0;
245                 List<List<PcapPacket>> secondList = signatures.get(second);
246                 int initialSecondListMembers = secondList.size();
247                 // Iterate over the sequences in the first list.
248                 for (List<PcapPacket> signature : firstList) {
249                     signature.removeIf(el -> el == null); // Clean up null elements.
250                     // Return the Conversation that the sequence is part of.
251                     Conversation conv = TcpConversationUtils.returnConversation(signature, conversations);
252                     // Find the element of the second list that is a match for that Conversation.
253                     for (List<PcapPacket> ppList : secondList) {
254                         ppList.removeIf(el -> el == null); // Clean up null elements.
255                         // Check if they are part of a Conversation and are adjacent to the first sequence.
256                         // If yes then merge into the first list.
257                         TcpConversationUtils.SignaturePosition position =
258                                 TcpConversationUtils.isPartOfConversationAndAdjacent(signature, ppList, conv);
259                         if (position == TcpConversationUtils.SignaturePosition.LEFT_ADJACENT) {
260                             // Merge to the left side of the first sequence.
261                             ppList.addAll(signature);
262                             // Remove and then add again to keep the same reference
263                             signature.removeAll(signature);
264                             signature.addAll(ppList);
265                             maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
266                             secondList.remove(ppList); // Remove as we merge.
267                             break;
268                         } else if (position == TcpConversationUtils.SignaturePosition.RIGHT_ADJACENT) {
269                             // Merge to the right side of the first sequence.
270                             signature.addAll(ppList);
271                             maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
272                             secondList.remove(ppList); // Remove as we merge.
273                             break;
274                         } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
275                     }
276                 }
277 //                System.out.println("First list size: " + firstList.get(35).size());
278                 // Call it a successful merging if there are only less than 5 elements from the second list that
279                 // cannot be merged.
280                 if (secondList.size() < SIGNATURE_MERGE_THRESHOLD) {
281                     // Prune the unsuccessfully merged sequences (i.e., these will have size() < maxSignatureEl).
282                     final int maxNumOfEl = maxSignatureEl;
283                     // TODO: DOUBLE CHECK IF WE REALLY NEED TO PRUNE FAILED BINDINGS
284                     // TODO: SOMETIMES THE SEQUENCES ARE JUST INCOMPLETE
285                     // TODO: AND BOTH THE COMPLETE AND INCOMPLETE SEQUENCES ARE VALID SIGNATURES!
286                     firstList.removeIf(el -> el.size() < maxNumOfEl);
287                     // Remove the merged set of sequences when successful.
288                     signatures.remove(secondList);
289                 } else if (secondList.size() < initialSecondListMembers) {
290                     // If only some of the sequences from the second list are merged, this means UNSUCCESSFUL merging.
291                     // Return the original copy of the signatures object.
292                     return copySignatures;
293                 }
294             }
295             if (signatures.size() < signaturesSize) {
296                 // If there is a concatenation, we check again from index 0
297                 signaturesSize = signatures.size();
298                 first = 0;
299             } else {
300                 signaturesSize = signatures.size();
301                 first++;
302             }
303
304         }
305         return signatures;
306     }
307
308     /**
309      * Clean up null values in in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
310      * @param signature A {@link List} of {@link List} of {@link List} of
311      *          {@link PcapPacket} objects that needs to be cleaned up from null values.
312      */
313     public static void cleanSignature(List<List<List<PcapPacket>>> signature) {
314
315         for(List<List<PcapPacket>> listOfListPcap : signature) {
316             for(List<PcapPacket> listOfPcap : listOfListPcap) {
317                 listOfPcap.removeIf(el -> el == null);
318             }
319         }
320     }
321
322         /**
323          * Deep copy to create an entirely new {@link List} of {@link List} of {@link List} of {@link PcapPacket} objects.
324          * @param destList A {@link List} of {@link List} of {@link List} of
325          *          {@link PcapPacket} objects that will be the final container of the deep copy
326          * @param sourceList A {@link List} of {@link List} of {@link List} of
327          *          {@link PcapPacket} objects that will be the source of the deep copy.
328          */
329     private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
330
331         for(List<List<PcapPacket>> llPcapPacket : sourceList) {
332             List<List<PcapPacket>> tmpListOfList = new ArrayList<>();
333             for(List<PcapPacket> lPcapPacket : llPcapPacket) {
334                 List<PcapPacket> tmpList = new ArrayList<>();
335                 for(PcapPacket pcapPacket : lPcapPacket) {
336                     tmpList.add(pcapPacket);
337                 }
338                 tmpListOfList.add(tmpList);
339             }
340             destList.add(tmpListOfList);
341         }
342     }
343
344     /**
345      * Sort the sequences in the {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
346      * The purpose of this is to sort the order of sequences in the sequence list. For detection purposes, we need
347      * to know if one sequence occurs earlier/later in time with respect to the other sequences for more confidence
348      * in detecting the occurrence of an event.
349      * @param signatures A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects that needs sorting.
350      *                   We assume that innermost {@code List} of {@code PcapPacket} objects have been sorted ascending
351      *                   by timestamps. By the time we use this method, we should have sorted it when calling the
352      *                   {@code clusterToListOfPcapPackets} method.
353      * @return A sorted {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
354      */
355     public static List<List<List<PcapPacket>>> sortSequences(List<List<List<PcapPacket>>> signatures) {
356         // TODO: This is the simplest solution!!! Might not cover all corner cases.
357         // TODO: Sort the list of lists based on the first packet's timestamps!
358 //        Collections.sort(signatures, (p1, p2) -> {
359 //            //return p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
360 //            int compare = p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
361 //            return compare;
362 //        });
363         // TODO: The following is a more complete solution that covers corner cases.
364         // Sort the list of lists based on one-to-one comparison between timestamps of signatures on both lists.
365         // This also takes into account the fact that the number of signatures in the two lists could be different.
366         // Additionally, this code forces the comparison between two signatures only if they occur in the
367         // INCLUSION_WINDOW_MILLIS window; otherwise, it tries to find the right pair of signatures in the time window.
368         Collections.sort(signatures, (p1, p2) -> {
369             int compare = 0;
370             int comparePrev = 0;
371             int count1 = 0;
372             int count2 = 0;
373             // Need to make sure that both are not out of bound!
374             while (count1 + 1 < p1.size() && count2 + 1 < p2.size()) {
375                 long timestamp1 = p1.get(count1).get(0).getTimestamp().toEpochMilli();
376                 long timestamp2 = p2.get(count2).get(0).getTimestamp().toEpochMilli();
377                 // The two timestamps have to be within a 15-second window!
378                 if (Math.abs(timestamp1 - timestamp2) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
379                     // If these two are within INCLUSION_WINDOW_MILLIS window then compare!
380                     compare = p1.get(count1).get(0).getTimestamp().compareTo(p2.get(count2).get(0).getTimestamp());
381                     overlapChecking(compare, comparePrev, p1.get(count1), p2.get(count2),
382                             signatures.indexOf(p1), signatures.indexOf(p2));
383                     comparePrev = compare;
384                     count1++;
385                     count2++;
386                 } else {
387                     // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
388                     // by incrementing one of them.
389                     if (timestamp1 < timestamp2)
390                         count1++;
391                     else
392                         count2++;
393                 }
394             }
395             return compare;
396         });
397         return signatures;
398     }
399
400     /**
401      * Checks for overlapping between two packet sequences.
402      * @param compare Current comparison value between packet sequences p1 and p2
403      * @param comparePrev Previous comparison value between packet sequences p1 and p2
404      * @param sequence1 The packet sequence ({@link List} of {@link PcapPacket} objects).
405      * @param sequence2 The packet sequence ({@link List} of {@link PcapPacket} objects).
406      * @param indexSequence1 The index of packet sequence ({@link List} of {@link PcapPacket} objects).
407      * @param indexSequence2 The index of packet sequence ({@link List} of {@link PcapPacket} objects).
408      */
409     private static void overlapChecking(int compare, int comparePrev,
410                                         List<PcapPacket> sequence1, List<PcapPacket> sequence2,
411                                         int indexSequence1, int indexSequence2) {
412
413         // Check if p1 occurs before p2 but both have same overlap
414         if (comparePrev != 0) { // First time since it is 0
415             if (Integer.signum(compare) != Integer.signum(comparePrev)) {
416                 // Throw an exception if the order of the two signatures is not consistent,
417                 // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
418                 throw new Error("OVERLAP WARNING: " + "" +
419                         "Two sequences have some overlap. Please remove one of the sequences: " +
420                         sequence1.get(0).length() + "... OR " +
421                         sequence2.get(0).length() + "...");
422             }
423         }
424         // Check if p1 is longer than p2 and p2 occurs during the occurrence of p1
425         int lastIndexOfSequence1 = sequence1.size() - 1;
426         // Check if the last index is null
427         while (sequence1.get(lastIndexOfSequence1) == null)
428             lastIndexOfSequence1--;
429         int lastIndexOfSequence2 = sequence2.size() - 1;
430         // Check if the last index is null
431         while (sequence2.get(lastIndexOfSequence2) == null)
432             lastIndexOfSequence2--;
433         int compareLast =
434                 sequence1.get(lastIndexOfSequence1).getTimestamp().compareTo(sequence2.get(lastIndexOfSequence2).getTimestamp());
435         // Check the signs of compare and compareLast
436         if ((compare <= 0 && compareLast > 0) ||
437             (compareLast <= 0 && compare > 0)) {
438             mOverlapCounter++;
439             // TODO: Probably not the best approach but we consider overlap if it happens more than once
440             if (mOverlapCounter > 1) {
441                 throw new Error("OVERLAP WARNING: " + "" +
442                         "One sequence is in the other. Please remove one of the sequences: " +
443                         sequence1.get(0).length() + "... OR " +
444                         sequence2.get(0).length() + "...");
445             }
446         }
447
448     }
449
450     /**
451      * Gets the {@link IpV4Packet} contained in {@code packet}, or throws a {@link NullPointerException} if
452      * {@code packet} does not contain an {@link IpV4Packet}.
453      * @param packet A {@link PcapPacket} that is expected to contain an {@link IpV4Packet}.
454      * @return The {@link IpV4Packet} contained in {@code packet}.
455      * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
456      */
457     private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
458         return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
459     }
460
461     /**
462      * Gets the {@link EthernetPacket} contained in {@code packet}, or throws a {@link NullPointerException} if
463      * {@code packet} does not contain an {@link EthernetPacket}.
464      * @param packet A {@link PcapPacket} that is expected to contain an {@link EthernetPacket}.
465      * @return The {@link EthernetPacket} contained in {@code packet}.
466      * @throws NullPointerException if {@code packet} does not encapsulate an {@link EthernetPacket}.
467      */
468     private static final EthernetPacket getEthernetPacketOrThrow(PcapPacket packet) {
469         return Objects.requireNonNull(packet.get(EthernetPacket.class), "not an Ethernet packet");
470     }
471
472     /**
473      * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
474      *
475      * @param signatures A {@link List} of {@link List} of {@link List} of
476      *          {@link PcapPacket} objects that needs to be printed.
477      * @param resultsWriter PrintWriter object to write into log file.
478      * @param printToOutput Boolean to decide whether to print out to screen or just log file.
479      */
480     public static void printSignatures(List<List<List<PcapPacket>>> signatures, PrintWriter resultsWriter, boolean
481                                        printToOutput) {
482
483         // Iterate over the list of all clusters/sequences
484         int sequenceCounter = 0;
485         for(List<List<PcapPacket>> listListPcapPacket : signatures) {
486             // Iterate over every member of a cluster/sequence
487             PrintWriterUtils.print("====== SEQUENCE " + ++sequenceCounter, resultsWriter, printToOutput);
488             PrintWriterUtils.println(" - " + listListPcapPacket.size() + " MEMBERS ======", resultsWriter,
489                     printToOutput);
490             for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
491                 // Print out packet lengths in a sequence
492                 int packetCounter = 0;
493                 for(PcapPacket pcapPacket : listPcapPacket) {
494                     if(pcapPacket != null) {
495                         String srcIp = pcapPacket.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress();
496                         String dstIp = pcapPacket.get(IpV4Packet.class).getHeader().getDstAddr().getHostAddress();
497                         String direction = srcIp.startsWith("10.") || srcIp.startsWith("192.168.") ?
498                                 "(C-" : "(S-";
499                         direction = dstIp.startsWith("10.") || dstIp.startsWith("192.168.") ?
500                                 direction + "C)" : direction + "S)";
501                         PrintWriterUtils.print(pcapPacket.length() + direction, resultsWriter, printToOutput);
502                     }
503                     if(packetCounter < listPcapPacket.size() - 1) {
504                         // Provide space if not last packet
505                         PrintWriterUtils.print(" ", resultsWriter, printToOutput);
506                     } else {
507                         // Newline if last packet
508                         PrintWriterUtils.println("", resultsWriter, printToOutput);
509                     }
510                     packetCounter++;
511                 }
512             }
513         }
514     }
515
516     /**
517      * Extract core point range in the form of {@code List} of {@code List} of {@code PcapPacket} objects.
518      *
519      * @param pairs The pairs for core points extraction.
520      * @param eps Epsilon value for the DBSCAN algorithm.
521      * @param minPts minPts value for the DBSCAN algorithm.
522      * @return A {@link List} of {@link List} of {@code PcapPacket} objects that contains core points range
523      *          in the first and second element.
524      */
525     public static List<List<PcapPacket>> extractRangeCorePoints(List<List<PcapPacket>> pairs, double eps, int minPts) {
526
527         // Initialize min and max value
528         PcapPacket minFirstElement = null;
529         PcapPacket maxFirstElement = null;
530         PcapPacket minSecondElement = null;
531         PcapPacket maxSecondElement = null;
532
533         // Iterate over pairs
534         for(List<PcapPacket> pair : pairs) {
535             if (isCorePoint(pair, pairs, eps, minPts)) {
536                 // Record the first element
537                 if (minFirstElement == null || pair.get(0).length() < minFirstElement.length()) {
538                     minFirstElement = pair.get(0);
539                 }
540                 if (maxFirstElement == null || pair.get(0).length() > maxFirstElement.length()) {
541                     maxFirstElement = pair.get(0);
542                 }
543                 // Record the second element
544                 if (minSecondElement == null || pair.get(1).length() < minSecondElement.length()) {
545                     minSecondElement = pair.get(1);
546                 }
547                 if (maxSecondElement == null || pair.get(1).length() > maxSecondElement.length()) {
548                     maxSecondElement = pair.get(1);
549                 }
550             }
551         }
552         List<PcapPacket> corePointLowerBound = new ArrayList<>();
553         corePointLowerBound.add(0, minFirstElement);
554         corePointLowerBound.add(1, minSecondElement);
555         List<PcapPacket> corePointUpperBound = new ArrayList<>();
556         corePointUpperBound.add(0, maxFirstElement);
557         corePointUpperBound.add(1, maxSecondElement);
558         // Combine lower and upper bounds
559         List<List<PcapPacket>> listRangeCorePoints = new ArrayList<>();
560         listRangeCorePoints.add(corePointLowerBound);
561         listRangeCorePoints.add(corePointUpperBound);
562
563         return listRangeCorePoints;
564     }
565
566     /**
567      * Test whether the {@code List} of {@code PcapPacket} objects is a core point.
568      *
569      * @param pair The pair to be tested.
570      * @param pairs All of the pairs.
571      * @param eps Epsilon value for the DBSCAN algorithm.
572      * @param minPts minPts value for the DBSCAN algorithm.
573      * @return True if the pair is a core point.
574      */
575     private static boolean isCorePoint(List<PcapPacket> pair, List<List<PcapPacket>> pairs, double eps, int minPts) {
576
577         int corePoints = 0;
578         int x1 = pair.get(0) == null ? 0 : pair.get(0).length();
579         int y1 = pair.get(1) == null ? 0 : pair.get(1).length();
580         // Check if we have enough core points
581         for(List<PcapPacket> pairInPairs : pairs) {
582             int x2 = pairInPairs.get(0) == null ? 0 : pairInPairs.get(0).length();
583             int y2 = pairInPairs.get(1) == null ? 0 : pairInPairs.get(1).length();
584             // Measure distance between x and y
585             double distance = Math.sqrt(Math.pow((double)(x2 - x1), 2) + Math.pow((double)(y2 - y1), 2));
586             // Increment core points count if this point is within eps
587             if (distance <= eps) {
588                 corePoints++;
589             }
590         }
591         // Return true if the number of core points >= minPts
592         if (corePoints >= minPts) {
593             return true;
594         }
595
596         return false;
597     }
598
599     /**
600      * Test the conservativeness of the signatures (basically whether we want strict or range-based matching).
601      * We go for a conservative approach (strict matching) when there is no range or there are ranges but the
602      * ranges overlap across multiple signatures, e.g., ON and OFF signatures.
603      *
604      * @param signature The signature we want to check and overwrite if needed.
605      * @param eps Epsilon value for the DBSCAN algorithm.
606      * @param otherSignatures Other signatures we want to check against this signature.
607      * @return A boolean that is True when range-based matching is used.
608      */
609     public static boolean isRangeBasedMatching(List<List<List<PcapPacket>>> signature, double eps,
610                                                 List<List<List<PcapPacket>>> ...otherSignatures) {
611         // Check against multiple signatures
612         // TODO: Per March 2019 we only support ON and OFF signatures though
613         for(List<List<List<PcapPacket>>> otherSig : otherSignatures) {
614             // Do conservative strict matching if there is any overlap
615             if (isConservativeChecking(signature, otherSig, eps)) {
616                 return false;
617             }
618         }
619         return true;
620     }
621
622     /**
623      * Test the conservativeness of the signatures (basically whether we want strict or range-based matching).
624      * We go for a conservative approach (strict matching) when there is no range or there are ranges but the
625      * ranges overlap across multiple signatures, e.g., ON and OFF signatures.
626      *
627      * @param signature The signature we want to check and overwrite if needed.
628      * @param corePointRange The core points range of this signature.
629      * @return A boolean that is True when range-based matching is used.
630      */
631     public static List<List<List<PcapPacket>>> useRangeBasedMatching(List<List<List<PcapPacket>>> signature,
632                                                                      List<List<List<PcapPacket>>> corePointRange) {
633         // Do range-based checking instead if there is no overlap
634         // Transform our signature into a range-based format
635         List<List<List<PcapPacket>>> rangeBasedSignature = getSequenceRanges(signature);
636         // We have to iterate sequence by sequence in the signature that has already gone through concatenation/merging
637         // And compare the packet lengths against the ones in corePointRange that are still in pairs/points
638         List<List<List<PcapPacket>>> finalSignature = new ArrayList<>();
639
640         // Construct the range-based signature
641         for(List<List<PcapPacket>> listOfSequences : rangeBasedSignature) {
642             List<PcapPacket> sequenceLowerBound = listOfSequences.get(0);
643             List<PcapPacket> sequenceUpperBound = listOfSequences.get(1);
644             List<List<PcapPacket>> newList = new ArrayList<>();
645             List<PcapPacket> newListLowerBound = new ArrayList<>();
646             List<PcapPacket> newListUpperBound = new ArrayList<>();
647             // Iterate over the packets
648             for(PcapPacket lowerBound : sequenceLowerBound) {
649                 // Look for the lower and upper bounds from the signature
650                 PcapPacket upperBound = sequenceUpperBound.get(sequenceLowerBound.indexOf(lowerBound));
651                 // Look for the lower and upper bounds from the cluster analysis (core point range)
652                 List<PcapPacket> bounds = getCorePointBounds(corePointRange, lowerBound, upperBound);
653                 // Add into list
654                 // The first element is the lower bound and the second element is the upper bound
655                 newListLowerBound.add(bounds.get(0));
656                 newListUpperBound.add(bounds.get(1));
657             }
658             newList.add(0, newListLowerBound);
659             newList.add(1, newListUpperBound);
660             finalSignature.add(newList);
661         }
662
663         return finalSignature;
664     }
665
666     /*
667      * Get the corresponding PcapPacket object for lower and upper bounds.
668      */
669     private static List<PcapPacket> getCorePointBounds(List<List<List<PcapPacket>>> corePointRange,
670                                                        PcapPacket lowerBound, PcapPacket upperBound) {
671
672         List<PcapPacket> listBounds = new ArrayList<>();
673         // Just return the lower and upper bounds when their values are the same --- faster
674         if (lowerBound.length() == upperBound.length()) {
675             listBounds.add(0, lowerBound);
676             listBounds.add(1, upperBound);
677             return listBounds;
678         }
679         // Iterate over PcapPacket one by one
680         for(List<List<PcapPacket>> listOfListPcapPacket : corePointRange) {
681             List<PcapPacket> listCorePointLowerBound = listOfListPcapPacket.get(0);
682             List<PcapPacket> listCorePointUpperBound = listOfListPcapPacket.get(1);
683             for(PcapPacket corePointLowerBound : listCorePointLowerBound) {
684                 if (corePointLowerBound == null) { // Skip if null!
685                     continue;
686                 }
687                 PcapPacket corePointUpperBound =
688                         listCorePointUpperBound.get(listCorePointLowerBound.indexOf(corePointLowerBound));
689                 // Return if the match for the core point bounds is found
690                 // Basically the core point range has to be within the signature range
691                 if (lowerBound.length() <= corePointLowerBound.length() &&
692                     corePointUpperBound.length() <= upperBound.length()) {
693                     listBounds.add(0, corePointLowerBound);
694                     listBounds.add(1, corePointUpperBound);
695                     return listBounds;
696                 }
697                 // Just skip the null elements
698                 if (lowerBound == null && upperBound == null) {
699                     continue;
700                 }
701             }
702         }
703         // Return null if not found
704         return null;
705     }
706
707     /**
708      * Check if there is any overlap between the signature stored in this class and another signature.
709      * Conditions:
710      * 1) If both signatures do not have any range, then we need to do conservative checking (return true).
711      * 2) If both signatures have the same number of packets/packet lengths, then we check the range; if the
712      *    numbers of packets/packet lengths are different then we assume that there is no overlap.
713      * 3) If there is any range in the signatures, then we need to check for overlap.
714      * 4) If there is overlap for EVERY packet/packet length, then we return true (conservative checking);
715      *    otherwise false (range-based checking).
716      *
717      * @param signature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
718      *                  for overlaps with the other signature.
719      * @param otherSignature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
720      *                       for overlaps with the signature.
721      * @param eps Epsilon value for the DBSCAN algorithm.
722      * @return A boolean that is true if there is an overlap; false otherwise.
723      */
724     public static boolean isConservativeChecking(List<List<List<PcapPacket>>> signature,
725                                                  List<List<List<PcapPacket>>> otherSignature,
726                                                  double eps) {
727
728         // Get the ranges of the two signatures
729         List<List<List<PcapPacket>>> signatureRanges = getSequenceRanges(signature);
730         List<List<List<PcapPacket>>> otherSignatureRanges = getSequenceRanges(otherSignature);
731         if (signature.size() == 1 && signature.get(0).get(0).size() == 2) {
732             // The signature only has 2 packets
733             return true;
734         } else if (!isRangeBased(signatureRanges) && !isRangeBased(otherSignatureRanges)) {
735             // Conservative checking when there is no range
736             return true;
737         } else if(signatureRanges.size() != otherSignatureRanges.size()) {
738             // The two signatures have different numbers of packets/packet lengths
739             return false;
740         } else {
741             // There is range; check if there is overlap
742             return checkOverlap(signatureRanges, otherSignatureRanges, eps);
743         }
744     }
745
746     /* Find the sequence with the minimum packet lengths.
747      * The second-layer list should contain the minimum sequence for element 0 and maximum sequence for element 1.
748      */
749     private static List<List<List<PcapPacket>>> getSequenceRanges(List<List<List<PcapPacket>>> signature) {
750
751         // Start from the first index
752         List<List<List<PcapPacket>>> rangeBasedSequence = new ArrayList<>();
753         for(List<List<PcapPacket>> listListPcapPacket : signature) {
754             List<List<PcapPacket>> minMaxSequence = new ArrayList<>();
755             // Both searches start from index 0
756             List<PcapPacket> minSequence = new ArrayList<>(listListPcapPacket.get(0));
757             List<PcapPacket> maxSequence = new ArrayList<>(listListPcapPacket.get(0));
758             for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
759                 for(PcapPacket pcapPacket : listPcapPacket) {
760                     int index = listPcapPacket.indexOf(pcapPacket);
761                     // Set the new minimum if length at the index is minimum
762                     if (pcapPacket.length() < minSequence.get(index).length()) {
763                         minSequence.set(index, pcapPacket);
764                     }
765                     // Set the new maximum if length at the index is maximum
766                     if (pcapPacket.length() > maxSequence.get(index).length()) {
767                         maxSequence.set(index, pcapPacket);
768                     }
769                 }
770             }
771             // minSequence as element 0 and maxSequence as element 1
772             minMaxSequence.add(minSequence);
773             minMaxSequence.add(maxSequence);
774             rangeBasedSequence.add(minMaxSequence);
775         }
776
777         return rangeBasedSequence;
778     }
779
780     /*
781      * Check for overlap since we have range in at least one of the signatures.
782      * Overlap is only true when all ranges overlap. We need to check in order.
783      */
784     private static boolean checkOverlap(List<List<List<PcapPacket>>> signatureRanges,
785                                  List<List<List<PcapPacket>>> otherSignatureRanges, double eps) {
786
787         for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
788             // Lower bound of the range is in index 0
789             // Upper bound of the range is in index 1
790             int sequenceSetIndex = signatureRanges.indexOf(listListPcapPacket);
791             List<PcapPacket> minSequenceSignature = listListPcapPacket.get(0);
792             List<PcapPacket> maxSequenceSignature = listListPcapPacket.get(1);
793             for(PcapPacket pcapPacket : minSequenceSignature) {
794                 // Get the lower and upper bounds of the current signature
795                 int packetIndex = minSequenceSignature.indexOf(pcapPacket);
796                 int lowerBound = pcapPacket.length();
797                 int upperBound = maxSequenceSignature.get(packetIndex).length();
798                 // Check for range overlap in the other signature!
799                 // Check the packet/packet length at the same position
800                 List<PcapPacket> minSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(0);
801                 List<PcapPacket> maxSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(1);
802                 int lowerBoundOther = minSequenceSignatureOther.get(packetIndex).length();
803                 int upperBoundOther = maxSequenceSignatureOther.get(packetIndex).length();
804                 if (!(lowerBoundOther-(int)eps <= lowerBound && lowerBound <= upperBoundOther+(int)eps) &&
805                     !(lowerBoundOther-(int)eps <= upperBound && upperBound <= upperBoundOther+(int)eps)) {
806                     return false;
807                 }
808             }
809         }
810
811         return true;
812     }
813
814     /*
815      * Check and see if there is any range in the signatures
816      */
817     private static boolean isRangeBased(List<List<List<PcapPacket>>> signatureRanges) {
818
819         for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
820             // Lower bound of the range is in index 0
821             // Upper bound of the range is in index 1
822             List<PcapPacket> minSequence = listListPcapPacket.get(0);
823             List<PcapPacket> maxSequence = listListPcapPacket.get(1);
824             for(PcapPacket pcapPacket : minSequence) {
825                 int index = minSequence.indexOf(pcapPacket);
826                 if (pcapPacket.length() != maxSequence.get(index).length()) {
827                     // If there is any packet length that differs in the minSequence
828                     // and maxSequence, then it is range-based
829                     return true;
830                 }
831             }
832         }
833
834         return false;
835     }
836
837     /**
838      * Remove a sequence in a signature object.
839      *
840      * @param signatures A {@link List} of {@link List} of {@link List} of
841      *          {@link PcapPacket} objects.
842      * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
843      *          {@link PcapPacket} objects.
844      */
845     public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
846
847         // Sequence index starts from 0
848         signatures.remove(sequenceIndex);
849     }
850 }