Algorithm Search⌘K

Algorithmadvanced

Malware behavior clustering

Also called scalable behavior-based malware clustering.

Turns sandbox traces into sets of behavioral features and clusters samples into families with locality-sensitive hashing and single linkage on the Jaccard index.

Time
O(n k l d + n^2 (d + log n)) worstO(n k l d + n c (d + log n)) averageO(n k l d) best
Space
O(n k l + n c) extra
Where
c = the candidate pairs per sample; d = the largest number of features of a sample; k = the hash functions per band; l = the number of bands; n = the number of samples
Properties
randomizednot exactofflinerandomizediterative
Origin
Ulrich Bayer, Paolo Milani Comparetti, Clemens Hlauschek, Christopher Kruegel, Engin Kirda, 2009

Malware behavior clustering groups malware samples into families by what they do when they run, not by their bytes. A sandbox runs each sample and records its actions on operating system objects. Each sample becomes a set of features, and two samples are similar when their sets have a high Jaccard index. Comparing all pairs costs n2/2n^2/2 similarity computations, which is too slow for tens of thousands of samples. Bayer, Milani Comparetti, Hlauschek, Kruegel and Kirda (NDSS 2009) used MinHash and locality-sensitive hashing to find the pairs that are probably similar, checked those pairs exactly, and joined them by single-linkage clustering. This page describes the clustering step on synthetic feature sets. It says nothing about how to build or run a sample, and the code reads no traces.

In plain words

Two programs that open the same kinds of files, write the same registry keys and contact the same kinds of servers are probably variants of one family. Write down the actions of each program as a set of short facts. Two sets that share most of their facts belong together.

There are too many pairs to compare them all. So give each set a short fingerprint made of a few random hash values. Two sets that share many facts often get the same fingerprint, and two sets that share none almost never do. Put the sets into buckets by fingerprint, and compare only the sets that meet in a bucket. Do this several times with different hash values, so that a similar pair is very likely to meet at least once.

Then join each pair that is really similar, and the groups that form are the families.

The problem

The input is a list of nn non-empty finite sets A1,…,AnA_1, \ldots, A_n, the behavior profiles, and a threshold t∈(0,1]t \in (0, 1]. Draw a graph GtG_t with an edge between ii and jj when J(Ai,Aj)=∣Ai∩Aj∣/∣Ai∪Aj∣≥tJ(A_i, A_j) = |A_i \cap A_j| / |A_i \cup A_j| \ge t. Exact single linkage at level tt returns the connected components of GtG_t. The task is to compute these components, or a close approximation of them, without computing all (n2)\binom{n}{2} similarities. This is a case of the clustering problem with a fixed threshold in place of a fixed number of clusters.

In the paper, a feature is a string built from the profile, such as an operation on a named object, or a dependence between two operations. Features that occur in only one sample are removed first, because they cannot make two samples similar. Here a feature is an integer.

The algorithm

The parameters are the threshold tt, the number kk of hash functions in a band, the number ll of bands and a seed. Each hash function is h(x)=(ax+c) mod Ph(x) = (a x + c) \bmod P for a large prime PP and random a≠0a \ne 0 and cc. The MinHash value of a set AA under hh is min⁡x∈Ah(x)\min_{x \in A} h(x).

  1. LSH-BEHAVIOR-CLUSTER(A[1..n], t, k, l)
  2. 1for each sample i and each of the k·l hash functions h: sig[i][h] ← min over x in A[i] of h(x)
  3. 2for each band b = 1..l: put each sample into a bucket keyed by its k values of band b
  4. 3C ← the pairs (i, j) that share a bucket in at least one band
  5. 4E ← the pairs of C with J(A[i], A[j]) ≥ t ▷ exact check of each candidate
  6. 5sort E by decreasing similarity
  7. 6make each sample a set of its own in a disjoint-set structure
  8. 7for each pair (i, j) of E in order: if FIND(i) ≠ FIND(j) then UNION(i, j) and record the merge
  9. 8return the sets of the disjoint-set structure as the clusters

Line L1 computes the signatures, klk l numbers for each sample. Lines L2 and L3 are the LSH step. Two samples land in the same bucket of a band only when all kk of their values in the band agree. A large kk makes a band strict, and many bands give a similar pair many chances. Line L4 removes the false candidates: pairs that met in a bucket by chance but have J<tJ < t. Lines L5 to L7 are single linkage: in the sorted order, the recorded merges form the single-linkage dendrogram above the level tt, which is Kruskal's method for a maximum spanning forest on the candidate edges. The clusters at level tt do not depend on the order of line L5; the order matters only for the dendrogram.

For one hash function, the probability that two sets get the same MinHash value is their Jaccard index ss, in the ideal model of a random permutation. So a pair of similarity ss is a candidate with probability

Pr⁡[candidate]=1−(1−sk)l.\Pr[\text{candidate}] = 1 - (1 - s^k)^l .

This is an S-shaped curve in ss. Bayer and coauthors chose k=10k = 10 and l=90l = 90 for t=0.7t = 0.7. Then a pair with s=0.7s = 0.7 is a candidate with probability about 0.924, and a pair with s=0.5s = 0.5 with probability about 0.084.

Example

Six samples A to F with made-up integer features. The threshold is t=0.6t = 0.6, with k=2k = 2 and l=4l = 4 (seed 1 in the code).

sample features band 1 band 2 band 3 band 4
A {1, 2, 3, 4, 5} 778, 505 232, 516 788, 164 364, 405
B {1, 2, 3, 4, 6} 778, 505 928, 379 617, 164 364, 405
C {1, 2, 3, 5, 6} 495, 505 928, 516 788, 197 364, 405
D {10, 11, 12, 13} 312, 374 475, 834 472, 983 777, 464
E {10, 11, 12, 14} 312, 587 475, 834 301, 950 777, 437
F {20, 21} 563, 833 967, 514 156, 802 190, 844

The table shows each MinHash value modulo 1000 to save space; equal entries are equal in full. Band 1 puts A and B together, band 2 puts D and E together, and band 4 puts A, B and C together. In the other places a band needs both values to agree: D and E agree on the first value of band 1 and of band 4, but not on the second, so these bands do not join them.

step candidate exact JJ action clusters
L3 (A, B), (A, C), (B, C), (D, E) 4 of the 15 pairs
L4 4/6, 4/6, 4/6, 3/5 all at least 0.6, keep all
L7 (A, B) 0.667 union {A, B} {C} {D} {E} {F}
L7 (A, C) 0.667 union {A, B, C} {D} {E} {F}
L7 (B, C) 0.667 same set, no merge {A, B, C} {D} {E} {F}
L7 (D, E) 0.600 union {A, B, C} {D, E} {F}

The result is {A, B, C}, {D, E} and {F}, which is also the exact single linkage at 0.6. The method computed 4 exact similarities instead of 15. With k=2k = 2 and l=4l = 4, a pair at s=0.6s = 0.6 is a candidate with probability 1−(1−0.36)4≈0.8321 - (1 - 0.36)^4 \approx 0.832, so with another seed one of these pairs can be missed.

Correctness

Every merge of line L7 uses a pair that passed the exact check of line L4, so every edge used is an edge of GtG_t. By the invariant of the disjoint-set loop (its trees have the vertex sets of the components of the edges seen so far), the output is the set of components of the graph HH of the candidate edges with J≥tJ \ge t. HH is a subgraph of GtG_t, so each output cluster lies inside one exact cluster: the method can split a family, but never joins samples that exact single linkage keeps apart. This holds for every seed. If the candidates contain a spanning tree of each component of GtG_t, the output is exactly the components of GtG_t. Identical sets are always candidates. In the ideal model of min-wise independent hash functions, the candidate probability is 1−(1−sk)l1 - (1 - s^k)^l. The full proof is in the proofs folder.

Proof: LSH behavior clustering returns a refinement of exact single linkage, and the exact clustering when the candidates connect itfull

Let A1,…,AnA_1, \ldots, A_n be non-empty finite sets, let 0<t≤10 < t \le 1, and write J(A,B)=∣A∩B∣/∣A∪B∣J(A, B) = |A \cap B| / |A \cup B| for the Jaccard index. The threshold graph GtG_t has the vertices 1,…,n1, \ldots, n and an edge {i,j}\{i, j\} for each pair with J(Ai,Aj)≥tJ(A_i, A_j) \ge t. Exact single linkage at level tt is the partition of the vertices into the connected components of GtG_t: two samples are in one cluster exactly when a chain of samples joins them, with similarity at least tt at each step. Let CC be the set of candidate pairs that lines L1 to L3 produce, and let HH be the graph with the edges C∩E(Gt)C \cap E(G_t).

Lemma 1 (the union-find loop). After line L7, find(u)=find(v)\mathrm{find}(u) = \mathrm{find}(v) exactly when uu and vv are in one connected component of HH. Line L8 therefore returns the components of HH.

Proof. Line L4 computes JJ exactly for each pair of CC and keeps the pairs with J≥tJ \ge t, so the list of line L5 is the edge list of HH. The invariant of the loop of line L7 is: the trees of the parent array have the same vertex sets as the components of the graph of the edges processed so far. It holds at the start, when line L6 makes every vertex a tree of its own and no edge is processed. An edge {i,j}\{i, j\} inside one tree changes neither the components nor the trees. An edge between two trees joins two components into one, and the loop makes one root the parent of the other, which joins the two trees. Path compression in find changes only the parent pointers inside one tree, never its vertex set. At the end, all edges of HH are processed. □\square

Theorem 2 (soundness). Every cluster of the output is contained in one cluster of exact single linkage at level tt.

Proof. HH is a subgraph of GtG_t, because each of its edges has J≥tJ \ge t. A path in HH is therefore a path in GtG_t, so each component of HH lies inside one component of GtG_t. By Lemma 1 the output is the set of components of HH. □\square

So the method can split a family, if the candidates miss the pairs that hold it together, but it never joins two samples that exact single linkage keeps apart. This holds for every seed and every choice of kk and ll.

Theorem 3 (exactness). If CC contains the edges of a spanning tree of each component of GtG_t, the output equals exact single linkage at level tt. In particular this holds when CC is the set of all pairs.

Proof. The spanning tree edges have J≥tJ \ge t, so they are edges of HH, and each component of GtG_t is connected in HH. With Theorem 2, the components of HH and of GtG_t are the same. □\square

Lemma 4 (equal sets are always candidates). If Ai=AjA_i = A_j, then (i,j)∈C(i, j) \in C for every seed and every k,l≥1k, l \ge 1.

Proof. Each MinHash value min⁡x∈Ah(x)\min_{x \in A} h(x) depends only on the set AA, so the two signature rows are equal and the two samples fall in the same bucket of every band. □\square

Lemma 5 (the candidate probability in the ideal model). Assume that the klkl hash functions are independent and min-wise independent, that is, for every finite set UU each element of UU has the same probability to be the one with the least hash value, and no two values are equal. Then a pair with J(Ai,Aj)=sJ(A_i, A_j) = s is in CC with probability 1−(1−sk)l1 - (1 - s^k)^l.

Proof. Fix one hash function hh and let U=Ai∪AjU = A_i \cup A_j. The element of UU with the least value of hh is uniform on UU. The two MinHash values agree exactly when this element is in Ai∩AjA_i \cap A_j: if it is in the intersection, it is the minimum of both sets; if it is only in AiA_i, then the minimum of AjA_j is a different element with a larger value. So the two values agree with probability ∣Ai∩Aj∣/∣U∣=s|A_i \cap A_j| / |U| = s. A band agrees on all kk rows with probability sks^k, by independence. The pair is a candidate when at least one of the ll independent bands agrees, which has probability 1−(1−sk)l1 - (1 - s^k)^l. □\square

The functions h(x)=(ax+c) mod Ph(x) = (a x + c) \bmod P of the code are permutations of {0,…,P−1}\{0, \ldots, P-1\} for a≠0a \ne 0, but they are not exactly min-wise independent. Lemma 5 is a statement about the ideal model. Theorems 2 and 3 do not depend on it.

Termination and cost. Line L1 computes klkl minima over each set, O(nkld)O(n k l d) time for sets of at most dd features. Line L2 puts each sample into one bucket per band, O(nkl)O(n k l) time with hashing. Line L3 lists each pair of a bucket once, so its time is O(∑buckets∣b∣2)O(\sum_{\text{buckets}} |b|^2), which is the number of candidate pairs with repeats, at most l(n2)l \binom{n}{2}. Line L4 is O(∣C∣d)O(|C| d), line L5 is O(∣C∣log⁡∣C∣)O(|C| \log |C|), and lines L6 to L8 use O(n+∣C∣)O(n + |C|) find operations. Every loop runs over a finite list, so the method stops. ■\blacksquare

The merges. Line L5 sorts the edges of HH by decreasing similarity, and line L7 records an edge when it joins two trees. This is Kruskal's method for a maximum spanning forest of HH, so the list of merges is the single-linkage dendrogram of HH above the level tt: cutting it at any level t′≥tt' \ge t gives the components of the edges of HH with J≥t′J \ge t'.

Complexity

  • Signatures. Line L1 evaluates klk l hash functions on each feature: O(nkld)O(n k l d) time and O(nkl)O(n k l) space.
  • Buckets. Line L2 puts each sample into ll buckets, O(nkl)O(n k l) time with a hash table.
  • Candidates. If each sample has cc candidates on average, line L3 lists O(nc)O(n c) pairs, and line L4 checks each in O(d)O(d) time with hash sets. The sort of line L5 takes O(nclog⁡(nc))=O(nclog⁡n)O(n c \log(n c)) = O(n c \log n).
  • Union-find. Lines L6 to L8 take O(n+nc α(n))O(n + n c\, \alpha(n)) time with union by rank and path compression.
  • Worst case. If all samples are nearly equal, every pair is a candidate, c=n−1c = n - 1, and the cost is O(nkld+n2(d+log⁡n))O(n k l d + n^2 (d + \log n)), the same order as comparing all pairs. The paper gives the same terms: O(nkld)O(n k l d) for hashing, O(ncd)O(n c d) for the similarities and O(nclog⁡(nc))O(n c \log(n c)) for the sort, with c=O(n)c = O(n) in the worst case.

In the experiment of the paper, 75692 samples gave 66528049 candidate pairs, of which 57024374 were above t=0.7t = 0.7. That is about 14% false candidates, and about 2.3% of the 2864601586 pairs of an all-pairs comparison. These are measurements on one data set, not bounds.

The model is the word RAM: features and hash values are machine words, and the code uses the prime P=261−1P = 2^{61} - 1.

Properties

  • Sound for every seed. The output refines exact single linkage (the theorem above). The randomness can cost recall, never precision with respect to the exact clustering.
  • Randomized recall. A pair of similarity s≥ts \ge t is missed with probability (1−sk)l(1 - s^k)^l in the ideal model. A family is usually still found, because single linkage needs only a spanning tree of its pairs, and a family of mm similar samples has (m2)\binom{m}{2} pairs.
  • Chaining. Single linkage joins two groups through one similar pair. A sample with the behavior of two families, or a long chain of small changes, joins them into one cluster.
  • A threshold, not a number of clusters. The number of clusters comes out of the data. The threshold is a choice; in the paper, values of tt from 0.6 to 0.9 gave good precision and recall on the reference set.
  • Hierarchical. The merges of line L7 give the dendrogram above tt, so a higher threshold needs no new computation.

Variants and improvements

  • Representatives. The paper also gives a way to cluster below the LSH threshold: give each cluster a representative made of the features found in at least half of its members, and cluster the representatives exactly. There are far fewer clusters than samples, so all pairs of representatives can be compared.
  • Other similarity measures. Bailey and coauthors (RAID 2007) clustered with the normalized compression distance, which has no LSH family, so all n2/2n^2/2 distances must be computed. In Table 2 of the Bayer paper, the LSH version on the richer profiles had a quality (precision times recall) of 0.959, against 0.916 for the earlier method with the compression distance.
  • Weighted features. If features have counts or weights, weighted MinHash or cosine similarity with random projections replaces the set model.
  • Other clustering. Density methods such as DBSCAN avoid some of the chaining, and the same LSH step can supply their neighbor queries.
  • Static features. The same pipeline works on sets of byte n-grams, of instruction n-grams, or of pieces from context-triggered piecewise hashing, with a different notion of similarity.

When to use it

Use it to group a large collection of samples or reports into families, when each item is a set of features and the Jaccard index is a good measure of similarity. It scales to tens of thousands of items on one machine, and the cost is close to linear when most pairs are far apart. For a few hundred items, compute all pairs and run exact single linkage, which is simpler and has no randomness. When the families must have a given number of members, or when chains are a problem, use a method with a different linkage. The output is only as good as the features: a sample that does nothing in the sandbox, or does different things on each run, gets a poor profile, and no clustering method repairs that.

Pitfalls

  • Joining candidates without the exact check. Writing E ← C in place of line L4 joins every pair that met in a bucket by chance. One false pair joins two families, and by chaining it can join many. Check each candidate exactly, as line L4 does.
  • Too strict bands. A large kk with few bands ll moves the S-curve to the right, and pairs just above tt are rarely candidates: the families split. Choose kk and ll so that 1−(1−tk)l1 - (1 - t^k)^l is close to 1, as the paper did with k=10k = 10 and l=90l = 90 for t=0.7t = 0.7.
  • Too loose bands. A small kk makes most pairs candidates, and the cost of line L4 goes back to O(n2d)O(n^2 d). The curve must also be low for similarities well below tt.
  • The same hash functions in every band. If line L1 uses the same functions for all bands, the bands are not independent, and the formula for the candidate probability is wrong. Draw klk l different functions.
  • Empty profiles. The MinHash of an empty set is not defined, and the Jaccard index of two empty sets is 0/00/0. Remove the samples with no features before line L1 and report them on their own.
  • A comparison at the boundary. A similarity of exactly tt, such as 3/53/5 with t=0.6t = 0.6, is computed in floating point on one side and given as a decimal on the other. Use the same arithmetic for JJ and tt, or compare ∣A∩B∣|A \cap B| with t ∣A∪B∣t\,|A \cup B| in exact rational numbers.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

malware_behavior_clustering.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/malware-behavior-clustering/. The authors are listed in prov/WPKYEC.jsonl.

"""Behavior clustering with MinHash, locality-sensitive hashing and single linkage.

After Bayer, Milani Comparetti, Hlauschek, Kruegel and Kirda (NDSS 2009). Each
sample is a set of behavior features, given here as integers. Pairs of samples
whose MinHash values agree on a whole band of k hash functions, in at least one
of l bands, are candidates. Candidates with an exact Jaccard similarity of at
least t are joined by single linkage. The code works on synthetic sets that the
caller builds; it reads no trace, no file and no sample.
"""

import random
from collections import defaultdict

P = (1 << 61) - 1  # a Mersenne prime; features are integers in [0, P)

FeatureSet = frozenset[int]


def jaccard(a: FeatureSet, b: FeatureSet) -> float:
    """|a & b| / |a | b| for non-empty sets. Cost: O(|a| + |b|)."""
    return len(a & b) / len(a | b)


def minhash_signatures(sets: list[FeatureSet], m: int, seed: int) -> list[list[int]]:
    """m MinHash values for each set, with h(x) = (a x + c) mod P. Cost: O(m) per feature."""
    rng = random.Random(seed)
    funcs = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(m)]
    return [[min((a * x + c) % P for x in s) for a, c in funcs] for s in sets]


def lsh_candidates(sets: list[FeatureSet], k: int, l: int, seed: int) -> set[tuple[int, int]]:
    """Pairs (i, j), i < j, whose signatures agree on all k rows of some band."""
    sig = minhash_signatures(sets, k * l, seed)  # @line L1
    pairs: set[tuple[int, int]] = set()
    for band in range(l):  # @line L2
        buckets: dict[tuple[int, ...], list[int]] = defaultdict(list)
        for i, row in enumerate(sig):
            buckets[tuple(row[band * k : (band + 1) * k])].append(i)
        for members in buckets.values():  # @line L3
            for x in range(len(members)):
                for y in range(x + 1, len(members)):
                    pairs.add((members[x], members[y]))
    return pairs


def cluster_from_candidates(
    sets: list[FeatureSet], pairs: set[tuple[int, int]], t: float
) -> tuple[list[list[int]], list[tuple[float, int, int]]]:
    """Single linkage at threshold t over the given candidate pairs.

    Returns the clusters (each a sorted list, in the order of their smallest
    member) and the merges as (similarity, i, j) in the order they were made.
    Cost: O(c d + c log c) for c pairs and sets of at most d features, plus
    near-linear union-find work.
    """
    kept = [(jaccard(sets[i], sets[j]), i, j) for i, j in pairs]  # @line L4
    kept = [e for e in kept if e[0] >= t]
    kept.sort(key=lambda e: (-e[0], e[1], e[2]))  # @line L5
    parent = list(range(len(sets)))  # @line L6

    def find(v: int) -> int:
        root = v
        while parent[root] != root:
            root = parent[root]
        while parent[v] != root:
            parent[v], v = root, parent[v]
        return root

    merges: list[tuple[float, int, int]] = []
    for s, i, j in kept:  # @line L7
        ri, rj = find(i), find(j)
        if ri != rj:
            parent[max(ri, rj)] = min(ri, rj)
            merges.append((s, i, j))
    groups: dict[int, list[int]] = defaultdict(list)  # @line L8
    for v in range(len(sets)):
        groups[find(v)].append(v)
    return sorted(groups.values()), merges


def behavior_clustering(
    sets: list[FeatureSet], t: float, k: int, l: int, seed: int
) -> list[list[int]]:
    """Cluster non-empty feature sets at Jaccard threshold t with l bands of k MinHash rows.

    Precondition: every set is non-empty, 0 < t <= 1, k >= 1 and l >= 1.
    Postcondition: two samples in one cluster are joined by a chain of pairs
    with similarity at least t, so the result refines exact single linkage.
    Cost: O(n k l d) for the signatures of n sets of at most d features, then
    O(c d + c log c) for c candidate pairs; c is O(n^2) in the worst case.
    """
    pairs = lsh_candidates(sets, k, l, seed)
    return cluster_from_candidates(sets, pairs, t)[0]


def candidate_probability(s: float, k: int, l: int) -> float:
    """The probability 1 - (1 - s^k)^l that a pair of similarity s is a candidate, for ideal MinHash."""
    return 1.0 - (1.0 - s**k) ** l
test_malware_behavior_clustering.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/malware-behavior-clustering/. The authors are listed in prov/WPKYEC.jsonl.

import random
from fractions import Fraction

from malware_behavior_clustering import (
    behavior_clustering,
    candidate_probability,
    cluster_from_candidates,
    lsh_candidates,
)


def exact_single_linkage(sets: list[frozenset[int]], t: float) -> list[list[int]]:
    """Connected components of the graph with an edge where the Jaccard index is at least t."""
    n = len(sets)
    q = Fraction(t).limit_denominator(1000)  # the rational number that t stands for
    adj = [[j for j in range(n) if j != i and Fraction(len(sets[i] & sets[j]), len(sets[i] | sets[j])) >= q] for i in range(n)]
    seen, out = [False] * n, []
    for s in range(n):
        if seen[s]:
            continue
        comp, stack = [], [s]
        seen[s] = True
        while stack:
            v = stack.pop()
            comp.append(v)
            for w in adj[v]:
                if not seen[w]:
                    seen[w] = True
                    stack.append(w)
        out.append(sorted(comp))
    return sorted(out)


def random_sets(rng: random.Random, n: int, universe: int) -> list[frozenset[int]]:
    return [frozenset(rng.sample(range(universe), rng.randrange(1, 6))) for _ in range(n)]


def planted_families(rng: random.Random, families: int, members: int, size: int, changed: int) -> tuple[list[frozenset[int]], list[int]]:
    sets, label = [], []
    for f in range(families):
        proto = rng.sample(range(10**9), size)
        for _ in range(members):
            s = set(proto)
            for x in rng.sample(proto, changed):
                s.discard(x)
            s.update(rng.randrange(10**9) for _ in range(changed))
            sets.append(frozenset(s))
            label.append(f)
    return sets, label


def test_example_of_the_page() -> None:
    sets = [frozenset(s) for s in ({1, 2, 3, 4, 5}, {1, 2, 3, 4, 6}, {1, 2, 3, 5, 6}, {10, 11, 12, 13}, {10, 11, 12, 14}, {20, 21})]
    assert behavior_clustering(sets, 0.6, 2, 4, seed=1) == [[0, 1, 2], [3, 4], [5]]
    clusters, merges = cluster_from_candidates(sets, {(i, j) for i in range(6) for j in range(i + 1, 6)}, 0.6)
    assert clusters == [[0, 1, 2], [3, 4], [5]]
    assert [(round(s, 3), i, j) for s, i, j in merges] == [(0.667, 0, 1), (0.667, 0, 2), (0.6, 3, 4)]


def test_all_pairs_gives_exact_single_linkage() -> None:
    rng = random.Random(10)
    for _ in range(500):
        n = rng.randrange(1, 9)
        sets = random_sets(rng, n, 8)
        t = rng.choice([0.2, 0.25, 1 / 3, 0.5, 0.6, 1.0])
        pairs = {(i, j) for i in range(n) for j in range(i + 1, n)}
        assert cluster_from_candidates(sets, pairs, t)[0] == exact_single_linkage(sets, t)


def test_lsh_clustering_refines_exact_clustering() -> None:
    rng = random.Random(11)
    for trial in range(500):
        n = rng.randrange(1, 9)
        sets = random_sets(rng, n, 8)
        t = rng.choice([0.25, 0.5, 0.6])
        got = behavior_clustering(sets, t, rng.randrange(1, 4), rng.randrange(1, 4), seed=trial)
        exact = exact_single_linkage(sets, t)
        where = {v: idx for idx, c in enumerate(exact) for v in c}
        for c in got:
            assert len({where[v] for v in c}) == 1
        assert sorted(v for c in got for v in c) == list(range(n))


def test_candidates_contain_identical_sets() -> None:
    rng = random.Random(12)
    for trial in range(100):
        base = frozenset(rng.sample(range(100), 5))
        sets = [base, frozenset(rng.sample(range(100), 5)), base]
        assert (0, 2) in lsh_candidates(sets, 3, 2, seed=trial)


def test_planted_families_are_found() -> None:
    rng = random.Random(13)
    sets, label = planted_families(rng, families=6, members=8, size=40, changed=4)
    got = behavior_clustering(sets, 0.5, 5, 20, seed=14)
    want = sorted(sorted(i for i in range(len(sets)) if label[i] == f) for f in range(6))
    assert got == want


def test_banding_reduces_the_number_of_pairs() -> None:
    rng = random.Random(15)
    sets, _ = planted_families(rng, families=10, members=6, size=30, changed=3)
    pairs = lsh_candidates(sets, 5, 20, seed=16)
    n = len(sets)
    assert len(pairs) < n * (n - 1) // 2 // 4


def test_candidate_probability_formula() -> None:
    assert candidate_probability(1.0, 10, 90) == 1.0
    assert candidate_probability(0.0, 10, 90) == 0.0
    assert abs(candidate_probability(0.7, 10, 90) - 0.9241) < 1e-3
    assert candidate_probability(0.5, 10, 90) < 0.1

History

Early automatic malware clustering compared all pairs. Bailey, Oberheide, Andersen, Mao, Jahanian and Nazario (RAID 2007) described each sample by its lasting changes to the system and clustered with the normalized compression distance. Bayer, Milani Comparetti, Hlauschek, Kruegel and Kirda (NDSS 2009) built richer profiles in their ANUBIS sandbox, with taint tracking to find dependences between operations, and turned them into feature sets. They used the locality-sensitive hashing of Indyk and Motwani (1998) with MinHash to avoid most of the pair comparisons. On a reference set of 2658 samples they found 87 clusters against 84 in the reference, with a precision of 0.984 and a recall of 0.930, and they clustered 75692 samples in 2 hours and 18 minutes. Later systems used the same pattern of features, an approximate neighbor step and a cheap clustering, for both behavior and static features.

References

  1. Ulrich Bayer, Paolo Milani Comparetti, Clemens Hlauschek, Christopher Kruegel and Engin Kirda, Scalable, behavior-based malware clustering, Network and Distributed System Security Symposium (NDSS) 2009, Section 5.1 (behavior profiles as feature sets), Section 5.2 (MinHash with random linear functions and the LSH bands), Section 5.3 (the exact check and single-linkage hierarchical clustering), Section 5.4 (the cost), Sections 6.1 to 6.3 (precision and recall on the reference set, the comparison in Table 2, and the run time in Table 3)
  2. Piotr Indyk and Rajeev Motwani, Approximate nearest neighbors, towards removing the curse of dimensionality, ACM Symposium on Theory of Computing (STOC) 1998, pages 604 to 613, the definition of locality-sensitive hash families and their use for approximate near neighbor search
  3. Michael Bailey, Jon Oberheide, Jon Andersen, Z. Morley Mao, Farnam Jahanian and Jose Nazario, Automated classification and analysis of internet malware, RAID 2007, the earlier behavior clustering with the normalized compression distance over all pairs

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example