1 package edu.uci.iotproject.util;
3 import edu.uci.iotproject.Conversation;
4 import edu.uci.iotproject.analysis.PcapPacketPair;
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
7 import org.apache.commons.math3.stat.clustering.Cluster;
8 import org.pcap4j.core.PcapPacket;
9 import org.pcap4j.packet.IpV4Packet;
10 import org.pcap4j.packet.TcpPacket;
15 * Utility methods for inspecting {@link PcapPacket} properties.
17 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
18 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
20 public final class PcapPacketUtils {
23 * This is the threshold value for a signature's number of members
24 * If after a merging the number of members of a signature falls below this threshold, then we can boldly
25 * get rid of that signature.
27 private static final int SIGNATURE_MERGE_THRESHOLD = 5;
30 * Determines if a given {@link PcapPacket} wraps a {@link TcpPacket}.
31 * @param packet The {@link PcapPacket} to inspect.
32 * @return {@code true} if {@code packet} wraps a {@link TcpPacket}, {@code false} otherwise.
34 public static boolean isTcp(PcapPacket packet) {
35 return packet.get(TcpPacket.class) != null;
39 * Gets the source IP (in decimal format) of an IPv4 packet.
40 * @param packet The packet for which the IPv4 source address is to be extracted.
41 * @return The decimal representation of the source IP of {@code packet} <em>iff</em> {@code packet} wraps an
43 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
45 public static String getSourceIp(PcapPacket packet) {
46 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().getHostAddress();
50 * Gets the destination IP (in decimal format) of an IPv4 packet.
51 * @param packet The packet for which the IPv4 source address is to be extracted.
52 * @return The decimal representation of the destination IP of {@code packet} <em>iff</em> {@code packet} wraps an
54 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
56 public static String getDestinationIp(PcapPacket packet) {
57 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().getHostAddress();
61 * Gets the source port of a TCP packet.
62 * @param packet The packet for which the source port is to be extracted.
63 * @return The source port of the {@link TcpPacket} encapsulated by {@code packet}.
64 * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
66 public static int getSourcePort(PcapPacket packet) {
67 TcpPacket tcpPacket = packet.get(TcpPacket.class);
68 if (tcpPacket == null) {
69 throw new IllegalArgumentException("not a TCP packet");
71 return tcpPacket.getHeader().getSrcPort().valueAsInt();
75 * Gets the destination port of a TCP packet.
76 * @param packet The packet for which the destination port is to be extracted.
77 * @return The destination port of the {@link TcpPacket} encapsulated by {@code packet}.
78 * @throws IllegalArgumentException if {@code packet} does not encapsulate a {@link TcpPacket}.
80 public static int getDestinationPort(PcapPacket packet) {
81 TcpPacket tcpPacket = packet.get(TcpPacket.class);
82 if (tcpPacket == null) {
83 throw new IllegalArgumentException("not a TCP packet");
85 return tcpPacket.getHeader().getDstPort().valueAsInt();
89 * Helper method to determine if the given combination of IP and port matches the source of the given packet.
90 * @param packet The packet to check.
91 * @param ip The IP to look for in the ip.src field of {@code packet}.
92 * @param port The port to look for in the tcp.port field of {@code packet}.
93 * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
95 public static boolean isSource(PcapPacket packet, String ip, int port) {
96 IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
97 // For now we only support TCP flows.
98 TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
99 String ipSrc = ipPacket.getHeader().getSrcAddr().getHostAddress();
100 int srcPort = tcpPacket.getHeader().getSrcPort().valueAsInt();
101 return ipSrc.equals(ip) && srcPort == port;
105 * Helper method to determine if the given combination of IP and port matches the destination of the given packet.
106 * @param packet The packet to check.
107 * @param ip The IP to look for in the ip.dst field of {@code packet}.
108 * @param port The port to look for in the tcp.dstport field of {@code packet}.
109 * @return {@code true} if the given ip+port match the corresponding fields in {@code packet}.
111 public static boolean isDestination(PcapPacket packet, String ip, int port) {
112 IpV4Packet ipPacket = Objects.requireNonNull(packet.get(IpV4Packet.class));
113 // For now we only support TCP flows.
114 TcpPacket tcpPacket = Objects.requireNonNull(packet.get(TcpPacket.class));
115 String ipDst = ipPacket.getHeader().getDstAddr().getHostAddress();
116 int dstPort = tcpPacket.getHeader().getDstPort().valueAsInt();
117 return ipDst.equals(ip) && dstPort == port;
121 * Checks if the source IP address of the {@link IpV4Packet} contained in {@code packet} is a local address, i.e.,
122 * if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
123 * @param packet The packet for which the source IP address is to be examined.
124 * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the source IP address is a local IP
125 * address, {@code false} otherwise.
126 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
128 public static boolean isSrcIpLocal(PcapPacket packet) {
129 return getIpV4PacketOrThrow(packet).getHeader().getSrcAddr().isSiteLocalAddress();
133 * Checks if the destination IP address of the {@link IpV4Packet} contained in {@code packet} is a local address,
134 * i.e., if it pertains to subnet 10.0.0.0/8, 172.16.0.0/16, or 192.168.0.0/16.
135 * @param packet The packet for which the destination IP address is to be examined.
136 * @return {@code true} if {@code packet} wraps a {@link IpV4Packet} for which the destination IP address is a local
137 * IP address, {@code false} otherwise.
138 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
140 public static boolean isDstIpLocal(PcapPacket packet) {
141 return getIpV4PacketOrThrow(packet).getHeader().getDstAddr().isSiteLocalAddress();
145 * Checks if {@code packet} wraps a TCP packet that has the SYN flag set.
146 * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the SYN flag is set.
147 * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the SYN flag is set,
148 * {@code false} otherwise.
150 public static boolean isSyn(PcapPacket packet) {
151 TcpPacket tcp = packet.get(TcpPacket.class);
152 return tcp != null && tcp.getHeader().getSyn();
156 * Checks if {@code packet} wraps a TCP packet that has the ACK flag set.
157 * @param packet A {@link PcapPacket} that is suspected to contain a {@link TcpPacket} for which the ACK flag is set.
158 * @return {@code true} <em>iff</em> {@code packet} contains a {@code TcpPacket} for which the ACK flag is set,
159 * {@code false} otherwise.
161 public static boolean isAck(PcapPacket packet) {
162 TcpPacket tcp = packet.get(TcpPacket.class);
163 return tcp != null && tcp.getHeader().getAck();
167 * Transform a {@code Cluster} of {@code PcapPacketPair} objects into a {@code List} of {@code List} of
168 * {@code PcapPacket} objects.
169 * @param cluster A {@link Cluster} of {@link PcapPacketPair} objects that needs to be transformed.
170 * @return A {@link List} of {@link List} of {@link PcapPacket} objects as the result of the transformation.
172 public static List<List<PcapPacket>> clusterToListOfPcapPackets(Cluster<PcapPacketPair> cluster) {
173 List<List<PcapPacket>> ppListOfList = new ArrayList<>();
174 for (PcapPacketPair ppp: cluster.getPoints()) {
175 // Create a list of PcapPacket objects (list of two members).
176 List<PcapPacket> ppList = new ArrayList<>();
177 ppList.add(ppp.getFirst());
178 if(ppp.getSecond().isPresent())
179 ppList.add(ppp.getSecond().get());
182 // Create a list of list of PcapPacket objects.
183 ppListOfList.add(ppList);
185 // Sort the list of lists based on the first packet's timestamp!
186 Collections.sort(ppListOfList, (p1, p2) -> p1.get(0).getTimestamp().compareTo(p2.get(0).getTimestamp()));
191 * Merge signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
192 * We cross-check these with {@code List} of {@code Conversation} objects to see
193 * if two {@code List} of {@code PcapPacket} objects actually belong to the same {@code Conversation}.
194 * @param signatures A {@link List} of {@link List} of {@link List} of
195 * {@link PcapPacket} objects that needs to be checked and merged.
196 * @param conversations A {@link List} of {@link Conversation} objects as reference for merging.
197 * @return A {@link List} of {@link List} of {@link List} of
198 * {@link PcapPacket} objects as the result of the merging.
200 public static List<List<List<PcapPacket>>>
201 mergeSignatures(List<List<List<PcapPacket>>> signatures, List<Conversation> conversations) {
203 // TODO: THIS IS NOT A DEEP COPY; IT BASICALLY CREATES A REFERENCE TO THE SAME LIST OBJECT
204 // List<List<List<PcapPacket>>> copySignatures = new ArrayList<>(signatures);
205 // Make a deep copy first.
206 List<List<List<PcapPacket>>> copySignatures = new ArrayList<>();
207 listDeepCopy(copySignatures, signatures);
208 // Traverse and look into the pairs of signatures.
209 for (int first = 0; first < signatures.size(); first++) {
210 List<List<PcapPacket>> firstList = signatures.get(first);
211 for (int second = first+1; second < signatures.size(); second++) {
212 int maxSignatureEl = 0; // Number of maximum signature elements.
213 List<List<PcapPacket>> secondList = signatures.get(second);
214 int initialSecondListMembers = secondList.size();
215 // Iterate over the signatures in the first list.
216 for (List<PcapPacket> signature : firstList) {
217 signature.removeIf(el -> el == null); // Clean up null elements.
218 // Return the Conversation that the signature is part of.
219 Conversation conv = TcpConversationUtils.returnConversation(signature, conversations);
220 // Find the element of the second list that is a match for that Conversation.
221 for (List<PcapPacket> ppList : secondList) {
222 ppList.removeIf(el -> el == null); // Clean up null elements.
223 // Check if they are part of a Conversation and are adjacent to the first signature.
224 // If yes then merge into the first list.
225 TcpConversationUtils.SignaturePosition position =
226 TcpConversationUtils.isPartOfConversationAndAdjacent(signature, ppList, conv);
227 if (position == TcpConversationUtils.SignaturePosition.LEFT_ADJACENT) {
228 // Merge to the left side of the first signature.
229 ppList.addAll(signature);
231 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
232 secondList.remove(ppList); // Remove as we merge.
234 } else if (position == TcpConversationUtils.SignaturePosition.RIGHT_ADJACENT) {
235 // Merge to the right side of the first signature.
236 signature.addAll(ppList);
237 maxSignatureEl = signature.size() > maxSignatureEl ? signature.size() : maxSignatureEl;
238 secondList.remove(ppList); // Remove as we merge.
240 } // TcpConversationUtils.SignaturePosition.NOT_ADJACENT.
243 // Call it a successful merging if there are only less than 5 elements from the second list that
245 if (secondList.size() < SIGNATURE_MERGE_THRESHOLD) {
246 // Prune the unsuccessfully merged signatures (i.e., these will have size() < maxSignatureEl).
247 final int maxNumOfEl = maxSignatureEl;
248 // TODO: DOUBLE CHECK IF WE REALLY NEED TO PRUNE FAILED BINDINGS
249 // TODO: SOMETIMES THE SEQUENCES ARE JUST INCOMPLETE
250 // TODO: AND BOTH THE COMPLETE AND INCOMPLETE SEQUENCES ARE VALID SIGNATURES!
251 firstList.removeIf(el -> el.size() < maxNumOfEl);
252 // Remove the merged set of signatures when successful.
253 signatures.remove(secondList);
254 } else if (secondList.size() < initialSecondListMembers) {
255 // If only some of the signatures from the second list are merged, this means UNSUCCESSFUL merging.
256 // Return the original copy of the signatures object.
257 return copySignatures;
265 * Deep copy to create an entirely new {@link List} of {@link List} of {@link List} of {@link PcapPacket} objects.
266 * @param destList A {@link List} of {@link List} of {@link List} of
267 * {@link PcapPacket} objects that will be the final container of the deep copy
268 * @param sourceList A {@link List} of {@link List} of {@link List} of
269 * {@link PcapPacket} objects that will be the source of the deep copy.
271 private static void listDeepCopy(List<List<List<PcapPacket>>> destList, List<List<List<PcapPacket>>> sourceList) {
273 for(List<List<PcapPacket>> llPcapPacket : sourceList) {
274 List<List<PcapPacket>> tmpListOfList = new ArrayList<>();
275 for(List<PcapPacket> lPcapPacket : llPcapPacket) {
276 List<PcapPacket> tmpList = new ArrayList<>();
277 for(PcapPacket pcapPacket : lPcapPacket) {
278 tmpList.add(pcapPacket);
280 tmpListOfList.add(tmpList);
282 destList.add(tmpListOfList);
287 * Sort the signatures in the {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
288 * The purpose of this is to sort the order of signatures in the signature list. For detection purposes, we need
289 * to know if one signature occurs earlier/later in time with respect to the other signatures for more confidence
290 * in detecting the occurrence of an event.
291 * @param signatures A {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects that needs sorting.
292 * We assume that innermost {@code List} of {@code PcapPacket} objects have been sorted ascending
293 * by timestamps. By the time we use this method, we should have sorted it when calling the
294 * {@code clusterToListOfPcapPackets} method.
295 * @return A sorted {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
297 public static List<List<List<PcapPacket>>> sortSignatures(List<List<List<PcapPacket>>> signatures) {
298 // TODO: This is the simplest solution!!! Might not cover all corner cases.
299 // TODO: Sort the list of lists based on the first packet's timestamps!
300 //Collections.sort(signatures, (p1, p2) -> {
301 // return p1.get(0).get(0).getTimestamp().compareTo(p2.get(0).get(0).getTimestamp());
303 // TODO: The following is a more complete solution that covers corner cases.
304 // Sort the list of lists based on one-to-one comparison between timestamps of signatures on both lists.
305 // This also takes into account the fact that the number of signatures in the two lists could be different.
306 // Additionally, this code forces the comparison between two signatures only if they occur in the
307 // INCLUSION_WINDOW_MILLIS window; otherwise, it tries to find the right pair of signatures in the time window.
308 Collections.sort(signatures, (p1, p2) -> {
313 // Need to make sure that both are not out of bound!
314 while (count1 + 1 < p1.size() && count2 + 1 < p2.size()) {
315 long timestamp1 = p1.get(count1).get(0).getTimestamp().toEpochMilli();
316 long timestamp2 = p2.get(count2).get(0).getTimestamp().toEpochMilli();
317 // The two timestamps have to be within a 15-second window!
318 if (Math.abs(timestamp1 - timestamp2) < TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS) {
319 // If these two are within INCLUSION_WINDOW_MILLIS window then compare!
320 compare = p1.get(count1).get(0).getTimestamp().compareTo(p2.get(count2).get(0).getTimestamp());
321 if (comparePrev != 0) { // First time since it is 0
322 if (Integer.signum(compare) != Integer.signum(comparePrev)) {
323 // Throw an exception if the order of the two signatures is not consistent,
324 // E.g., 111, 222, 333 in one occassion and 222, 333, 111 in the other.
325 throw new Error("For some reason, the order of signatures are not always consistent!" +
326 "Returning the original data structure of signatures...");
329 comparePrev = compare;
333 // If not within INCLUSION_WINDOW_MILLIS window then find the correct pair
334 // by incrementing one of them.
335 if (timestamp1 < timestamp2)
347 * Gets the {@link IpV4Packet} contained in {@code packet}, or throws a {@link NullPointerException} if
348 * {@code packet} does not contain an {@link IpV4Packet}.
349 * @param packet A {@link PcapPacket} that is expected to contain a {@link IpV4Packet}.
350 * @return The {@link IpV4Packet} contained in {@code packet}.
351 * @throws NullPointerException if {@code packet} does not encapsulate an {@link IpV4Packet}.
353 private static IpV4Packet getIpV4PacketOrThrow(PcapPacket packet) {
354 return Objects.requireNonNull(packet.get(IpV4Packet.class), "not an IPv4 packet");
358 * Print signatures in {@code List} of {@code List} of {@code List} of {@code PcapPacket} objects.
360 * @param signatures A {@link List} of {@link List} of {@link List} of
361 * {@link PcapPacket} objects that needs to be printed.
363 public static void printSignatures(List<List<List<PcapPacket>>> signatures) {
365 // Iterate over the list of all clusters/sequences
366 int sequenceCounter = 0;
367 for(List<List<PcapPacket>> listListPcapPacket : signatures) {
368 // Iterate over every member of a cluster/sequence
369 System.out.print("====== SEQUENCE " + sequenceCounter++);
370 System.out.println(" - " + listListPcapPacket.size() + " MEMBERS ======");
371 for(List<PcapPacket> listPcapPacket : listListPcapPacket) {
372 // Print out packet lengths in a sequence
373 int packetCounter = 0;
374 for(PcapPacket pcapPacket : listPcapPacket) {
375 System.out.print(pcapPacket.length());
376 if(packetCounter < listPcapPacket.size() - 1) {
377 System.out.print(" "); // Provide space if not last packet
379 System.out.println(); // Newline if last packet
388 * Remove a sequence in a signature object.
390 * @param signatures A {@link List} of {@link List} of {@link List} of
391 * {@link PcapPacket} objects.
392 * @param sequenceIndex An index for a sequence that consists of {{@link List} of {@link List} of
393 * {@link PcapPacket} objects.
395 public static void removeSequenceFromSignature(List<List<List<PcapPacket>>> signatures, int sequenceIndex) {
397 // Sequence index starts from 0
398 signatures.remove(sequenceIndex);