b5c3f663fc865bdce7c560be3b5ca575d72b9015
[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     /**
29      * Create a {@code Layer2SequenceMatcher}.
30      * @param sequence The sequence to match against (search for).
31      * @param trainingRouterWlanMac The training router's WLAN MAC (used for determining the direction of packets).
32      * @param routerWlanMac The target trace router's WLAN MAC (used for determining the direction of packets).
33      */
34     public Layer2SequenceMatcher(List<PcapPacket> sequence, int inclusionTimeMillis, String trainingRouterWlanMac,
35                                  String routerWlanMac) {
36         super(sequence, trainingRouterWlanMac, routerWlanMac);
37         mSequence = sequence;
38         // Compute packet directions for sequence.
39         for (int i = 0; i < sequence.size(); i++) {
40             if (i == 0) {
41                 // No previous packet; boolean parameter is ignored in this special case.
42                 mPacketDirections[i] = getPacketDirection(null, true, sequence.get(i));
43             } else {
44                 // Base direction marker on direction of previous packet.
45                 PcapPacket prevPkt = mSequence.get(i-1);
46                 boolean prevPktDirection = mPacketDirections[i-1];
47                 mPacketDirections[i] = getPacketDirection(prevPkt, prevPktDirection, sequence.get(i));
48             }
49         }
50         mInclusionTimeMillis =
51                 inclusionTimeMillis == 0 ? TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS : inclusionTimeMillis;
52     }
53
54     /**
55      * Attempt to advance this {@code Layer2SequenceMatcher} by matching {@code packet} against the packet that this
56      * {@code Layer2SequenceMatcher} expects as the next packet of the sequence it is searching for.
57      * @param packet
58      * @return {@code true} if this {@code Layer2SequenceMatcher} could advance by adding {@code packet} to its set of
59      *         matched packets, {@code false} otherwise.
60      */
61     public boolean matchPacket(PcapPacket packet) {
62         if (getMatchedPacketsCount() == getTargetSequencePacketCount()) {
63             // We already matched the entire sequence, so we can't match any more packets.
64             return false;
65         }
66
67         // Verify that new packet pertains to same flow as previously matched packets, if any.
68         if (getMatchedPacketsCount() > 0) {
69             MacAddress pktSrc = PcapPacketUtils.getEthSrcAddr(packet);
70             MacAddress pktDst = PcapPacketUtils.getEthDstAddr(packet);
71             MacAddress earlierPktSrc = PcapPacketUtils.getEthSrcAddr(mMatchedPackets.get(0));
72             MacAddress earlierPktDst = PcapPacketUtils.getEthDstAddr(mMatchedPackets.get(0));
73             if (!(pktSrc.equals(earlierPktSrc) && pktDst.equals(earlierPktDst) ||
74                     pktSrc.equals(earlierPktDst) && pktDst.equals(earlierPktSrc))) {
75                 return false;
76             }
77         }
78
79         // Get representative of the packet we expect to match next.
80         PcapPacket expected = mSequence.get(mMatchedPackets.size());
81         // First verify if the received packet has the length we're looking for.
82         if (packet.getOriginalLength() == expected.getOriginalLength()) {
83             // If this is the first packet, we only need to verify that its length is correct. Time constraints are
84             // obviously satisfied as there are no previous packets. Furthermore, direction matches by definition as we
85             // don't know the MAC of the device (or phone) in advance, so we can't enforce a rule saying "first packet
86             // must originate from this particular MAC".
87             if (getMatchedPacketsCount() == 0) {
88                 // Store packet as matched and advance.
89                 mMatchedPackets.add(packet);
90                 return true;
91             }
92             // Check if direction of packet matches expected direction.
93             boolean actualDirection = getPacketDirection(mMatchedPackets.get(getMatchedPacketsCount()-1),
94                     mPacketDirections[getMatchedPacketsCount()-1], packet);
95             boolean expectedDirection = mPacketDirections[getMatchedPacketsCount()];
96             if (actualDirection != expectedDirection) {
97                 return false;
98             }
99             // Next apply timing constraints:
100             // 1: to be a match, the packet must have a later timestamp than any other packet currently matched
101             // 2: does adding the packet cause the max allowed time between first packet and last packet to be exceeded?
102             if (!packet.getTimestamp().isAfter(mMatchedPackets.get(getMatchedPacketsCount()-1).getTimestamp())) {
103                 return false;
104             }
105 //            if (packet.getTimestamp().isAfter(mMatchedPackets.get(0).getTimestamp().
106 //                            plusMillis(TriggerTrafficExtractor.INCLUSION_WINDOW_MILLIS))) {
107             if (packet.getTimestamp().isAfter(mMatchedPackets.get(0).getTimestamp().
108                 plusMillis(mInclusionTimeMillis))) {
109                 return false;
110             }
111             // If we made it here, it means that this packet has the expected length, direction, and obeys the timing
112             // constraints, so we store it and advance.
113             mMatchedPackets.add(packet);
114             if (mMatchedPackets.size() == mSequence.size()) {
115                 // TODO report (to observers?) that we are done?
116             }
117             return true;
118         }
119         return false;
120     }
121
122     public int getTargetSequencePacketCount() {
123         return mSequence.size();
124     }
125
126     public List<PcapPacket> getTargetSequence() {
127         return mSequence;
128     }
129
130 }