79a945ffe790bf4a850d9471fe2e7d548b834732
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2ClusterMatcher.java
1 package edu.uci.iotproject.detection.layer2;
2
3 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassembler;
4 import edu.uci.iotproject.trafficreassembly.layer2.Layer2Flow;
5 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowReassemblerObserver;
6 import edu.uci.iotproject.detection.AbstractClusterMatcher;
7 import edu.uci.iotproject.trafficreassembly.layer2.Layer2FlowObserver;
8 import org.pcap4j.core.*;
9
10 import java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14
15 /**
16  * Attempts to detect members of a cluster (packet sequence mutations) in layer 2 flows.
17  *
18  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
19  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
20  */
21 public class Layer2ClusterMatcher extends AbstractClusterMatcher implements Layer2FlowReassemblerObserver, Layer2FlowObserver {
22
23     /**
24      * Maps from a flow to a table of {@link Layer2SequenceMatcher}s for that particular flow. The table {@code t} is
25      * structured such that {@code t[i][j]} is a {@link Layer2SequenceMatcher} that attempts to match member {@code i}
26      * of {@link #mCluster} and has so far matched {@code j} packets of that particular sequence.
27      */
28     private final Map<Layer2Flow, Layer2SequenceMatcher[][]> mPerFlowSeqMatchers = new HashMap<>();
29
30
31     public Layer2ClusterMatcher(List<List<PcapPacket>> cluster) {
32         super(cluster);
33     }
34
35     @Override
36     public void onNewPacket(Layer2Flow flow, PcapPacket newPacket) {
37         if (mPerFlowSeqMatchers.get(flow) == null) {
38             // If this is the first time we encounter this flow, we need to set up sequence matchers for it.
39             // All sequences of the cluster have the same length, so we only need to compute the length of the nested
40             // arrays once. We want to make room for a cluster matcher in each state, including the initial empty state
41             // but excluding the final "full match" state (as there is no point in keeping a terminated sequence matcher
42             // around), so the length of the inner array is simply the sequence length.
43             Layer2SequenceMatcher[][] matchers = new Layer2SequenceMatcher[mCluster.size()][mCluster.get(0).size()];
44             // Prepare a "state 0" sequence matcher for each sequence variation in the cluster.
45             for (int i = 0; i < matchers.length; i++) {
46                 matchers[i][0] = new Layer2SequenceMatcher(mCluster.get(i));
47             }
48             // Associate the new sequence matcher table with the new flow
49             mPerFlowSeqMatchers.put(flow, matchers);
50         }
51         // Fetch table that contains sequence matchers for this flow.
52         Layer2SequenceMatcher[][] matchers = mPerFlowSeqMatchers.get(flow);
53         // Present the packet to all sequence matchers.
54         for (int i = 0; i < matchers.length; i++) {
55             // Present packet to the sequence matchers that has advanced the most first. This is to prevent discarding
56             // the sequence matchers that have advanced the most in the special case where the searched sequence
57             // contains two packets of the same length going in the same direction.
58             for (int j = matchers[i].length - 1; j >= 0 ; j--) {
59                 Layer2SequenceMatcher sm = matchers[i][j];
60                 if (sm == null) {
61                     // There is currently no sequence matcher that has managed to match j packets.
62                     continue;
63                 }
64                 boolean matched = sm.matchPacket(newPacket);
65                 if (matched) {
66                     if (sm.getMatchedPacketsCount() == sm.getTargetSequencePacketCount()) {
67                         // Sequence matcher has a match. Report it to observers.
68                         mObservers.forEach(o -> o.onMatch(this, sm.getMatchedPackets()));
69                         // Remove the now terminated sequence matcher.
70                         matchers[i][j] = null;
71                     } else {
72                         // Sequence matcher advanced one step, so move it to its corresponding new position iff the
73                         // packet that advanced it has a later timestamp than that of the last matched packet of the
74                         // sequence matcher at the new index, if any. In most traces, a small amount of the packets
75                         // appear out of order (with regards to their timestamp), which is why this check is required.
76                         // Obviously it would not be needed if packets where guaranteed to be processed in timestamp
77                         // order here.
78                         if (matchers[i][j+1] == null ||
79                                 newPacket.getTimestamp().isAfter(matchers[i][j+1].getLastPacket().getTimestamp())) {
80                             matchers[i][j+1] = sm;
81                         }
82                     }
83                     // We always want to have a sequence matcher in state 0, regardless of if the one that advanced
84                     // from state zero completed its matching or if it replaced a different one in state 1 or not.
85                     if (sm.getMatchedPacketsCount() == 1) {
86                         matchers[i][j] = new Layer2SequenceMatcher(sm.getTargetSequence());
87                     }
88                 }
89             }
90         }
91     }
92
93
94     @Override
95     protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster) {
96         // Note: we assume that all sequences in the input cluster are of the same length and that their packet
97         // directions are identical.
98         List<List<PcapPacket>> prunedCluster = new ArrayList<>();
99         for (List<PcapPacket> originalClusterSeq : cluster) {
100             boolean alreadyPresent = prunedCluster.stream().anyMatch(pcPkts -> {
101                 for (int i = 0; i < pcPkts.size(); i++) {
102                     if (pcPkts.get(i).getOriginalLength() != originalClusterSeq.get(i).getOriginalLength()) {
103                         return false;
104                     }
105                 }
106                 return true;
107             });
108             if (!alreadyPresent) {
109                 // Add the sequence if not already present in the pruned cluster.
110                 prunedCluster.add(originalClusterSeq);
111             }
112         }
113         return prunedCluster;
114     }
115
116
117     @Override
118     public void onNewFlow(Layer2FlowReassembler reassembler, Layer2Flow newFlow) {
119         // Subscribe to the new flow to get updates whenever a new packet pertaining to the flow is processed.
120         newFlow.addFlowObserver(this);
121     }
122 }