Algorithm Search⌘K

Problemadvanced

Binary code similarity

Also called binary diffing, binary function search.

Decide how similar two binary functions or programs are, across compilers and options, to find known bugs or patched code.

Origin
Halvar Flake, Yaniv David, Eran Yahav, Jannik Pewny, Xiaojun Xu, Steven H. H. Ding, Irfan Ul Haq, Juan Caballero, 2004

Binary code similarity asks how similar two pieces of machine code are, most often two functions, where the source code is not available. The pieces can come from the same source compiled by different compilers, with different optimization options or for different processors, or from different versions of the same program. The ground truth is usually "built from the same source function", and a method gives a score that should be high for such pairs and low for others. Since equivalence of behavior is undecidable, every method is an approximation, and its quality is a measurement on a benchmark, not a theorem. The problem is the basis of three kinds of work: finding a function with a known bug in other binaries, comparing two versions of a program to see which functions an update changed, and grouping related malware. Methods compare instruction sequences, the shape of the control flow graph, the behavior of code on sample inputs, or vectors learned from code.

Notation. A binary function ff has a control flow graph Gf=(Vf,Ef)G_f = (V_f, E_f) whose nodes are basic blocks, each a sequence of instructions. s(f,g)∈[0,1]s(f, g) \in [0, 1] is a similarity score. A repository RR holds nn functions. J(A,B)=∣A∩B∣/∣A∪B∣J(A, B) = |A \cap B| / |A \cup B| is the Jaccard similarity of two sets.

In plain words

Two people translate the same story into the same language. The words differ, the order of some sentences differs, one translation adds a short explanation, but the story is the same. A reader can tell that both come from one story, and can tell them apart from a different story that happens to use many of the same words.

Compilers translate source code into machine code in much the same way, and the choices of a compiler change the instructions, their order and the shape of the code. Binary code similarity is the work of telling which pieces of machine code come from the same source, when all you have is the machine code.

Definition

The similarity problem. The input is two binary functions ff and gg. The output is a score s(f,g)s(f, g). The target is a relation same(f,g)\mathrm{same}(f, g), true when ff and gg were built from the same source function, possibly by different toolchains, options or architectures. A method is good on a distribution of pairs if ss is high on pairs with same\mathrm{same} and low on the others, which is measured with precision and recall at a cut-off, or with the area under the ROC curve.

The search problem (binary function search). The input is a query function qq and a repository RR. The output is the kk functions of RR with the highest scores s(q,g)s(q, g). Its quality is measured by how often the true matches are in the top kk, and its cost by the time per query as nn grows.

The diffing problem (binary diffing). The input is two binaries PP and P′P', for example two versions of one program. The output is a one-to-one matching between some functions of PP and some functions of P′P', and for each matched pair, whether it changed. The other functions are reported as added or removed.

The score is not a metric in general, and the target relation same\mathrm{same} is defined by how the binaries were built, not by their behavior: two functions can come from different sources and behave the same.

Variants

Haq and Caballero (2021) classify methods along these lines:

  • By the kind of comparison: one to one (two functions), one to many (search) and many to many (clustering of a set).
  • By granularity: instructions, basic blocks, functions, or whole programs. The input and the output can have different granularities, for example functions compared through their blocks.
  • By what may differ: the compiler, the optimization options, the processor architecture, the version of the source, or an obfuscation applied to the code. Cross-architecture and obfuscated cases are the hardest.
  • By the kind of similarity: syntactic (the instructions), structural (the graphs), or semantic (the effect on registers and memory).
  • By the analysis: static, dynamic (traces of runs), or both.

Examples

Take three made-up functions, with the mnemonics of their instructions in the order of the code. A and B come from the same source, a function that adds the elements of an array, compiled with two levels of optimization. C comes from a different source, a function that finds the position of a value in an array.

function mnemonics basic blocks edges
A mov, mov, cmp, jge, add, add, jmp, ret entry (mov, mov), head (cmp, jge), body (add, add, jmp), exit (ret) entry to head, head to body, head to exit, body to head
B mov, mov, cmp, jge, add, add, cmp, jl, ret entry (mov, mov, cmp, jge), body (add, add, cmp, jl), exit (ret) entry to body, entry to exit, body to body, body to exit
C mov, mov, cmp, je, mov, add, jmp, ret entry (mov, mov), head (cmp, je), body (mov, add, jmp), exit (ret) entry to head, head to body, head to exit, body to head

Syntactic features. Take the set of pairs of consecutive mnemonics of each function.

  • A has 7 pairs, B has 8, and C has 7, all distinct within each function.
  • A and B share 5 pairs (mov mov, mov cmp, cmp jge, jge add, add add). So J=5/(7+8−5)=5/10=0.5J = 5 / (7 + 8 - 5) = 5/10 = 0.5.
  • A and C share 4 pairs (mov mov, mov cmp, add jmp, jmp ret). So J=4/(7+7−4)=4/10=0.4J = 4 / (7 + 7 - 4) = 4/10 = 0.4.
  • B and C share 2 pairs. So J=2/(8+7−2)=2/13≈0.15J = 2 / (8 + 7 - 2) = 2/13 \approx 0.15.

The true match B scores only a little more than the false match C, against A.

Structural features. The graphs of A and C are isomorphic: four blocks, a loop through the head, and an exit from the head. The graph of B has three blocks, because the optimizer moved the test to the end of the loop. A test of graph shape alone says that A matches C and not B, which is wrong.

Semantic features. On the same input, an array of three elements with the values 3, 1 and 2, A and B both return 6, and C returns a position. Comparing outputs on sampled inputs, as Pewny and coauthors (2015) did for basic blocks, separates the true match from the false one here. It needs the code to be run or emulated, and the inputs and outputs of the two functions to be put in correspondence.

The example shows why practical methods combine features, and why their quality is measured on large benchmarks of real compiled code.

Known algorithms

Each method is a heuristic for the target relation. Their reported accuracy is a measurement on the benchmarks of each paper.

  • Graph properties and fixed points (Flake 2004). Give each function a signature from its graph, such as the numbers of blocks, edges and calls. Match functions with unique signatures first. Then extend the matching along the call graph: the callers and callees of matched functions are likely to match. Inside matched functions, match basic blocks in the same way. This is fast and works well between two versions built the same way. It is weak when the compiler or the options change the shape of the graphs.
  • Hashes of normalized code. Replace registers, constants and addresses by placeholders, then hash instructions, blocks or n-grams of mnemonics. Exact hashes find identical code. Sets of n-grams compared with Jaccard similarity, and estimated with MinHash, find near copies. This is the method of the example, with its weakness.
  • Tracelets (David and Yahav 2014). Split each control flow graph into tracelets, short paths of a few consecutive basic blocks. Compare tracelets by an alignment of their instructions, like edit distance, and by a step that rewrites the registers and constants of one tracelet to match the other where possible. Two functions are similar if many of their tracelets match.
  • Graph matching. Compare the control flow graphs with graph edit distance, the maximum common subgraph or a matching of basic blocks with costs. Exact versions are NP-hard, so methods use approximations, such as a matching found with the Hungarian algorithm on the costs between blocks, or iterative refinement of block labels in the manner of the Weisfeiler-Leman test.
  • Behavior on sampled inputs (Pewny and coauthors 2015). Translate code from each architecture into one intermediate representation, run each basic block on sampled inputs, and compare blocks by their outputs. Start from the best matching pair of blocks and extend the match through the graph. MinHash makes the comparison of the sets of outputs fast. Because the comparison is on behavior, it works across architectures.
  • Learned embeddings of graphs (Xu and coauthors 2017). Give each basic block a vector of simple features, and train a neural network that turns the attributed control flow graph into one vector. The training uses pairs of functions labeled as the same or different. The score is the cosine similarity of the two vectors. Search computes the vectors of the repository once, so a query costs one embedding and a nearest neighbor search.
  • Learned representations of assembly (Ding, Fung and Charland 2019). Asm2Vec takes paths through the control flow graph of each function, treats instructions as words, and learns vectors for functions and tokens together, in the manner of word embeddings. It uses no knowledge of the compiler and needs no labeled pairs. Its authors measured it as robust to the optimization levels and the obfuscations in their tests.

Bounds

Each item is a theorem, unless it says otherwise.

  • Undecidability. Whether two functions have the same behavior on every input is undecidable, by Rice's theorem. So no method decides semantic equivalence in general, and every method either misses some equivalent pairs or reports some pairs that are not equivalent.
  • Exact graph comparison. Testing whether two control flow graphs are isomorphic is the graph isomorphism problem, which is not known to be in polynomial time. Finding the largest common subgraph and computing the graph edit distance are NP-hard. These bounds are in the size of the graphs. Control flow graphs of single functions are often small, so exact methods are feasible for many of them in practice (a measurement, not a bound).
  • Search. A linear scan over nn stored vectors of dimension dd costs O(nd)O(nd) per query. Locality-sensitive hashing answers approximate queries in time sublinear in nn, with a probability of error that the parameters control.
  • Diffing. Given a score for every pair, a one-to-one matching of the largest total score between functions of two binaries with nn functions each is found in O(n3)O(n^3) time by the Hungarian algorithm.

Reductions

Applications

  • Search for known bugs. Given a function with a known security bug, find copies of it in other programs and in firmware, possibly built for other processors, so that defenders can update them. This is the main application of cross-architecture methods.
  • Analysis of updates. Compare a program before and after a security update to find the functions that changed. Defenders use this to check that an update is present in a product, and to understand what it fixed.
  • Malware analysis. Find the shared code of samples, group them into families, and trace their lineage. This complements behavior clustering and the detectors of metamorphic malware.
  • Software provenance. Find the libraries inside a binary and their versions, and detect code copied against its license.
  • Limits from obfuscation. Control-flow flattening and virtualization obfuscation remove most of the syntactic and structural signal, so methods based on behavior or on deobfuscated code are needed for protected programs.

References

  1. Irfan Ul Haq and Juan Caballero, A survey of binary code similarity, ACM Computing Surveys 54(3), 2021, article 51, the classification of approaches by comparison type, granularity, features, and the kinds of compiler, option and architecture differences they handle
  2. Halvar Flake, Structural comparison of executable objects, Detection of Intrusions and Malware and Vulnerability Assessment (DIMVA) 2004, the matching of functions between two executables by properties of their control flow graphs and of the call graph
  3. Yaniv David and Eran Yahav, Tracelet-based code search in executables, ACM Conference on Programming Language Design and Implementation (PLDI) 2014, the split of a control flow graph into tracelets, short paths of basic blocks, and their comparison by alignment and rewriting
  4. Jannik Pewny, Behrad Garmany, Robert Gawlik, Christian Rossow and Thorsten Holz, Cross-architecture bug search in binary executables, IEEE Symposium on Security and Privacy 2015, the translation of code from several architectures into one intermediate representation, the comparison of basic blocks by their behavior on sampled inputs, and the search for known bugs
  5. Xiaojun Xu, Chang Liu, Qian Feng, Heng Yin, Le Song and Dawn Song, Neural network-based graph embedding for cross-platform binary code similarity detection, ACM Conference on Computer and Communications Security (CCS) 2017, the embedding of attributed control flow graphs by a neural network trained on pairs, and search by the distance between embeddings
  6. Steven H. H. Ding, Benjamin C. M. Fung and Philippe Charland, Asm2Vec: boosting static representation robustness for binary clone search against code obfuscation and compiler optimization, IEEE Symposium on Security and Privacy 2019, the learned representation of assembly functions from paths in their control flow graphs, with no prior knowledge of the compiler

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a known algorithm
  • a contract.yaml