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