Finding Bugs in VMs with a Theorem Prover

Originally published January 22nd, 2012 on OpenRCE.

Equivalence checking is a popular technique in the academic literature and in industrial practice, used to verify that two "things" are equivalent.  Commonly, it involves translating those things into some logic that is supported by a theorem prover, and asking the decision procedure to prove whether the two things must always be equal.  Equivalently, we ask whether there exists any circumstances where the two things might not be equal.  If the two things must always be equal under all circumstances, then a complete decision procedure will eventually report that the formula is unsatisfiable.  If they can ever deviate, then it will return a "counterexample" illustrating a scenario in which the things differ.  The decision procedure may not terminate in a reasonable amount of time, or do so at all if the logic is undecidable or the decision procedure is incomplete.


Equivalence checking is commonly found in the hardware world (particularly, in a field known as Electronic Design Automation, or EDA), but it has been applied to software as well, for tasks such as verification that compiler optimizations have been implemented correctly, verification of cryptographic implementations, and other forms of specification-conformance.  In this blog, we'll take a look at an application of equivalence checking in deobfuscation.

Equivalence Checking

We begin by giving an example proving the equivalence between an x86 sequence and a machine instruction.

Bit-level hackers -- those who study the works of the original MIT "hackers", whose work bequeathed the term "hacker" -- will know the following example regarding taking the population count of a 32-bit integer.  The "population count" of a given integer is the number of one-bits set in the integer.  This operation is known as "popcnt", and the x86 instruction set features an instruction of the same name, whose syntax is "popcnt r32, r/m32" and whose semantics dictate that the population count of the right-hand side (32- or 16-bit, depending upon encoding) be deposited into the location specified by the left-hand side.  We can easily imagine implementing this functionality with a loop:

int popcnt = 0;
for(int mask = 1; mask; popcnt += !!(mask & value_to_compute_popcnt_of), mask <<= 1);

A hoary MIT HAKMEM gem shows how to compute the same value via a series of arithmetic manipulations and no explicit loop.  We summarize the procedure below.

Consider some 8-bit integer, whose bits we shall represent symbolically with letters as in the following:

abcdefgh

Let's demonstrate how the method computes the population count of this integer.  First, we separate out all of the even bits and the odd bits:

x = ((x & 0xAA) >> 1) + (x 0x55);
abcdefgh AND
10101010
--------
a0c0e0g0 SHR 1
--------
0a0c0e0g


abcdefgh AND
01010101
--------
0b0d0f0h


Adding these two quantities together, we obtain the following result:

wwxxyyzz

Where ww, xx, yy, and zz are each two-bit quantities such that ww = a + b, xx = c + d, yy = e + f, and zz = g + h.  By adding these masked-and-shifted quantities together, we thereby compute the sum of two adjacent bits, and store the sum in that location within the integer that corresponds to those two bits.  Given that 0+0 = 0, 0+1 = 1, 1+0 = 1, and 1+1 = 10, the sum can never overflow, and is hence neatly contained in those two bits.

Next, we perform the same kind of trick to compute the sum of each two-bit quantity.  We use a similar shift-and-add tableau:

x = ((x & 0xCC) >> 2) + (x & 0x33);
wwxxyyzz AND
11001100
--------
ww00yy00 SHR 2
--------
00ww00yy

wwxxyyzz AND
00110011
--------
00xx00zz

Adding these two quantities together, we get:

iiiijjjj

Where iiii and jjjj are the 4-bit results such that iiii = ww + xx and jjjj = yy + zz.  Once again, this sum is safe from overflow because ww and xx are at most 2-bits, whereas iiii and jjjj are 4-bits.

We pull the same trick again to sum the quantities iiii and jjjj:

x = ((x & 0xF0) >> 4) + (x & 0x0F);
iiiijjjj AND
11110000
--------
iiii0000 SHR 4
--------
0000iiii

iiiijjjj AND
00001111
--------
0000jjjj

Adding these two quantifies together, we get kkkkkkkk, where kkkkkkkk = iiii + jjjj = ww + xx + yy + zz = a + b + c + d + e + f + g + h.  This corresponds to the definition of the population count of an 8-bit integer.  We can easily imagine extending the same procedure for 16-, 32-bit, 64-bit, and generally 2^n-bit quantities.  Below we display a fragment of x86 assembly language that computes the population count for a 32-bit integer

Sequence (1) -- messy bit hack for eax = popcnt(ebx)

mov eax, ebx
and eax, 55555555h
shr ebx, 1
and ebx, 55555555h
add ebx, eax
mov eax, ebx
and eax, 33333333h
shr ebx, 2
and ebx, 33333333h
add ebx, eax
mov eax, ebx
and eax, 0F0F0F0Fh
shr ebx, 4
and ebx, 0F0F0F0Fh
add ebx, eax
mov eax, ebx
and eax, 00FF00FFh
shr ebx, 8
and ebx, 00FF00FFh
add ebx, eax
mov eax, ebx
and eax, 0000FFFFh
shr ebx, 16 
and ebx, 0000FFFFh
add ebx, eax
mov eax, ebx

This is equivalent to the x86 instruction

Sequence (2) -- direct ISA computation of eax = popcnt(ebx)
popcnt eax, ebx

Except that the former example also modifies the flags in some certain way, and modifies the ebx register, whereas the popcnt instruction modifies the flags in a different way and does not modify ebx.

We would like to prove the equivalence of sequences (1) and (2) with respect to the relationship of the resulting eax register with the original ebx register.  We must not consider the resulting value of the ebx register or the flags, for in that case, the sequences will not be equivalent in general.  The code for performing this task in Pandemic follows.

(* Define the x86 sequences *)
let hack_sequence_x86   = (* declaration of sequence (1) as X86.x86instrpref variant types *)
let popcnt_sequence_x86 = (* declaration of sequence (2) as X86.x86instrpref variant types *)

(* This function converts each sequence to IR *)
let make_ir_sequence x86l = List.concat (List.map (X86ToIR.translate_instr 0l) x86l)

(* These bindings are the IR translations *)
let hack_sequence_ir   = make_ir_sequence   hack_sequence_x86
let popcnt_sequence_ir = make_ir_sequence popcnt_sequence_x86

(* These bindings are the results of converting the IR sequences to SSA form *)
let   hack_tbl,  hack_sequence_ir_ssa = IRSSA.bb_to_ssa_state_out X86ToIRUtil.num_reserved_vars   hack_sequence_ir
let popcnt_tbl,popcnt_sequence_ir_ssa = IRSSA.bb_to_ssa_state_out X86ToIRUtil.num_reserved_vars popcnt_sequence_ir

(* The postcondition says that sequence(1).eax != sequence(2).eax *)
let hack_popcnt_postcondition = 
  IRUtil.mk_not 
   (IRUtil.mk_eq 
     (IRUtil.mk_evar (Hashtbl.find   hack_tbl X86ToIRUtil.vEax))
     (IRUtil.mk_evar (Hashtbl.find popcnt_tbl X86ToIRUtil.vEax)))

(* We query the theorem prover as to whether eax from the ends of the respective 
   sequences are equal.  We do this by asking the theorem prover to generate an
   example where they are not equal, which it is unable to do (the formula is
   unsatisfiable), and therefore they are equal on all inputs. *)
let _ = IDA.msg "%s\n" (Z3SymbolicExecute.symbolic_execute (Z3SymbolicExecute.mk_context ()) (hack_sequence_ir_ssa@popcnt_sequence_ir_ssa) hack_popcnt_postcondition)

The theorem prover cranks for 10 seconds and returns that the formula is unsatisfiable, in other words, that it was not able to generate a counterexample where sequence(1).eax != sequence(2).eax.  Assuming the soundness of Z3 with respect to propositional logic over the bitvector and array theories of finite domain, we have just generated a mathematical proof that the sequences have the same effect on the eax register.  Z3 can be configured to output the proof explicitly so that it may be checked by other tools.

Equivalence checking for verification of deobfuscation results

I had written a deobfuscation procedure (e.g., a program of the type described here) for a commercial VM ("VM" meaning virtualization obfuscator in this context), and I wanted to know whether my deobfuscation was correct, since I felt like I might've taken some shortcuts along the way.  Given access to some obfuscating transformation O, and access to a deobfuscating transformation D, we want to know if D(O(p)) is a semantics-preserving translation for all programs p.  We'll settle for random testing:  generating a "random" executable according to some guidelines, obfuscating it, deobfuscating it, and comparing (by equivalence checking) the deobfuscated program against the original, pre-obfuscated version.  As it turns out, the translation D(O(p)) is not semantics-preserving because VM itself has many bugs that could affect the translation of the original x86 into the VM bytecode. 

The procedure in the last paragraph can provide us with straight-line sequences of code (or control flow graphs) such that one is the original, and the other is the obfuscated version with deobfuscation applied.  We can then apply equivalence checking to determine whether these sequences are semantically equivalent.

It turns out that they often are not.  For example, consider this obfuscated sequence (which has been mostly deobfuscated for the sake of easy illustration):

mov cx, word ptr [esp]
add esp, 2
ror dword ptr ss:[esp], cl
pushfd

And the corresponding deobfuscated sequence:

pop cx
ror dword ptr ss:[esp], cl
pushfd

The former example has a similar effect as the latter one, but it modifies the flags before the rol instruction executes.  The rol instruction does not change the flags if cl is zero, therefore, the two sequences are not semantically equivalent if cl = 0.  The theorem prover finds this bug, the same bug for ror word ptr and ror byte ptr, and the equivalent bugs for rcr, rcl, rol, shl, shr, and sar.  This is a total of 21 buggy VM handlers.

Similarly, obfuscation can also affect the value of the flags register prior to the execution of the inc and dec instructions.  Consider this deobfuscated sequence:

pop eax
dec dword ptr ss:[esp]
pushfd

inc and dec do not change the value of the carry flag, but add and sub do.  Therefore, obfuscation applied upon the vicinity of the pop eax instruction can destroy the value of the carry flag in these circumstances.  As there are three sizes that these instructions might be applied to, there are 6 bugs of this variety.

The theorem prover also found more subtle bugs.  Consider the following deobfuscated instruction sequence, where esi points to the VM bytecode.

lodsd dword ptr ds:[esi]
sub eax, ebx
xor eax, 7134B21Ah
add eax, 2564E385h
xor ebx, eax
movzx ax, byte ptr ds:[eax]
push ax
 

The program's obfuscator would alter the behavior of this snippet by introducing writes to the stack that were not present in the original version, therefore the state of the stack after execution of the obfuscated and non-obfuscated sequences would differ.  The memory read on the second-to-last line might therefore target the area below the stack pointer, which would cause it to read a different value in the obfuscated and deobfuscated world.  This bug is unlikely to manifest itself in the obfuscation of a real-world program, although it demonstrates the ruthless efficacy of theorem proving towards this problem:  the ability to discover tricky situations like this one by considering all possible concrete behaviors of the individual snippets, and generate countermodels for inequal scenarios, no matter how far-fetched.

When taking these factors into consideration, I am able to say that my deobfuscator is correct modulo the bugs in the original obfuscator, which demonstrably number at least 33 (or about 20% of the total handlers).