1 package edu.uci.iotproject.detection.layer3;
3 import edu.uci.iotproject.detection.AbstractClusterMatcher;
4 import edu.uci.iotproject.trafficreassembly.layer3.Conversation;
5 import edu.uci.iotproject.trafficreassembly.layer3.TcpReassembler;
6 import edu.uci.iotproject.analysis.TcpConversationUtils;
7 import edu.uci.iotproject.io.PcapHandleReader;
8 import edu.uci.iotproject.util.PrintUtils;
9 import org.pcap4j.core.*;
11 import java.time.ZoneId;
13 import java.util.stream.Collectors;
15 import static edu.uci.iotproject.util.PcapPacketUtils.*;
18 * Searches a traffic trace for sequences of packets "belong to" a given cluster (in other words, attempts to classify
19 * traffic as pertaining to a given cluster).
21 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
22 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
24 public class Layer3ClusterMatcher extends AbstractClusterMatcher implements PacketListener {
27 public static void main(String[] args) throws PcapNativeException, NotOpenException {
29 // String path = "/scratch/July-2018"; // Rahmadi
30 String path = "/Users/varmarken/temp/UCI IoT Project/experiments"; // Janus
31 final String inputPcapFile = path + "/2018-07/dlink/dlink.wlan1.local.pcap";
32 final String signatureFile = path + "/2018-07/dlink/offSignature1.sig";
34 List<List<PcapPacket>> signature = PrintUtils.deserializeClustersFromFile(signatureFile);
35 Layer3ClusterMatcher clusterMatcher = new Layer3ClusterMatcher(signature, null,
36 (sig, match) -> System.out.println(
37 String.format("[ !!! SIGNATURE DETECTED AT %s !!! ]",
38 match.get(0).getTimestamp().atZone(ZoneId.of("America/Los_Angeles")))
44 handle = Pcaps.openOffline(inputPcapFile, PcapHandle.TimestampPrecision.NANO);
45 } catch (PcapNativeException pne) {
46 handle = Pcaps.openOffline(inputPcapFile);
48 PcapHandleReader reader = new PcapHandleReader(handle, p -> true, clusterMatcher);
49 reader.readFromHandle();
50 clusterMatcher.performDetection();
54 * The ordered directions of packets in the sequences that make up {@link #mCluster}.
56 private final Conversation.Direction[] mClusterMemberDirections;
59 * For reassembling the observed traffic into TCP connections.
61 private final TcpReassembler mTcpReassembler = new TcpReassembler();
64 * IP of the router's WAN port (if analyzed traffic is captured at the ISP's point of view).
66 private final String mRouterWanIp;
68 private final ClusterMatchObserver[] mObservers;
71 * Create a {@link Layer3ClusterMatcher}.
72 * @param cluster The cluster that traffic is matched against.
73 * @param routerWanIp The router's WAN IP if examining traffic captured at the ISP's point of view (used for
74 * determining the direction of packets).
75 * @param detectionObservers Client code that wants to get notified whenever the {@link Layer3ClusterMatcher} detects that
76 * (a subset of) the examined traffic is similar to the traffic that makes up
77 * {@code cluster}, i.e., when the examined traffic is classified as pertaining to
80 public Layer3ClusterMatcher(List<List<PcapPacket>> cluster, String routerWanIp, ClusterMatchObserver... detectionObservers) {
82 // ===================== PRECONDITION SECTION =====================
83 mObservers = Objects.requireNonNull(detectionObservers, "detectionObservers cannot be null");
84 if (mObservers.length == 0) {
85 throw new IllegalArgumentException("no detectionObservers provided");
87 // Build the cluster members' direction sequence.
88 // Note: assumes that the provided cluster was captured within the local network (routerWanIp is set to null).
89 mClusterMemberDirections = getPacketDirections(cluster.get(0), null);
91 * Enforce restriction on cluster members: all representatives must exhibit the same direction pattern and
92 * contain the same number of packets. Note that this is a somewhat heavy operation, so it may be disabled later
93 * on in favor of performance. However, it is only run once (at instantiation), so the overhead may be warranted
94 * in order to ensure correctness, especially during the development/debugging phase.
96 if (mCluster.stream().
97 anyMatch(inner -> !Arrays.equals(mClusterMemberDirections, getPacketDirections(inner, null)))) {
98 throw new IllegalArgumentException(
99 "cluster members must contain the same number of packets and exhibit the same packet direction " +
103 // ================================================================
104 mRouterWanIp = routerWanIp;
108 public void gotPacket(PcapPacket packet) {
109 // Present packet to TCP reassembler so that it can be mapped to a connection (if it is a TCP packet).
110 mTcpReassembler.gotPacket(packet);
114 * Get the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
115 * @return the cluster that describes the packet sequence that this {@link Layer3ClusterMatcher} is searching for.
117 public List<List<PcapPacket>> getCluster() {
121 public void performDetection() {
123 * Let's start out simple by building a version that only works for signatures that do not span across multiple
124 * TCP conversations...
126 for (Conversation c : mTcpReassembler.getTcpConversations()) {
127 if (c.isTls() && c.getTlsApplicationDataPackets().isEmpty() || !c.isTls() && c.getPackets().isEmpty()) {
128 // Skip empty conversations.
131 for (List<PcapPacket> signatureSequence : mCluster) {
132 if (isTlsSequence(signatureSequence) != c.isTls()) {
133 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
136 // Fetch set of packets to examine based on TLS or not.
137 List<PcapPacket> cPkts = c.isTls() ? c.getTlsApplicationDataPackets() : c.getPackets();
139 * Note: we embed the attempt to detect the signature sequence in a loop in order to capture those cases
140 * where the same signature sequence appears multiple times in one Conversation.
142 * Note: since we expect all sequences that together make up the signature to exhibit the same direction
143 * pattern, we can simply pass the precomputed direction array for the signature sequence so that it
144 * won't have to be recomputed internally in each call to findSubsequenceInSequence().
146 Optional<List<PcapPacket>> match;
147 while ((match = findSubsequenceInSequence(signatureSequence, cPkts, mClusterMemberDirections, null)).
149 List<PcapPacket> matchSeq = match.get();
150 // Notify observers about the match.
151 Arrays.stream(mObservers).forEach(o -> o.onMatch(Layer3ClusterMatcher.this, matchSeq));
153 * Get the index in cPkts of the last packet in the sequence of packets that matches the searched
154 * signature sequence.
156 int matchSeqEndIdx = cPkts.indexOf(matchSeq.get(matchSeq.size()-1));
157 // We restart the search for the signature sequence immediately after that index, so truncate cPkts.
158 cPkts = cPkts.stream().skip(matchSeqEndIdx + 1).collect(Collectors.toList());
163 * if no item in cluster matches, also perform a distance-based matching to cover those cases where we did
164 * not manage to capture every single mutation of the sequence during training.
166 * Need to compute average/centroid of cluster to do so...? Compute within-cluster variance, then check if
167 * distance between input conversation and cluster average/centroid is smaller than or equal to the computed
174 * Checks if {@code sequence} is a sequence of TLS packets. Note: the current implementation relies on inspection
175 * of the port numbers when deciding between TLS vs. non-TLS. Therefore, only the first packet of {@code sequence}
176 * is examined as it is assumed that all packets in {@code sequence} pertain to the same {@link Conversation} and
177 * hence share the same set of two src/dst port numbers (albeit possibly alternating between which one is the src
178 * and which one is the dst, as packets in {@code sequence} may be in alternating directions).
179 * @param sequence The sequence of packets for which it is to be determined if it is a sequence of TLS packets or
181 * @return {@code true} if {@code sequence} is a sequence of TLS packets, {@code false} otherwise.
183 private boolean isTlsSequence(List<PcapPacket> sequence) {
184 // NOTE: Assumes ALL packets in sequence pertain to the same TCP connection!
185 PcapPacket firstPkt = sequence.get(0);
186 int srcPort = getSourcePort(firstPkt);
187 int dstPort = getDestinationPort(firstPkt);
188 return TcpConversationUtils.isTlsPort(srcPort) || TcpConversationUtils.isTlsPort(dstPort);
192 * Examine if a given sequence of packets ({@code sequence}) contains a given shorter sequence of packets
193 * ({@code subsequence}). Note: the current implementation actually searches for a substring as it does not allow
194 * for interleaving packets in {@code sequence} that are not in {@code subsequence}; for example, if
195 * {@code subsequence} consists of packet lengths [2, 3, 5] and {@code sequence} consists of packet lengths
196 * [2, 3, 4, 5], the result will be that there is no match (because of the interleaving 4). If we are to allow
197 * interleaving packets, we need a modified version of
198 * <a href="https://stackoverflow.com/a/20545604/1214974">this</a>.
200 * @param subsequence The sequence to search for.
201 * @param sequence The sequence to search.
202 * @param subsequenceDirections The directions of packets in {@code subsequence} such that for all {@code i},
203 * {@code subsequenceDirections[i]} is the direction of the packet returned by
204 * {@code subsequence.get(i)}. May be set to {@code null}, in which this call will
205 * internally compute the packet directions.
206 * @param sequenceDirections The directions of packets in {@code sequence} such that for all {@code i},
207 * {@code sequenceDirections[i]} is the direction of the packet returned by
208 * {@code sequence.get(i)}. May be set to {@code null}, in which this call will internally
209 * compute the packet directions.
211 * @return An {@link Optional} containing the part of {@code sequence} that matches {@code subsequence}, or an empty
212 * {@link Optional} if no part of {@code sequence} matches {@code subsequence}.
214 private Optional<List<PcapPacket>> findSubsequenceInSequence(List<PcapPacket> subsequence,
215 List<PcapPacket> sequence,
216 Conversation.Direction[] subsequenceDirections,
217 Conversation.Direction[] sequenceDirections) {
218 if (sequence.size() < subsequence.size()) {
219 // If subsequence is longer, it cannot be contained in sequence.
220 return Optional.empty();
222 if (isTlsSequence(subsequence) != isTlsSequence(sequence)) {
223 // We consider it a mismatch if one is a TLS application data sequence and the other is not.
224 return Optional.empty();
226 // If packet directions have not been precomputed by calling code, we need to construct them.
227 if (subsequenceDirections == null) {
228 subsequenceDirections = getPacketDirections(subsequence, mRouterWanIp);
230 if (sequenceDirections == null) {
231 sequenceDirections = getPacketDirections(sequence, mRouterWanIp);
235 while (seqIdx < sequence.size()) {
236 PcapPacket subseqPkt = subsequence.get(subseqIdx);
237 PcapPacket seqPkt = sequence.get(seqIdx);
238 // We only have a match if packet lengths and directions match.
239 if (subseqPkt.getOriginalLength() == seqPkt.getOriginalLength() &&
240 subsequenceDirections[subseqIdx] == sequenceDirections[seqIdx]) {
241 // A match; advance both indices to consider next packet in subsequence vs. next packet in sequence.
244 if (subseqIdx == subsequence.size()) {
245 // We managed to match the entire subsequence in sequence.
246 // Return the sublist of sequence that matches subsequence.
249 * ASSUMES THE BACKING LIST (i.e., 'sequence') IS _NOT_ STRUCTURALLY MODIFIED, hence may not work
252 return Optional.of(sequence.subList(seqIdx - subsequence.size(), seqIdx));
258 * If we managed to match parts of subsequence, we restart the search for subsequence in sequence at
259 * the index of sequence where the current mismatch occurred. I.e., we must reset subseqIdx, but
260 * leave seqIdx untouched.
265 * First packet of subsequence didn't match packet at seqIdx of sequence, so we move forward in
266 * sequence, i.e., we continue the search for subsequence in sequence starting at index seqIdx+1 of
273 return Optional.empty();
277 * Given a cluster, produces a pruned version of that cluster. In the pruned version, there are no duplicate cluster
278 * members. Two cluster members are considered identical if their packets lengths and packet directions are
279 * identical. The resulting pruned cluster is unmodifiable (this applies to both the outermost list as well as the
280 * nested lists) in order to preserve its integrity when exposed to external code (e.g., through
281 * {@link #getCluster()}).
283 * @param cluster A cluster to prune.
284 * @return The resulting pruned cluster.
287 protected List<List<PcapPacket>> pruneCluster(List<List<PcapPacket>> cluster) {
288 List<List<PcapPacket>> prunedCluster = new ArrayList<>();
289 for (List<PcapPacket> originalClusterSeq : cluster) {
290 boolean alreadyPresent = false;
291 for (List<PcapPacket> prunedClusterSeq : prunedCluster) {
292 Optional<List<PcapPacket>> duplicate = findSubsequenceInSequence(originalClusterSeq, prunedClusterSeq,
293 mClusterMemberDirections, mClusterMemberDirections);
294 if (duplicate.isPresent()) {
295 alreadyPresent = true;
299 if (!alreadyPresent) {
300 prunedCluster.add(Collections.unmodifiableList(originalClusterSeq));
303 return Collections.unmodifiableList(prunedCluster);
307 * Given a {@code List<PcapPacket>}, generate a {@code Conversation.Direction[]} such that each entry in the
308 * resulting {@code Conversation.Direction[]} specifies the direction of the {@link PcapPacket} at the corresponding
309 * index in the input list.
310 * @param packets The list of packets for which to construct a corresponding array of packet directions.
311 * @param routerWanIp The IP of the router's WAN port. This is used for determining the direction of packets when
312 * the traffic is captured just outside the local network (at the ISP side of the router). Set to
313 * {@code null} if {@code packets} stem from traffic captured within the local network.
314 * @return A {@code Conversation.Direction[]} specifying the direction of the {@link PcapPacket} at the
315 * corresponding index in {@code packets}.
317 private static Conversation.Direction[] getPacketDirections(List<PcapPacket> packets, String routerWanIp) {
318 Conversation.Direction[] directions = new Conversation.Direction[packets.size()];
319 for (int i = 0; i < packets.size(); i++) {
320 PcapPacket pkt = packets.get(i);
321 if (getSourceIp(pkt).equals(getDestinationIp(pkt))) {
322 // Sanity check: we shouldn't be processing loopback traffic
323 throw new AssertionError("loopback traffic detected");
325 if (isSrcIpLocal(pkt) || getSourceIp(pkt).equals(routerWanIp)) {
326 directions[i] = Conversation.Direction.CLIENT_TO_SERVER;
327 } else if (isDstIpLocal(pkt) || getDestinationIp(pkt).equals(routerWanIp)) {
328 directions[i] = Conversation.Direction.SERVER_TO_CLIENT;
330 throw new IllegalArgumentException("no local IP or router WAN port IP found, can't detect direction");
337 * Interface used by client code to register for receiving a notification whenever the {@link Layer3ClusterMatcher}
338 * detects traffic that is similar to the traffic that makes up the cluster returned by
339 * {@link Layer3ClusterMatcher#getCluster()}.
341 interface ClusterMatchObserver {
343 * Callback that is invoked whenever a sequence that is similar to a sequence associated with the cluster (i.e.,
344 * a sequence is a member of the cluster) is detected in the traffic that the associated {@link Layer3ClusterMatcher}
346 * @param clusterMatcher The {@link Layer3ClusterMatcher} that detected a match (classified traffic as pertaining to
347 * its associated cluster).
348 * @param match The traffic that was deemed to match the cluster associated with {@code clusterMatcher}.
350 void onMatch(Layer3ClusterMatcher clusterMatcher, List<PcapPacket> match);