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