1 package edu.uci.iotproject.detection.layer3;
3 import edu.uci.iotproject.detection.AbstractClusterMatcher;
4 import edu.uci.iotproject.detection.ClusterMatcherObserver;
5 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
6 import edu.uci.iotproject.trafficreassembly.layer3.TcpReassembler;
7 import edu.uci.iotproject.analysis.TcpConversationUtils;
8 import edu.uci.iotproject.io.PcapHandleReader;
9 import edu.uci.iotproject.util.PrintUtils;
10 import org.pcap4j.core.*;
12 import java.time.ZoneId;
14 import java.util.stream.Collectors;
16 import static edu.uci.iotproject.util.PcapPacketUtils.*;
19 * Searches a traffic trace for sequences of packets "belong to" a given cluster (in other words, attempts to classify
20 * traffic as pertaining to a given cluster).
22 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
23 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
25 public class Layer3ClusterMatcher extends AbstractClusterMatcher implements PacketListener {
28 public static void main(String[] args) throws PcapNativeException, NotOpenException {
30 // String path = "/scratch/July-2018"; // Rahmadi
31 // String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
32 // final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
33 // final String signatureFile = path + "/2018-07/dlink/offSignature1.sig";
35 // List<List<PcapPacket>> signature = PrintUtils.deserializeClustersFromFile(signatureFile);
36 // Layer3ClusterMatcher clusterMatcher = new Layer3ClusterMatcher(signature, null,
37 // (sig, match) -> System.out.println(
38 // String.format("[ !!! SIGNATURE DETECTED AT %s !!! ]",
39 // match.get(0).getTimestamp().atZone(ZoneId.of("America/Los_Angeles")))
45 // handle = Pcaps.openOffline(inputPcapFile, PcapHandle.TimestampPrecision.NANO);
46 // } catch (PcapNativeException pne) {
47 // handle = Pcaps.openOffline(inputPcapFile);
49 // PcapHandleReader reader = new PcapHandleReader(handle, p -> true, clusterMatcher);
50 // reader.readFromHandle();
51 // clusterMatcher.performDetection();
55 * The ordered directions of packets in the sequences that make up {@link #mCluster}.
57 private final Conversation.Direction[] mClusterMemberDirections;
60 * For reassembling the observed traffic into TCP connections.
62 private final TcpReassembler mTcpReassembler = new TcpReassembler();
65 * IP of the router's WAN port (if analyzed traffic is captured at the ISP's point of view).
67 private final String mRouterWanIp;
70 * Epsilon value used by the DBSCAN algorithm; it is used again for range-based matching here.
72 private final double mEps;
75 * Create a {@link Layer3ClusterMatcher}.
76 * @param cluster The cluster that traffic is matched against.
77 * @param routerWanIp The router's WAN IP if examining traffic captured at the ISP's point of view (used for
78 * determining the direction of packets).
79 * @param eps The epsilon value used in the DBSCAN algorithm.
80 * @param isRangeBased The boolean that decides if it is range-based vs. strict matching.
81 * @param detectionObservers Client code that wants to get notified whenever the {@link Layer3ClusterMatcher} detects that
82 * (a subset of) the examined traffic is similar to the traffic that makes up
83 * {@code cluster}, i.e., when the examined traffic is classified as pertaining to
86 public Layer3ClusterMatcher(List<List<PcapPacket>> cluster, String routerWanIp, boolean isRangeBased, double eps,
87 ClusterMatcherObserver... detectionObservers) {
88 super(cluster, isRangeBased);
89 Objects.requireNonNull(detectionObservers, "detectionObservers cannot be null");
90 for (ClusterMatcherObserver obs : detectionObservers) {
93 // Build the cluster members' direction sequence.
94 // Note: assumes that the provided cluster was captured within the local network (routerWanIp is set to null).
95 mClusterMemberDirections = getPacketDirections(cluster.get(0), null);
97 * Enforce restriction on cluster members: all representatives must exhibit the same direction pattern and
98 * contain the same number of packets. Note that this is a somewhat heavy operation, so it may be disabled later
99 * on in favor of performance. However, it is only run once (at instantiation), so the overhead may be warranted
100 * in order to ensure correctness, especially during the development/debugging phase.
102 if (!isRangeBased) { // Only when it is not range-based
103 if (mCluster.stream().
104 anyMatch(inner -> !Arrays.equals(mClusterMemberDirections, getPacketDirections(inner, null)))) {
105 throw new IllegalArgumentException(
106 "cluster members must contain the same number of packets and exhibit the same packet direction " +
112 mRouterWanIp = routerWanIp;
116 public void gotPacket(PcapPacket packet) {
117 // Present packet to TCP reassembler so that it can be mapped to a connection (if it is a TCP packet).
118 mTcpReassembler.gotPacket(packet);
122 * Get the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
123 * @return the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
125 public List<List<PcapPacket>> getCluster() {
129 public void performDetectionRangeBased() {
131 * Let's start out simple by building a version that only works for signatures that do not span across multiple
132 * TCP conversations...
134 for (Conversation c : mTcpReassembler.getTcpConversations()) {
135 if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
136 // Skip empty conversations.
139 List<PcapPacket> lowerBound = mCluster.get(0);
140 List<PcapPacket> upperBound = mCluster.get(1);
141 if (isTlsSequence(lowerBound) != c.isTls() || isTlsSequence(upperBound) != c.isTls()) {
142 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
145 // Fetch set of packets to examine based on TLS or not.
146 List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
147 Optional<List<PcapPacket>> match;
148 while ((match = findSubsequenceInSequence(lowerBound, upperBound, cPkts, mClusterMemberDirections, null)).
150 List<PcapPacket> matchSeq = match.get();
151 // Notify observers about the match.
152 mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
154 * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
155 * signature sequence.
157 int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size() - 1));
158 // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
159 cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
164 public void performDetectionConservative() {
166 * Let's start out simple by building a version that only works for signatures that do not span across multiple
167 * TCP conversations...
169 for (Conversation c : mTcpReassembler.getTcpConversations()) {
170 if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
171 // Skip empty conversations.
174 for (List<PcapPacket> signatureSequence : mCluster) {
175 if (isTlsSequence(signatureSequence) != c.isTls()) {
176 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
179 // Fetch set of packets to examine based on TLS or not.
180 List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
182 * Note: we embed the attempt to detect the signature sequence in a loop in order to capture those cases
183 * where the same signature sequence appears multiple times in one Conversation.
185 * Note: since we expect all sequences that together make up the signature to exhibit the same direction
186 * pattern, we can simply pass the precomputed direction array for the signature sequence so that it
187 * won't have to be recomputed internally in each call to findSubsequenceInSequence().
189 Optional<List<PcapPacket>> match;
190 while ((match = findSubsequenceInSequence(signatureSequence, cPkts, mClusterMemberDirections, null)).
192 List<PcapPacket> matchSeq = match.get();
193 // Notify observers about the match.
194 mObservers.forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
196 * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
197 * signature sequence.
199 int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size() - 1));
200 // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
201 cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
207 * if no item in cluster matches, also perform a distance-based matching to cover those cases where we did
208 * not manage to capture every single mutation of the sequence during training.
210 * Need to compute average/centroid of cluster to do so...? Compute within-cluster variance, then check if
211 * distance between input conversation and cluster average/centroid is smaller than or equal to the computed
218 * Checks if {@code sequence} is a sequence of TLS packets. Note: the current implementation relies on inspection
219 * of the port numbers when deciding between TLS vs. non-TLS. Therefore, only the first packet of {@code sequence}
220 * is examined as it is assumed that all packets in {@code sequence} pertain to the same {@link Conversation} and
221 * hence share the same set of two src/dst port numbers (albeit possibly alternating between which one is the src
222 * and which one is the dst, as packets in {@code sequence} may be in alternating directions).
223 * @param sequence The sequence of packets for which it is to be determined if it is a sequence of TLS packets or
225 * @return {@code true} if {@code sequence} is a sequence of TLS packets, {@code false} otherwise.
227 private boolean isTlsSequence(List<PcapPacket> sequence) {
228 // NOTE: Assumes ALL packets in sequence pertain to the same TCP connection!
229 PcapPacket firstPkt = sequence.get(0);
230 int srcPort = getSourcePort(firstPkt);
231 int dstPort = getDestinationPort(firstPkt);
232 return TcpConversationUtils.isTlsPort(srcPort) || TcpConversationUtils.isTlsPort(dstPort);
236 * Examine if a given sequence of packets ({@code sequence}) contains a given shorter sequence of packets
237 * ({@code subsequence}). Note: the current implementation actually searches for a substring as it does not allow
238 * for interleaving packets in {@code sequence} that are not in {@code subsequence}; for example, if
239 * {@code subsequence} consists of packet lengths [2, 3, 5] and {@code sequence} consists of packet lengths
240 * [2, 3, 4, 5], the result will be that there is no match (because of the interleaving 4). If we are to allow
241 * interleaving packets, we need a modified version of
242 * <a href="https://stackoverflow.com/a/20545604/1214974">this</a>.
244 * @param subsequence The sequence to search for.
245 * @param sequence The sequence to search.
246 * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
247 * {@code subsequenceDirections[i]} is the direction of the packet returned by
248 * {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
249 * internally compute the packet directions.
250 * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
251 * {@code sequenceDirections[i]} is the direction of the packet returned by
252 * {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
253 * compute the packet directions.
255 * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
256 * {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
258 private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> subsequence,
259 List<PcapPacket> sequence,
260 Conversation.Direction[] subsequenceDirections,
261 Conversation.Direction[] sequenceDirections) {
262 if (sequence.size() < subsequence.size()) {
263 // If subsequence is longer, it cannot be contained in sequence.
264 return Optional.empty();
266 if (isTlsSequence(subsequence) != isTlsSequence(sequence)) {
267 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
268 return Optional.empty();
270 // If packet directions have not been precomputed by calling code, we need to construct them.
271 if (subsequenceDirections == null) {
272 subsequenceDirections = getPacketDirections(subsequence, mRouterWanIp);
274 if (sequenceDirections == null) {
275 sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
279 while (seqIdx < sequence.size()) {
280 PcapPacket subseqPkt = subsequence.get(subseqIdx);
281 PcapPacket seqPkt = sequence.get(seqIdx);
282 // We only have a match if packet lengths and directions match.
283 if (subseqPkt.getOriginalLength() == seqPkt.getOriginalLength() &&
284 subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
285 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
288 if (subseqIdx == subsequence.size()) {
289 // We managed to match the entire subsequence in sequence.
290 // Return the sublist of sequence that matches subsequence.
293 * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
296 return Optional.of(sequence.subList(seqIdx - subsequence.size(), seqIdx));
302 * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
303 * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
304 * leave seqIdx untouched.
309 * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
310 * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
317 return Optional.empty();
321 * Overloading the method {@code findSubsequenceInSequence} for range-based matching. Instead of a sequence,
322 * we have sequences of lower and upper bounds.
324 * @param lowerBound The lower bound of the sequence we search for.
325 * @param upperBound The upper bound of the sequence we search for.
326 * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
327 * {@code subsequenceDirections[i]} is the direction of the packet returned by
328 * {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
329 * internally compute the packet directions.
330 * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
331 * {@code sequenceDirections[i]} is the direction of the packet returned by
332 * {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
333 * compute the packet directions.
335 * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
336 * {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
338 private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> lowerBound,
339 List<PcapPacket> upperBound,
340 List<PcapPacket> sequence,
341 Conversation.Direction[] subsequenceDirections,
342 Conversation.Direction[] sequenceDirections) {
343 // Just do the checks for either lower or upper bound!
344 // TODO: For now we use just the lower bound
345 if (sequence.size() < lowerBound.size()) {
346 // If subsequence is longer, it cannot be contained in sequence.
347 return Optional.empty();
349 if (isTlsSequence(lowerBound) != isTlsSequence(sequence)) {
350 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
351 return Optional.empty();
353 // If packet directions have not been precomputed by calling code, we need to construct them.
354 if (subsequenceDirections == null) {
355 subsequenceDirections = getPacketDirections(lowerBound, mRouterWanIp);
357 if (sequenceDirections == null) {
358 sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
362 while (seqIdx < sequence.size()) {
363 PcapPacket lowBndPkt = lowerBound.get(subseqIdx);
364 PcapPacket upBndPkt = upperBound.get(subseqIdx);
365 PcapPacket seqPkt = sequence.get(seqIdx);
366 // We only have a match if packet lengths and directions match.
367 // The packet lengths have to be in the range of [lowerBound - eps, upperBound+eps]
368 // TODO: Maybe we could do better here for the double to integer conversion?
369 int epsLowerBound = lowBndPkt.length() - (int) mEps;
370 int epsUpperBound = upBndPkt.length() + (int) mEps;
371 if (epsLowerBound <= seqPkt.getOriginalLength() &&
372 seqPkt.getOriginalLength() <= epsUpperBound &&
373 subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
374 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
377 if (subseqIdx == lowerBound.size()) {
378 // We managed to match the entire subsequence in sequence.
379 // Return the sublist of sequence that matches subsequence.
382 * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
385 return Optional.of(sequence.subList(seqIdx - lowerBound.size(), seqIdx));
391 * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
392 * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
393 * leave seqIdx untouched.
398 * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
399 * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
406 return Optional.empty();
410 * Given a cluster, produces a pruned version of that cluster. In the pruned version, there are no duplicate cluster
411 * members. Two cluster members are considered identical if their packets lengths and packet directions are
412 * identical. The resulting pruned cluster is unmodifiable (this applies to both the outermost list as well as the
413 * nested lists) in order to preserve its integrity when exposed to external code (e.g., through
414 * {@link #getCluster()}).
416 * @param cluster A cluster to prune.
417 * @return The resulting pruned cluster.
420 protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster) {
421 List<List<PcapPacket>> prunedCluster = new ArrayList<>();
422 for (List<PcapPacket> originalClusterSeq : cluster) {
423 boolean alreadyPresent = false;
424 for (List<PcapPacket> prunedClusterSeq : prunedCluster) {
425 Optional<List<PcapPacket>> duplicate = findSubsequenceInSequence(originalClusterSeq, prunedClusterSeq,
426 mClusterMemberDirections, mClusterMemberDirections);
427 if (duplicate.isPresent()) {
428 alreadyPresent = true;
432 if (!alreadyPresent) {
433 prunedCluster.add(Collections.unmodifiableList(originalClusterSeq));
436 return Collections.unmodifiableList(prunedCluster);
440 * Given a {@code List<PcapPacket>}, generate a {@code Conversation.Direction[]} such that each entry in the
441 * resulting {@code Conversation.Direction[]} specifies the direction of the {@link PcapPacket} at the corresponding
442 * index in the input list.
443 * @param packets The list of packets for which to construct a corresponding array of packet directions.
444 * @param routerWanIp The IP of the router's WAN port. This is used for determining the direction of packets when
445 * the traffic is captured just outside the local network (at the ISP side of the router). Set to
446 * {@code null} if {@code packets} stem from traffic captured within the local network.
447 * @return A {@code Conversation.Direction[]} specifying the direction of the {@link PcapPacket} at the
448 * corresponding index in {@code packets}.
450 private static Conversation.Direction[] getPacketDirections(List<PcapPacket> packets, String routerWanIp) {
451 Conversation.Direction[] directions = new Conversation.Direction[packets.size()];
452 for (int i = 0; i < packets.size(); i++) {
453 PcapPacket pkt = packets.get(i);
454 if (getSourceIp(pkt).equals(getDestinationIp(pkt))) {
455 // Sanity check: we shouldn't be processing loopback traffic
456 throw new AssertionError("loopback traffic detected");
458 if (isSrcIpLocal(pkt) || getSourceIp(pkt).equals(routerWanIp)) {
459 directions[i] = Conversation.Direction.CLIENT_TO_SERVER;
460 } else if (isDstIpLocal(pkt) || getDestinationIp(pkt).equals(routerWanIp)) {
461 directions[i] = Conversation.Direction.SERVER_TO_CLIENT;
463 //throw new IllegalArgumentException("no local IP or router WAN port IP found, can't detect direction");