Attempting to add router's MAC address as a reference for packet direction in layer...
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2ClusterMatcher.java
1 package edu.uci.iotproject.detection.layer2;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassembler;
5 import edu.uci.iotproject.trafficreassembly.layer2.Layer2Flow;
6 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassemblerObserver;
7 import edu.uci.iotproject.detection.AbstractClusterMatcher;
8 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowObserver;
9 import org.pcap4j.core.*;
10
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.function.Function;
16
17 /**
18  * Attempts to detect members of a cluster (packet sequence mutations) in layer 2 flows.
19  *
20  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
21  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
22  */
23 public class Layer2ClusterMatcher extends AbstractClusterMatcher implements Layer2FlowReassemblerObserver, Layer2FlowObserver {
24
25     /**
26      * Maps from a flow to a table of {@link Layer2SequenceMatcher}s for that particular flow. The table {@code t} is
27      * structured such that {@code t[i][j]} is a {@link Layer2SequenceMatcher} that attempts to match member {@code i}
28      * of {@link #mCluster} and has so far matched {@code j} packets of that particular sequence.
29      */
30     private final Map<Layer2Flow, Layer2SequenceMatcher[][]> mPerFlowSeqMatchers = new HashMap<>();
31     private final Map<Layer2Flow, List<Layer2RangeMatcher>> mPerFlowRangeMatcher = new HashMap<>();
32
33     private final Function<Layer2Flow, Boolean> mFlowFilter;
34
35     /**
36      * Specifying range-based instead of conservative exact matching.
37      */
38     private final boolean mRangeBased;
39
40     /**
41      * Epsilon value used by the DBSCAN algorithm; it is used again for range-based matching here.
42      */
43     private final double mEps;
44
45     private int mInclusionTimeMillis;
46
47     /**
48      * Keeping track of maximum number of skipped packets
49      */
50     private int mMaxSkippedPackets;
51     private List<Integer> mSkippedPackets;
52
53     private int mLimitSkippedPackets;
54
55     /**
56      * Router's WLAN MAC.
57      */
58     private String mTrainingRouterWlanMac;
59     private String mRouterWlanMac;
60
61     /**
62      * Create a new {@link Layer2ClusterMatcher} that attempts to find occurrences of {@code cluster}'s members.
63      * @param cluster The sequence mutations that the new {@link Layer2ClusterMatcher} should search for.
64      */
65     public Layer2ClusterMatcher(List<List<PcapPacket>> cluster, String trainingRouterWlanMac, String routerWlanMac, int inclusionTimeMillis,
66                                 boolean isRangeBased, double eps, int limitSkippedPackets) {
67         // Consider all flows if no flow filter specified.
68         this(cluster, trainingRouterWlanMac, routerWlanMac, flow -> true, inclusionTimeMillis, isRangeBased, eps,
69                 limitSkippedPackets);
70     }
71
72     /**
73      * Create a new {@link Layer2ClusterMatcher} that attempts to find occurrences of {@code cluster}'s members.
74      * @param cluster The sequence mutations that the new {@link Layer2ClusterMatcher} should search for.
75      * @param trainingRouterWlanMac The training router's WLAN MAC (used for determining the direction of packets).
76      * @param routerWlanMac The target trace router's WLAN MAC (used for determining the direction of packets).
77      * @param flowFilter A filter that defines what {@link Layer2Flow}s the new {@link Layer2ClusterMatcher} should
78      *                   search for {@code cluster}'s members in. If {@code flowFilter} returns {@code true}, the flow
79      *                   will be included (searched). Note that {@code flowFilter} is only queried once for each flow,
80      *                   namely when the {@link Layer2FlowReassembler} notifies the {@link Layer2ClusterMatcher} about
81      *                   the new flow. This functionality may for example come in handy when one only wants to search
82      *                   for matches in the subset of flows that involves a specific (range of) MAC(s).
83      * @param inclusionTimeMillis Packet inclusion time limit for matching.
84      * @param isRangeBased The boolean that decides if it is range-based vs. strict matching.
85      * @param eps The epsilon value used in the DBSCAN algorithm.
86      */
87     public Layer2ClusterMatcher(List<List<PcapPacket>> cluster, String trainingRouterWlanMac, String routerWlanMac,
88                                 Function<Layer2Flow, Boolean> flowFilter, int inclusionTimeMillis, boolean isRangeBased,
89                                 double eps, int limitSkippedPackets) {
90         super(cluster, isRangeBased);
91         mFlowFilter = flowFilter;
92         mTrainingRouterWlanMac = trainingRouterWlanMac;
93         mRouterWlanMac = routerWlanMac;
94         mRangeBased = isRangeBased;
95         mEps = eps;
96         mInclusionTimeMillis =
97                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
98         mMaxSkippedPackets = 0;
99         mSkippedPackets = new ArrayList<>();
100         // Give integer's MAX_VALUE if -1
101         mLimitSkippedPackets = limitSkippedPackets == -1 ? Integer.MAX_VALUE : limitSkippedPackets;
102     }
103
104     @Override
105     public void onNewPacket(Layer2Flow flow, PcapPacket newPacket) {
106         if (mRangeBased) {
107             rangeBasedMatching(flow, newPacket);
108         } else {
109             conservativeMatching(flow, newPacket);
110         }
111     }
112
113     private void conservativeMatching(Layer2Flow flow, PcapPacket newPacket) {
114         if (mPerFlowSeqMatchers.get(flow) == null) {
115             // If this is the first time we encounter this flow, we need to set up sequence matchers for it.
116             // All sequences of the cluster have the same length, so we only need to compute the length of the nested
117             // arrays once. We want to make room for a cluster matcher in each state, including the initial empty state
118             // but excluding the final "full match" state (as there is no point in keeping a terminated sequence matcher
119             // around), so the length of the inner array is simply the sequence length.
120             Layer2SequenceMatcher[][] matchers = new Layer2SequenceMatcher[mCluster.size()][mCluster.get(0).size()];
121             // Prepare a "state 0" sequence matcher for each sequence variation in the cluster.
122             for (int i = 0; i < matchers.length; i++) {
123                 matchers[i][0] = new Layer2SequenceMatcher(mCluster.get(i), mInclusionTimeMillis, mTrainingRouterWlanMac,
124                         mRouterWlanMac);
125             }
126             // Associate the new sequence matcher table with the new flow
127             mPerFlowSeqMatchers.put(flow, matchers);
128         }
129         // Fetch table that contains sequence matchers for this flow.
130         Layer2SequenceMatcher[][] matchers = mPerFlowSeqMatchers.get(flow);
131         // Present the packet to all sequence matchers.
132         for (int i = 0; i < matchers.length; i++) {
133             // Present packet to the sequence matchers that has advanced the most first. This is to prevent discarding
134             // the sequence matchers that have advanced the most in the special case where the searched sequence
135             // contains two packets of the same length going in the same direction.
136             for (int j = matchers[i].length - 1; j >= 0 ; j--) {
137                 Layer2SequenceMatcher sm = matchers[i][j];
138                 if (sm == null) {
139                     // There is currently no sequence matcher that has managed to match j packets.
140                     continue;
141                 }
142                 boolean matched = sm.matchPacket(newPacket);
143                 if (matched) {
144                     if (sm.getMatchedPacketsCount() == sm.getTargetSequencePacketCount()) {
145                         // Update maximum skipped packets
146                         boolean stillMatch = checkMaxSkippedPackets(flow.getPackets(), sm.getMatchedPackets());
147                         if (stillMatch) {
148                             // Sequence matcher has a match. Report it to observers.
149                             mObservers.forEach(o -> o.onMatch(this, sm.getMatchedPackets()));
150                         }
151                         // Remove the now terminated sequence matcher.
152                         matchers[i][j] = null;
153                     } else {
154                         // Sequence matcher advanced one step, so move it to its corresponding new position iff the
155                         // packet that advanced it has a later timestamp than that of the last matched packet of the
156                         // sequence matcher at the new index, if any. In most traces, a small amount of the packets
157                         // appear out of order (with regards to their timestamp), which is why this check is required.
158                         // Obviously it would not be needed if packets where guaranteed to be processed in timestamp
159                         // order here.
160                         if (matchers[i][j+1] == null ||
161                                 newPacket.getTimestamp().isAfter(matchers[i][j+1].getLastPacket().getTimestamp())) {
162                             matchers[i][j+1] = sm;
163                         }
164                     }
165                     // We always want to have a sequence matcher in state 0, regardless of if the one that advanced
166                     // from state zero completed its matching or if it replaced a different one in state 1 or not.
167                     if (sm.getMatchedPacketsCount() == 1) {
168                         matchers[i][j] = new Layer2SequenceMatcher(sm.getTargetSequence(), mInclusionTimeMillis,
169                                 mTrainingRouterWlanMac, mRouterWlanMac);
170                     }
171                 }
172             }
173         }
174     }
175
176     // Update the maximum number of skipped packets.
177     private boolean checkMaxSkippedPackets(List<PcapPacket> flowPackets, List<PcapPacket> matchedPackets) {
178         // Count number of skipped packets by looking into
179         // the difference of indices of two matched packets.
180         boolean stillMatch = true;
181         for(int i = 1; i < matchedPackets.size(); ++i) {
182             int currIndex = flowPackets.indexOf(matchedPackets.get(i-1));
183             int nextIndex = flowPackets.indexOf(matchedPackets.get(i));
184             int skippedPackets = nextIndex - currIndex;
185             if (mMaxSkippedPackets < skippedPackets) {
186                 mMaxSkippedPackets = skippedPackets;
187             }
188             if (mLimitSkippedPackets < skippedPackets) {
189                 stillMatch = false;
190             }
191             mSkippedPackets.add(skippedPackets);
192         }
193         return stillMatch;
194     }
195
196     private void rangeBasedMatching(Layer2Flow flow, PcapPacket newPacket) {
197         // TODO: For range-based matching, we need to create a new matcher every time we see the first element of
198         //  the sequence (between lower and upper bounds).
199         if (mPerFlowRangeMatcher.get(flow) == null) {
200             // If this is the first time we encounter this flow, we need to set up a list of sequence matchers.
201             List<Layer2RangeMatcher> listMatchers = new ArrayList<>();
202             // Prepare a "state 0" sequence matcher.
203             Layer2RangeMatcher matcher = new Layer2RangeMatcher(mCluster.get(0), mCluster.get(1),
204                     mInclusionTimeMillis, mEps, mTrainingRouterWlanMac, mRouterWlanMac);
205             listMatchers.add(matcher);
206             // Associate the new sequence matcher table with the new flow.
207             mPerFlowRangeMatcher.put(flow, listMatchers);
208         }
209         // Fetch table that contains sequence matchers for this flow.
210         List<Layer2RangeMatcher> listMatchers = mPerFlowRangeMatcher.get(flow);
211         // Add a new matcher if all matchers have already advanced to the next stage.
212         // We always need a new matcher to match from NO packets.
213         boolean addOneArray = true;
214         for(Layer2RangeMatcher matcher : listMatchers) {
215             if (matcher.getMatchedPacketsCount() == 0) {
216                 addOneArray = false;
217             }
218         }
219         // Add the new matcher into the list
220         if (addOneArray) {
221             Layer2RangeMatcher newMatcher = new Layer2RangeMatcher(mCluster.get(0), mCluster.get(1),
222                     mInclusionTimeMillis, mEps, mTrainingRouterWlanMac, mRouterWlanMac);
223             listMatchers.add(newMatcher);
224         }
225         // Present packet to the sequence matchers.
226         // Make a shallow copy of the list so that we can clean up the actual list when a matcher is terminated.
227         // Otherwise, we would get an exception for changing the list while iterating on it.
228         List<Layer2RangeMatcher> listMatchersCopy = new ArrayList<>(listMatchers);
229         Layer2RangeMatcher previousMatcher = null;
230         for(Layer2RangeMatcher matcher : listMatchersCopy) {
231             Layer2RangeMatcher sm = matcher;
232             // Check if no packets are matched yet or if there are matched packets, the next packet to be matched
233             // has to be later than the last matched packet.
234             // In most traces, a small amount of the packets appear out of order (with regards to their timestamp),
235             // which is why this check is required.
236             // Obviously it would not be needed if packets where guaranteed to be processed in timestamp
237             // order here.
238             if (sm.getMatchedPacketsCount() == 0 ||
239                     newPacket.getTimestamp().isAfter(sm.getLastPacket().getTimestamp())) {
240                 boolean matched = sm.matchPacket(newPacket);
241                 if (matched) {
242                     // BUG: found on May 29, 2019
243                     // We need to remove a previous match if the current match is later in time.
244                     // This is done only if we have matched at least 1 packet (we are about to match the second or
245                     // later packets) and we match for the same packet position in the signature (check the size!).
246                     if (previousMatcher != null && sm.getMatchedPacketsCount() > 1 &&
247                             previousMatcher.getMatchedPacketsCount() == sm.getMatchedPacketsCount()) {
248                         List<PcapPacket> previouslyMatchedPackets = previousMatcher.getMatchedPackets();
249                         List<PcapPacket> currentlyMatchedPackets = sm.getMatchedPackets();
250                         // We need to check 1 packet before the last matched packet from the previous matcher.
251                         int packetIndexToCheck = (sm.getMatchedPacketsCount() - 1) - 1;
252                         if (currentlyMatchedPackets.get(packetIndexToCheck).getTimestamp().
253                             isAfter(previouslyMatchedPackets.get(packetIndexToCheck).getTimestamp())) {
254                             listMatchers.remove(previousMatcher);
255                         }
256                     }
257                     if (sm.getMatchedPacketsCount() == sm.getTargetSequencePacketCount()) {
258                         // Update maximum skipped packets
259                         boolean stillMatch = checkMaxSkippedPackets(flow.getPackets(), sm.getMatchedPackets());
260                         if (stillMatch) {
261                             // Sequence matcher has a match. Report it to observers.
262                             mObservers.forEach(o -> o.onMatch(this, sm.getMatchedPackets()));
263                         }
264                         // Terminate sequence matcher since matching is complete.
265                         listMatchers.remove(matcher);
266                     }
267                     previousMatcher = sm;
268                 }
269             }
270         }
271     }
272
273     @Override
274     protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster) {
275         // Note: we assume that all sequences in the input cluster are of the same length and that their packet
276         // directions are identical.
277         List<List<PcapPacket>> prunedCluster = new ArrayList<>();
278         for (List<PcapPacket> originalClusterSeq : cluster) {
279             boolean alreadyPresent = prunedCluster.stream().anyMatch(pcPkts -> {
280                 for (int i = 0; i < pcPkts.size(); i++) {
281                     if (pcPkts.get(i).getOriginalLength() != originalClusterSeq.get(i).getOriginalLength()) {
282                         return false;
283                     }
284                 }
285                 return true;
286             });
287             if (!alreadyPresent) {
288                 // Add the sequence if not already present in the pruned cluster.
289                 prunedCluster.add(originalClusterSeq);
290             }
291         }
292         return prunedCluster;
293     }
294
295     private static final boolean DEBUG = false;
296
297     @Override
298     public void onNewFlow(Layer2FlowReassembler reassembler, Layer2Flow newFlow) {
299         // New flow detected. Check if we should consider it when searching for cluster member matches.
300         if (mFlowFilter.apply(newFlow)) {
301             if (DEBUG) {
302                 System.out.println(">>> ACCEPTING FLOW: " + newFlow + " <<<");
303             }
304             // Subscribe to the new flow to get updates whenever a new packet pertaining to the flow is processed.
305             newFlow.addFlowObserver(this);
306         } else if (DEBUG) {
307             System.out.println(">>> IGNORING FLOW: " + newFlow + " <<<");
308         }
309     }
310
311     /**
312       * Return the maximum number of skipped packets.
313       */
314     public int getMaxSkippedPackets() {
315        return mMaxSkippedPackets;
316     }
317
318     /**
319      * Return the numbers of skipped packets.
320      */
321     public List<Integer> getSkippedPackets() {
322         return mSkippedPackets;
323     }
324 }