Adding the basic signature harvesting (i.e., also saving to and reading back from...
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / util / PrintUtils.java
1 package edu.uci.iotproject.util;
2
3 import edu.uci.iotproject.DnsMap;
4 import edu.uci.iotproject.analysis.PcapPacketPair;
5 import org.apache.commons.math3.stat.clustering.Cluster;
6
7 import java.io.FileInputStream;
8 import java.io.FileOutputStream;
9 import java.io.ObjectInputStream;
10 import java.io.ObjectOutputStream;
11 import java.util.List;
12 import java.util.Optional;
13 import java.util.Set;
14 import java.util.stream.Collectors;
15
16 import org.pcap4j.core.PcapPacket;
17
18 /**
19  * Utility methods for generating (output) strings.
20  *
21  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
22  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
23  */
24 public class PrintUtils {
25
26     /**
27      * This is the path for writing the list of list of packet pairs {@code List<List<PcapPacket>>} into a file.
28      * The packet pairs are the pairs in one cluster, so the list represents a cluster that has been derived through
29      * the DBSCAN algorithm.
30      *
31      * E.g., this file could contain a list like the following:
32      *
33      * [[1109, 613],[1111, 613],[1115, 613],...]
34      *
35      * This list has lists of PcapPacket pairs as its members. We do not maintain the pairs in the form of
36      * {@code Cluster<PcapPacketPair>} objects because there might be a situation where we could combine multiple
37      * PcapPacketPair objects into a longer signature, i.e., a string of PcapPacket objects and not just a pair.
38      */
39     private static final String SERIALIZABLE_FILE_PATH = "./signature.sig";
40
41     private PrintUtils() { /* private constructor to prevent instantiation */ }
42
43     /**
44      * Write the list of list of packet pairs {@code List<List<PcapPacket>>} into a file.
45      *
46      * After the DBSCAN algorithm derives the clusters from pairs, we save the signature in the form of list of
47      * packet pairs. We harvest the pairs and transform them back into a list of PcapPacket objects.
48      * We do not maintain the pairs in the form of {@code Cluster<PcapPacketPair>} objects because there might be
49      * a situation where we could combine multiple PcapPacketPair objects into a longer signature, i.e., a string of
50      * PcapPacket objects and not just a pair.
51      *
52      * @param fileName The path of the file in {@link String}. We could leave this one {@code null} if we wanted the
53      *                 default file name {@code SERIALIZABLE_FILE_PATH}.
54      * @param clusterPackets The {@link Cluster} objects in the form of list of {@code PcapPacket} objects.
55      */
56     public static void serializeClustersIntoFile(String fileName, List<List<PcapPacket>> clusterPackets) {
57         if (fileName == null)
58             fileName = SERIALIZABLE_FILE_PATH;
59         try (ObjectOutputStream oos =
60                 new ObjectOutputStream(new FileOutputStream(fileName))) {
61             oos.writeObject(clusterPackets);
62         } catch (Exception ex) {
63             ex.printStackTrace();
64         }
65     }
66
67     /**
68      * Read the list of list of packet pairs {@code List<List<PcapPacket>>} from a file.
69      *
70      * After the DBSCAN algorithm derives the clusters from pairs, we save the signature in the form of list of
71      * packet pairs. We harvest the pairs and transform them back into a list of PcapPacket objects.
72      * We do not maintain the pairs in the form of {@code Cluster<PcapPacketPair>} objects because there might be
73      * a situation where we could combine multiple PcapPacketPair objects into a longer signature, i.e., a string of
74      * PcapPacket objects and not just a pair.
75      *
76      * @param fileName The path of the file in {@link String}. We could leave this one {@code null} if we wanted the
77      *                 default file name {@code SERIALIZABLE_FILE_PATH}.
78      * @return The list of list of {@link Cluster} objects ({@code List<List<PcapPacket>>}) that is read from file.
79      */
80     public static List<List<PcapPacket>> serializeClustersFromFile(String fileName) {
81         if (fileName == null)
82             fileName = SERIALIZABLE_FILE_PATH;
83         List<List<PcapPacket>> ppListOfList = null;
84         try (ObjectInputStream ois =
85                      new ObjectInputStream(new FileInputStream(fileName))) {
86             ppListOfList = (List<List<PcapPacket>>) ois.readObject();
87         } catch (Exception ex) {
88             ex.printStackTrace();
89         }
90
91         return ppListOfList;
92     }
93
94     /**
95      * Converts a {@code PcapPacketPair} into a CSV string containing the packet lengths of the two packets in the pair.
96      *
97      * For example, the resulting string will be "123, 456" if the first packet of the pair has a length of 123 and the
98      * second packet of the pair has a length of 456.
99      *
100      * <b>Note:</b> if the {@link PcapPacketPair} has no second element, 0 is printed as the length of the second packet
101      * in the pair.
102      *
103      * @return a CSV string containing the packet lengths of the two packets of the given {@code PcapPacketPair}.
104      */
105     public static String toCsv(PcapPacketPair packetPair) {
106         return String.format("%d, %d", packetPair.getFirst().getOriginalLength(),
107                 packetPair.getSecond().map(pp -> pp.getOriginalLength()).orElse(0));
108     }
109
110     /**
111      * Converts a {@code PcapPacketPair} into a CSV string containing the packet lengths of the two packets in the pair
112      * followed by the source of each packet. The source will be a (set of) hostname(s) if the source IP can be resolved
113      * to a (set of) hostname(s) using the provided {@link DnsMap}.
114      *
115      * For example, the resulting string will be "123, 456, 192.168.1.42, domain.com" if the first packet of the pair
116      * has a length of 123, the second packet of the pair has a length of 456, the first packet of the pair the pair has
117      * a source IP of '192.168.1.42' that cannot be resolved to a hostname, and the second packet of the pair has an IP
118      * that resolves to 'domain.com'.
119      *
120      * <b>Note:</b> if the {@link PcapPacketPair} has no second element, 0 is printed as the length of the second packet
121      * in the pair, and null is printed for its source.
122      *
123      * @return a CSV string containing the packet lengths of the two packets of the given {@code PcapPacketPair} as well
124      *         as their respective sources.
125      */
126     public static String toCsv(PcapPacketPair packetPair, DnsMap ipHostnameMappings) {
127         // First obtain source IPs
128         String firstSrc = PcapPacketUtils.getSourceIp(packetPair.getFirst());
129         // Note: use optional for second item in pair as there might not be one.
130         Optional<String> secondSrc = packetPair.getSecond().map(pkt -> PcapPacketUtils.getSourceIp(pkt));
131
132         // If possible, map source IPs to hostnames.
133         Set<String> firstHostnames = ipHostnameMappings.getHostnamesForIp(firstSrc);
134         Optional<Set<String>> secondHostnames = secondSrc.map(src -> ipHostnameMappings.getHostnamesForIp(src));
135         final String delimiter = " ";
136         if (firstHostnames != null) {
137             // If one IP maps to multiple hostnames, we concatenate the hostnames (separated by a delimiter)
138             firstSrc = firstHostnames.stream().collect(Collectors.joining(delimiter));
139         }
140         // If one IP maps to multiple hostnames, we concatenate the hostnames (separated by a delimiter)
141         Optional<String> hostnames = secondHostnames.map(hostnameSet -> hostnameSet.stream().collect(Collectors.joining(delimiter)));
142         // Fall back to IP if we couldn't second pair is present, but we couldn't map to (a) hostname(s).
143         secondSrc = hostnames.isPresent() ? hostnames : secondSrc;
144
145         // Check if the first source is C (client) or S (server)
146         String firstSrcCorS = packetPair.isFirstClient() ? "C" : "S";
147         String secondSrcCorS = packetPair.isSecondClient() ? "C" : "S";
148
149         return String.format("%d, %d, %s, %s, %s, %s", packetPair.getFirst().getOriginalLength(),
150                 packetPair.getSecond().map(pp -> pp.getOriginalLength()).orElse(0),
151                 firstSrc,
152                 secondSrc.orElse("null"),
153                 firstSrcCorS,
154                 secondSrcCorS);
155     }
156
157     /**
158      * Generate a string that summarizes/describes {@code cluster}.
159      * @param cluster The {@link Cluster} to summarize/describe.
160      * @return A string that summarizes/describes {@code cluster}.
161      */
162     public static String toSummaryString(Cluster<PcapPacketPair> cluster) {
163         StringBuilder sb = new StringBuilder();
164         for (PcapPacketPair ppp : cluster.getPoints()) {
165             sb.append(toCsv(ppp, ppp.getDnsMap()) + System.lineSeparator());
166         }
167         return sb.toString();
168     }
169 }