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