Bringing down time constraint to packet level so that we will exclude those pairs...
[pingpong.git] / Code / Projects / PacketLevelSignatureExtractor / src / main / java / edu / uci / iotproject / detection / layer2 / Layer2SequenceMatcher.java
1 package edu.uci.iotproject.detection.layer2;
2
3 import edu.uci.iotproject.analysis.TriggerTrafficExtractor;
4 import edu.uci.iotproject.util.PcapPacketUtils;
5 import org.pcap4j.core.PcapPacket;
6 import org.pcap4j.util.MacAddress;
7
8 import java.util.ArrayList;
9 import java.util.List;
10
11 /**
12  * Attempts to detect the presence of a specific packet sequence in the set of packets provided through multiple calls
13  * to {@link #matchPacket(PcapPacket)}, considering only layer 2 information.
14  *
15  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
16  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
17  */
18 public class Layer2SequenceMatcher extends Layer2AbstractMatcher {
19
20     /**
21      * The sequence this {@link Layer2SequenceMatcher} is searching for.
22      */
23     private final List<PcapPacket> mSequence;
24
25     private int mInclusionTimeMillis;
26
27     /**
28      * Create a {@code Layer2SequenceMatcher}.
29      * @param sequence The sequence to match against (search for).
30      */
31     public Layer2SequenceMatcher(List<PcapPacket> sequence, int inclusionTimeMillis) {
32         super(sequence);
33         mSequence = sequence;
34         // Compute packet directions for sequence.
35         for (int i = 0; i < sequence.size(); i++) {
36             if (i == 0) {
37                 // No previous packet; boolean parameter is ignored in this special case.
38                 mPacketDirections[i] = getPacketDirection(null, true, sequence.get(i));
39             } else {
40                 // Base direction marker on direction of previous packet.
41                 PcapPacket prevPkt = mSequence.get(i-1);
42                 boolean prevPktDirection = mPacketDirections[i-1];
43                 mPacketDirections[i] = getPacketDirection(prevPkt, prevPktDirection, sequence.get(i));
44             }
45         }
46         mInclusionTimeMillis =
47                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
48     }
49
50     /**
51      * Attempt to advance this {@code Layer2SequenceMatcher} by matching {@code packet} against the packet that this
52      * {@code Layer2SequenceMatcher} expects as the next packet of the sequence it is searching for.
53      * @param packet
54      * @return {@code true} if this {@code Layer2SequenceMatcher} could advance by adding {@code packet} to its set of
55      *         matched packets, {@code false} otherwise.
56      */
57     public boolean matchPacket(PcapPacket packet) {
58         if (getMatchedPacketsCount() == getTargetSequencePacketCount()) {
59             // We already matched the entire sequence, so we can't match any more packets.
60             return false;
61         }
62
63         // Verify that new packet pertains to same flow as previously matched packets, if any.
64         if (getMatchedPacketsCount() > 0) {
65             MacAddress pktSrc = PcapPacketUtils.getEthSrcAddr(packet);
66             MacAddress pktDst = PcapPacketUtils.getEthDstAddr(packet);
67             MacAddress earlierPktSrc = PcapPacketUtils.getEthSrcAddr(mMatchedPackets.get(0));
68             MacAddress earlierPktDst = PcapPacketUtils.getEthDstAddr(mMatchedPackets.get(0));
69             if (!(pktSrc.equals(earlierPktSrc) && pktDst.equals(earlierPktDst) ||
70                     pktSrc.equals(earlierPktDst) && pktDst.equals(earlierPktSrc))) {
71                 return false;
72             }
73         }
74
75         // Get representative of the packet we expect to match next.
76         PcapPacket expected = mSequence.get(mMatchedPackets.size());
77         // First verify if the received packet has the length we're looking for.
78         if (packet.getOriginalLength() == expected.getOriginalLength()) {
79             // If this is the first packet, we only need to verify that its length is correct. Time constraints are
80             // obviously satisfied as there are no previous packets. Furthermore, direction matches by definition as we
81             // don't know the MAC of the device (or phone) in advance, so we can't enforce a rule saying "first packet
82             // must originate from this particular MAC".
83             if (getMatchedPacketsCount() == 0) {
84                 // Store packet as matched and advance.
85                 mMatchedPackets.add(packet);
86                 return true;
87             }
88             // Check if direction of packet matches expected direction.
89             boolean actualDirection = getPacketDirection(mMatchedPackets.get(getMatchedPacketsCount()-1),
90                     mPacketDirections[getMatchedPacketsCount()-1], packet);
91             boolean expectedDirection = mPacketDirections[getMatchedPacketsCount()];
92             if (actualDirection != expectedDirection) {
93                 return false;
94             }
95             // Next apply timing constraints:
96             // 1: to be a match, the packet must have a later timestamp than any other packet currently matched
97             // 2: does adding the packet cause the max allowed time between first packet and last packet to be exceeded?
98             if (!packet.getTimestamp().isAfter(mMatchedPackets.get(getMatchedPacketsCount()-1).getTimestamp())) {
99                 return false;
100             }
101 //            if (packet.getTimestamp().isAfter(mMatchedPackets.get(0).getTimestamp().
102 //                            plusMillis(TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS))) {
103             if (packet.getTimestamp().isAfter(mMatchedPackets.get(0).getTimestamp().
104                 plusMillis(mInclusionTimeMillis))) {
105                 return false;
106             }
107             // If we made it here, it means that this packet has the expected length, direction, and obeys the timing
108             // constraints, so we store it and advance.
109             mMatchedPackets.add(packet);
110             if (mMatchedPackets.size() == mSequence.size()) {
111                 // TODO report (to observers?) that we are done?
112             }
113             return true;
114         }
115         return false;
116     }
117
118     public int getTargetSequencePacketCount() {
119         return mSequence.size();
120     }
121
122     public List<PcapPacket> getTargetSequence() {
123         return mSequence;
124     }
125
126 }