TExcelTAD
Home › Malware Analysis, Digital Forensics & Incident Response › Fuzzy Hashing with ssdeep, and TLSH

Fuzzy Hashing with ssdeep, and TLSH

The previous lesson ended with a problem: a builder that changes one byte per victim gives every copy a new SHA-256, so a hash list never catches the next one. What the analyst wants is a hash that answers a different question: not "is this the same file?" but "is this file similar to one I have seen?" That is what similarity hashes do. Two are standard in malware analysis: ssdeep (context-triggered piecewise hashing) and TLSH (a locality-sensitive hash).

Definitions

  • Context-triggered piecewise hashing (CTPH): the idea behind ssdeep (Jesse Kornblum, 2006). A rolling hash slides over the file, and wherever its value hits a trigger condition (it depends only on the last few bytes, the context), the current piece ends. Each piece is hashed to one Base64 character. Because boundaries depend on content, not on offsets, an insertion only disturbs the pieces near it; the rest of the signature stays the same.
  • ssdeep signature: blocksize:sig1:sig2. The block size sets how often the trigger fires (about one piece per block size bytes); sig2 is the same at double the block size, so files of different sizes can still be compared.
  • ssdeep score: 0 to 100, from an edit distance between the signatures. 100 means near-identical, 0 means no detectable similarity. Signatures with block sizes more than a factor of two apart can't be compared at all.
  • TLSH (Trend Micro Locality Sensitive Hash, published 2013): builds a histogram of byte triplets from a sliding window, quantises it into a 35-byte digest written as 70 hex characters (72 with the T1 version prefix that current versions put in front), and compares digests with a distance: 0 for identical, small for similar, larger for different (no upper bound of 100). It needs at least 50 bytes of input with enough variety, and is more robust than ssdeep to reordering and small files.
  • imphash, section hashes: exact hashes of normalised features, discussed in PE Triage. They complement fuzzy hashes.

ssdeep on synthetic variants

The session builds a 16 KiB base file of word-like text from a fixed seed (fuzzy hashes need a few KiB to be meaningful) and four relatives: one character changed, 1 KiB inserted in the middle, the second half replaced, and an unrelated file from another seed. Then it hashes them and compares every file against the hash of the base.

bash · try it yourself
python3 - <<'PY'
import random
def text(seed, n):
    r = random.Random(seed)
    words = "beacon config lab test server update interval report agent token value file data".split()
    out = []
    while sum(len(w) + 1 for w in out) < n:
        out.append(r.choice(words) + str(r.randrange(100)))
    return " ".join(out).encode()[:n]
base = text(1, 16384)
open("base.bin", "wb").write(base)
open("edit1.bin", "wb").write(base[:8000] + b"X" + base[8001:])
open("insert.bin", "wb").write(base[:8000] + text(2, 1024) + base[8000:])
open("halfnew.bin", "wb").write(base[:8192] + text(3, 8192))
open("other.bin", "wb").write(text(4, 16384))
PY
ssdeep -b base.bin > known.ssdeep
cut -c1-60 known.ssdeep
echo "--- matches against the known base hash"
ssdeep -b -m known.ssdeep edit1.bin insert.bin halfnew.bin other.bin
echo "--- every pair (-d: compare files with each other)"
ssdeep -b -d base.bin edit1.bin insert.bin halfnew.bin other.bin
ssdeep,1.1--blocksize:hash:hash,filename
192:jo3PaLjWuuIMfWrITxEgtHjkwUfYQOTEpu+skEe+gAZBgY/BHeWVDwk2
--- matches against the known base hash
edit1.bin matches known.ssdeep:base.bin (99)
insert.bin matches known.ssdeep:base.bin (97)
halfnew.bin matches known.ssdeep:base.bin (52)
--- every pair (-d: compare files with each other)
edit1.bin matches base.bin (99)
insert.bin matches base.bin (97)
insert.bin matches edit1.bin (97)
halfnew.bin matches base.bin (52)
halfnew.bin matches edit1.bin (52)
halfnew.bin matches insert.bin (50)

The one-character edit and the 1 KiB insertion keep a high score, because only the pieces around the change differ. Replacing half the file drops the score but still links it to the base. The unrelated file doesn't appear at all: ssdeep prints only matches above zero. Compare that with SHA-256, which says "different" for all four.

Why it works: content-defined boundaries

The core idea fits in a few lines. The example uses a simple rolling sum over a 7-byte window as the trigger (ssdeep uses a stronger rolling hash, and FNV for the pieces) and shows that inserting bytes at the front shifts every offset but leaves almost all pieces unchanged:

python · try it yourself
import hashlib, random

def pieces(data, window=7, blocksize=64):
    out, start, rolling = [], 0, 0
    for i, b in enumerate(data):
        rolling += b
        if i >= window:
            rolling -= data[i - window]
        if rolling % blocksize == blocksize - 1:          # the trigger depends only on the last 7 bytes
            out.append(hashlib.sha256(data[start:i + 1]).hexdigest()[:2])
            start = i + 1
    return out

r = random.Random(9)
data = bytes(r.choice(b"abcdefghijklmnopqrstuvwxyz ") for _ in range(4000))
shifted = b"INSERTED HEADER " + data

a, b = pieces(data), pieces(shifted)
print("pieces:", len(a), "vs", len(b))
print("signature a:", "".join(a[:24]), "…")
print("signature b:", "".join(b[:24]), "…")
print("pieces shared:", len(set(enumerate(a[1:])) & set(enumerate(b[1:]))), "of", len(a) - 1)
pieces: 60 vs 60
signature a: ea4629c045a711801ce203fce8cb6fc493984767726db627 …
signature b: d94629c045a711801ce203fce8cb6fc493984767726db627 …
pieces shared: 59 of 59

Only the first piece differs: after the insertion, the rolling window sees the same bytes again and fires at the same places. A fixed-size block hash (cut every 64 bytes) would have changed every block.

How fuzzy hashes are used in detection

  • Clustering: compare a new sample against a corpus; samples with high scores join the same family cluster, and analysis of one helps with all.
  • Hunting: VirusTotal and similar repositories index ssdeep and TLSH, so "find files similar to this one" works across millions of samples.
  • Forensics: find modified copies of a sensitive document on seized disks, or versions of a tool an intruder kept improving.

How to use them well

  • Use both an exact hash (identity) and a similarity hash (relatives).
  • Prefer TLSH for large-scale clustering (stable distance, works well with indexes) and ssdeep where it is the format partners use; record which, with its version.
  • Compare like with like: packed files are similar to everything packed with the same packer, so unpack or compare the unpacked code (packing).

Pitfalls

  • Small files. Below a few KiB ssdeep has too few pieces; TLSH refuses inputs that are too short or too uniform.
  • Shared boilerplate. Two unrelated programs built with the same compiler, runtime or installer can score high. Similarity is a lead, not a verdict.
  • High-entropy content. Encrypted or compressed sections change completely with a new key, so fuzzy hashes of packed samples link the packer, not the payload.
  • Thresholds. There is no universal "same family" score; calibrate on your own corpus.

Practice

1. Why can ssdeep compare files of different sizes at all?

The signature contains two hashes, at block size b and 2b. Two files can be compared when their block sizes are equal or differ by a factor of two, because then one of the signature pairs uses the same block size.

2. In the Python demo, what would happen with fixed 64-byte blocks instead of content-defined ones?

The 16-byte insertion would shift every block boundary relative to the content, so every block hash would change and nothing would be shared.

3. Two different installers built with the same installer framework score 60 in ssdeep. Are they the same malware family?

Not necessarily: the shared installer stub explains the similarity. Compare the payloads they install, the imphash of the payload, strings and behaviour.

Test yourself

What question does a fuzzy hash answer that SHA-256 cannot?

  1. Is the file signed?
  2. Is this file similar to a known one?
  3. Who wrote the file?
  4. Is the file encrypted?

Why does an insertion near the start of a file not change most of an ssdeep signature?

  1. ssdeep ignores the first kilobyte
  2. Piece boundaries are triggered by content, so they realign after the change
  3. ssdeep only hashes the end of the file
  4. The insertion is compressed away

How is a TLSH comparison expressed?

  1. A percentage from 0 to 100, higher is more similar
  2. A distance, where 0 is identical and larger is more different
  3. A yes/no flag
  4. An MD5 value

Why can fuzzy hashes of packed samples be misleading?

  1. Packed files are too small
  2. They mostly reflect the packer stub and random-looking packed data, not the payload
  3. ssdeep refuses executables
  4. Packing removes the file name