Sketch code for extracting packet pairs (unfinished - unsure how to apply it to recon...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / analysis / TcpConversationUtils.java
1 package edu.uci.iotproject.analysis;
2
3 import edu.uci.iotproject.Conversation;
4 import edu.uci.iotproject.util.PcapPacketUtils;
5 import org.pcap4j.core.PcapPacket;
6 import org.pcap4j.packet.IpV4Packet;
7 import org.pcap4j.packet.TcpPacket;
8
9 import java.util.ArrayList;
10 import java.util.List;
11
12 /**
13  * TODO add class documentation.
14  *
15  * @author Janus Varmarken
16  */
17 public class TcpConversationUtils {
18
19     public static List<PcapPacketPair> extractPacketPairs(Conversation conv) {
20         List<PcapPacket> packets = conv.getPackets();
21         List<PcapPacketPair> pairs = new ArrayList<>();
22         int i = 0;
23         while (i < packets.size()) {
24             PcapPacket p1 = packets.get(i);
25             String p1SrcIp = p1.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress();
26             int p1SrcPort = p1.get(TcpPacket.class).getHeader().getSrcPort().valueAsInt();
27             if (i+1 < packets.size()) {
28                 PcapPacket p2 = packets.get(i+1);
29                 if (PcapPacketUtils.isSource(p2, p1SrcIp, p1SrcPort)) {
30                     // Two packets in a row going in the same direction -> create one item pair for p1
31                     pairs.add(new PcapPacketPair(p1, null));
32                     // Advance one packet as the following two packets may form a valid two-item pair.
33                     i++;
34                 } else {
35                     // The two packets form a response-reply pair, create two-item pair.
36                     pairs.add(new PcapPacketPair(p1, p2));
37                     // Advance two packets as we have already processed the packet at index i+1 in order to create the pair.
38                     i += 2;
39                 }
40             } else {
41                 // Last packet of conversation => one item pair
42                 pairs.add(new PcapPacketPair(p1, null));
43                 // Advance i to ensure termination.
44                 i++;
45             }
46         }
47         return pairs;
48         // TODO: what if there is long time between response and reply packet? Should we add a threshold and exclude those cases?
49     }
50
51 }