1 package edu.uci.iotproject.util;
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;
15 import java.io.PrintWriter;
19 * Utility methods for inspecting {@link PcapPacket} properties.
21 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
22 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
24 public final class PcapPacketUtils {
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.
31 private static final int SIGNATURE_MERGE_THRESHOLD = 5;
34 * This is an overlap counter (we consider overlaps between signatures if it happens more than once)
36 private static int mOverlapCounter = 0;
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}.
44 public static MacAddress getEthSrcAddr(PcapPacket packet) {
45 return getEthernetPacketOrThrow(packet).getHeader().getSrcAddr();
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}.
53 public static MacAddress getEthDstAddr(PcapPacket packet) {
54 return getEthernetPacketOrThrow(packet).getHeader().getDstAddr();
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.
62 public static boolean isTcp(PcapPacket packet) {
63 return packet.get(TcpPacket.class) != null;
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
71 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
73 public static String getSourceIp(PcapPacket packet) {
74 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().getHostAddress();
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
82 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
84 public static String getDestinationIp(PcapPacket packet) {
85 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().getHostAddress();
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}.
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");
99 return tcpPacket.getHeader().getSrcPort().valueAsInt();
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}.
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");
113 return tcpPacket.getHeader().getDstPort().valueAsInt();
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}.
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;
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}.
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;
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}.
156 public static boolean isSrcIpLocal(PcapPacket packet) {
157 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().isSiteLocalAddress();
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}.
168 public static boolean isDstIpLocal(PcapPacket packet) {
169 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().isSiteLocalAddress();
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.
178 public static boolean isSyn(PcapPacket packet) {
179 TcpPacket tcp = packet.get(TcpPacket.class);
180 return tcp != null && tcp.getHeader().getSyn();
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.
189 public static boolean isAck(PcapPacket packet) {
190 TcpPacket tcp = packet.get(TcpPacket.class);
191 return tcp != null && tcp.getHeader().getAck();
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.
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());
210 // Create a list of list of PcapPacket objects.
211 ppListOfList.add(ppList);
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()));
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.
228 public static List<List<List<PcapPacket>>>
229 concatSequences(List<List<List<PcapPacket>>> signatures, List<Conversation> conversations) {
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++) {
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.
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.
274 } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
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
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;
295 if (signatures.size() < signaturesSize) {
296 // If there is a concatenation, we check again from index 0
297 signaturesSize = signatures.size();
300 signaturesSize = signatures.size();
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.
313 public static void cleanSignature(List<List<List<PcapPacket>>> signature) {
315 for(List<List<PcapPacket>> listOfListPcap : signature) {
316 for(List<PcapPacket> listOfPcap : listOfListPcap) {
317 listOfPcap.removeIf(el -> el == null);
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.
329 private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
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);
338 tmpListOfList.add(tmpList);
340 destList.add(tmpListOfList);
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.
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());
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) -> {
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;
387 // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
388 // by incrementing one of them.
389 if (timestamp1 < timestamp2)
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).
409 private static void overlapChecking(int compare, int comparePrev,
410 List<PcapPacket> sequence1, List<PcapPacket> sequence2,
411 int indexSequence1, int indexSequence2) {
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() + "...");
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--;
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)) {
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() + "...");
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}.
457 private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
458 return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
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}.
468 private static final EthernetPacket getEthernetPacketOrThrow(PcapPacket packet) {
469 return Objects.requireNonNull(packet.get(EthernetPacket.class), "not an Ethernet packet");
473 * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
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.
480 public static void printSignatures(List<List<List<PcapPacket>>> signatures, PrintWriter resultsWriter, boolean
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,
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.") ?
499 direction = dstIp.startsWith("10.") || dstIp.startsWith("192.168.") ?
500 direction + "C)" : direction + "S)";
501 PrintWriterUtils.print(pcapPacket.length() + direction, resultsWriter, printToOutput);
503 if(packetCounter < listPcapPacket.size() - 1) {
504 // Provide space if not last packet
505 PrintWriterUtils.print(" ", resultsWriter, printToOutput);
507 // Newline if last packet
508 PrintWriterUtils.println("", resultsWriter, printToOutput);
517 * Extract core point range in the form of {@code List} of {@code List} of {@code PcapPacket} objects.
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.
525 public static List<List<PcapPacket>> extractRangeCorePoints(List<List<PcapPacket>> pairs, double eps, int minPts) {
527 // Initialize min and max value
528 PcapPacket minFirstElement = null;
529 PcapPacket maxFirstElement = null;
530 PcapPacket minSecondElement = null;
531 PcapPacket maxSecondElement = null;
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);
540 if (maxFirstElement == null || pair.get(0).length() > maxFirstElement.length()) {
541 maxFirstElement = pair.get(0);
543 // Record the second element
544 if (minSecondElement == null || pair.get(1).length() < minSecondElement.length()) {
545 minSecondElement = pair.get(1);
547 if (maxSecondElement == null || pair.get(1).length() > maxSecondElement.length()) {
548 maxSecondElement = pair.get(1);
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);
563 return listRangeCorePoints;
567 * Test whether the {@code List} of {@code PcapPacket} objects is a core point.
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.
575 private static boolean isCorePoint(List<PcapPacket> pair, List<List<PcapPacket>> pairs, double eps, int minPts) {
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) {
591 // Return true if the number of core points >= minPts
592 if (corePoints >= minPts) {
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.
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.
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)) {
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.
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.
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<>();
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);
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));
658 newList.add(0, newListLowerBound);
659 newList.add(1, newListUpperBound);
660 finalSignature.add(newList);
663 return finalSignature;
667 * Get the corresponding PcapPacket object for lower and upper bounds.
669 private static List<PcapPacket> getCorePointBounds(List<List<List<PcapPacket>>> corePointRange,
670 PcapPacket lowerBound, PcapPacket upperBound) {
672 List<PcapPacket> listBounds = new ArrayList<>();
673 // Iterate over PcapPacket one by one
674 for(List<List<PcapPacket>> listOfListPcapPacket : corePointRange) {
675 List<PcapPacket> listCorePointLowerBound = listOfListPcapPacket.get(0);
676 List<PcapPacket> listCorePointUpperBound = listOfListPcapPacket.get(1);
677 for(PcapPacket corePointLowerBound : listCorePointLowerBound) {
678 if (corePointLowerBound == null) { // Skip if null!
681 PcapPacket corePointUpperBound =
682 listCorePointUpperBound.get(listCorePointLowerBound.indexOf(corePointLowerBound));
683 // Return if the match for the core point bounds is found
684 // Basically the core point range has to be within the signature range
685 if (lowerBound.length() <= corePointLowerBound.length() &&
686 corePointUpperBound.length() <= upperBound.length()) {
687 listBounds.add(0, corePointLowerBound);
688 listBounds.add(1, corePointUpperBound);
691 // Just skip the null elements
692 if (lowerBound == null && upperBound == null) {
697 // Return null if not found
702 * Check if there is any overlap between the signature stored in this class and another signature.
704 * 1) If both signatures do not have any range, then we need to do conservative checking (return true).
705 * 2) If both signatures have the same number of packets/packet lengths, then we check the range; if the
706 * numbers of packets/packet lengths are different then we assume that there is no overlap.
707 * 3) If there is any range in the signatures, then we need to check for overlap.
708 * 4) If there is overlap for EVERY packet/packet length, then we return true (conservative checking);
709 * otherwise false (range-based checking).
711 * @param signature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
712 * for overlaps with the other signature.
713 * @param otherSignature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
714 * for overlaps with the signature.
715 * @param eps Epsilon value for the DBSCAN algorithm.
716 * @return A boolean that is true if there is an overlap; false otherwise.
718 public static boolean isConservativeChecking(List<List<List<PcapPacket>>> signature,
719 List<List<List<PcapPacket>>> otherSignature,
722 // Get the ranges of the two signatures
723 List<List<List<PcapPacket>>> signatureRanges = getSequenceRanges(signature);
724 List<List<List<PcapPacket>>> otherSignatureRanges = getSequenceRanges(otherSignature);
725 if (signature.size() == 1 && signature.get(0).get(0).size() == 2) {
726 // The signature only has 2 packets
728 } else if (!isRangeBased(signatureRanges) && !isRangeBased(otherSignatureRanges)) {
729 // Conservative checking when there is no range
731 } else if(signatureRanges.size() != otherSignatureRanges.size()) {
732 // The two signatures have different numbers of packets/packet lengths
735 // There is range; check if there is overlap
736 return checkOverlap(signatureRanges, otherSignatureRanges, eps);
740 /* Find the sequence with the minimum packet lengths.
741 * The second-layer list should contain the minimum sequence for element 0 and maximum sequence for element 1.
743 private static List<List<List<PcapPacket>>> getSequenceRanges(List<List<List<PcapPacket>>> signature) {
745 // Start from the first index
746 List<List<List<PcapPacket>>> rangeBasedSequence = new ArrayList<>();
747 for(List<List<PcapPacket>> listListPcapPacket : signature) {
748 List<List<PcapPacket>> minMaxSequence = new ArrayList<>();
749 // Both searches start from index 0
750 List<PcapPacket> minSequence = new ArrayList<>(listListPcapPacket.get(0));
751 List<PcapPacket> maxSequence = new ArrayList<>(listListPcapPacket.get(0));
752 for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
753 for(PcapPacket pcapPacket : listPcapPacket) {
754 int index = listPcapPacket.indexOf(pcapPacket);
755 // Set the new minimum if length at the index is minimum
756 if (pcapPacket.length() < minSequence.get(index).length()) {
757 minSequence.set(index, pcapPacket);
759 // Set the new maximum if length at the index is maximum
760 if (pcapPacket.length() > maxSequence.get(index).length()) {
761 maxSequence.set(index, pcapPacket);
765 // minSequence as element 0 and maxSequence as element 1
766 minMaxSequence.add(minSequence);
767 minMaxSequence.add(maxSequence);
768 rangeBasedSequence.add(minMaxSequence);
771 return rangeBasedSequence;
775 * Check for overlap since we have range in at least one of the signatures.
776 * Overlap is only true when all ranges overlap. We need to check in order.
778 private static boolean checkOverlap(List<List<List<PcapPacket>>> signatureRanges,
779 List<List<List<PcapPacket>>> otherSignatureRanges, double eps) {
781 for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
782 // Lower bound of the range is in index 0
783 // Upper bound of the range is in index 1
784 int sequenceSetIndex = signatureRanges.indexOf(listListPcapPacket);
785 List<PcapPacket> minSequenceSignature = listListPcapPacket.get(0);
786 List<PcapPacket> maxSequenceSignature = listListPcapPacket.get(1);
787 for(PcapPacket pcapPacket : minSequenceSignature) {
788 // Get the lower and upper bounds of the current signature
789 int packetIndex = minSequenceSignature.indexOf(pcapPacket);
790 int lowerBound = pcapPacket.length();
791 int upperBound = maxSequenceSignature.get(packetIndex).length();
792 // Check for range overlap in the other signature!
793 // Check the packet/packet length at the same position
794 List<PcapPacket> minSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(0);
795 List<PcapPacket> maxSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(1);
796 int lowerBoundOther = minSequenceSignatureOther.get(packetIndex).length();
797 int upperBoundOther = maxSequenceSignatureOther.get(packetIndex).length();
798 if (!(lowerBoundOther-(int)eps <= lowerBound && lowerBound <= upperBoundOther+(int)eps) &&
799 !(lowerBoundOther-(int)eps <= upperBound && upperBound <= upperBoundOther+(int)eps)) {
809 * Check and see if there is any range in the signatures
811 private static boolean isRangeBased(List<List<List<PcapPacket>>> signatureRanges) {
813 for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
814 // Lower bound of the range is in index 0
815 // Upper bound of the range is in index 1
816 List<PcapPacket> minSequence = listListPcapPacket.get(0);
817 List<PcapPacket> maxSequence = listListPcapPacket.get(1);
818 for(PcapPacket pcapPacket : minSequence) {
819 int index = minSequence.indexOf(pcapPacket);
820 if (pcapPacket.length() != maxSequence.get(index).length()) {
821 // If there is any packet length that differs in the minSequence
822 // and maxSequence, then it is range-based
832 * Remove a sequence in a signature object.
834 * @param signatures A {@link List} of {@link List} of {@link List} of
835 * {@link PcapPacket} objects.
836 * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
837 * {@link PcapPacket} objects.
839 public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
841 // Sequence index starts from 0
842 signatures.remove(sequenceIndex);