1 package edu.uci.iotproject.util;
3 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
4 import edu.uci.iotproject.analysis.PcapPacketPair;
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
7 import org.apache.commons.math3.stat.clustering.Cluster;
8 import org.pcap4j.core.PcapPacket;
9 import org.pcap4j.packet.EthernetPacket;
10 import org.pcap4j.packet.IpV4Packet;
11 import org.pcap4j.packet.TcpPacket;
12 import org.pcap4j.util.MacAddress;
17 * Utility methods for inspecting {@link PcapPacket} properties.
19 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
20 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
22 public final class PcapPacketUtils {
25 * This is the threshold value for a signature's number of members
26 * If after a merging the number of members of a signature falls below this threshold, then we can boldly
27 * get rid of that signature.
29 private static final int SIGNATURE_MERGE_THRESHOLD = 5;
32 * This is an overlap counter (we consider overlaps between signatures if it happens more than once)
34 private static int mOverlapCounter = 0;
38 * Gets the source address of the Ethernet part of {@code packet}.
39 * @param packet The packet for which the Ethernet source address is to be extracted.
40 * @return The source address of the Ethernet part of {@code packet}.
42 public static MacAddress getEthSrcAddr(PcapPacket packet) {
43 return getEthernetPacketOrThrow(packet).getHeader().getSrcAddr();
47 * Gets the destination address of the Ethernet part of {@code packet}.
48 * @param packet The packet for which the Ethernet destination address is to be extracted.
49 * @return The destination address of the Ethernet part of {@code packet}.
51 public static MacAddress getEthDstAddr(PcapPacket packet) {
52 return getEthernetPacketOrThrow(packet).getHeader().getDstAddr();
56 * Determines if a given {@link PcapPacket} wraps a {@link TcpPacket}.
57 * @param packet The {@link PcapPacket} to inspect.
58 * @return {@code true} if {@code packet} wraps a {@link TcpPacket}, {@code false} otherwise.
60 public static boolean isTcp(PcapPacket packet) {
61 return packet.get(TcpPacket.class) != null;
65 * Gets the source IP (in decimal format) of an IPv4 packet.
66 * @param packet The packet for which the IPv4 source address is to be extracted.
67 * @return The decimal representation of the source IP of {@code packet} <em>iff</em> {@code packet} wraps an
69 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
71 public static String getSourceIp(PcapPacket packet) {
72 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().getHostAddress();
76 * Gets the destination IP (in decimal format) of an IPv4 packet.
77 * @param packet The packet for which the IPv4 source address is to be extracted.
78 * @return The decimal representation of the destination IP of {@code packet} <em>iff</em> {@code packet} wraps an
80 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
82 public static String getDestinationIp(PcapPacket packet) {
83 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().getHostAddress();
87 * Gets the source port of a TCP packet.
88 * @param packet The packet for which the source port is to be extracted.
89 * @return The source port of the {@link TcpPacket} encapsulated by {@code packet}.
90 * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
92 public static int getSourcePort(PcapPacket packet) {
93 TcpPacket tcpPacket = packet.get(TcpPacket.class);
94 if (tcpPacket == null) {
95 throw new IllegalArgumentException("not a TCP packet");
97 return tcpPacket.getHeader().getSrcPort().valueAsInt();
101 * Gets the destination port of a TCP packet.
102 * @param packet The packet for which the destination port is to be extracted.
103 * @return The destination port of the {@link TcpPacket} encapsulated by {@code packet}.
104 * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
106 public static int getDestinationPort(PcapPacket packet) {
107 TcpPacket tcpPacket = packet.get(TcpPacket.class);
108 if (tcpPacket == null) {
109 throw new IllegalArgumentException("not a TCP packet");
111 return tcpPacket.getHeader().getDstPort().valueAsInt();
115 * Helper method to determine if the given combination of IP and port matches the source of the given packet.
116 * @param packet The packet to check.
117 * @param ip The IP to look for in the ip.src field of {@code packet}.
118 * @param port The port to look for in the tcp.port field of {@code packet}.
119 * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
121 public static boolean isSource(PcapPacket packet, String ip, int port) {
122 IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
123 // For now we only support TCP flows.
124 TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
125 String ipSrc = ipPacket.getHeader().getSrcAddr().getHostAddress();
126 int srcPort = tcpPacket.getHeader().getSrcPort().valueAsInt();
127 return ipSrc.equals(ip) && srcPort == port;
131 * Helper method to determine if the given combination of IP and port matches the destination of the given packet.
132 * @param packet The packet to check.
133 * @param ip The IP to look for in the ip.dst field of {@code packet}.
134 * @param port The port to look for in the tcp.dstport field of {@code packet}.
135 * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
137 public static boolean isDestination(PcapPacket packet, String ip, int port) {
138 IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
139 // For now we only support TCP flows.
140 TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
141 String ipDst = ipPacket.getHeader().getDstAddr().getHostAddress();
142 int dstPort = tcpPacket.getHeader().getDstPort().valueAsInt();
143 return ipDst.equals(ip) && dstPort == port;
147 * Checks if the source IP address of the {@link IpV4Packet} contained in {@code packet} is a local address, i.e.,
148 * if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
149 * @param packet The packet for which the source IP address is to be examined.
150 * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the source IP address is a local IP
151 * address, {@code false} otherwise.
152 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
154 public static boolean isSrcIpLocal(PcapPacket packet) {
155 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().isSiteLocalAddress();
159 * Checks if the destination IP address of the {@link IpV4Packet} contained in {@code packet} is a local address,
160 * i.e., if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
161 * @param packet The packet for which the destination IP address is to be examined.
162 * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the destination IP address is a local
163 * IP address, {@code false} otherwise.
164 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
166 public static boolean isDstIpLocal(PcapPacket packet) {
167 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().isSiteLocalAddress();
171 * Checks if {@code packet} wraps a TCP packet that has the SYN flag set.
172 * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the SYN flag is set.
173 * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the SYN flag is set,
174 * {@code false} otherwise.
176 public static boolean isSyn(PcapPacket packet) {
177 TcpPacket tcp = packet.get(TcpPacket.class);
178 return tcp != null && tcp.getHeader().getSyn();
182 * Checks if {@code packet} wraps a TCP packet th at has the ACK flag set.
183 * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the ACK flag is set.
184 * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the ACK flag is set,
185 * {@code false} otherwise.
187 public static boolean isAck(PcapPacket packet) {
188 TcpPacket tcp = packet.get(TcpPacket.class);
189 return tcp != null && tcp.getHeader().getAck();
193 * Transform a {@code Cluster} of {@code PcapPacketPair} objects into a {@code List} of {@code List} of
194 * {@code PcapPacket} objects.
195 * @param cluster A {@link Cluster} of {@link PcapPacketPair} objects that needs to be transformed.
196 * @return A {@link List} of {@link List} of {@link PcapPacket} objects as the result of the transformation.
198 public static List<List<PcapPacket>> clusterToListOfPcapPackets(Cluster<PcapPacketPair> cluster) {
199 List<List<PcapPacket>> ppListOfList = new ArrayList<>();
200 for (PcapPacketPair ppp: cluster.getPoints()) {
201 // Create a list of PcapPacket objects (list of two members).
202 List<PcapPacket> ppList = new ArrayList<>();
203 ppList.add(ppp.getFirst());
204 if(ppp.getSecond().isPresent())
205 ppList.add(ppp.getSecond().get());
208 // Create a list of list of PcapPacket objects.
209 ppListOfList.add(ppList);
211 // Sort the list of lists based on the first packet's timestamp!
212 Collections.sort(ppListOfList, (p1, p2) -> p1. get(0).getTimestamp().compareTo(p2.get(0).getTimestamp()));
217 * Merge signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
218 * We cross-check these with {@code List} of {@code Conversation} objects to see
219 * if two {@code List} of {@code PcapPacket} objects actually belong to the same {@code Conversation}.
220 * @param signatures A {@link List} of {@link List} of {@link List} of
221 * {@link PcapPacket} objects that needs to be checked and merged.
222 * @param conversations A {@link List} of {@link Conversation} objects as reference for merging.
223 * @return A {@link List} of {@link List} of {@link List} of
224 * {@link PcapPacket} objects as the result of the merging.
226 public static List<List<List<PcapPacket>>>
227 mergeSignatures(List<List<List<PcapPacket>>> signatures, List<Conversation> conversations) {
229 // TODO: THIS IS NOT A DEEP COPY; IT BASICALLY CREATES A REFERENCE TO THE SAME LIST OBJECT
230 // List<List<List<PcapPacket>>> copySignatures = new ArrayList<>(signatures);
231 // Make a deep copy first.
232 List<List<List<PcapPacket>>> copySignatures = new ArrayList<>();
233 listDeepCopy(copySignatures, signatures);
234 // Traverse and look into the pairs of signatures.
235 for (int first = 0; first < signatures.size(); first++) {
236 List<List<PcapPacket>> firstList = signatures.get(first);
237 for (int second = first+1; second < signatures.size(); second++) {
238 int maxSignatureEl = 0; // Number of maximum signature elements.
239 List<List<PcapPacket>> secondList = signatures.get(second);
240 int initialSecondListMembers = secondList.size();
241 // Iterate over the signatures in the first list.
242 for (List<PcapPacket> signature : firstList) {
243 signature.removeIf(el -> el == null); // Clean up null elements.
244 // Return the Conversation that the signature is part of.
245 Conversation conv = TcpConversationUtils.returnConversation(signature, conversations);
246 // Find the element of the second list that is a match for that Conversation.
247 for (List<PcapPacket> ppList : secondList) {
248 ppList.removeIf(el -> el == null); // Clean up null elements.
249 // Check if they are part of a Conversation and are adjacent to the first signature.
250 // If yes then merge into the first list.
251 TcpConversationUtils.SignaturePosition position =
252 TcpConversationUtils.isPartOfConversationAndAdjacent(signature, ppList, conv);
253 if (position == TcpConversationUtils.SignaturePosition.LEFT_ADJACENT) {
254 // Merge to the left side of the first signature.
255 ppList.addAll(signature);
257 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
258 secondList.remove(ppList); // Remove as we merge.
260 } else if (position == TcpConversationUtils.SignaturePosition.RIGHT_ADJACENT) {
261 // Merge to the right side of the first signature.
262 signature.addAll(ppList);
263 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
264 secondList.remove(ppList); // Remove as we merge.
266 } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
269 // Call it a successful merging if there are only less than 5 elements from the second list that
271 if (secondList.size() < SIGNATURE_MERGE_THRESHOLD) {
272 // Prune the unsuccessfully merged signatures (i.e., these will have size() < maxSignatureEl).
273 final int maxNumOfEl = maxSignatureEl;
274 // TODO: DOUBLE CHECK IF WE REALLY NEED TO PRUNE FAILED BINDINGS
275 // TODO: SOMETIMES THE SEQUENCES ARE JUST INCOMPLETE
276 // TODO: AND BOTH THE COMPLETE AND INCOMPLETE SEQUENCES ARE VALID SIGNATURES!
277 firstList.removeIf(el -> el.size() < maxNumOfEl);
278 // Remove the merged set of signatures when successful.
279 signatures.remove(secondList);
280 } else if (secondList.size() < initialSecondListMembers) {
281 // If only some of the signatures from the second list are merged, this means UNSUCCESSFUL merging.
282 // Return the original copy of the signatures object.
283 return copySignatures;
291 * Deep copy to create an entirely new {@link List} of {@link List} of {@link List} of {@link PcapPacket} objects.
292 * @param destList A {@link List} of {@link List} of {@link List} of
293 * {@link PcapPacket} objects that will be the final container of the deep copy
294 * @param sourceList A {@link List} of {@link List} of {@link List} of
295 * {@link PcapPacket} objects that will be the source of the deep copy.
297 private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
299 for(List<List<PcapPacket>> llPcapPacket : sourceList) {
300 List<List<PcapPacket>> tmpListOfList = new ArrayList<>();
301 for(List<PcapPacket> lPcapPacket : llPcapPacket) {
302 List<PcapPacket> tmpList = new ArrayList<>();
303 for(PcapPacket pcapPacket : lPcapPacket) {
304 tmpList.add(pcapPacket);
306 tmpListOfList.add(tmpList);
308 destList.add(tmpListOfList);
313 * Sort the signatures in the {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
314 * The purpose of this is to sort the order of signatures in the signature list. For detection purposes, we need
315 * to know if one signature occurs earlier/later in time with respect to the other signatures for more confidence
316 * in detecting the occurrence of an event.
317 * @param signatures A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects that needs sorting.
318 * We assume that innermost {@code List} of {@code PcapPacket} objects have been sorted ascending
319 * by timestamps. By the time we use this method, we should have sorted it when calling the
320 * {@code clusterToListOfPcapPackets} method.
321 * @return A sorted {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
323 public static List<List<List<PcapPacket>>> sortSignatures(List<List<List<PcapPacket>>> signatures) {
324 // TODO: This is the simplest solution!!! Might not cover all corner cases.
325 // TODO: Sort the list of lists based on the first packet's timestamps!
326 // Collections.sort(signatures, (p1, p2) -> {
327 // //return p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
328 // int compare = p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
331 // TODO: The following is a more complete solution that covers corner cases.
332 // Sort the list of lists based on one-to-one comparison between timestamps of signatures on both lists.
333 // This also takes into account the fact that the number of signatures in the two lists could be different.
334 // Additionally, this code forces the comparison between two signatures only if they occur in the
335 // INCLUSION_WINDOW_MILLIS window; otherwise, it tries to find the right pair of signatures in the time window.
336 Collections.sort(signatures, (p1, p2) -> {
341 // Need to make sure that both are not out of bound!
342 while (count1 + 1 < p1.size() && count2 + 1 < p2.size()) {
343 long timestamp1 = p1.get(count1).get(0).getTimestamp().toEpochMilli();
344 long timestamp2 = p2.get(count2).get(0).getTimestamp().toEpochMilli();
345 // The two timestamps have to be within a 15-second window!
346 if (Math.abs(timestamp1 - timestamp2) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
347 // If these two are within INCLUSION_WINDOW_MILLIS window then compare!
348 compare = p1.get(count1).get(0).getTimestamp().compareTo(p2.get(count2).get(0).getTimestamp());
349 // if (comparePrev != 0) { // First time since it is 0
350 // if (Integer.signum(compare) != Integer.signum(comparePrev)) {
351 // // Throw an exception if the order of the two signatures is not consistent,
352 // // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
353 // throw new Error("OVERLAP WARNING: " + "" +
354 // "Please remove one of the sequences: " +
355 // p1.get(0).get(0).length() + "... OR " +
356 // p2.get(0).get(0).length() + "...");
359 overlapChecking(compare, comparePrev, p1.get(count1), p2.get(count2));
360 comparePrev = compare;
364 // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
365 // by incrementing one of them.
366 if (timestamp1 < timestamp2)
378 * Checks for overlapping between two packet sequences.
379 * @param compare Current comparison value between packet sequences p1 and p2
380 * @param comparePrev Previous comparison value between packet sequences p1 and p2
381 * @param sequence1 The packet sequence ({@link List} of {@link PcapPacket} objects).
382 * @param sequence2 The packet sequence ({@link List} of {@link PcapPacket} objects).
384 private static void overlapChecking(int compare, int comparePrev, List<PcapPacket> sequence1, List<PcapPacket> sequence2) {
386 // Check if p1 occurs before p2 but both have same overlap
387 if (comparePrev != 0) { // First time since it is 0
388 if (Integer.signum(compare) != Integer.signum(comparePrev)) {
389 // Throw an exception if the order of the two signatures is not consistent,
390 // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
391 throw new Error("OVERLAP WARNING: " + "" +
392 "Two sequences have some overlap. Please remove one of the sequences: " +
393 sequence1.get(0).length() + "... OR " +
394 sequence2.get(0).length() + "...");
397 // Check if p1 is longer than p2 and p2 occurs during the occurrence of p1
398 int lastIndexOfSequence1 = sequence1.size() - 1;
399 int lastIndexOfSequence2 = sequence2.size() - 1;
401 sequence1.get(lastIndexOfSequence1).getTimestamp().compareTo(sequence2.get(lastIndexOfSequence2).getTimestamp());
402 // Check the signs of compare and compareLast
403 if ((compare <= 0 && compareLast > 0) ||
404 (compareLast <= 0 && compare > 0)) {
406 // TODO: Probably not the best approach but we consider overlap if it happens more than once
407 if (mOverlapCounter > 1) {
408 throw new Error("OVERLAP WARNING: " + "" +
409 "One sequence is in the other. Please remove one of the sequences: " +
410 sequence1.get(0).length() + "... OR " +
411 sequence2.get(0).length() + "...");
418 * Gets the {@link IpV4Packet} contained in {@code packet}, or throws a {@link NullPointerException} if
419 * {@code packet} does not contain an {@link IpV4Packet}.
420 * @param packet A {@link PcapPacket} that is expected to contain an {@link IpV4Packet}.
421 * @return The {@link IpV4Packet} contained in {@code packet}.
422 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
424 private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
425 return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
429 * Gets the {@link EthernetPacket} contained in {@code packet}, or throws a {@link NullPointerException} if
430 * {@code packet} does not contain an {@link EthernetPacket}.
431 * @param packet A {@link PcapPacket} that is expected to contain an {@link EthernetPacket}.
432 * @return The {@link EthernetPacket} contained in {@code packet}.
433 * @throws NullPointerException if {@code packet} does not encapsulate an {@link EthernetPacket}.
435 private static final EthernetPacket getEthernetPacketOrThrow(PcapPacket packet) {
436 return Objects.requireNonNull(packet.get(EthernetPacket.class), "not an Ethernet packet");
440 * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
442 * @param signatures A {@link List} of {@link List} of {@link List} of
443 * {@link PcapPacket} objects that needs to be printed.
445 public static void printSignatures(List<List<List<PcapPacket>>> signatures) {
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 System.out.print("====== SEQUENCE " + ++sequenceCounter);
452 System.out.println(" - " + listListPcapPacket.size() + " MEMBERS ======");
453 for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
454 // Print out packet lengths in a sequence
455 int packetCounter = 0;
456 for(PcapPacket pcapPacket : listPcapPacket) {
457 if(pcapPacket != null) {
458 System.out.print(pcapPacket.length());
460 if(packetCounter < listPcapPacket.size() - 1) {
461 System.out.print(" "); // Provide space if not last packet
463 System.out.println(); // Newline if last packet
472 * Remove a sequence in a signature object.
474 * @param signatures A {@link List} of {@link List} of {@link List} of
475 * {@link PcapPacket} objects.
476 * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
477 * {@link PcapPacket} objects.
479 public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
481 // Sequence index starts from 0
482 signatures.remove(sequenceIndex);