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++) {
238 List<List<PcapPacket>> firstList = signatures.get(first);
239 for (int second = first+1; second < signatures.size(); second++) {
240 int maxSignatureEl = 0;
241 List<List<PcapPacket>> secondList = signatures.get(second);
242 int initialSecondListMembers = secondList.size();
243 // Iterate over the sequences in the first list.
244 for (List<PcapPacket> signature : firstList) {
245 signature.removeIf(el -> el == null); // Clean up null elements.
246 // Return the Conversation that the sequence is part of.
247 Conversation conv = TcpConversationUtils.returnConversation(signature, conversations);
248 // Find the element of the second list that is a match for that Conversation.
249 for (List<PcapPacket> ppList : secondList) {
250 ppList.removeIf(el -> el == null); // Clean up null elements.
251 // Check if they are part of a Conversation and are adjacent to the first sequence.
252 // If yes then merge into the first list.
253 TcpConversationUtils.SignaturePosition position =
254 TcpConversationUtils.isPartOfConversationAndAdjacent(signature, ppList, conv);
255 if (position == TcpConversationUtils.SignaturePosition.LEFT_ADJACENT) {
256 // Merge to the left side of the first sequence.
257 ppList.addAll(signature);
259 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
260 secondList.remove(ppList); // Remove as we merge.
262 } else if (position == TcpConversationUtils.SignaturePosition.RIGHT_ADJACENT) {
263 // Merge to the right side of the first sequence.
264 signature.addAll(ppList);
265 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
266 secondList.remove(ppList); // Remove as we merge.
268 } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
271 // Call it a successful merging if there are only less than 5 elements from the second list that
273 if (secondList.size() < SIGNATURE_MERGE_THRESHOLD) {
274 // Prune the unsuccessfully merged sequences (i.e., these will have size() < maxSignatureEl).
275 final int maxNumOfEl = maxSignatureEl;
276 // TODO: DOUBLE CHECK IF WE REALLY NEED TO PRUNE FAILED BINDINGS
277 // TODO: SOMETIMES THE SEQUENCES ARE JUST INCOMPLETE
278 // TODO: AND BOTH THE COMPLETE AND INCOMPLETE SEQUENCES ARE VALID SIGNATURES!
279 firstList.removeIf(el -> el.size() < maxNumOfEl);
280 // Remove the merged set of sequences when successful.
281 signatures.remove(secondList);
282 } else if (secondList.size() < initialSecondListMembers) {
283 // If only some of the sequences from the second list are merged, this means UNSUCCESSFUL merging.
284 // Return the original copy of the signatures object.
285 return copySignatures;
293 * Deep copy to create an entirely new {@link List} of {@link List} of {@link List} of {@link PcapPacket} objects.
294 * @param destList A {@link List} of {@link List} of {@link List} of
295 * {@link PcapPacket} objects that will be the final container of the deep copy
296 * @param sourceList A {@link List} of {@link List} of {@link List} of
297 * {@link PcapPacket} objects that will be the source of the deep copy.
299 private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
301 for(List<List<PcapPacket>> llPcapPacket : sourceList) {
302 List<List<PcapPacket>> tmpListOfList = new ArrayList<>();
303 for(List<PcapPacket> lPcapPacket : llPcapPacket) {
304 List<PcapPacket> tmpList = new ArrayList<>();
305 for(PcapPacket pcapPacket : lPcapPacket) {
306 tmpList.add(pcapPacket);
308 tmpListOfList.add(tmpList);
310 destList.add(tmpListOfList);
315 * Sort the sequences in the {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
316 * The purpose of this is to sort the order of sequences in the sequence list. For detection purposes, we need
317 * to know if one sequence occurs earlier/later in time with respect to the other sequences for more confidence
318 * in detecting the occurrence of an event.
319 * @param signatures A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects that needs sorting.
320 * We assume that innermost {@code List} of {@code PcapPacket} objects have been sorted ascending
321 * by timestamps. By the time we use this method, we should have sorted it when calling the
322 * {@code clusterToListOfPcapPackets} method.
323 * @return A sorted {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
325 public static List<List<List<PcapPacket>>> sortSequences(List<List<List<PcapPacket>>> signatures) {
326 // TODO: This is the simplest solution!!! Might not cover all corner cases.
327 // TODO: Sort the list of lists based on the first packet's timestamps!
328 // Collections.sort(signatures, (p1, p2) -> {
329 // //return p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
330 // int compare = p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
333 // TODO: The following is a more complete solution that covers corner cases.
334 // Sort the list of lists based on one-to-one comparison between timestamps of signatures on both lists.
335 // This also takes into account the fact that the number of signatures in the two lists could be different.
336 // Additionally, this code forces the comparison between two signatures only if they occur in the
337 // INCLUSION_WINDOW_MILLIS window; otherwise, it tries to find the right pair of signatures in the time window.
338 Collections.sort(signatures, (p1, p2) -> {
343 // Need to make sure that both are not out of bound!
344 while (count1 + 1 < p1.size() && count2 + 1 < p2.size()) {
345 long timestamp1 = p1.get(count1).get(0).getTimestamp().toEpochMilli();
346 long timestamp2 = p2.get(count2).get(0).getTimestamp().toEpochMilli();
347 // The two timestamps have to be within a 15-second window!
348 if (Math.abs(timestamp1 - timestamp2) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
349 // If these two are within INCLUSION_WINDOW_MILLIS window then compare!
350 compare = p1.get(count1).get(0).getTimestamp().compareTo(p2.get(count2).get(0).getTimestamp());
351 overlapChecking(compare, comparePrev, p1.get(count1), p2.get(count2),
352 signatures.indexOf(p1), signatures.indexOf(p2));
353 comparePrev = compare;
357 // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
358 // by incrementing one of them.
359 if (timestamp1 < timestamp2)
371 * Checks for overlapping between two packet sequences.
372 * @param compare Current comparison value between packet sequences p1 and p2
373 * @param comparePrev Previous comparison value between packet sequences p1 and p2
374 * @param sequence1 The packet sequence ({@link List} of {@link PcapPacket} objects).
375 * @param sequence2 The packet sequence ({@link List} of {@link PcapPacket} objects).
376 * @param indexSequence1 The index of packet sequence ({@link List} of {@link PcapPacket} objects).
377 * @param indexSequence2 The index of packet sequence ({@link List} of {@link PcapPacket} objects).
379 private static void overlapChecking(int compare, int comparePrev,
380 List<PcapPacket> sequence1, List<PcapPacket> sequence2,
381 int indexSequence1, int indexSequence2) {
383 // Check if p1 occurs before p2 but both have same overlap
384 if (comparePrev != 0) { // First time since it is 0
385 if (Integer.signum(compare) != Integer.signum(comparePrev)) {
386 // Throw an exception if the order of the two signatures is not consistent,
387 // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
388 throw new Error("OVERLAP WARNING: " + "" +
389 "Two sequences have some overlap. Please remove one of the sequences: " +
390 sequence1.get(0).length() + " with index " + indexSequence1 + " OR " +
391 sequence2.get(0).length() + " with index " + indexSequence2);
394 // Check if p1 is longer than p2 and p2 occurs during the occurrence of p1
395 int lastIndexOfSequence1 = sequence1.size() - 1;
396 int lastIndexOfSequence2 = sequence2.size() - 1;
398 sequence1.get(lastIndexOfSequence1).getTimestamp().compareTo(sequence2.get(lastIndexOfSequence2).getTimestamp());
399 // Check the signs of compare and compareLast
400 if ((compare <= 0 && compareLast > 0) ||
401 (compareLast <= 0 && compare > 0)) {
403 // TODO: Probably not the best approach but we consider overlap if it happens more than once
404 if (mOverlapCounter > 1) {
405 throw new Error("OVERLAP WARNING: " + "" +
406 "One sequence is in the other. Please remove one of the sequences: " +
407 sequence1.get(0).length() + "... OR " +
408 sequence2.get(0).length() + "...");
415 * Gets the {@link IpV4Packet} contained in {@code packet}, or throws a {@link NullPointerException} if
416 * {@code packet} does not contain an {@link IpV4Packet}.
417 * @param packet A {@link PcapPacket} that is expected to contain an {@link IpV4Packet}.
418 * @return The {@link IpV4Packet} contained in {@code packet}.
419 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
421 private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
422 return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
426 * Gets the {@link EthernetPacket} contained in {@code packet}, or throws a {@link NullPointerException} if
427 * {@code packet} does not contain an {@link EthernetPacket}.
428 * @param packet A {@link PcapPacket} that is expected to contain an {@link EthernetPacket}.
429 * @return The {@link EthernetPacket} contained in {@code packet}.
430 * @throws NullPointerException if {@code packet} does not encapsulate an {@link EthernetPacket}.
432 private static final EthernetPacket getEthernetPacketOrThrow(PcapPacket packet) {
433 return Objects.requireNonNull(packet.get(EthernetPacket.class), "not an Ethernet packet");
437 * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
439 * @param signatures A {@link List} of {@link List} of {@link List} of
440 * {@link PcapPacket} objects that needs to be printed.
441 * @param resultsWriter PrintWriter object to write into log file.
442 * @param printToOutput Boolean to decide whether to print out to screen or just log file.
444 public static void printSignatures(List<List<List<PcapPacket>>> signatures, PrintWriter resultsWriter, boolean
447 // Iterate over the list of all clusters/sequences
448 int sequenceCounter = 0;
449 for(List<List<PcapPacket>> listListPcapPacket : signatures) {
450 // Iterate over every member of a cluster/sequence
451 PrintWriterUtils.print("====== SEQUENCE " + ++sequenceCounter, resultsWriter, printToOutput);
452 PrintWriterUtils.println(" - " + listListPcapPacket.size() + " MEMBERS ======", resultsWriter,
454 for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
455 // Print out packet lengths in a sequence
456 int packetCounter = 0;
457 for(PcapPacket pcapPacket : listPcapPacket) {
458 if(pcapPacket != null) {
459 PrintWriterUtils.print(pcapPacket.length(), resultsWriter, printToOutput);
461 if(packetCounter < listPcapPacket.size() - 1) {
462 // Provide space if not last packet
463 PrintWriterUtils.print(" ", resultsWriter, printToOutput);
465 // Newline if last packet
466 PrintWriterUtils.println("", resultsWriter, printToOutput);
475 * Extract core point range in the form of {@code List} of {@code List} of {@code PcapPacket} objects.
477 * @param pairs The pairs for core points extraction.
478 * @param eps Epsilon value for the DBSCAN algorithm.
479 * @param minPts minPts value for the DBSCAN algorithm.
480 * @return A {@link List} of {@link List} of {@code PcapPacket} objects that contains core points range
481 * in the first and second element.
483 public static List<List<PcapPacket>> extractRangeCorePoints(List<List<PcapPacket>> pairs, double eps, int minPts) {
485 // Initialize min and max value
486 PcapPacket minFirstElement = null;
487 PcapPacket maxFirstElement = null;
488 PcapPacket minSecondElement = null;
489 PcapPacket maxSecondElement = null;
491 // Iterate over pairs
492 for(List<PcapPacket> pair : pairs) {
493 if (isCorePoint(pair, pairs, eps, minPts)) {
494 // Record the first element
495 if (minFirstElement == null || pair.get(0).length() < minFirstElement.length()) {
496 minFirstElement = pair.get(0);
498 if (maxFirstElement == null || pair.get(0).length() > maxFirstElement.length()) {
499 maxFirstElement = pair.get(0);
501 // Record the second element
502 if (minSecondElement == null || pair.get(1).length() < minSecondElement.length()) {
503 minSecondElement = pair.get(1);
505 if (maxSecondElement == null || pair.get(1).length() > maxSecondElement.length()) {
506 maxSecondElement = pair.get(1);
510 List<PcapPacket> corePointLowerBound = new ArrayList<>();
511 corePointLowerBound.add(0, minFirstElement);
512 corePointLowerBound.add(1, minSecondElement);
513 List<PcapPacket> corePointUpperBound = new ArrayList<>();
514 corePointUpperBound.add(0, maxFirstElement);
515 corePointUpperBound.add(1, maxSecondElement);
516 // Combine lower and upper bounds
517 List<List<PcapPacket>> listRangeCorePoints = new ArrayList<>();
518 listRangeCorePoints.add(corePointLowerBound);
519 listRangeCorePoints.add(corePointUpperBound);
521 return listRangeCorePoints;
525 * Test whether the {@code List} of {@code PcapPacket} objects is a core point.
527 * @param pair The pair to be tested.
528 * @param pairs All of the pairs.
529 * @param eps Epsilon value for the DBSCAN algorithm.
530 * @param minPts minPts value for the DBSCAN algorithm.
531 * @return True if the pair is a core point.
533 private static boolean isCorePoint(List<PcapPacket> pair, List<List<PcapPacket>> pairs, double eps, int minPts) {
536 int x1 = pair.get(0) == null ? 0 : pair.get(0).length();
537 int y1 = pair.get(1) == null ? 0 : pair.get(1).length();
538 // Check if we have enough core points
539 for(List<PcapPacket> pairInPairs : pairs) {
540 int x2 = pairInPairs.get(0) == null ? 0 : pairInPairs.get(0).length();
541 int y2 = pairInPairs.get(1) == null ? 0 : pairInPairs.get(1).length();
542 // Measure distance between x and y
543 double distance = Math.sqrt(Math.pow((double)(x2 - x1), 2) + Math.pow((double)(y2 - y1), 2));
544 // Increment core points count if this point is within eps
545 if (distance <= eps) {
549 // Return true if the number of core points >= minPts
550 if (corePoints >= minPts) {
558 * Test the conservativeness of the signatures (basically whether we want strict or range-based matching).
559 * We go for a conservative approach (strict matching) when there is no range or there are ranges but the
560 * ranges overlap across multiple signatures, e.g., ON and OFF signatures.
562 * @param signature The signature we want to check and overwrite if needed.
563 * @param eps Epsilon value for the DBSCAN algorithm.
564 * @param otherSignatures Other signatures we want to check against this signature.
565 * @return A boolean that is True when range-based matching is used.
567 public static boolean isRangeBasedMatching(List<List<List<PcapPacket>>> signature, double eps,
568 List<List<List<PcapPacket>>> ...otherSignatures) {
569 // Check against multiple signatures
570 // TODO: Per March 2019 we only support ON and OFF signatures though
571 for(List<List<List<PcapPacket>>> otherSig : otherSignatures) {
572 // Do conservative strict matching if there is any overlap
573 if (isConservativeChecking(signature, otherSig, eps)) {
581 * Test the conservativeness of the signatures (basically whether we want strict or range-based matching).
582 * We go for a conservative approach (strict matching) when there is no range or there are ranges but the
583 * ranges overlap across multiple signatures, e.g., ON and OFF signatures.
585 * @param signature The signature we want to check and overwrite if needed.
586 * @param corePointRange The core points range of this signature.
587 * @return A boolean that is True when range-based matching is used.
589 public static List<List<List<PcapPacket>>> useRangeBasedMatching(List<List<List<PcapPacket>>> signature,
590 List<List<List<PcapPacket>>> corePointRange) {
591 // Do range-based checking instead if there is no overlap
592 // Transform our signature into a range-based format
593 List<List<List<PcapPacket>>> rangeBasedSignature = getSequenceRanges(signature);
594 // We have to iterate sequence by sequence in the signature that has already gone through concatenation/merging
595 // And compare the packet lengths against the ones in corePointRange that are still in pairs/points
596 List<List<List<PcapPacket>>> finalSignature = new ArrayList<>();
598 // Construct the range-based signature
599 for(List<List<PcapPacket>> listOfSequences : rangeBasedSignature) {
600 List<PcapPacket> sequenceLowerBound = listOfSequences.get(0);
601 List<PcapPacket> sequenceUpperBound = listOfSequences.get(1);
602 List<List<PcapPacket>> newList = new ArrayList<>();
603 List<PcapPacket> newListLowerBound = new ArrayList<>();
604 List<PcapPacket> newListUpperBound = new ArrayList<>();
605 // Iterate over the packets
606 for(PcapPacket lowerBound : sequenceLowerBound) {
607 // Look for the lower and upper bounds from the signature
608 PcapPacket upperBound = sequenceUpperBound.get(sequenceLowerBound.indexOf(lowerBound));
609 // Look for the lower and upper bounds from the cluster analysis (core point range)
610 List<PcapPacket> bounds = getCorePointBounds(corePointRange, lowerBound, upperBound);
612 // The first element is the lower bound and the second element is the upper bound
613 newListLowerBound.add(bounds.get(0));
614 newListUpperBound.add(bounds.get(1));
616 newList.add(0, newListLowerBound);
617 newList.add(1, newListUpperBound);
618 finalSignature.add(newList);
621 return finalSignature;
625 * Get the corresponding PcapPacket object for lower and upper bounds.
627 private static List<PcapPacket> getCorePointBounds(List<List<List<PcapPacket>>> corePointRange,
628 PcapPacket lowerBound, PcapPacket upperBound) {
630 List<PcapPacket> listBounds = new ArrayList<>();
631 // Iterate over PcapPacket one by one
632 for(List<List<PcapPacket>> listOfListPcapPacket : corePointRange) {
633 List<PcapPacket> listCorePointLowerBound = listOfListPcapPacket.get(0);
634 List<PcapPacket> listCorePointUpperBound = listOfListPcapPacket.get(1);
635 for(PcapPacket corePointLowerBound : listCorePointLowerBound) {
636 if (corePointLowerBound == null) { // Skip if null!
639 PcapPacket corePointUpperBound =
640 listCorePointUpperBound.get(listCorePointLowerBound.indexOf(corePointLowerBound));
641 // Return if the match for the core point bounds is found
642 // Basically the core point range has to be within the signature range
643 if (lowerBound.length() <= corePointLowerBound.length() &&
644 corePointUpperBound.length() <= upperBound.length()) {
645 listBounds.add(0, corePointLowerBound);
646 listBounds.add(1, corePointUpperBound);
649 // Just skip the null elements
650 if (lowerBound == null && upperBound == null) {
655 // Return null if not found
660 * Check if there is any overlap between the signature stored in this class and another signature.
662 * 1) If both signatures do not have any range, then we need to do conservative checking (return true).
663 * 2) If both signatures have the same number of packets/packet lengths, then we check the range; if the
664 * numbers of packets/packet lengths are different then we assume that there is no overlap.
665 * 3) If there is any range in the signatures, then we need to check for overlap.
666 * 4) If there is overlap for EVERY packet/packet length, then we return true (conservative checking);
667 * otherwise false (range-based checking).
669 * @param signature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
670 * for overlaps with the other signature.
671 * @param otherSignature A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects to be checked
672 * for overlaps with the signature.
673 * @param eps Epsilon value for the DBSCAN algorithm.
674 * @return A boolean that is true if there is an overlap; false otherwise.
676 public static boolean isConservativeChecking(List<List<List<PcapPacket>>> signature,
677 List<List<List<PcapPacket>>> otherSignature,
680 // Get the ranges of the two signatures
681 List<List<List<PcapPacket>>> signatureRanges = getSequenceRanges(signature);
682 List<List<List<PcapPacket>>> otherSignatureRanges = getSequenceRanges(otherSignature);
683 if (signature.size() == 1 && signature.get(0).get(0).size() == 2) {
684 // The signature only has 2 packets
686 } else if (!isRangeBased(signatureRanges) && !isRangeBased(otherSignatureRanges)) {
687 // Conservative checking when there is no range
689 } else if(signatureRanges.size() != otherSignatureRanges.size()) {
690 // The two signatures have different numbers of packets/packet lengths
693 // There is range; check if there is overlap
694 return checkOverlap(signatureRanges, otherSignatureRanges, eps);
698 /* Find the sequence with the minimum packet lengths.
699 * The second-layer list should contain the minimum sequence for element 0 and maximum sequence for element 1.
701 private static List<List<List<PcapPacket>>> getSequenceRanges(List<List<List<PcapPacket>>> signature) {
703 // Start from the first index
704 List<List<List<PcapPacket>>> rangeBasedSequence = new ArrayList<>();
705 for(List<List<PcapPacket>> listListPcapPacket : signature) {
706 List<List<PcapPacket>> minMaxSequence = new ArrayList<>();
707 // Both searches start from index 0
708 List<PcapPacket> minSequence = new ArrayList<>(listListPcapPacket.get(0));
709 List<PcapPacket> maxSequence = new ArrayList<>(listListPcapPacket.get(0));
710 for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
711 for(PcapPacket pcapPacket : listPcapPacket) {
712 int index = listPcapPacket.indexOf(pcapPacket);
713 // Set the new minimum if length at the index is minimum
714 if (pcapPacket.length() < minSequence.get(index).length()) {
715 minSequence.set(index, pcapPacket);
717 // Set the new maximum if length at the index is maximum
718 if (pcapPacket.length() > maxSequence.get(index).length()) {
719 maxSequence.set(index, pcapPacket);
723 // minSequence as element 0 and maxSequence as element 1
724 minMaxSequence.add(minSequence);
725 minMaxSequence.add(maxSequence);
726 rangeBasedSequence.add(minMaxSequence);
729 return rangeBasedSequence;
733 * Check for overlap since we have range in at least one of the signatures.
734 * Overlap is only true when all ranges overlap. We need to check in order.
736 private static boolean checkOverlap(List<List<List<PcapPacket>>> signatureRanges,
737 List<List<List<PcapPacket>>> otherSignatureRanges, double eps) {
739 for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
740 // Lower bound of the range is in index 0
741 // Upper bound of the range is in index 1
742 int sequenceSetIndex = signatureRanges.indexOf(listListPcapPacket);
743 List<PcapPacket> minSequenceSignature = listListPcapPacket.get(0);
744 List<PcapPacket> maxSequenceSignature = listListPcapPacket.get(1);
745 for(PcapPacket pcapPacket : minSequenceSignature) {
746 // Get the lower and upper bounds of the current signature
747 int packetIndex = minSequenceSignature.indexOf(pcapPacket);
748 int lowerBound = pcapPacket.length();
749 int upperBound = maxSequenceSignature.get(packetIndex).length();
750 // Check for range overlap in the other signature!
751 // Check the packet/packet length at the same position
752 List<PcapPacket> minSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(0);
753 List<PcapPacket> maxSequenceSignatureOther = otherSignatureRanges.get(sequenceSetIndex).get(1);
754 int lowerBoundOther = minSequenceSignatureOther.get(packetIndex).length();
755 int upperBoundOther = maxSequenceSignatureOther.get(packetIndex).length();
756 if (!(lowerBoundOther-(int)eps <= lowerBound && lowerBound <= upperBoundOther+(int)eps) &&
757 !(lowerBoundOther-(int)eps <= upperBound && upperBound <= upperBoundOther+(int)eps)) {
767 * Check and see if there is any range in the signatures
769 private static boolean isRangeBased(List<List<List<PcapPacket>>> signatureRanges) {
771 for(List<List<PcapPacket>> listListPcapPacket : signatureRanges) {
772 // Lower bound of the range is in index 0
773 // Upper bound of the range is in index 1
774 List<PcapPacket> minSequence = listListPcapPacket.get(0);
775 List<PcapPacket> maxSequence = listListPcapPacket.get(1);
776 for(PcapPacket pcapPacket : minSequence) {
777 int index = minSequence.indexOf(pcapPacket);
778 if (pcapPacket.length() != maxSequence.get(index).length()) {
779 // If there is any packet length that differs in the minSequence
780 // and maxSequence, then it is range-based
790 * Remove a sequence in a signature object.
792 * @param signatures A {@link List} of {@link List} of {@link List} of
793 * {@link PcapPacket} objects.
794 * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
795 * {@link PcapPacket} objects.
797 public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
799 // Sequence index starts from 0
800 signatures.remove(sequenceIndex);