Merging changes.
[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.DnsMap;
5 import edu.uci.iotproject.util.PcapPacketUtils;
6 import org.pcap4j.core.PcapPacket;
7 import org.pcap4j.packet.IpV4Packet;
8 import org.pcap4j.packet.TcpPacket;
9
10 import java.util.*;
11 import java.util.stream.Collectors;
12 import java.util.stream.Stream;
13
14 import static edu.uci.iotproject.util.PcapPacketUtils.*;
15
16 /**
17  * Utility functions for analyzing and structuring (sets of) {@link Conversation}s.
18  *
19  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
20  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
21  */
22 public class TcpConversationUtils {
23
24     /**
25      * <p>
26      *      Given a {@link Conversation}, extract its set of "packet pairs", i.e., pairs of request-reply packets.
27      * </p>
28      *
29      * <b>Note:</b> in the current implementation, if one endpoint sends multiple packets back-to-back with no
30      * interleaved reply packets from the other endpoint, such packets are converted to one-item pairs (i.e., instances
31      * of {@lin PcapPacketPair} where {@link PcapPacketPair#getSecond()} is {@code null}).
32      *
33      * @param conv The {@code Conversation} for which packet pairs are to be extracted.
34      * @return The packet pairs extracted from {@code conv}.
35      */
36     public static List<PcapPacketPair> extractPacketPairs(Conversation conv) {
37         List<PcapPacket> packets = conv.getPackets();
38         List<PcapPacketPair> pairs = new ArrayList<>();
39         int i = 0;
40         while (i < packets.size()) {
41             PcapPacket p1 = packets.get(i);
42             String p1SrcIp = p1.get(IpV4Packet.class).getHeader().getSrcAddr().getHostAddress();
43             int p1SrcPort = p1.get(TcpPacket.class).getHeader().getSrcPort().valueAsInt();
44             if (i+1 < packets.size()) {
45                 PcapPacket p2 = packets.get(i+1);
46                 if (PcapPacketUtils.isSource(p2, p1SrcIp, p1SrcPort)) {
47                     // Two packets in a row going in the same direction -> create one item pair for p1
48                     pairs.add(new PcapPacketPair(p1, null));
49                     // Advance one packet as the following two packets may form a valid two-item pair.
50                     i++;
51                 } else {
52                     // The two packets form a response-reply pair, create two-item pair.
53                     pairs.add(new PcapPacketPair(p1, p2));
54                     // Advance two packets as we have already processed the packet at index i+1 in order to create the pair.
55                     i += 2;
56                 }
57             } else {
58                 // Last packet of conversation => one item pair
59                 pairs.add(new PcapPacketPair(p1, null));
60                 // Advance i to ensure termination.
61                 i++;
62             }
63         }
64         return pairs;
65         // TODO: what if there is long time between response and reply packet? Should we add a threshold and exclude those cases?
66     }
67
68     /**
69      * Given a collection of TCP conversations and associated DNS mappings, groups the conversations by hostname.
70      * @param tcpConversations The collection of TCP conversations.
71      * @param ipHostnameMappings The associated DNS mappings.
72      * @return A map where each key is a hostname and its associated value is a list of conversations where one of the
73      *         two communicating hosts is that hostname (i.e. its IP maps to the hostname).
74      */
75     public static Map<String, List<Conversation>> groupConversationsByHostname(Collection<Conversation> tcpConversations, DnsMap ipHostnameMappings) {
76         HashMap<String, List<Conversation>> result = new HashMap<>();
77         for (Conversation c : tcpConversations) {
78             if (c.getPackets().size() == 0) {
79                 String warningStr = String.format("Detected a %s [%s] with no payload packets.",
80                         c.getClass().getSimpleName(), c.toString());
81                 System.err.println(warningStr);
82                 continue;
83             }
84             IpV4Packet firstPacketIp = c.getPackets().get(0).get(IpV4Packet.class);
85             String ipSrc = firstPacketIp.getHeader().getSrcAddr().getHostAddress();
86             String ipDst = firstPacketIp.getHeader().getDstAddr().getHostAddress();
87             // Check if src or dst IP is associated with one or more hostnames.
88             Set<String> hostnames = ipHostnameMappings.getHostnamesForIp(ipSrc);
89             if (hostnames == null) {
90                 // No luck with src ip (possibly because it's a client->srv packet), try dst ip.
91                 hostnames = ipHostnameMappings.getHostnamesForIp(ipDst);
92             }
93             if (hostnames != null) {
94                 // Put a reference to the conversation for each of the hostnames that the conversation's IP maps to.
95                 for (String hostname : hostnames) {
96                     List<Conversation> newValue = new ArrayList<>();
97                     newValue.add(c);
98                     result.merge(hostname, newValue, (l1, l2) -> { l1.addAll(l2); return l1; });
99                 }
100                 if (hostnames.size() > 1) {
101                     // Print notice of IP mapping to multiple hostnames (debugging)
102                     System.err.println(String.format("%s: encountered an IP that maps to multiple (%d) hostnames",
103                             TcpConversationUtils.class.getSimpleName(), hostnames.size()));
104                 }
105             } else {
106                 // If no hostname mapping, store conversation under the key that is the concatenation of the two IPs.
107                 // In order to ensure consistency when mapping conversations, use lexicographic order to select which IP
108                 // goes first.
109                 String delimiter = "_";
110                 // Note that the in case the comparison returns 0, the strings are equal, so it doesn't matter which of
111                 // ipSrc and ipDst go first (also, this case should not occur in practice as it means that the device is
112                 // communicating with itself!)
113                 String key = ipSrc.compareTo(ipDst) <= 0 ? ipSrc + delimiter + ipDst : ipDst + delimiter + ipSrc;
114                 List<Conversation> newValue = new ArrayList<>();
115                 newValue.add(c);
116                 result.merge(key, newValue, (l1, l2) -> { l1.addAll(l2); return l1; });
117             }
118         }
119         return result;
120     }
121
122     public static Map<String, Integer> countPacketSequenceFrequencies(Collection<Conversation> conversations) {
123         Map<String, Integer> result = new HashMap<>();
124         for (Conversation conv : conversations) {
125             if (conv.getPackets().size() == 0) {
126                 // Skip conversations with no payload packets.
127                 continue;
128             }
129             StringBuilder sb = new StringBuilder();
130             for (PcapPacket pp : conv.getPackets()) {
131                 sb.append(pp.length() + " ");
132             }
133             result.merge(sb.toString(), 1, (i1, i2) -> i1+i2);
134         }
135         return result;
136     }
137
138     /**
139      * Given a {@link Collection} of {@link Conversation}s, builds a {@link Map} from {@link String} to {@link List}
140      * of {@link Conversation}s such that each key is the <em>concatenation of the packet lengths of all payload packets
141      * (i.e., the set of packets returned by {@link Conversation#getPackets()}) separated by a delimiter</em> of any
142      * {@link Conversation} pointed to by that key. In other words, what the {@link Conversation}s {@code cs} pointed to
143      * by the key {@code s} have in common is that they all contain exactly the same number of payload packets <em>and
144      * </em> these payload packets are identical across all {@code Conversation}s in {@code cs} in terms of packet
145      * length and packet order. For example, if the key is "152 440 550", this means that every individual
146      * {@code Conversation} in the list of {@code Conversation}s pointed to by that key contain exactly three payload
147      * packet of lengths 152, 440, and 550, and these three packets are ordered in the order prescribed by the key.
148      *
149      * @param conversations The collection of {@code Conversation}s to group by packet sequence.
150      * @param verbose If set to {@code true}, the grouping (and therefore the key) will also include SYN/SYNACK,
151      *                FIN/FINACK, RST packets, and each payload-carrying packet will have an indication of the direction
152      *                of the packet prepended.
153      * @return a {@link Map} from {@link String} to {@link List} of {@link Conversation}s such that each key is the
154      *         <em>concatenation of the packet lengths of all payload packets (i.e., the set of packets returned by
155      *         {@link Conversation#getPackets()}) separated by a delimiter</em> of any {@link Conversation} pointed to
156      *         by that key.
157      */
158     public static Map<String, List<Conversation>> groupConversationsByPacketSequence(Collection<Conversation> conversations, boolean verbose) {
159         return conversations.stream().collect(Collectors.groupingBy(c -> toSequenceString(c, verbose)));
160     }
161
162     public static Map<String, List<Conversation>> groupConversationsByTlsApplicationDataPacketSequence(Collection<Conversation> conversations) {
163         return conversations.stream().collect(Collectors.groupingBy(
164                 c -> c.getTlsApplicationDataPackets().stream().map(p -> Integer.toString(p.getOriginalLength())).
165                         reduce("", (s1, s2) -> s1.length() == 0 ? s2 : s1 + " " + s2))
166         );
167     }
168
169     /**
170      * Given a {@link Conversation}, counts the frequencies of each unique packet length seen as part of the
171      * {@code Conversation}.
172      * @param c The {@code Conversation} for which unique packet length frequencies are to be determined.
173      * @return A mapping from packet length to its frequency.
174      */
175     public static Map<Integer, Integer> countPacketLengthFrequencies(Conversation c) {
176         Map<Integer, Integer> result = new HashMap<>();
177         for (PcapPacket packet : c.getPackets()) {
178             result.merge(packet.length(), 1, (i1, i2) -> i1 + i2);
179         }
180         return result;
181     }
182
183     /**
184      * Like {@link #countPacketLengthFrequencies(Conversation)}, but counts packet length frequencies for a collection
185      * of {@code Conversation}s, i.e., the frequency of a packet length becomes the total number of packets with that
186      * length across <em>all</em> {@code Conversation}s in {@code conversations}.
187      * @param conversations The collection of {@code Conversation}s for which packet length frequencies are to be
188      *                      counted.
189      * @return A mapping from packet length to its frequency.
190      */
191     public static Map<Integer, Integer> countPacketLengthFrequencies(Collection<Conversation> conversations) {
192         Map<Integer, Integer> result = new HashMap<>();
193         for (Conversation c : conversations) {
194             Map<Integer, Integer> intermediateResult = countPacketLengthFrequencies(c);
195             for (Map.Entry<Integer, Integer> entry : intermediateResult.entrySet()) {
196                 result.merge(entry.getKey(), entry.getValue(), (i1, i2) -> i1 + i2);
197             }
198         }
199         return result;
200     }
201
202     public static Map<String, Integer> countPacketPairFrequencies(Collection<PcapPacketPair> pairs) {
203         Map<String, Integer> result = new HashMap<>();
204         for (PcapPacketPair ppp : pairs) {
205             result.merge(ppp.toString(), 1, (i1, i2) -> i1 + i2);
206         }
207         return result;
208     }
209
210     public static Map<String, Map<String, Integer>> countPacketPairFrequenciesByHostname(Collection<Conversation> tcpConversations, DnsMap ipHostnameMappings) {
211         Map<String, List<Conversation>> convsByHostname = groupConversationsByHostname(tcpConversations, ipHostnameMappings);
212         HashMap<String, Map<String, Integer>> result = new HashMap<>();
213         for (Map.Entry<String, List<Conversation>> entry : convsByHostname.entrySet()) {
214             // Merge all packet pairs exchanged during the course of all conversations with hostname into one list
215             List<PcapPacketPair> allPairsExchangedWithHostname = new ArrayList<>();
216             entry.getValue().forEach(conversation -> allPairsExchangedWithHostname.addAll(extractPacketPairs(conversation)));
217             // Then count the frequencies of packet pairs exchanged with the hostname, irrespective of individual
218             // conversations
219             result.put(entry.getKey(), countPacketPairFrequencies(allPairsExchangedWithHostname));
220         }
221         return result;
222     }
223
224     /**
225      * Given a {@link Conversation}, extract its packet length sequence.
226      * @param c The {@link Conversation} from which a packet length sequence is to be extracted.
227      * @return An {@code Integer[]} that holds the packet lengths of all payload-carrying packets in {@code c}. The
228      *         packet lengths in the returned array are ordered by packet timestamp.
229      */
230     public static Integer[] getPacketLengthSequence(Conversation c) {
231         return getPacketLengthSequence(c.getPackets());
232     }
233
234
235     /**
236      * Given a {@link Conversation}, extract its packet length sequence, but only include packet lengths of those
237      * packets that carry TLS Application Data.
238      * @param c The {@link Conversation} from which a TLS Application Data packet length sequence is to be extracted.
239      * @return An {@code Integer[]} that holds the packet lengths of all packets in {@code c} that carry TLS Application
240      *         Data. The packet lengths in the returned array are ordered by packet timestamp.
241      */
242     public static Integer[] getPacketLengthSequenceTlsAppDataOnly(Conversation c) {
243         if (!c.isTls()) {
244             throw new IllegalArgumentException("Provided " + c.getClass().getSimpleName() + " was not a TLS session");
245         }
246         return getPacketLengthSequence(c.getTlsApplicationDataPackets());
247     }
248
249     /**
250      * Given a list of packets, extract the packet lengths and wrap them in an array such that the packet lengths in the
251      * resulting array appear in the same order as their corresponding packets in the input list.
252      * @param packets The list of packets for which the packet lengths are to be extracted.
253      * @return An array containing the packet lengths in the same order as their corresponding packets in the input list.
254      */
255     private static Integer[] getPacketLengthSequence(List<PcapPacket> packets) {
256         return packets.stream().map(pkt -> pkt.getOriginalLength()).toArray(Integer[]::new);
257     }
258
259     /**
260      * Builds a string representation of the sequence of packets exchanged as part of {@code c}.
261      * @param c The {@link Conversation} for which a string representation of the packet sequence is to be constructed.
262      * @param verbose {@code true} if set to true, the returned sequence string will also include SYN/SYNACK,
263      *                FIN/FINACK, RST packets, as well as an indication of the direction of payload-carrying packets.
264      * @return a string representation of the sequence of packets exchanged as part of {@code c}.
265      */
266     private static String toSequenceString(Conversation c, boolean verbose) {
267         // Payload-parrying packets are always included, but only prepend direction if verbose output is chosen.
268         Stream<String> s = c.getPackets().stream().map(p -> verbose ? c.getDirection(p).toCompactString() + p.getOriginalLength() : Integer.toString(p.getOriginalLength()));
269         if (verbose) {
270             // In the verbose case, we also print SYN, FIN and RST packets.
271             // Convert the SYN packets to a string representation and prepend them in front of the payload packets.
272             s = Stream.concat(c.getSynPackets().stream().map(p -> isSyn(p) && isAck(p) ? "SYNACK" : "SYN"), s);
273             // Convert the FIN packets to a string representation and append them after the payload packets.
274             s = Stream.concat(s, c.getFinAckPairs().stream().map(f -> f.isAcknowledged() ? "FINACK" : "FIN"));
275             // Convert the RST packets to a string representation and append at the end.
276             s = Stream.concat(s, c.getRstPackets().stream().map(r -> "RST"));
277         }
278         /*
279          * Note: the collector internally uses a StringBuilder, which is more efficient than simply doing string
280          * concatenation as in the following example:
281          * s.reduce("", (s1, s2) -> s1.length() == 0 ? s2 : s1 + " " + s2);
282          * (above code is O(N^2) where N is the number of characters)
283          */
284         return s.collect(Collectors.joining(" "));
285     }
286
287     /**
288      * Appends a space to {@code sb} <em>iff</em> {@code sb} already contains some content.
289      * @param sb A {@link StringBuilder} that should have a space appended <em>iff</em> it is not empty.
290      */
291     private static void appendSpaceIfNotEmpty(StringBuilder sb) {
292         if (sb.length() != 0) {
293             sb.append(" ");
294         }
295     }
296 }