Hamm-Grams: An Algorithm for Mining Regular Expressions of Bytes


Abstract

Malware poses a critical and ever-evolving threat, and robust and effective systems for detecting and classifying malware are of essential importance. \(n\)-grams features are among the common static features used in effective machine learning systems for malware, but these features are inherently brittle. We propose an algorithm for constructing more robust features, hamm-grams, which are a special class of regular expressions having a fixed length and single-character wildcards. We devise an efficient algorithm for finding common hamm-grams using a new locality-sensitive hash designed to produce collisions among pairs of small Hamming distance and a clustering within hash buckets to place wildcards. We then demonstrate the advantages of these features in malware classification and detection tasks.

1 Introduction↩︎

The detection of malware is a problem of utmost importance. Therefore, designing reliable and robust machine-learning features for malware detection is an ongoing field of research and activity. The need for cheap deployment and training costs is of particular relevance, as malware is increasingly observed in extremely limited compute environments with resources too limited to run parsing. Notable incidents have included industrial control systems [1] and satellites [2] as targets of malware. Such systems may have as little as 256 KB of system RAM [3], requiring especially small models.

\(n\)-gram features, sequences of \(n\) consecutive characters, form a powerful tool in the machine learning toolbox. Combined with linear classifiers such as \(L_1\)-penalized logistic regression, \(n\)-grams create a formidable and effective baseline and are commonly used in practice. Such models are cheap to train, do not require GPU co-processors, and are small and fast enough to deploy in almost all situations. For static malware detection, \(n\)-grams of bytes are commonly used features; however, as \(n\) increases, the likelihood of an \(n\)-gram re-occurring decreases, as all \(n\) tokens from the alphabet \(\Sigma\) must match. If any single entry changes, the feature effectively “disappears”, making \(n\)-grams brittle when larger values of \(n\) are desired.

An example that illustrates one failure case of \(n\)-grams for malware detection is the following x86 assembly sequence:

push ebp
sub edx, edx
mov ebp, esp

which corresponds to the byte 5-gram (in hex) 55 29 D2 89 E5. The second assembly instruction sets the value to zero and could be equivalently replaced with the instruction xor edx,edx, which would change the 5-gram to 55 31 D2 89 E5. A Hamming distance of one separates these two \(5\)-grams, and many other assembly instructions also have fixed-length equivalent counterparts. Situations like this one are especially likely to occur in register renaming and changes of the function or data addresses that are prevalent even in non-adversarial recompilation. If we could learn to detect the regular expression 55 ? D2 89 E5, we would have a feature that is robust to these changes.

Thus far, automated methods for constructing regular expressions for use in detecting malware have been hampered by the technical limitations of existing algorithms. For example, regular language induction methods, having been designed for problems in natural language rather than assembly, can not be applied directly due to the much larger sequence lengths and sample sizes. Prior approaches have also relied on genetic algorithms and similar search strategies that are not scalable  [4], [5]. The open challenge is in finding regular expressions in a computationally efficient manner that can readily scale to the data necessary to train modern-day malware systems.

In this work, we propose a new method of mining frequently occurring patterns based on the Hamming similarity between fixed-length token sequences. We allow wildcard tokens; a sequence with \(\mathcal{K}\) wildcard tokens can match a set of \(n\)-grams within a Hamming distance of \(\mathcal{K}\). Thus, we term these features hamm-grams. As a simple example, the hamm-gram AB?D matches both ABCD and ABFD, but does not match ABDC. By restraining ourselves to the space of hamming similarity, a set of hamm-grams forms a regular language. This guarantees that a search for matches can be done efficiently in linear time with respect to the input sequence length.

The rest of this article is organized as follows. First, we briefly discuss the related work in regular language induction, regular expressions, and \(n\)-grams in 2. Next, we design an efficient algorithm for hamm-gram extraction in 3. Finally, to demonstrate how our approach provides benefits for both malware family classification and malicious vs benign classification, we perform studies on the publicly available Drebin android malware family dataset and Ember 2018 Windows malware dataset in 4.

2 Related Work↩︎

Regular expressions have been important building blocks of malware signature detection for decades, across file types and platforms [6][9], and are still used by most modern anti-virus products[10]. However, these regular expressions have thus far been constructed by human effort. Reverse-engineering a binary file to identify signatures can take days or weeks for an expert analyst [11], [12], and so the acceleration and automation of this process is highly valuable.

The field of regular language induction has benefited from significant study [4], [5], [13][15], but the methods that have been developed are not applicable malware detection. Those methods often require a fixed subset of languages and a corpus of known positive and negative samples, and incur hard-to-quantify computational complexity and slow inference. In our case, the set of possible exemplars is all observed \(n\)-grams, on the order of \(10^{12}\) unique substrings in large corpora, which is orders-of-magnitude beyond the scales (\(10^{3}\) or less) for which regular language induction methods are feasible.

The method we propose uses algorithmic tools from regular languages to build deterministic finite automata (DFA) to efficiently search for matches to all stored hamm-grams. Moreover, we restrict our regular expressions to the space of hamm-grams to create a computationally feasible approach. This extends the literal characters by a symbol that can match any single literal character (which we denote throughout by ‘?’) and requires each expression to have a predetermined fixed length. Consequently, this subset of DFA can be implemented by a prefix tree (Trie) extended to allow child nodes to be wildcards.

\(n\)-grams have been popular features since the first works applying machine learning to the malware problem [16], and have remained popular in both machine learning and security venues [17][20] with significant effort to reduce the cost of \(n\)-gram extraction [21][26]. Prior attempts to build static features with more flexibility than \(n\)-grams have not become popular due to reduced accuracy. The study [27] proposed “\(n\)-perms”, where a byte-sequence was sorted to a canonical order to reduce specificity. As an example, CBA, BCA, and ABC would all be considered equivalent \(n\)-perms because they are all identical to ABC after being sorted. Others have attempted to reduce \(n\)-gram specificity by first disassembling an executable to apply domain knowledge: e.g., [28] proposed reducing instructions like mov eax,42 to just the instruction mnemonic mov; [29] proposed reducing the operands to a reduced set of tokens denoting the type, for example, mov eax,42 would become mov.register.constant to denote that the first and second arguments were a register type and a constant type. However, subsequent works applying these techniques to larger industry-sized corpora have found that simple byte \(n\)-grams were more accurate [30]. In contrast, our work develops a method that finds hamm-grams without any extra domain knowledge. Other challenges in malware detection, like measuring effect size and label confidence, are beyond the scope of this chapter [31][34].

3 Complex LSH Method and properties↩︎

Creating hamm-grams from a candidate collection of \(n\)-grams first requires a way to bin \(n\)-grams of small mutual Hamming distance together. Otherwise, an algorithm would require a number of comparisons that scales at least quadratically in the total collection size. This binning will be achieved by developing a rolling hash function that is locality-sensitive by Hamming distance. The approach will be given in 3.1, and we show analytically that it corresponds to the Hamming distance in 3.2. In 3.3 we confirm experimentally that this rolling LSH accomplishes our goals. Once \(n\)-grams have been hashed such that similar \(n\)-grams collide, we employ an agglomerative clustering method for mining hamm-grams from the buckets, and this is described in 3.4.

3.1 Description of Complex LSH↩︎

Consider sequences of length \(m\), \[[s_0, s_1, ..., s_{m-1}],\] where \(s_i\) are drawn from a finite alphabet \(\mathcal{A}\) of \(T\) characters. Let our tokenizer \(\mathcal{T}\), defined such that \[\mathcal{T}: \mathcal{A} \rightarrow \{ e^{i\psi_0}, e^{i\psi_1}, ..., e^{i\psi_T}\},\] be a bijective function that maps every element of the alphabet to a unique complex number with unit modulus. It follows that each sequence can be uniquely represented by a sequence of tokens: \[[\mathcal{T}(s_0), \mathcal{T}(s_1), ..., \mathcal{T}(s_{m-1})] \equiv [t_0, t_1, ..., t_{m-1}].\]

Consider breaking each sequence into \(n\)-grams:\[[t_0, t_1, ..., t_{n-1}], ..., [t_{m-n-1}, t_{m-n}, ..., t_{m-1}].\] We require a locality-sensitive hashing algorithm that is sensitive to the Hamming distance [35] between \(n\)-grams and can be computed in sub-linear time in \(n\). The algorithm we developed that fulfills these needs is described below.

First we fill a vector \(\boldsymbol{w}\) of size \(n\) with powers of unit-modulus complex number \(a\), \[\boldsymbol{w} \equiv [a^1, a^2, ..., a^n]\] where \[a \equiv e^{i \phi},\] and \(\phi\) is sampled from \(\rm{Uniform}[0, 2\pi]\). This is convenient for taking powers: \[a^r = e^{i r \phi},\] from which it follows that \[a^{-1} = e^{-i\phi}.\] In the following, we use the notation \(\boldsymbol{v}_{[i:j]}\) to denote the slice of a vector \(\boldsymbol{v}\) beginning at \(v_i\) and ending at \(v_{j-1}\). Consider the dot product between our weight vector \(\boldsymbol{w}\) and our tokens, \[\label{eqn:curr95hash} h_p \equiv \boldsymbol{w} \cdot \boldsymbol{t}_{[j:j+n]} = a^1 t_j + a^2 t_{j+1} + \cdots + a^n t_{j+n-1}.\tag{1}\] Further, note that the dot product between the weight vector and the adjacent window is given by \[\boldsymbol{w} \cdot \boldsymbol{t}_{[j+1:j+n+1]} = a^1 t_{j+1} + a^2 t_{j+2} + \cdots + a^n t_{j+n}.\] Using that \[a^{-1}h_p - t_j = a^1 t_{j+1} + a^2 t_{j+2} + \cdots + a^{n-1}t_{j+n-1},\] it follows that \[h_u \equiv \boldsymbol{w} \cdot \boldsymbol{t}_{[j+1:j+n+1]} = a^{-1}h_p - t_j + a^{n}t_{j+n}.\] Thus, we’ve shown that the updated complex hash \(h_u\) (the dot-product between the adjacent window and the weights) can be computed with complex multiplication and addition involving only the previous complex hash \(h_p\), the excluded token \(t_j\), and the new token \(t_{j+n}\). This computation scales as \(\mathcal{O}(1)\) with respect to the vector length \(n\), and therefore will be efficient enough to be applied to every \(n\)-gram in each file.

Figure 1: An illustration of how the complex hashing function tends to put similar sequences into the same hash bucket, illustrated on 3-grams of English letters: fax and fox which get a “1”-bit for their hash, and ace which receives a “0” bit for it’s hash. Each a^i \mathcal{T}(\cdot) applies a new rotation and fixed step size. The accumulation of such operations results in similarly shaped trajectories that differ in expectation as a function of how many steps in the sequence differ, i.e., the hamming distance. It is thus more likely for two sequences with low hamming distance to end up in the same half of the plane. E.g., fax and fox are both on the right hand size and receive a “0” bit in this example.

In Fig. 1 we’ve provided an illustration that explains intuitively how the hash we have devised is locality-sensitive under the Hamming distance. As an example, we consider computing the hash on the \(3\)-grams of English letters, fax, fox, and ace. Each of the three letters is assigned (randomly) a unit vector in the complex plane, which are denoted \(\mathcal{T}(\text{f})\), \(\mathcal{T}(\text{o})\), and so on for all letters considered. Now, according to equation  1 , the complex value assigned to the \(3\)-gram fox is \(a^1 \mathcal{T}(\text{f}) + a^2 \mathcal{T}(\text{o}) + a^3 \mathcal{T}(\text{x})\), and similarly for the others. Because \(a\) and all of the complex values assigned to the letters are unit-length vectors, their products are also unit-length vectors. Therefore, in each sum we have unit-length vectors added tip-to-tail. Now, it should be clear why fox and fax are more likely to be mapped to complex values that lie closer together, and therefore more likely to fall within the same half-plane. This example also illustrates that although fax and ace both have the character a, because they occur at different positions in the sequence, they get multiplied by differing powers of \(a\) and are mapped to different vectors in each sum.

Finally, once the complex hashes \(h_i\) have been computed for all possible windows, a bit hash-code \(b_i\) can be assigned to each according to the truth value of the following statement: \[b_i \equiv (\mathcal{R}\{h_i\} > 0).\] This entire process can be repeated \(M\) times with independently and randomly sampled angles \(\phi\) to define an \(M\)-bit hash code. In the following sections, we demonstrate both by analytic considerations and experiments that the hash code we have developed is locality-sensitive under the Hamming distance.

3.2 Semi-analytic approximation↩︎

In this section, we demonstrate that the hashing algorithm described above is locality-sensitive with respect to the Hamming distance (rather than the Jaccard distance [36], for example). To do so, we derive certain approximate analytic results under the assumption of uniformly random sequences. To that end, we consider again the expression for the dot product between a random weight vector \(\boldsymbol{w}\) and a particular tokenized n-gram, \[\label{eqn:dot95prod} \boldsymbol{w} \cdot \boldsymbol{t} = e^{i[\phi + \psi_0]} + e^{i[2\phi + \psi_1]} + \cdots + e^{i[n\phi + \psi_{n-1}]}.\tag{2}\] Since both the weight-vector phasors \(e^{i j \phi}\) and the token phasors \(e^{i \psi_{j}}\) are drawn from circularly symmetric distributions, it follows that their product \(e^{i(j\phi)} e^{i\psi_{j-1}} = e^{i[(j\phi)+\psi_{j-1}]}\) is also a uniform distribution over the ring of unit modulus [37]. Therefore Eqn. 2 is equivalent to a sum of the form \[Z_n \equiv \sum_{j=1}^{n} e^{i\theta_j},\] where \(\theta_j \sim \rm{Uniform}[0, 2\pi]\). This sum has familiar and useful properties [38], which we briefly review. We note that the following results are derived in the approximation \(n, k \gg 1\), and we use the notation \(\langle \cdots \rangle\) for expectation values.

Lemma 1 (Properties of \(Z_n\)). The random walk \(Z_n = \sum_{j=1}^n e^{i\theta_j}\), where \(\theta_j \sim \mathrm{Uniform}[0, 2\pi]\), satisfies the following properties: \[\langle Z_n \rangle = 0, \quad \langle |Z_n|^2 \rangle = n, \quad \langle \mathcal{R}\{Z_n\}^2 \rangle = \langle \mathcal{I}\{Z_n\}^2 \rangle = n/2.\] Furthermore, for large \(n\), the distribution of \(x_n = \mathcal{R}\{Z_n\}\) is approximately \[x_n \sim \mathcal{N}(0, n/2).\]

Proof. The distribution is circularly symmetric, and therefore \[\langle Z_n \rangle = \langle \mathcal{R}\{Z_n\} \rangle = \langle \mathcal{I}\{Z_n\} \rangle = 0.\] Moreover, \[\begin{align} \langle |Z_n|^2 \rangle = \left\langle \sum^{n}_{i=1} \sum^{n}_{k=1} e^{i(\theta_j - \theta_k)} \right\rangle \\ = n + \left\langle \sum^{n}_{j \neq k} e^{i(\theta_j-\theta_k)} \right\rangle = n \end{align}\] Since by definition, \[|Z_n|^2 = \mathcal{R}\{Z_n\}^2 + \mathcal{I}\{Z_n\}^2,\] it follows by symmetry that \[\langle \mathcal{R}\{Z_n\}^2 \rangle = \langle \mathcal{I}\{Z_n\}^2 \rangle = n/2.\]

The sum \(Z_n\) is equivalent to a random walk in the complex plane with unit-length steps. The resulting approximate probability distribution in the limit of large-n is usually attributed to Lord Rayleigh [39]. In the continuous limit, the problem is equivalent to a diffusion equation, which yields a probability density given by the multivariate Gaussian. Therefore, denoting \(x_n \equiv \mathcal{R}\{Z_n\}\), we can approximate the probability density for \(x_n\) by \[x_n \sim \mathcal{N}(0, n/2).\] ◻

Lemma 2 (Probabilistic Relation for Hamming Distance). Let \(x_c\) and \(\Delta x\) be the real parts of the sums of random walks for vectors differing by Hamming distance \(k\). The probability that \(|\Delta x| > |x_c|\) is given by \[p = \frac{1}{\pi} \tan^{-1}\left(\sqrt{\frac{\bar{k}}{1-\bar{k}}}\right), \quad \text{where } \bar{k} = k/n.\]

Proof. Now consider the complex hashes (before we take the sign of the real part) of two vectors \(\boldsymbol{t}\) and \(\boldsymbol{t}'\) which differ by exactly \(k\) tokens; that is, the two vectors are separated by Hamming distance equal to \(k\). Let \(t_c\) be the subvector of length \(n-k\) which is common to both \(\boldsymbol{t}\) and \(\boldsymbol{t}'\), and \(\boldsymbol{w}_c\) the corresponding subvector (according to index) of \(\boldsymbol{w}\). Similarly, let \(\boldsymbol{t}_d\) and \(\boldsymbol{t}_d'\) be the subvectors of \(k\) elements which are unique to \(\boldsymbol{t}\) and \(\boldsymbol{t}'\) respectively, and \(\boldsymbol{w}_d\) the corresponding subvector (according to index) of \(\boldsymbol{w}\).

To more easily estimate the probability that their bit hash codes differ, we note that it is equivalent to the following probability: Sample three random walks starting from the origin, one of length \((n-k)\), and two of length \(k\). Suppose, without loss of generality, that the walk of length \((n-k)\) yields a positive real value \(x_c\). What is the probability that exactly one of the two walks of length \(k\) yields a negative real value \(\Delta x\) with a magnitude larger than \(x_c\)? If \(p\) denotes the probability that the first walk yields a negative real value with a magnitude larger than \(x_c\), from the independence of the two random walks, it follows that \(1-p\) gives the probability that the second walk does not. Therefore, altogether the probability we seek is given by \(2p(1-p)\), with a factor of two counting the two possible situations (either the first or second walk may be the one that yields the negative real value).

To solve for \(p\), we note that \[p = \frac{1}{2}\mathcal{P}(|\Delta x| > |x_c|),\] where \(x_c \sim \mathcal{N}(0, (n-k)/2)\) and \(\Delta x \sim \mathcal{N}(0, k/2)\). The factor of \(1/2\) accounts for the fact that a larger magnitude alone is not sufficient, but it must also have opposite sign (two possibilities which are equal by symmetry). The probability distribution of the absolute value of a zero-mean normal random variable is given by the half-normal distribution with zero location parameter, therefore \(|x_c| \sim {\rm HN}(0, (n-k)/2)\) and \(|\Delta x| \sim {\rm HN}(0, k/2)\). The cumulative distribution function for the half-normal distribution with zero location parameter and scale parameter \(\sigma\) is given by \[\mathcal{P}(|\Delta x| < a) = \rm{erf}\left(\frac{a}{\sqrt{2}\sigma}\right).\] Let \[I \equiv \mathcal{P}(|\Delta x| < |x_c|) = \int_0^{\infty} da \mathcal{P}(|\Delta x| < a)\rho(|x_c|).\] We have the result that \[I = 1 - \frac{2}{\pi} \rm{tan}^{-1} \left( \frac{\sqrt{k}}{\sqrt{n-k}} \right).\] It follows that \[\mathcal{P}(|\Delta x| > |x_c|) = \frac{2}{\pi} \rm{tan}^{-1} \left( \frac{\sqrt{k}}{\sqrt{n-k}} \right),\] and therefore that \[p = \frac{1}{\pi} \rm{tan}^{-1} \left( \frac{\sqrt{k}}{\sqrt{n-k}} \right) = \frac{1}{\pi} \rm{tan}^{-1} \left( \sqrt{\frac{\bar{k}}{1-\bar{k}}} \right),\] where we have defined \(\bar{k} \equiv k/n\). ◻

Theorem 1 (Collision Probability). The probability of a hash-code collision given Hamming distance \(k\) is \[\mathcal{P}(\mathrm{coll.} \mid H_d = k) = 1 - 2p(1-p),\] where \(p\) is as given in Lemma 2. For \(\bar{k} \to 1\), the asymptotic behavior is \[\mathcal{P}(\mathrm{coll.} \mid H_d = k) \approx \frac{1}{2} + \frac{2}{\pi^2} \frac{1-\bar{k}}{\bar{k}}.\]

Proof. The probability decays with a long tail as the scaled Hamming distance increases. Specifically, consider the Taylor expansion of \(\rm{tan}^{-1}(z)\) as \(z \rightarrow \infty\): \[\rm{tan}^{-1}(z) = \frac{\pi}{2} - \frac{1}{z} + \text{(Higher Order Terms) }.\]

Therefore, denoting \[z \equiv \sqrt{\frac{\bar{k}}{1-\bar{k}}},\] we have that \[p \approx \frac{1}{2} - \frac{1}{\pi}\sqrt{ \frac{1-\bar{k}}{\bar{k}} }.\]

Therefore, for values of \(\bar{k}\) close to one, and keeping only leading order terms, \[\mathcal{P}({\rm coll.} | H_d = k) \approx \frac{1}{2} + \frac{2}{\pi^2}\frac{1-\bar{k}}{\bar{k}}.\] ◻

a

b

Figure 2: (left) Approximate probability of two \(n\)-grams having a single-bit hash code collision given that they differ by Hamming distance \(k\). (right) 95% credible interval for collision probability between pairs of \((n=100)\)-grams as a function of normalized Hamming distance \(H_d / n\)..

We see that the derived approximations obey the expected asymptotic limits, with identical sequences being assigned the same bit code with probability one, while maximally different sequences have a purely random 50% chance of being assigned the same bit (there are two possible bits). In practice, we use \(M\)-bit hash codes, and the probability of an \(M\)-bit collision will decay much more rapidly. This is observed in the experiment in the following section.

3.3 Experiments on random \(n\)-grams↩︎

As an experimental test of our complex LSH scheme, we generate 100 independent random experiments. In each experiment, we first create 10 random weight vectors (giving our final bit hash-code space dimensionality \(2^{10}\)), create 1000 random \((n=100)\)-grams by sampling an alphabet of 256 unique tokens, as well as creating Hamming neighbors by swapping exactly \(H_d\) tokens with random alternates. The collision probabilities are shown in Fig.  2 as a function of Hamming distance. The 95% credible interval over random experiments is shown assuming a Gaussian distribution. We see that the probability of collision of all ten-bit hash codes decays rapidly as a function of (normalized) Hamming distance.

3.4 Extracting Hamm-Grams↩︎

We have now established the algorithm by which we can run a rolling hash function over a sequence of bytes such that byte sequences with small Hamming distance are more likely to collide into the same hash bucket. Using this new hash, we extend the KiloGrams approach to extract commonly occurring hamm-grams.

Figure 3: Hamm-Gram Extraction

The KiloGrams algorithm [40] used a rolling hash function to find the top-\(k\) hashes by frequency of n-grams, ignoring that collisions would occur. A second pass over the data would then use the Space Savings data structure to find the true top-\(k\) \(n\)-grams by ignoring any \(n\)-gram that did not have a top-\(k\) hash. Because the vast majority of \(n\)-grams are singletons, and the true top-\(k\) are selected with high probability, it allowed them to find the true top-\(k\) \(n\)-grams with high probability for almost arbitrary values of \(n\).

Selecting the top-\(k\) hamm-grams is non-trivial, as finding a minimum set of hamm-grams (\(n\)-grams with wildcard tokens) is computationally intractable. We instead devise a procedure to build possible hamm-grams after the second pass, followed by a third pass which performs matching against the training corpus, sorts regular expressions by number of matches, and keeps only the top-\(k\).

Our algorithm is detailed in Algorithm 3, where the first two loops over all documents in a corpus \(\mathcal{C}\) run a modified KiloGram algorithm, collecting the most frequent hashes, and then saving all \(n\)-grams that reside in the top-\(k\) buckets. Agglomerative clustering with a fixed stopping condition is used to create hamm-grams from the n-grams within each bucket. This can be implemented in sub-cubic time (in the number of n-grams within the bucket) by an implementation using priority queues [41]. Two hamm-grams are candidates for ‘merging’ if wildcards can be placed in a new expression until it matches both expressions without exceeding the predetermined budget of wildcards. Among all candidates, the two hamm-grams of the smallest Hamming distance are merged. This process is iterated until there are no mergeable hamm-grams left. Additionally, because the Hamming distance is defined as an integer, any pair found to have a Hamming distance of zero can be immediately merged without calculating the remaining distances. This results in runtime in practice significantly better than worst-case scaling.

4 Hamm-Gram Results on Malware↩︎

4.1 Results on Drebin Android Malware Family Task↩︎

We demonstrate and compare the performance of the top-\(k\) hamm-grams and top-\(k\) n-grams on the Drebin [42] android malware family classification dataset. We have first taken a subset of the twenty malware classes in the dataset which have at least forty samples, leaving a dataset of twenty classes totaling 4661 samples. In each experiment performed, we kept either the top-(\(k \mathord{=} 5e2\)) or top-(\(k \mathord{=} 5e3\)) grams. We begin by examining the learned \(n\)- and hamm-gram features, measures of information they carry regarding the malware family, and how well these features cluster into groups. Then we compare the performance of Logistic Regression models trained and these features.

a

b

Figure 4: Balanced accuracy scores of Logistic Regression classifiers trained on the top-\((k \mathord{=} 5e3)\) (left) or top-\((k \mathord{=} 5e2)\) (right) features, as a function of gram size. The standard deviation over ten random experiments is shown as vertical bars..

Finally, we trained and tested Logistic Regression classifiers on random training/testing splits of the \(n\)-gram and hamm-gram features for various gram sizes \(n\), for ten random experiments each. These are shown in Fig. 4. In the first case, we keep the top-\((k \mathord{=} 5e3)\) features. In this case, we see both \(n\)-gram and hamm-gram features achieving balanced accuracies of greater than 95%. These accuracies are considerable given the challenge of a few examples per malware family. In the second case, we keep only the top-\((k \mathord{=} 5e2)\) features. In this case, we see that for all gram sizes (\(n\)), hamm-grams significantly outperform ordinary \(n\)-grams. For \((n \mathord{=} 8)\)-grams, the balanced accuracy is barely better than random guessing, while for size 8 hamm-grams the balanced accuracy is already better than 80 %, significantly better, and large considering the difficulty of learning to classify twenty families of malware with as low as 40 examples of each. Thus we see that hamm-gram features can provide significant advantages in cases where model computations are considerably memory- and/or latency-constrained.

Figure 5: Comparison between hamm-gram features and three additional hash baselines, ssdeep, sdhash, and LZJD.

Additionally, in Fig. 5 we compare against three similarity hashing methods: ssdeep [43], sdhash [44], and LZJD [45]. ssdeep is a fuzzy hash that runs hash functions on fixed-size segments of the data. sdhash is a fuzzy hash that uses bloom filters and can generate similarity scores. LZJD creates Lempel-Ziv dictionaries and measures file similarity via Jaccard distance between their vocabularies. Each of these methods is intended to work when some small number of bytes have been altered and for malware data. However, they are harder to deploy in many situations because the k-NN strategy requires storing all data and several orders of magnitude more compute than logistic regression. We also used the hamm-gram and \(n\)-gram feature vectors and k-NN classification under cosine distance. As can be seen, our hamm-gram features are significantly better than ssdeep and sdhash, two industry-standard tools, for similarity search. Hamm-grams perform similarly to PyLZJD and \(n\)-grams for nearest-neighbor search on this dataset, but a hamm-gram LR classifier outperforms LZJD. This further shows the value of our approach in building malware family detectors that have more robustness to natural changes that occur as malware spreads and modifies, while being faster and lighter weight to deploy on endpoints in a network.

4.2 Examples of Learned Hamm-Gram Features for Drebin↩︎

As empirically demonstrated, the hamm-gram approach significantly improves the accuracy when only a smaller number of features can be considered due to computational constraints. This was further expanded by exploring the top-\(k\) features produced by each algorithm. Most notably, the normal \(n\)-gram approach suffers from extreme feature redundancy that reduces the effective information available to the underlying algorithm. In this section, we specifically examine certain explicit features learned on the Drebin corpus.

A prominent failure case of the standard \(n\)-gram features on the Drebin dataset are various alterations of the pattern SHA1-Digest: ???, each occupying capacity in the top-k features. On the other hand, the hamm-gram model with size 16 found this RegEx itself as a feature, freeing up space for other semantically different features. By coalescing these highly redundant \(n\)-grams, our hamm-gram approach enables more capacity in the final top-\(k\) list for informative features that are both wild-card free (i.e., a normal \(n\)-gram that would not have been kept otherwise, because common and semantically redundant \(n\)-grams would have kept it out of the feature selection stage) or that actively use the wild-card capability.

Another example containing wild cards is variants of the byte sequence of <FONT C????>.html where the “?” indicates a wild card. In this case, it found a RegEx feature identifying a malicious family that uses fonts as a vector for malware. In each sample in the corpus, the font has a different name that always begins with a “C”, and is four or five characters long. This pattern was identified by our hamm-gram approach. Normal \(n\)-grams do not find this feature, since the created font names are each unique.

4.3 Results on Ember 2018 Malware Classification Task↩︎

Table 1: Standardized Partial AUCs for different features sets and sizes, on EMBER 2018 dataset, for liblinear model with \(k\)=1e4.
feature \(n\) AUC(FPR \(< 0.001\)) AUC(FPR \(< 0.01\))
\(n\)-gram 8 0.580 0.737
\(n\)-gram 16 0.557 0.703
\(h\)-gram 8 0.605 0.770
\(h\)-gram 16 0.585 0.736
Table 2: Standardized Partial AUCs for different features sets and sizes, on EMBER 2018 dataset, for liblinear model with k=1e5.
feature \(n\) AUC(FPR \(< 0.001\)) AUC(FPR \(< 0.01\))
\(n\)-gram 8 0.684 0.857
\(n\)-gram 16 0.600 0.785
\(h\)-gram 8 0.746 0.893
\(h\)-gram 16 0.694 0.852

In this section, we report a comparison between Logistic Regression models trained and tested on the EMBER 2018 dataset [46] using either the top-\(k\) \(n\)-gram features or top-\(k\) hamm-gram features. The EMBER 2018 dataset consists of Windows Portable Executable (PE) files, \(600, 000\) training samples, and \(200, 000\) testing samples, split evenly between malicious and benign samples.

In Table 1 are shown the standardized partial AUC scores for logistic regression models using either the top-\(k\) \(n\)-gram features or top-\(k\) hamm-gram features, for \(k=10^4\). We show the standardized partial AUC because high false positive rates are unacceptable in deployed malware detection scenarios. These models were trained using LIBLINEAR with a Lasso penalty hyperparameter which was optimized on validation data by Optuna. We see that the model with hamm-gram features of length \(8\) (and with a wildcard budget of \(2\)), is the best-performing model. Additionally, the model with hamm-gram features of length \(16\) (and with a wildcard budget of \(4\)) performs similarly to the best-performing \(n\)-gram model.

Similarly, in Table 2 are shown the standardized partial AUC scores for logistic regression models using either the top-\(k\) \(n\)-gram features or top-\(k\) hamm-gram features, for \(k=10^5\). Again, we see that the model with hamm-gram features of size \(8\) (with a wildcard budget of \(2\)), has the strongest performance, and the model with hamm-gram features of length \(16\) (and with a wildcard budget of \(4\)) performs similarly to the best performing \(n\)-gram model.

4.4 Results on PDF Classification Task↩︎

Table 3: Partial AUCs for different features sets and sizes, on PDF dataset, for liblinear model with k=1e4.
feature \(n\) AUC(FPR \(< 0.001\)) AUC(FPR \(< 0.01\))
\(n\)-gram 8 0.957 0.991
\(n\)-gram 16 0.944 0.985
\(h\)-gram 8 0.985 0.994
\(h\)-gram 16 0.978 0.991

In this section, we report comparisons on a dataset of 100K train and 10k test malicious and benign PDFs scraped from VirusTotal. The comparison in Table 3 yields similar conclusions, with hamm-gram features of size 8 performing the best on the task, better than \(n\)-gram features of size 8 or 16. Additionally, the hamm-grams of size 16 perform as well as the best \(n\)-gram model (\(n\)=8).

5 Conclusion↩︎

In this manuscript, we have proposed a novel algorithm for mining hamm-grams, common regular expressions of bytes, utilizing a newly developed Locality Sensitive Hash. We have demonstrated that hamm-grams provide significant increases in model performance on an Android malware classification task and on large malware detection tasks for Windows Portable Executables and PDFs. Finally, we have demonstrated examples of mined hamm-gram features where allowing wildcards was essential to discovering a meaningful underlying concept in the data.

References↩︎

[1]
Ralph Langner.2011. . IEEE Security & Privacy9, 3(2011), 49–51. https://doi.org/10.1109/MSP.2011.67.
[2]
Charlotte Van Camp Walter Peeters.2022. . Space Policy59(2022), 101458. https://doi.org/10.1016/j.spacepol.2021.101458.
[3]
Ji Lin, Wei-Ming Chen, John Cohn, Chuang Gan, and Song Han.2020. . In Annual Conference on Neural Information Processing Systems (NeurIPS).
[4]
Dana Angluin.1982. . J. ACM29, 3(jul1982), 741–765. https://doi.org/10.1145/322326.322334.
[5]
Dana Angluin, Sarah Eisenstat, and Dana Fisman.2015. . In Proceedings of the 24th International Conference on Artificial Intelligence(IJCAI’15). AAAI Press, 3308–3314.
[6]
Katja Hahn.2014. Robust Static Analysis of Portable Executable Malware. Master thesis. HTWK Leipzig.
[7]
Charles Smutz Angelos Stavrou.2012. . In Proceedings of the 28th Annual Computer Security Applications Conference. ACM, 239–248.
[8]
R.B. van Baar, H.M.A. van Beek, and E.J. van Eijk.2014. . Digital Investigation11(2014), S54–S62. https://doi.org/10.1016/j.diin.2014.03.007.
[9]
Kirill Levchenko, Andreas Pitsillidis, Neha Chachra, Brandon Enright, Márk Félegyházi, Chris Grier, Tristan Halvorson, Chris Kanich, Christian Kreibich, He Liu, Damon McCoy, Nicholas Weaver, Vern Paxson, Geoffrey M Voelker, and Stefan Savage.2011. . In Proceedings of the 2011 IEEE Symposium on Security and Privacy(SP ’11). IEEE Computer Society, Washington, DC, USA, 431–446. https://doi.org/10.1109/SP.2011.24.
[10]
Marcus Botacin, Felipe Duarte Domingues, Fabrício Ceschin, Raphael Machnicki, Marco Antonio Zanata Alves, Paulo Lício de Geus, and André Grégio.2021. . Computers & Securityi(oct2021), 102500. https://doi.org/10.1016/j.cose.2021.102500.
[11]
Daniel Votipka, Seth M. Rabin, Kristopher Micinski, Jeffrey S. Foster, and Michelle M. Mazurek.2019. . In USENIX Security Symposium.
[12]
Miuyin Yong Wong, Matthew Landen, Manos Antonakakis, Douglas M Blough, Elissa M Redmiles, and Mustaque Ahamad.2021. . In Proceedings of the 2021 ACM SIGSAC Conference on Computer and Communications Security(CCS ’21). Association for Computing Machinery, New York, NY, USA, 3053–3069. https://doi.org/10.1145/3460120.3484759.
[13]
Pierre Dupont, Laurent Miclet, and Enrique Vidal.1994. . In Proceedings of the Second International Colloquium on Grammatical Inference and Applications(ICGI ’94). Springer-Verlag, Berlin, Heidelberg, 25–37.
[14]
F Coste J Nicolas.1997. . Workshop on Grammatical Inference, Automata Induction, and Language Acquisition (ICML’97)(1997). .nj.nec.com/coste97regular.html.
[15]
Mineichi Kudo Masaru Shimbo.1988. . Pattern Recognition21, 4(1988), 401–409. https://doi.org/10.1016/0031-3203(88)90053-2.
[16]
Jeffrey O Kephart, Gregory B Sorkin, William C Arnold, David M Chess, Gerald J Tesauro, and Steve R White.1995. . In Proceedings of the 14th International Joint Conference on Artificial Intelligence - Volume 1(IJCAI’95). Morgan Kaufmann Publishers Inc., San Francisco, CA, USA, 985–996. ://dl.acm.org/citation.cfm?id=1625855.1625983.
[17]
Jiyong Jang, David Brumley, and Shobha Venkataraman.2011. . In Proceedings of the 18th ACM conference on Computer and communications security - CCS. ACM Press, New York, New York, USA, 309–320. https://doi.org/10.1145/2046707.2046742.
[18]
Jeremy Z. Kolter Marcus A. Maloof.2004. . In Proceedings of the 2004 ACM SIGKDD international conference on Knowledge discovery and data mining - KDD ’04. ACM Press, New York, New York, USA, 470–478. https://doi.org/10.1145/1014052.1014105.
[19]
Jake Drew, Tyler Moore, and Michael Hahsler.2016. . In 2016 IEEE Security and Privacy Workshops (SPW). IEEE, 81–87. https://doi.org/10.1109/SPW.2016.30.
[20]
Ehsan Shareghi, Daniela Gerz, Ivan Vulić, and Anna Korhonen.2019. . In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, Volume 1 (Long and Short Papers), Jill Burstein, Christy Doran, and Thamar Solorio(Eds.). Association for Computational Linguistics, Minneapolis, Minnesota, 4113–4118. https://doi.org/10.18653/v1/N19-1417.
[21]
Zdenek Ceska, Ivo Hanak, and Roman Tesar.2007. . In 2007 IEEE International Conference on Intelligent Computer Communication and Processing. IEEE, 209–216. https://doi.org/10.1109/ICCP.2007.4352162.
[22]
Edward Raff, Ryan R. Curtin, Derek Everett, Robert J. Joyce, and James Holt.2025. . In Proceedings of the 34th ACM International Conference on Information and Knowledge Management(CIKM ’25). Association for Computing Machinery, New York, NY, USA, 5988–5996. https://doi.org/10.1145/3746252.3761551.
[23]
Ryan R. Curtin, Fred Lu, Edward Raff, and Priyanka Ranade.2026. . In Proceedings of the AAAI Conference on Artificial Intelligence, Vol. 40. arXiv. https://doi.org/10.48550/arXiv.2511.14955.
[24]
Edward Raff Charles Nicholas.2018. . In Proceedings of the ACM Symposium on Document Engineering 2018. ACM, Halifax, NS, Canada. https://doi.org/10.1145/3209280.3229085.
[25]
Edward Raff Mark McLean.2018. . In 2018 IEEE International Conference on Big Data (Big Data). IEEE, 158–165. https://doi.org/10.1109/BigData.2018.8622043.
[26]
Siddhant Gupta, Fred Lu, Andrew Barlow, Edward Raff, Francis Ferraro, Cynthia Matuszek, Charles Nicholas, and James Holt.2024. . In 2024 IEEE International Conference on Big Data (BigData). 2624–2634. https://doi.org/10.1109/BigData62323.2024.10825735.
[27]
Andrew Walenstein, Michael Venable, Matthew Hayes, Christopher Thompson, and Arun Lakhotia.2007. . In Proc. BlackHat DC Conf.
[28]
Asaf Shabtai, Robert Moskovitch, Yuval Elovici, and Chanan Glezer.2009. . Information Security Technical Report14, 1(2009), 16–29. https://doi.org/10.1016/j.istr.2009.03.003.
[29]
Mohammad M. Masud, Latifur Khan, and Bhavani Thuraisingham.2008. . Information Systems Frontiers10, 1(mar2008), 33–45. https://doi.org/10.1007/s10796-007-9054-3.
[30]
Richard Zak, Edward Raff, and Charles Nicholas.2017. . In 2017 12th International Conference on Malicious and Unwanted Software (MALWARE). IEEE, 109–118. https://doi.org/10.1109/MALWARE.2017.8323963.
[31]
Tirth Patel, Fred Lu, Edward Raff, Charles Nicholas, Cynthia Matuszek, and James Holt.2023. Proceedings of the Conference on Applied Machine Learning in Information Security(2023). ://arxiv.org/abs/2312.15813.
[32]
Robert J Joyce, Dev Amlani, Charles Nicholas, and Edward Raff.2022. . In The AAAI-22 Workshop on Artificial Intelligence for Cyber Security (AICS). https://doi.org/10.48550/arXiv.2111.15031.
[33]
Robert J. Joyce, Derek Everett, Maya Fuchs, Edward Raff, and James Holt.2025. . In Companion Proceedings of the ACM on Web Conference 2025(WWW ’25). Association for Computing Machinery, New York, NY, USA, 277–286. https://doi.org/10.1145/3701716.3715212.
[34]
Robert J Joyce, Edward Raff, and Charles Nicholas.2021. . In Proceedings of the 14th ACM Workshop on Artificial Intelligence and Security (AISec ’21). Association for Computing Machinery. https://doi.org/10.1145/3474369.3486867.
[35]
R. W. Hamming.1950. . The Bell System Technical Journal29, 2(1950), 147–160. https://doi.org/10.1002/j.1538-7305.1950.tb00463.x.
[36]
Paul Jaccard.1912. . New phytologist11, 2(1912), 37–50.
[37]
D. Tse P. Viswanath.2005. Fundamentals of Wireless Communication. Cambridge University Press. ://books.google.com/books?id=66XBb5tZX6EC.
[38]
Eric W. Weisstein.[n. d.]. Random Walk–2-Dimensional. ://mathworld.wolfram.com/RandomWalk2-Dimensional.html.
[39]
Rayleigh.1905. . Nature72, 1866(1905), 318–318. https://doi.org/10.1038/072318a0.
[40]
Edward Raff, William Fleming, Richard Zak, Hyrum Anderson, Bill Finlayson, Charles Nicholas, and Mark Mclean.2019. . arXiv preprint arXiv:1908.00200(2019).
[41]
Christopher D Manning.2008. Introduction to information retrieval. Syngress Publishing,.
[42]
Daniel Arp, Michael Spreitzenbarth, Malte Hubner, Hugo Gascon, Konrad Rieck, and CERT Siemens.2014. . In Ndss, Vol. 14. 23–26.
[43]
Jesse Kornblum.2006. . Digital investigation3(2006), 91–97.
[44]
Vassil Roussev.2010. . In Advances in Digital Forensics VI: Sixth IFIP WG 11.9 International Conference on Digital Forensics, Hong Kong, China, January 4-6, 2010, Revised Selected Papers 6. Springer, 207–226.
[45]
Edward Raff Charles Nicholas.2018. . Digital Investigation24(2018), 34–49.
[46]
H. S. Anderson P. Roth.2018. . ArXiv e-prints(April2018).  [cs.CR].