1 package edu.uci.iotproject.detection.layer2;
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.*;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.List;
16 import java.util.concurrent.CopyOnWriteArrayList;
17 import java.util.function.Function;
20 * Attempts to detect members of a cluster (packet sequence mutations) in layer 2 flows.
22 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
23 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
25 public class Layer2ClusterMatcher extends AbstractClusterMatcher implements Layer2FlowReassemblerObserver, Layer2FlowObserver {
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.
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<>();
36 private final Function<Layer2Flow, Boolean> mFlowFilter;
39 * Specifying range-based instead of conservative exact matching.
41 private final boolean mRangeBased;
44 * Epsilon value used by the DBSCAN algorithm; it is used again for range-based matching here.
46 private final double mEps;
48 private int mInclusionTimeMillis;
51 * Keeping track of maximum number of skipped packets
53 //private int mMaxSkippedPackets;
54 private List<Integer> mMaxSkippedPackets;
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.
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);
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.
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;
85 mInclusionTimeMillis =
86 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
87 //mMaxSkippedPackets = 0;
88 mMaxSkippedPackets = new ArrayList<>();
92 public void onNewPacket(Layer2Flow flow, PcapPacket newPacket) {
94 rangeBasedMatching(flow, newPacket);
96 conservativeMatching(flow, newPacket);
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);
112 // Associate the new sequence matcher table with the new flow
113 mPerFlowSeqMatchers.put(flow, matchers);
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];
125 // There is currently no sequence matcher that has managed to match j packets.
128 boolean matched = sm.matchPacket(newPacket);
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;
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
144 if (matchers[i][j+1] == null ||
145 newPacket.getTimestamp().isAfter(matchers[i][j+1].getLastPacket().getTimestamp())) {
146 matchers[i][j+1] = sm;
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);
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;
170 mMaxSkippedPackets.add(skippedPackets);
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);
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) {
197 // Add the new matcher into the list
199 Layer2RangeMatcher newMatcher = new Layer2RangeMatcher(mCluster.get(0), mCluster.get(1),
200 mInclusionTimeMillis, mEps);
201 listMatchers.add(newMatcher);
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
215 if (sm.getMatchedPacketsCount() == 0 ||
216 newPacket.getTimestamp().isAfter(sm.getLastPacket().getTimestamp())) {
217 boolean matched = sm.matchPacket(newPacket);
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);
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()) {
246 if (!alreadyPresent) {
247 // Add the sequence if not already present in the pruned cluster.
248 prunedCluster.add(originalClusterSeq);
251 return prunedCluster;
254 private static final boolean DEBUG = false;
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)) {
261 System.out.println(">>> ACCEPTING FLOW: " + newFlow + " <<<");
263 // Subscribe to the new flow to get updates whenever a new packet pertaining to the flow is processed.
264 newFlow.addFlowObserver(this);
266 System.out.println(">>> IGNORING FLOW: " + newFlow + " <<<");
271 * Return the maximum number of skipped packets.
273 // public int getMaxSkippedPackets() {
274 // return mMaxSkippedPackets;
276 public List<Integer> getMaxSkippedPackets() {
277 return mMaxSkippedPackets;