Algorithm Search⌘K

Algorithmcore

Byte n-gram malware classification

Also called Kolter-Maloof classifier.

Represents each executable by the presence of selected byte n-grams and trains a standard classifier to tell malware from clean files.

Time
O(n L log L) worstO(n L + U log k) average
Space
O(n L) extra
Where
L = the total number of bytes in the training files; U = the number of distinct n-grams in the training files; k = the number of selected n-grams; n = the n-gram length
Properties
deterministicofflineiterativesupervised
Origin
J. Zico Kolter, Marcus A. Maloof, 2004

Byte n-gram classification is a learned detector for malicious executables. It reads each file as a string of bytes, lists the overlapping substrings of nn bytes (the n-grams), and keeps for each file only the yes or no answer "does this n-gram occur". From the training files it keeps the kk n-grams that tell the most about the class, measured by information gain, and trains a standard classifier on these kk answers. Kolter and Maloof (2004, 2006) used n=4n = 4 and k=500k = 500 and found that boosted decision trees did best on their data. The method needs no disassembly and no execution of the file. This page describes the detector only. The example and the code use random byte strings with planted made-up patterns, never real programs.

In plain words

Cut every file into all its short overlapping pieces of four bytes. For each piece, ask a simple question: does this file contain it or not?

Most pieces tell you nothing, because they are as common in clean files as in bad ones. So, on a set of files whose labels you know, score each piece by how much its presence tells you about the label. Keep the few hundred best pieces.

Now each file is a short list of yes and no answers. Give these lists and the labels to any standard learning method. To judge a new file, cut it into pieces, answer the same questions, and let the trained method decide.

The method finds byte patterns that the training malware shares. It can miss new malware that shares none of them.

The problem

The input is a training set of byte strings x1,…,xNx_1, \ldots, x_N with labels yj∈{0,1}y_j \in \{0, 1\}, where 1 means malicious, and parameters n≥1n \ge 1 and k≥0k \ge 0. The output is a classifier that maps any byte string to 0 or 1. For a byte string xx, let G(x)G(x) be the set of its n-grams, x[i..i+n−1]x[i..i+n-1] for 0≤i≤∣x∣−n0 \le i \le |x| - n. The feature vector of xx is ([w∈G(x)])w∈S([w \in G(x)])_{w \in S} for a selected set SS of kk n-grams.

For an n-gram ww, let cy(w)c_y(w) be the number of training files of class yy that contain ww, and NyN_y the number of files of class yy. Kolter and Maloof rank n-grams by the information gain

IG(w)=∑v∈{0,1}∑y∈{0,1}P(v,y)log⁡P(v,y)P(v)P(y),\mathrm{IG}(w) = \sum_{v \in \{0, 1\}} \sum_{y \in \{0, 1\}} P(v, y) \log \frac{P(v, y)}{P(v) P(y)},

where vv is the presence of ww and the probabilities are proportions in the training set. This is the mutual information between presence and class. The goal of the learner is a low error on new files, which is an empirical matter: nothing in the method guarantees it.

The algorithm

The classifier here is Bernoulli naive Bayes with add-one (Laplace) estimates. Kolter and Maloof also used decision trees, support vector machines, nearest neighbors and boosted versions of these on the same features.

  1. TRAIN(x1..xN, y1..yN, n, k)
  2. 1for each file xj do Gj ← the set of n-grams of xj
  3. 2for each n-gram w in some Gj do c[w, y] ← the number of files of class y with w in Gj
  4. 3for each such w do IG(w) ← the mutual information of presence and class
  5. 4S ← the k n-grams of largest IG, ties to the smaller n-gram in byte order
  6. 5for y in {0, 1} do π[y] ← (Ny + 1) / (N + 2)
  7. 6for each w in S and y in {0, 1} do θ[w, y] ← (c[w, y] + 1) / (Ny + 2)
  8. 7return S, π, θ
  9. CLASSIFY(S, π, θ, x)
  10. 8for y in {0, 1} do s[y] ← log π[y] + Σ over w in S of (log θ[w, y] if w occurs in x, else log (1 - θ[w, y]))
  11. 9return 1 if s[1] > s[0], else 0

Line L1 uses a set, so a file that contains an n-gram many times counts once. Line L3 uses only the n-grams that occur in the training set: one that occurs nowhere has a constant feature and gain 0. Line L4 is a selection of the top kk, not a full sort. Lines L5 and L6 add one to each count, so no estimate is 0 or 1 and every logarithm in line L8 is defined. Line L8 works with logarithms because a product of 500 factors would underflow.

Example

The training set has 4 malicious and 4 benign files of random bytes. Four made-up 4-grams A, B, C and D are planted in some of them, and random filler separates the pieces, so every other 4-gram occurs in one file only. The gains are in nats.

n-gram malicious files with it benign files with it information gain
A 4 0 0.6931
B 4 1 0.3804
C 1 3 0.1308
D 2 2 0
any filler 4-gram 1 or 0 0 or 1 0.0956

A splits the classes perfectly, so its gain is ln⁡2=0.6931\ln 2 = 0.6931, the entropy of the class. D occurs equally often in both classes and tells nothing. With k=2k = 2, line L4 selects A and B. Lines L5 and L6 give π=(1/2,1/2)\pi = (1/2, 1/2), θ[A]=(1/6,5/6)\theta[A] = (1/6, 5/6) and θ[B]=(2/6,5/6)\theta[B] = (2/6, 5/6) for (benign, malicious).

A new file that contains B but not A has joint probabilities 12⋅56⋅26=536\frac{1}{2} \cdot \frac{5}{6} \cdot \frac{2}{6} = \frac{5}{36} for benign and 12⋅16⋅56=572\frac{1}{2} \cdot \frac{1}{6} \cdot \frac{5}{6} = \frac{5}{72} for malicious, so the posterior of malicious is 1/31/3 and line L9 returns benign. A file with both A and B has posterior 25/2725/27 for malicious, and a file with neither has 1/211/21.

Correctness

What the algorithm computes is exact, and the full proof is in the proof file. Line L1 gives the set of n-grams of each file, and line L2 gives the counts. The value of line L3 equals H(Y)−H(Y∣V)H(Y) - H(Y \mid V), the drop in the entropy of the class when the presence VV of the n-gram is known, so it is never negative. Line L4 returns kk n-grams such that no unselected n-gram has a larger gain. Lines L8 and L9 return the class with the larger posterior in the Bernoulli naive Bayes model with the add-one estimates, because the log of the joint probability is the sum in line L8.

These are theorems about the computation. That the selected n-grams and the classifier detect malware is a measurement on a data set. The naive Bayes decision is optimal only if the features are independent given the class and the estimates are the true values, and neither holds for real files.

Proof: The trainer keeps the k n-grams of largest information gain and the classifier returns the naive Bayes decisionfull

The training set is a list of byte strings x1,…,xNx_1, \ldots, x_N with labels yj∈{0,1}y_j \in \{0, 1\}, where N1N_1 files have label 1 and N0=N−N1N_0 = N - N_1 have label 0. Fix n≥1n \ge 1 and k≥0k \ge 0. For a byte string ww of length nn, let cy(w)c_y(w) be the number of files of class yy that contain ww as a contiguous substring. What the algorithm computes is exact. Whether the result separates malware from clean files is an empirical question, and the proof says nothing about it.

Lemma 1 (features). Line L1 gives, for each file xx, the set G(x)G(x) of all ww of length nn that occur in xx, and line L2 gives c1(w)c_1(w) and c0(w)c_0(w) for every ww in ⋃jG(xj)\bigcup_j G(x_j).

Proof. The substrings of length nn of xx are exactly x[i..i+n−1]x[i..i+n-1] for 0≤i≤∣x∣−n0 \le i \le |x| - n, and line L1 collects them in a set, so each occurs once. Line L2 visits each pair of a file and an element of its set once, and adds 1 to the counter of its class. □\square

An nn-gram that occurs in no training file has c0=c1=0c_0 = c_1 = 0, so its presence is constant and its information gain is 0. Leaving it out of line L3 changes no ranking among n-grams with positive gain.

Lemma 2 (information gain). Let VV be the presence of ww in a file drawn uniformly from the training set, and YY its class. The value of line L3 is

IG(w)=∑v∈{0,1}∑y∈{0,1}P(v,y)ln⁡P(v,y)P(v)P(y)=H(Y)−H(Y∣V)≥0,\mathrm{IG}(w) = \sum_{v \in \{0, 1\}} \sum_{y \in \{0, 1\}} P(v, y) \ln \frac{P(v, y)}{P(v) P(y)} = H(Y) - H(Y \mid V) \ge 0,

with P(1,y)=cy(w)/NP(1, y) = c_y(w)/N, P(0,y)=(Ny−cy(w))/NP(0, y) = (N_y - c_y(w))/N, and the terms with P(v,y)=0P(v, y) = 0 omitted.

Proof. The function sums exactly these four terms. Write ln⁡P(v,y)P(v)P(y)=ln⁡P(y∣v)−ln⁡P(y)\ln \frac{P(v, y)}{P(v) P(y)} = \ln P(y \mid v) - \ln P(y). Summing P(v,y)P(v, y) times the first part over vv and yy gives −H(Y∣V)-H(Y \mid V), and the second part gives H(Y)H(Y) because ∑vP(v,y)=P(y)\sum_v P(v, y) = P(y). The sum is the Kullback-Leibler divergence of the joint law from the product of its marginals, which is nonnegative by Gibbs' inequality. □\square

Lemma 3 (selection). Line L4 returns min⁡(k,U)\min(k, U) distinct n-grams, where UU is the number of distinct n-grams in the training set, such that no unselected n-gram has a larger gain than a selected one.

Proof. Line L4 orders the n-grams by the key (−IG(w),w)(-\mathrm{IG}(w), w), which is a total order because the second part breaks every tie, and returns the first min⁡(k,U)\min(k, U). Each selected key is at most each unselected key, so its gain is at least as large. □\square

Theorem 1 (classifier). Let SS be the selected set, and define the Laplace estimates πy=(Ny+1)/(N+2)\pi_y = (N_y + 1)/(N + 2) and θw,y=(cy(w)+1)/(Ny+2)\theta_{w, y} = (c_y(w) + 1)/(N_y + 2) for w∈Sw \in S (lines L5 and L6). For a byte string xx, line L8 computes

sy(x)=ln⁡πy+∑w∈S,w∈G(x)ln⁡θw,y+∑w∈S,w∉G(x)ln⁡(1−θw,y),s_y(x) = \ln \pi_y + \sum_{w \in S, w \in G(x)} \ln \theta_{w, y} + \sum_{w \in S, w \notin G(x)} \ln (1 - \theta_{w, y}),

and line L9 returns 11 if s1(x)>s0(x)s_1(x) > s_0(x) and 00 otherwise. This is the class of larger posterior probability in the Bernoulli naive Bayes model with parameters π\pi and θ\theta, with ties to class 0.

Proof. All estimates lie strictly between 0 and 1, so every logarithm is defined. In the model, the features [w∈G(x)][w \in G(x)] for w∈Sw \in S are independent given the class, with P([w∈G(x)]=1∣y)=θw,yP([w \in G(x)] = 1 \mid y) = \theta_{w, y}, so the joint probability of the class yy and the observed feature vector is πy∏w∈G(x)θw,y∏w∉G(x)(1−θw,y)\pi_y \prod_{w \in G(x)} \theta_{w, y} \prod_{w \notin G(x)} (1 - \theta_{w, y}), whose logarithm is sy(x)s_y(x). The posterior is this joint probability divided by a quantity that does not depend on yy, and ln⁡\ln is increasing, so comparing s1s_1 with s0s_0 compares the posteriors. □\square

If the features were in fact independent given the class and π\pi and θ\theta were the true parameters, this decision would minimize the probability of error among all rules that see only these features (the Bayes rule). Neither condition holds for real files, and the estimates come from a finite sample, so this is a statement about the model.

Cost. Let L=∑j∣xj∣L = \sum_j |x_j|. Line L1 hashes LL slices of nn bytes, which is O(nL)O(nL) expected time. Line L2 does at most LL counter updates. Line L3 is O(1)O(1) per distinct n-gram, so O(U)O(U) with U≤LU \le L. Line L4 is a heap selection in O(Ulog⁡k)O(U \log k). Lines L5 to L7 cost O(k)O(k). Classifying xx costs O(n∣x∣)O(n |x|) for its set and O(k)O(k) for the sums. The space is O(U)O(U) counters plus the sets of the training files, which hold at most LL n-grams in total. ■\blacksquare

Complexity

The model is the word RAM. Let LL be the total number of training bytes and U≤LU \le L the number of distinct n-grams. Line L1 hashes LL slices of nn bytes, in O(nL)O(nL) expected time. Line L2 does at most LL counter updates and line L3 does O(1)O(1) work per distinct n-gram. Line L4 is a heap selection in O(Ulog⁡k)O(U \log k). With balanced search trees instead of hash tables, each of the LL lookups costs O(nlog⁡L)O(n \log L) in the worst case, which gives O(nLlog⁡L)O(n L \log L). The sets of n-grams take O(nL)O(nL) bytes. Classifying a file of length ℓ\ell costs O(nℓ+k)O(n \ell + k).

The real cost is the size of UU. Kolter and Maloof report 255,904,403 distinct 4-grams in their larger collection, so the counting step dominates, and they note that selecting the features took a great deal of time and space while the learning on 500 features was fast.

Properties

  • Static. It reads the bytes of the file and never runs it.
  • Format blind. It ignores the structure of the file: headers, code and data give n-grams in the same way.
  • Sparse features. Each file has at most ∣x∣−n+1|x| - n + 1 distinct n-grams out of 256n256^n possible ones, so the features are Boolean and sparse.
  • Learner independent. The selection step does not depend on the classifier. Kolter and Maloof used the same 500 features for all their learners.

Variants and improvements

  • Other learners. In the larger study of Kolter and Maloof, boosted J48 decision trees had the highest area under the ROC curve, and plain naive Bayes the lowest among their methods. See boosting and decision trees.
  • Other n and k. In a pilot study on 476 malicious and 561 benign files, they tried kk from 10 to 10,000 and nn from 1 to 10, and 500 4-grams of single bytes gave the best results. This is a measurement on that data, not a general rule.
  • Counts instead of presence. A feature can be the frequency of the n-gram, often weighted as in tf-idf, instead of a yes or no answer.
  • Other features. Schultz et al. (2001) used byte sequences from a hex dump, imported library calls and strings, with naive Bayes classifiers. Later work uses n-grams of disassembled instructions or of system calls.
  • Payload function. Kolter and Maloof also trained the same pipeline to tell which function a malicious file performs, with lower areas under the ROC curve, about 0.9.

When to use it

Use it as a fast static filter when many labeled samples of the same platform are available and the goal is to catch new variants of known families. It is a poor fit for packed or encrypted files, whose bytes look random. A detector of high entropy or an unpacking step is then needed first.

Pitfalls

  • Data leakage. The n-grams must be selected inside each training fold. Selecting them on all data and then cross-validating overstates the accuracy. Kolter and Maloof selected the 500 n-grams again in each fold.
  • Spurious features. An n-gram can separate the classes because of how the data were collected, for example a compiler or an installer that occurs only in the clean files. The classifier then learns the collection, not malice.
  • Evasion. An adversary who knows the features can add bytes that look clean or remove the selected patterns. This is an evasion attack on the learner, and the static byte view is easy to change.
  • Base rates. A small false positive rate on a large number of clean files gives many false alarms. See the base-rate fallacy.
  • Drift. The selected n-grams reflect the malware of the training period. Detection drops as new families appear.

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.

byte_n_gram_malware_classification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/byte-n-gram-malware-classification/. The authors are listed in prov/9D0N1Y.jsonl.

"""Byte n-gram classification (after Kolter and Maloof 2006) on synthetic byte strings.

Each file is represented by the set of its overlapping byte n-grams. The
trainer keeps the k n-grams with the largest information gain about the
class and fits a Bernoulli naive Bayes model on their presence. Class 0 is
benign and class 1 is malicious. The code works on byte strings that the
caller gives; it never opens a file. The tests use random bytes only.
"""

import heapq
import math


def ngrams(data: bytes, n: int) -> set[bytes]:
    """Set of the overlapping n-grams of data. Cost: O(n len(data)) expected."""
    if n < 1:
        raise ValueError("n must be at least 1")
    return {data[i : i + n] for i in range(len(data) - n + 1)}


def information_gain(c1: int, c0: int, n1: int, n0: int) -> float:
    """Mutual information (in nats) between presence of an n-gram and the class.

    c1, c0: number of class 1 and class 0 files that contain the n-gram;
    n1, n0: number of class 1 and class 0 files. Precondition: 0 <= c1 <= n1,
    0 <= c0 <= n0, n1 + n0 > 0. Cost: O(1).
    """
    total = n1 + n0
    cells = ((c1, c0), (n1 - c1, n0 - c0))  # presence v = 1, then v = 0
    ig = 0.0
    for a, b in cells:
        pv = (a + b) / total
        for joint, py in ((a, n1 / total), (b, n0 / total)):
            if joint:
                p = joint / total
                ig += p * math.log(p / (pv * py))
    return ig


def train(files: list[bytes], labels: list[int], n: int, k: int) -> dict:
    """Select k n-grams by information gain and fit Bernoulli naive Bayes.

    Precondition: len(files) == len(labels) >= 1, labels in {0, 1}, n >= 1,
    k >= 0. Ties in information gain go to the smaller n-gram in byte order.
    Cost: O(n L + U log k) expected time for L training bytes and U distinct
    n-grams, and O(U) space.
    """
    if len(files) != len(labels) or not files or k < 0:
        raise ValueError("bad training set")
    if any(y not in (0, 1) for y in labels):
        raise ValueError("labels must be 0 or 1")
    sets = [ngrams(x, n) for x in files]  # @line L1
    counts: dict[bytes, list[int]] = {}
    for g, y in zip(sets, labels):  # @line L2
        for w in g:
            counts.setdefault(w, [0, 0])[y] += 1
    n1 = sum(labels)
    n0 = len(labels) - n1
    gains = {w: information_gain(c[1], c[0], n1, n0) for w, c in counts.items()}  # @line L3
    selected = heapq.nsmallest(k, gains, key=lambda w: (-gains[w], w))  # @line L4
    prior = [(n0 + 1) / (len(labels) + 2), (n1 + 1) / (len(labels) + 2)]  # @line L5
    theta = {  # @line L6
        w: [(counts[w][0] + 1) / (n0 + 2), (counts[w][1] + 1) / (n1 + 2)] for w in selected
    }
    return {"n": n, "selected": selected, "gain": {w: gains[w] for w in selected},  # @line L7
            "prior": prior, "theta": theta}


def scores(model: dict, data: bytes) -> list[float]:
    """Log joint probability of data's selected-feature vector with each class."""
    present = ngrams(data, model["n"])
    out = []
    for y in (0, 1):
        s = math.log(model["prior"][y])  # @line L8
        for w in model["selected"]:
            t = model["theta"][w][y]
            s += math.log(t) if w in present else math.log(1.0 - t)
        out.append(s)
    return out


def classify(model: dict, data: bytes) -> int:
    """Return 1 (malicious) or 0 (benign); ties go to 0. Cost: O(n len(data) + k)."""
    s0, s1 = scores(model, data)
    return 1 if s1 > s0 else 0  # @line L9
test_byte_n_gram_malware_classification.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/byte-n-gram-malware-classification/. The authors are listed in prov/9D0N1Y.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

from byte_n_gram_malware_classification import (
    classify,
    information_gain,
    ngrams,
    scores,
    train,
)


def test_ngrams_against_search() -> None:
    rng = random.Random(1)
    for _ in range(300):
        alphabet = bytes(rng.sample(range(256), rng.randint(1, 3)))
        data = bytes(rng.choice(alphabet) for _ in range(rng.randint(0, 12)))
        n = rng.randint(1, 4)
        got = ngrams(data, n)
        for t in itertools.product(alphabet, repeat=n):
            w = bytes(t)
            assert (w in got) == (data.find(w) >= 0)
        assert all(len(w) == n for w in got)


def entropy(ps) -> float:
    return -sum(p * math.log(p) for p in ps if p > 0)


def test_information_gain_is_entropy_drop() -> None:
    rng = random.Random(2)
    for _ in range(600):
        n1, n0 = rng.randint(0, 30), rng.randint(0, 30)
        if n1 + n0 == 0:
            continue
        c1, c0 = rng.randint(0, n1), rng.randint(0, n0)
        tot = n1 + n0
        hy = entropy((n1 / tot, n0 / tot))
        hcond = 0.0
        for a, b in ((c1, c0), (n1 - c1, n0 - c0)):
            if a + b:
                hcond += (a + b) / tot * entropy((a / (a + b), b / (a + b)))
        assert abs(information_gain(c1, c0, n1, n0) - (hy - hcond)) < 1e-12
        assert information_gain(c1, c0, n1, n0) >= -1e-15


def test_page_example() -> None:
    # 4 files of each class. Counts (malicious, benign) of four n-grams A to D.
    assert round(information_gain(4, 0, 4, 4), 4) == 0.6931
    assert round(information_gain(4, 1, 4, 4), 4) == 0.3804
    assert round(information_gain(1, 3, 4, 4), 4) == 0.1308
    assert information_gain(2, 2, 4, 4) == 0.0
    a, b, c, d = b"\x11\x22\x33\x44", b"\x55\x66\x77\x88", b"\x99\xaa\xbb\xcc", b"\xdd\xee\xff\x00"
    mal = [[a, b, d], [a, b, d], [a, b, c], [a, b]]
    ben = [[b, c], [c, d], [c, d], []]
    # Random filler between the pieces makes every other 4-gram rare.
    rng = random.Random(8)

    def build(pieces: list[bytes]) -> bytes:
        out = bytes(rng.randrange(256) for _ in range(3))
        for p in pieces:
            out += p + bytes(rng.randrange(256) for _ in range(3))
        return out

    files = [build(p) for p in mal + ben]
    model = train(files, [1, 1, 1, 1, 0, 0, 0, 0], 4, 2)
    assert model["selected"] == [a, b]
    s0, s1 = scores(model, b)
    assert abs(math.exp(s1) - 5 / 72) < 1e-12 and abs(math.exp(s0) - 5 / 36) < 1e-12
    assert classify(model, b) == 0 and classify(model, a + b) == 1


def random_set(rng: random.Random):
    files, labels = [], []
    for _ in range(rng.randint(1, 8)):
        files.append(bytes(rng.choice(b"ab") for _ in range(rng.randint(0, 8))))
        labels.append(rng.randint(0, 1))
    return files, labels


def test_selection_and_naive_bayes_against_oracle() -> None:
    rng = random.Random(2006)
    for _ in range(500):
        files, labels = random_set(rng)
        n, k = rng.randint(1, 3), rng.randint(0, 5)
        model = train(files, labels, n, k)
        sets = [ngrams(x, n) for x in files]
        universe = set().union(*sets)
        n1 = sum(labels)
        n0 = len(labels) - n1

        def gain(w: bytes) -> float:
            c1 = sum(1 for g, y in zip(sets, labels) if y == 1 and w in g)
            c0 = sum(1 for g, y in zip(sets, labels) if y == 0 and w in g)
            return information_gain(c1, c0, n1, n0)

        sel = model["selected"]
        assert len(sel) == min(k, len(universe)) and len(set(sel)) == len(sel)
        if sel:
            worst = min(gain(w) for w in sel)
            assert all(gain(w) <= worst + 1e-12 for w in universe - set(sel))
        # Exact naive Bayes with Fractions on a random test string.
        x = bytes(rng.choice(b"ab") for _ in range(rng.randint(0, 8)))
        present = ngrams(x, n)
        post = []
        for y, ny in ((0, n0), (1, n1)):
            p = Fraction(ny + 1, len(labels) + 2)
            for w in sel:
                c = sum(1 for g, lab in zip(sets, labels) if lab == y and w in g)
                t = Fraction(c + 1, ny + 2)
                p *= t if w in present else 1 - t
            post.append(p)
        s = scores(model, x)
        assert abs(s[0] - math.log(post[0])) < 1e-9 and abs(s[1] - math.log(post[1])) < 1e-9
        if post[0] != post[1]:
            assert classify(model, x) == (1 if post[1] > post[0] else 0)


def synthetic_files(rng: random.Random, patterns: list[bytes], count: int):
    """Random byte strings; malicious ones get one planted made-up pattern."""
    files, labels = [], []
    for i in range(count):
        body = bytearray(rng.randrange(256) for _ in range(rng.randint(150, 300)))
        y = i % 2
        if y == 1:
            p = rng.choice(patterns)
            j = rng.randrange(len(body) - len(p))
            body[j : j + len(p)] = p
        files.append(bytes(body))
        labels.append(y)
    return files, labels


def test_planted_patterns_are_learned() -> None:
    rng = random.Random(4)
    patterns = [bytes(rng.randrange(256) for _ in range(12)) for _ in range(3)]
    train_x, train_y = synthetic_files(rng, patterns, 200)
    test_x, test_y = synthetic_files(rng, patterns, 200)
    model = train(train_x, train_y, 4, 30)
    planted = set().union(*(ngrams(p, 4) for p in patterns))
    assert planted <= set(model["selected"])
    correct = sum(classify(model, x) == y for x, y in zip(test_x, test_y))
    assert correct >= 190


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        ngrams(b"abc", 0)
    with pytest.raises(ValueError):
        train([b"ab"], [2], 1, 1)
    with pytest.raises(ValueError):
        train([], [], 1, 1)
    with pytest.raises(ValueError):
        train([b"ab"], [0, 1], 1, 1)

History

Schultz, Eskin, Zadok and Stolfo (2001) applied data mining to detect new malicious executables, with byte sequences from a hex dump among their features. Kolter and Maloof (2004) made byte n-grams the main feature, chose them by information gain, and compared several learners. Their journal study (2006) used a collection gathered in the summer of 2003, with 1,971 benign and 1,651 malicious executables. With stratified ten-fold cross-validation and 500 selected 4-grams, boosted decision trees had an area under the ROC curve of 0.996. On 291 malicious executables discovered later, from July 2003 to August 2004, and with thresholds set for a desired false positive rate of 0.05, boosted decision trees detected about 98% and missed 6. These are measurements on that data, not properties of the method.

References

  1. J. Zico Kolter and Marcus A. Maloof, Learning to detect and classify malicious executables in the wild, Journal of Machine Learning Research 7, 2006, pages 2721 to 2744, Section 3 (the data and the 4-gram features), Section 4 (the information gain formula, the 500 selected n-grams and the learners), Section 5 (the pilot studies and the cross-validation results), Section 7 (the evaluation on 291 later malicious executables)
  2. Jeremy Z. Kolter and Marcus A. Maloof, Learning to detect malicious executables in the wild, ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD) 2004, pages 470 to 478, the first version of the method and the experiment on the small collection
  3. Matthew G. Schultz, Eleazar Eskin, Erez Zadok and Salvatore J. Stolfo, Data mining methods for detection of new malicious executables, IEEE Symposium on Security and Privacy 2001, pages 38 to 49, byte sequences from a hex dump as features, and naive Bayes classifiers compared with a signature scanner

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.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