Main.java: add paths for truncated TP Link Plug trace
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / Main.java
1 package edu.uci.iotproject;
2
3 import static edu.uci.iotproject.analysis.UserAction.Type;
4
5 import edu.uci.iotproject.analysis.TcpConversationUtils;
6 import edu.uci.iotproject.analysis.TrafficLabeler;
7 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
8 import edu.uci.iotproject.analysis.UserAction;
9 import edu.uci.iotproject.io.TriggerTimesFileReader;
10 import org.pcap4j.core.*;
11 import org.pcap4j.packet.namednumber.DataLinkType;
12
13 import java.io.EOFException;
14 import java.net.UnknownHostException;
15 import java.time.Instant;
16 import java.util.*;
17 import java.util.concurrent.TimeoutException;
18
19 /**
20  * This is a system that reads PCAP files to compare
21  * patterns of DNS hostnames, packet sequences, and packet
22  * lengths with training data to determine certain events
23  * or actions for smart home devices.
24  *
25  * @author Janus Varmarken
26  * @author Rahmadi Trimananda (rtrimana@uci.edu)
27  * @version 0.1
28  */
29 public class Main {
30
31
32     public static void main(String[] args) throws PcapNativeException, NotOpenException, EOFException, TimeoutException, UnknownHostException {
33         // -------------------------------------------------------------------------------------------------------------
34         // ------------ # Code for extracting traffic generated by a device within x seconds of a trigger # ------------
35         // Paths to input and output files (consider supplying these as arguments instead) and IP of the device for
36         // which traffic is to be extracted:
37         String path = "/scratch/July-2018"; // Rahmadi
38         //String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
39
40         // 1) D-Link July 26 experiment
41 //        final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
42 //        final String outputPcapFile = path + "/2018-07/dlink/dlink-processed.pcap";
43 //        final String triggerTimesFile = path + "/2018-07/dlink/dlink-july-26-2018.timestamps";
44 //        final String deviceIp = "192.168.1.199"; // .246 == phone; .199 == dlink plug?
45
46         // 2) TP-Link July 25 experiment
47 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.pcap";
48 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.pcap";
49 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.timestamps";
50 //        final String deviceIp = "192.168.1.159";
51
52         // 2b) TP-Link July 25 experiment TRUNCATED:
53         // Only contains "true local" events, i.e., before the behavior changes to remote-like behavior.
54         // Last included event is at July 25 10:38:11; file filtered to only include packets with arrival time <= 10:38:27.
55 //        final String inputPcapFile = path + "/2018-07/tplink/tplink.wlan1.local.truncated.pcap";
56 //        final String outputPcapFile = path + "/2018-07/tplink/tplink-processed.truncated.pcap";
57 //        final String triggerTimesFile = path + "/2018-07/tplink/tplink-july-25-2018.truncated.timestamps";
58 //        final String deviceIp = "192.168.1.159";
59
60         // 3) SmartThings Plug July 25 experiment
61 //        final String inputPcapFile = path + "/2018-07/stplug/stplug.wlan1.local.pcap";
62 //        final String outputPcapFile = path + "/2018-07/stplug/stplug-processed.pcap";
63 //        final String triggerTimesFile = path + "/2018-07/stplug/smartthings-july-25-2018.timestamps";
64 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
65
66         // 4) Wemo July 30 experiment
67 //        final String inputPcapFile = path + "/2018-07/wemo/wemo.wlan1.local.pcap";
68 //        final String outputPcapFile = path + "/2018-07/wemo/wemo-processed.pcap";
69 //        final String triggerTimesFile = path + "/2018-07/wemo/wemo-july-30-2018.timestamps";
70 //        final String deviceIp = "192.168.1.145";
71
72         // 5) Wemo Insight July 31 experiment
73 //        final String inputPcapFile = path + "/2018-07/wemoinsight/wemoinsight.wlan1.local.pcap";
74 //        final String outputPcapFile = path + "/2018-07/wemoinsight/wemoinsight-processed.pcap";
75 //        final String triggerTimesFile = path + "/2018-07/wemoinsight/wemo-insight-july-31-2018.timestamps";
76 //        final String deviceIp = "192.168.1.135";
77
78         // 6) TP-Link Bulb August 1 experiment
79 //        final String inputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb.wlan1.local.pcap";
80 //        final String outputPcapFile = path + "/2018-08/tplink-bulb/tplinkbulb-processed.pcap";
81 //        final String triggerTimesFile = path + "/2018-08/tplink-bulb/tplink-bulb-aug-3-2018.timestamps";
82 //        final String deviceIp = "192.168.1.140";
83
84         // 7) Kwikset Doorlock August 6 experiment
85 //        final String inputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock.wlan1.local.pcap";
86 //        final String outputPcapFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-processed.pcap";
87 //        final String triggerTimesFile = path + "/2018-08/kwikset-doorlock/kwikset-doorlock-aug-6-2018.timestamps";
88 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .142 == SmartThings Hub (note: use eth0 capture for this!)
89
90         // 8) Hue Bulb August 7 experiment
91 //        final String inputPcapFile = path + "/2018-08/hue-bulb/hue-bulb.wlan1.local.pcap";
92 //        final String outputPcapFile = path + "/2018-08/hue-bulb/hue-bulb-processed.pcap";
93 //        final String triggerTimesFile = path + "/2018-08/hue-bulb/hue-bulb-aug-7-2018.timestamps";
94 //        final String deviceIp = "192.168.1.246";
95
96         // 9) Lifx Bulb August 8 experiment
97 //        final String inputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb.wlan1.local.pcap";
98 //        final String outputPcapFile = path + "/2018-08/lifx-bulb/lifx-bulb-processed.pcap";
99 //        final String triggerTimesFile = path + "/2018-08/lifx-bulb/lifx-bulb-aug-8-2018.timestamps";
100 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .231 == Lifx
101
102         // 10) Amcrest Camera August 9 experiment
103 //        final String inputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera.wlan1.local.pcap";
104 //        final String outputPcapFile = path + "/2018-08/amcrest-camera/amcrest-camera-processed.pcap";
105 //        final String triggerTimesFile = path + "/2018-08/amcrest-camera/amcrest-camera-aug-9-2018.timestamps";
106 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .235 == camera
107
108         // 11) Arlo Camera August 10 experiment
109 //        final String inputPcapFile = path + "/2018-08/arlo-camera/arlo-camera.wlan1.local.pcap";
110 //        final String outputPcapFile = path + "/2018-08/arlo-camera/arlo-camera-processed.pcap";
111 //        final String triggerTimesFile = path + "/2018-08/arlo-camera/arlo-camera-aug-10-2018.timestamps";
112 //        final String deviceIp = "192.168.1.140"; // .246 == phone; .140 == camera
113
114         // 12) Blossom sprinkler August 13 experiment
115 //        final String inputPcapFile = path + "/2018-08/blossom/blossom.wlan1.local.pcap";
116 //        final String outputPcapFile = path + "/2018-08/blossom/blossom-processed.pcap";
117 //        final String triggerTimesFile = path + "/2018-08/blossom/blossom-aug-13-2018.timestamps";
118 //        final String deviceIp = "192.168.1.229"; // .246 == phone; .229 == sprinkler
119
120         // 13) DLink siren August 14 experiment
121 //        final String inputPcapFile = path + "/2018-08/dlink-siren/dlink-siren.wlan1.local.pcap";
122 //        final String outputPcapFile = path + "/2018-08/dlink-siren/dlink-siren-processed.pcap";
123 //        final String triggerTimesFile = path + "/2018-08/dlink-siren/dlink-siren-aug-14-2018.timestamps";
124 //        final String deviceIp = "192.168.1.183"; // .246 == phone; .183 == siren
125
126         // 14) Nest thermostat August 15 experiment
127 //        final String inputPcapFile = path + "/2018-08/nest/nest.wlan1.local.pcap";
128 //        final String outputPcapFile = path + "/2018-08/nest/nest-processed.pcap";
129 //        final String triggerTimesFile = path + "/2018-08/nest/nest-aug-15-2018.timestamps";
130 //        final String deviceIp = "192.168.1.246"; // .246 == phone; .127 == Nest thermostat
131
132         // 15) Alexa August 16 experiment
133 //        final String inputPcapFile = path + "/2018-08/alexa/alexa.wlan1.local.pcap";
134 //        final String outputPcapFile = path + "/2018-08/alexa/alexa-processed.pcap";
135 //        final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-16-2018.timestamps";
136 //        final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
137         // August 17
138         final String inputPcapFile = path + "/2018-08/alexa/alexa2.wlan1.local.pcap";
139         final String outputPcapFile = path + "/2018-08/alexa/alexa2-processed.pcap";
140         final String triggerTimesFile = path + "/2018-08/alexa/alexa-aug-17-2018.timestamps";
141         final String deviceIp = "192.168.1.225"; // .246 == phone; .225 == Alexa
142
143         TriggerTimesFileReader ttfr = new TriggerTimesFileReader();
144         List<Instant> triggerTimes = ttfr.readTriggerTimes(triggerTimesFile, false);
145         // Tag each trigger with "ON" or "OFF", assuming that the first trigger is an "ON" and that they alternate.
146         List<UserAction> userActions = new ArrayList<>();
147         for (int i = 0; i < triggerTimes.size(); i++) {
148             userActions.add(new UserAction(i % 2 == 0 ? Type.TOGGLE_ON : Type.TOGGLE_OFF, triggerTimes.get(i)));
149         }
150         TriggerTrafficExtractor tte = new TriggerTrafficExtractor(inputPcapFile, triggerTimes, deviceIp);
151         final PcapDumper outputter = Pcaps.openDead(DataLinkType.EN10MB, 65536).dumpOpen(outputPcapFile);
152         DnsMap dnsMap = new DnsMap();
153         TcpReassembler tcpReassembler = new TcpReassembler();
154         TrafficLabeler trafficLabeler = new TrafficLabeler(userActions);
155         tte.performExtraction(pkt -> {
156             try {
157                 outputter.dump(pkt);
158             } catch (NotOpenException e) {
159                 e.printStackTrace();
160             }
161         }, dnsMap, tcpReassembler, trafficLabeler);
162         outputter.flush();
163         outputter.close();
164
165         if (tte.getPacketsIncludedCount() != trafficLabeler.getTotalPacketCount()) {
166             // Sanity/debug check
167             throw new AssertionError(String.format("mismatch between packet count in %s and %s",
168                     TriggerTrafficExtractor.class.getSimpleName(), TrafficLabeler.class.getSimpleName()));
169         }
170
171         // Extract all conversations present in the filtered trace.
172         List<Conversation> allConversations = tcpReassembler.getTcpConversations();
173         // Group conversations by hostname.
174         Map<String, List<Conversation>> convsByHostname = TcpConversationUtils.groupConversationsByHostname(allConversations, dnsMap);
175         System.out.println("Grouped conversations by hostname.");
176         // For each hostname, count the frequencies of packet lengths exchanged with that hostname.
177         final Map<String, Map<Integer, Integer>> pktLenFreqsByHostname = new HashMap<>();
178         convsByHostname.forEach((host, convs) -> pktLenFreqsByHostname.put(host, TcpConversationUtils.countPacketLengthFrequencies(convs)));
179         System.out.println("Counted frequencies of packet lengths exchanged with each hostname.");
180         // For each hostname, count the frequencies of packet sequences (i.e., count how many conversations exchange a
181         // sequence of packets of some specific lengths).
182         final Map<String, Map<String, Integer>> pktSeqFreqsByHostname = new HashMap<>();
183         convsByHostname.forEach((host, convs) -> pktSeqFreqsByHostname.put(host, TcpConversationUtils.countPacketSequenceFrequencies(convs)));
184         System.out.println("Counted frequencies of packet sequences exchanged with each hostname.");
185         // For each hostname, count frequencies of packet pairs exchanged with that hostname across all conversations
186         final Map<String, Map<String, Integer>> pktPairFreqsByHostname =
187                 TcpConversationUtils.countPacketPairFrequenciesByHostname(allConversations, dnsMap);
188         System.out.println("Counted frequencies of packet pairs per hostname");
189         // For each user action, reassemble the set of TCP connections occurring shortly after
190         final Map<UserAction, List<Conversation>> userActionToConversations = trafficLabeler.getLabeledReassembledTcpTraffic();
191         final Map<UserAction, Map<String, List<Conversation>>> userActionsToConvsByHostname = trafficLabeler.getLabeledReassembledTcpTraffic(dnsMap);
192         System.out.println("Reassembled TCP conversations occurring shortly after each user event");
193
194
195
196         // Contains all ON events: hostname -> sequence identifier -> list of conversations with that sequence
197         Map<String, Map<String, List<Conversation>>> ons = new HashMap<>();
198         // Contains all OFF events: hostname -> sequence identifier -> list of conversations with that sequence
199         Map<String, Map<String, List<Conversation>>> offs = new HashMap<>();
200         userActionsToConvsByHostname.forEach((ua, hostnameToConvs) -> {
201             Map<String, Map<String, List<Conversation>>> outer = ua.getType() == Type.TOGGLE_ON ? ons : offs;
202             hostnameToConvs.forEach((host, convs) -> {
203                 Map<String, List<Conversation>> seqsToConvs = TcpConversationUtils.
204                         groupConversationsByPacketSequence(convs);
205                 outer.merge(host, seqsToConvs, (oldMap, newMap) -> {
206                     newMap.forEach((sequence, cs) -> oldMap.merge(sequence, cs, (list1, list2) -> {
207                         list1.addAll(list2);
208                         return list1;
209                     }));
210                     return oldMap;
211                 });
212             });
213         });
214
215         System.out.println("");
216
217         // -------------------------------------------------------------------------------------------------------------
218         // -------------------------------------------------------------------------------------------------------------
219     }
220
221 }
222
223
224 // TP-Link MAC 50:c7:bf:33:1f:09 and usually IP 192.168.1.159 (remember to verify per file)
225 // frame.len >= 556 && frame.len <= 558 && ip.addr == 192.168.1.159