Merge branch 'master' of https://github.uci.edu/rtrimana/smart_home_traffic
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / trafficreassembly / layer3 / TcpReassembler.java
1 package edu.uci.iotproject.trafficreassembly.layer3;
2
3 import org.pcap4j.core.PacketListener;
4 import org.pcap4j.core.PcapPacket;
5 import org.pcap4j.packet.*;
6
7 import java.util.*;
8
9 /**
10  * Reassembles TCP conversations (streams).
11  * <b>Note: current version only supports TCP over IPv4.</b>
12  *
13  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
14  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
15  */
16 public class TcpReassembler implements PacketListener {
17
18     /**
19      * Holds <em>open</em> {@link Conversation}s, i.e., {@code Conversation}s that have <em>not</em> been detected as
20      * (gracefully) terminated based on the set of packets observed thus far.
21      * A {@link Conversation} is moved to {@link #mTerminatedConversations} if it can be determined that it is has
22      * terminated. Termination can be detected by a) observing two {@link FinAckPair}s, one in each direction, (graceful
23      * termination, see {@link Conversation#isGracefullyShutdown()}) or b) by observing a SYN packet that matches the
24      * four tuple of an existing {@code Conversation}, but which holds a <em>different</em> sequence number than the
25      * same-direction SYN packet recorded for the {@code Conversation}.
26      * <p>
27      * Note that due to limitations of the {@link Set} interface (specifically, there is no {@code get(T t)} method),
28      * we have to resort to a {@link Map} (in which keys map to themselves) to "mimic" a set with {@code get(T t)}
29      * functionality.
30      *
31      * @see <a href="https://stackoverflow.com/questions/7283338/getting-an-element-from-a-set">this question on StackOverflow.com</a>
32      */
33     private final Map<Conversation, Conversation> mOpenConversations = new HashMap<>();
34
35     /**
36      * Holds <em>terminated</em> {@link Conversation}s.
37      */
38     private final List<Conversation> mTerminatedConversations = new ArrayList<>();
39
40     @Override
41     public void gotPacket(PcapPacket pcapPacket) {
42         IpV4Packet ipPacket = pcapPacket.get(IpV4Packet.class);
43         TcpPacket tcpPacket = pcapPacket.get(TcpPacket.class);
44
45         if (ipPacket == null || tcpPacket == null) {
46             return;
47         }
48         // ... TODO?
49         processPacket(pcapPacket);
50 //        Class clazz = pcapPacket.getClass();
51 //        RadiotapPacket radiotapPacket = pcapPacket.get(RadiotapPacket.class);
52 //        Dot11ManagementPacket dot11ManagementPacket = pcapPacket.get(Dot11ManagementPacket.class);
53 //        if (dot11ManagementPacket != null) {
54 //            return;
55 //        }
56 //        if (radiotapPacket != null) {
57 //            processRadiotapPacket(pcapPacket);
58 //        }
59     }
60
61     /**
62      * Get the reassembled TCP connections. Note that if this is called while packets are still being processed (by
63      * calls to {@link #gotPacket(PcapPacket)}), the behavior is undefined and the returned list may be inconsistent.
64      * @return The reassembled TCP connections.
65      */
66     public List<Conversation> getTcpConversations() {
67         ArrayList<Conversation> combined = new ArrayList<>();
68         combined.addAll(mTerminatedConversations);
69         combined.addAll(mOpenConversations.values());
70         return combined;
71     }
72
73     private void processRadiotapPacket(PcapPacket pcapPacket) {
74         RadiotapPacket radiotapPacket = pcapPacket.get(RadiotapPacket.class);
75
76         RadiotapPacket.RadiotapHeader header = radiotapPacket.getHeader();
77         short length = header.getLength();
78         ArrayList<RadiotapPacket.RadiotapData> radiotapData = header.getDataFields();
79         // TODO: We can handle this 802.11 QoS data by creating our own class
80         // TODO: We only need to handle the first few bytes for source, destination, receiver, and transmitter
81         // TODO: addresses
82         Packet dataPacket = radiotapPacket.getPayload();
83         int dataLength = dataPacket.length();
84     }
85
86     private void processPacket(PcapPacket pcapPacket) {
87         TcpPacket tcpPacket = pcapPacket.get(TcpPacket.class);
88         // Handle client connection initiation attempts.
89         if (tcpPacket.getHeader().getSyn() && !tcpPacket.getHeader().getAck()) {
90             // A segment with the SYN flag set, but no ACK flag indicates that a client is attempting to initiate a new
91             // connection.
92             processNewConnectionRequest(pcapPacket);
93             return;
94         }
95         // Handle server connection initiation acknowledgement
96         if (tcpPacket.getHeader().getSyn() && tcpPacket.getHeader().getAck()) {
97             // A segment with both the SYN and ACK flags set indicates that the server has accepted the client's request
98             // to initiate a new connection.
99             processNewConnectionAck(pcapPacket);
100             return;
101         }
102         // Handle resets
103         if (tcpPacket.getHeader().getRst()) {
104             processRstPacket(pcapPacket);
105             return;
106         }
107         // Handle FINs
108         if (tcpPacket.getHeader().getFin()) {
109             // Handle FIN packet.
110             processFinPacket(pcapPacket);
111         }
112         // Handle ACKs (currently only ACKs of FINS)
113         if (tcpPacket.getHeader().getAck()) {
114             processAck(pcapPacket);
115         }
116         // Handle packets that carry payload (application data).
117         if (tcpPacket.getPayload() != null) {
118             processPayloadPacket(pcapPacket);
119         }
120     }
121
122     private void processNewConnectionRequest(PcapPacket clientSynPacket) {
123         // A SYN w/o ACK always originates from the client.
124         Conversation conv = Conversation.fromPcapPacket(clientSynPacket, true);
125         conv.addSynPacket(clientSynPacket);
126         // Is there an ongoing conversation for the same four tuple (clientIp, clientPort, serverIp, serverPort) as
127         // found in the new SYN packet?
128         Conversation ongoingConv = mOpenConversations.get(conv);
129         if (ongoingConv != null) {
130             if (ongoingConv.isRetransmission(clientSynPacket)) {
131                 // SYN retransmission detected, do nothing.
132                 return;
133                 // TODO: the way retransmission detection is implemented may cause a bug for connections where we have
134                 // not recorded the initial SYN, but only the SYN ACK, as retransmission is determined by comparing the
135                 // sequence numbers of initial SYNs -- and if no initial SYN is present for the Conversation, the new
136                 // SYN will be interpreted as a retransmission. Possible fix: let isRentransmission ALWAYS return false
137                 // when presented with a SYN packet when the Conversation already holds a SYN ACK packet?
138             } else {
139                 // New SYN has different sequence number than SYN recorded for ongoingConv, so this must be an attempt
140                 // to establish a new conversation with the same four tuple as ongoingConv.
141                 // Mark existing connection as terminated.
142                 // TODO: is this 100% theoretically correct, e.g., if many connection attempts are made back to back? And RST packets?
143                 mTerminatedConversations.add(ongoingConv);
144                 mOpenConversations.remove(ongoingConv);
145             }
146         }
147         // Finally, update the map of open connections with the new connection.
148         mOpenConversations.put(conv, conv);
149     }
150
151
152     /*
153      * TODO a problem across the board for all processXPacket methods below:
154      * if we start the capture in the middle of a TCP connection, we will not have an entry for the conversation in the
155      * map as we have not seen the initial SYN packet.
156      * Two ways we can address this:
157      * a) Perform null-checks and ignore packets for which we have not seen SYN
158      *    + easy to get correct
159      *    - we discard data (issue for long-lived connections!)
160      * b) Add a corresponding conversation entry whenever we encounter a packet that does not map to a conversation
161      *    + we consider all data
162      *    - not immediately clear if this will introduce bugs (incorrectly mapping packets to wrong conversations?)
163      *
164      *  [[[ I went with option b) for now; see getOngoingConversationOrCreateNew(PcapPacket pcapPacket). ]]]
165      */
166
167     private void processNewConnectionAck(PcapPacket srvSynPacket) {
168         // Find the corresponding ongoing connection, if any (if we start the capture just *after* the initial SYN, no
169         // ongoing conversation entry will exist, so it must be created in that case).
170 //        Conversation conv = mOpenConversations.get(Conversation.fromPcapPacket(srvSynPacket, false));
171         Conversation conv = getOngoingConversationOrCreateNew(srvSynPacket);
172         // Note: exploits &&'s short-circuit operation: only attempts to add non-retransmissions.
173         if (!conv.isRetransmission(srvSynPacket) && !conv.addSynPacket(srvSynPacket)) {
174             // For safety/debugging: if NOT a retransmission and add fails,
175             // something has gone terribly wrong/invariant is broken.
176 //            throw new AssertionError("Attempt to add SYN ACK packet that was NOT a retransmission failed." +
177 //                    Conversation.class.getSimpleName() + " invariant broken.");
178         }
179     }
180
181     private void processRstPacket(PcapPacket rstPacket) {
182         Conversation conv = getOngoingConversationOrCreateNew(rstPacket);
183         // Add RST packet to conversation.
184         conv.addRstPacket(rstPacket);
185         // Move conversation to set of terminated conversations.
186         mTerminatedConversations.add(conv);
187         mOpenConversations.remove(conv, conv);
188     }
189
190     private void processFinPacket(PcapPacket finPacket) {
191 //        getOngoingConversationForPacket(finPacket).addFinPacket(finPacket);
192         getOngoingConversationOrCreateNew(finPacket).addFinPacket(finPacket);
193     }
194
195     private void processAck(PcapPacket ackPacket) {
196 //        getOngoingConversationForPacket(ackPacket).attemptAcknowledgementOfFin(ackPacket);
197         // Note that unlike the style for SYN, FIN, and payload packets, for "ACK only" packets, we want to avoid
198         // creating a new conversation.
199         Conversation conv = getOngoingConversationForPacket(ackPacket);
200         if (conv != null) {
201             // The ACK may be an ACK of a FIN, so attempt to mark the FIN as ack'ed.
202             conv.attemptAcknowledgementOfFin(ackPacket);
203             if (conv.isGracefullyShutdown()) {
204                 // Move conversation to set of terminated conversations.
205                 mTerminatedConversations.add(conv);
206                 mOpenConversations.remove(conv);
207             }
208         }
209         // Note: add (additional) processing of ACKs (that are not ACKs of FINs) as necessary here...
210     }
211
212     private void processPayloadPacket(PcapPacket pcapPacket) {
213 //        getOngoingConversationForPacket(pcapPacket).addPacket(pcapPacket, true);
214         getOngoingConversationOrCreateNew(pcapPacket).addPacket(pcapPacket, true);
215     }
216
217     /**
218      * Locates an ongoing conversation (if any) that {@code pcapPacket} pertains to.
219      * @param pcapPacket The packet that is to be mapped to an ongoing {@code Conversation}.
220      * @return The {@code Conversation} matching {@code pcapPacket} or {@code null} if there is no match.
221      */
222     private Conversation getOngoingConversationForPacket(PcapPacket pcapPacket) {
223         // We cannot know if this is a client-to-server or server-to-client packet without trying both options...
224         Conversation conv = mOpenConversations.get(Conversation.fromPcapPacket(pcapPacket, true));
225         if (conv == null) {
226             conv = mOpenConversations.get(Conversation.fromPcapPacket(pcapPacket, false));
227         }
228         return conv;
229     }
230
231     /**
232      * Like {@link #getOngoingConversationForPacket(PcapPacket)}, but creates and inserts a new {@code Conversation}
233      * into {@link #mOpenConversations} if no open conversation is found (i.e., in the case that
234      * {@link #getOngoingConversationForPacket(PcapPacket)} returns {@code null}).
235      *
236      * @param pcapPacket The packet that is to be mapped to an ongoing {@code Conversation}.
237      * @return The existing, ongoing {@code Conversation} matching {@code pcapPacket} or the newly created one in case
238      *         no match was found.
239      */
240     private Conversation getOngoingConversationOrCreateNew(PcapPacket pcapPacket) {
241         Conversation conv = getOngoingConversationForPacket(pcapPacket);
242         if (conv == null) {
243             TcpPacket tcpPacket = pcapPacket.get(TcpPacket.class);
244             if (tcpPacket.getHeader().getSyn() && tcpPacket.getHeader().getAck()) {
245                 // A SYN ACK packet always originates from the server (it is a reply to the initial SYN packet from the client)
246                 conv = Conversation.fromPcapPacket(pcapPacket, false);
247             } else {
248                 // TODO: can we do anything else but arbitrarily select who is designated as the server in this case?
249                 // We can check if the IP prefix matches a local IP when handling traffic observed inside the local
250                 // network, but that obviously won't be a useful strategy for an observer at the WAN port.
251                 String srcIp = pcapPacket.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress();
252                 // TODO: REPLACE THE ROUTER'S IP WITH A PARAMETER!!!
253                 boolean clientIsSrc = srcIp.startsWith("10.") || srcIp.startsWith("192.168.") || srcIp.equals("128.195.205.105");
254                 conv = Conversation.fromPcapPacket(pcapPacket, clientIsSrc);
255             }
256             mOpenConversations.put(conv, conv);
257         }
258         return conv;
259     }
260 }