Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 30 min read

Inside Arxan, Appendix B: taking the protection out, step by step

This is Appendix B of the series "Inside Arxan in Modern Warfare (2019)". The main article is the first in the series; the list at the top links all five. The main article says what a removal has to supply and why a rou

This is Appendix B of the series "Inside Arxan in Modern Warfare (2019)". The main article is the first in the series; the list at the top links all five.

The main article says what a removal has to supply and why a routine cannot simply be skipped. This article goes through every rewrite in turn, with the count of each, what could go wrong with it, and the emulator run that shows it did not.

Taking the protection out

A decrypted file still contains all of Arxan. Every routine is there, every call chain, every disguised jump, the injected start-up path and the second import table. The last step is to remove them and export what remains.

A word on vocabulary first. This is usually called devirtualizing, but this build has no bytecode virtual machine to undo. What it has is the list in the previous sentence, and each item needs a different kind of removal.

What removal has to mean

Deleting the protection would break the program, because the program has come to depend on it in three ways.

  1. Decrypted bytes. Covered already: both layers are static.
  2. The start-up path. Two of the three start-up routines do work the program needs. One makes memory writable. One fills the second import table.
  3. Published state. A checksum guard writes its digest into a slot inside a code section before it compares, and other code reads those slots later.

Everything else is protection for its own sake: the comparisons, the debugger probes, the clocks, the repair writes.

So removal is not deletion. For the start-up path, the program needs the function the thunk was hiding, and one import table instead of two. For published state, it needs the values the guards would have written, already in place. Only then can the routines stop running.

The entry point gets its call back

The entry-layout walker already knows how to follow the entry point's call into its thunk and through the three chains. The instruction after the last chain is a jump to the function the call originally named. So the fix is to write that function's address back into the call.

site shipped restored
entry point, 0x70D9228 call 0x1B07FCB (thunk, three routines) call 0x70DD5F0 (__security_init_cookie)
TLS callback 0, 0xA80D10 jmp 0x1A274F7 (three routines, then the body) jmp 0x2776055E (the body)

Eight bytes. Nothing else in the file refers to either thunk.

One import table

The third start-up routine existed to copy 667 pointers into the old import table, for the 1,251 instructions that still use it. There are two ways to make that routine unnecessary. One is to do its copy somewhere else. The other is to make those instructions stop needing it: add the distance between an old slot and its twin in the loader's table to each instruction's displacement.

Finding the instructions takes a little care, because a four-byte pattern is not an instruction. Scanning both code sections for any 32-bit field that would land on a copied slot if it were a RIP-relative displacement gives 1,485 candidates. Each is kept only if some instruction start in the eleven bytes before it decodes to an instruction whose displacement field is exactly that field. 1,251 survive: 1,226 call, 21 jmp and 4 mov, the same count the census of both tables gave earlier. The other 234 are windows that straddle two instructions.

After those 1,251 patches nothing in the image refers to the old table, and the import directory already describes the one everything uses.

Checking the start

This much can be proven end to end in the emulator, on the exported image.

  • Entry point. Run from the entry point with hooks on the thunk and on all three start-up routines. The trace is __security_init_cookie, then __scrt_common_main_seh, and no hook fires. The API calls made on the way are GetSystemTimeAsFileTime, GetCurrentThreadId, GetCurrentProcessId and QueryPerformanceCounter, which are exactly the four calls the compiler's cookie initialisation makes.
  • TLS callback 0. Called with the loader's arguments, it arrives at its own first instruction with every argument, every non-volatile register and the stack pointer as passed.
  • Imports. Each of the 1,251 retargeted instructions is executed alone and compared with the function its original named through the old table. 1,251 of 1,251 go to the same DLL and function.

615 chains at the doors

The entry point and the callback were two of 205 entries that carry the three start-up calls. The other 203 are the exported functions, and their chains are still there.

With the image stored decrypted and one import table, none of the three routines has anything left to do. A chain around a routine that does nothing saves a set of registers and restores the same set. So each of the 615 chains is replaced by a five-byte jmp from its first instruction to the instruction after its last.

One thing does change. A chain aligns the stack with test rsp, 0Fh and undoes it with add rsp, [rsp+8], and unless it saves the flags, it leaves different flags behind than it found. Skipping it leaves the old flags. Following the code after each of the 615 exits until every status flag is either overwritten or read shows that nothing reads them: all 615 exits have dead flags.

A routine that only returns

The 730 routines spliced into game code look like the same case, and the obvious experiment is the same: write ret at a routine's entry and run the code around it.

Here is one such place, in a game function at 0x7013EBC, laid out with the idioms resolved.

07013EBC  push 25842E17 ; push 27FEF75C ; ret
27FEF75C  push 040F51A4 ; push 041011FF ; ret
041011FF  push 03FEB276 ; push 00B03667 ; ret
00B03667  ; save context: 11 registers, 16 XMM
          ; align stack
24F7F1E3  push 250A7A89 ; push 250326B2 ; ret      ; call the routine
250A7A89  ; restore context
250A7B27  ret

Three "calls" are nested around the chain before it starts, so three return addresses lie on the stack above the saved registers. After the chain restores its context it executes ret, which takes the innermost of them, 0x3FEB276.

With the routine replaced by ret, that is where the emulator ends up, 98 instructions later:

03FEB276  mov   r9, [rsp+48h]
03FEB27B  add   r9, 0E5h
03FEB282  mov   [rsp+0B0h], r9
03FEB28A  movzx eax, byte ptr [r9]

This is the middle of an unrelated function, entered with a stack that is not its own. The other two addresses are no better. 0x40F51A4 is a jmp in the middle of some other function, and 0x25842E17 is inside one of the protection's routines.

The same experiment on 60 chains spread over the 730 gives the same answer 60 times. None arrives anywhere the game function could continue.

The routine is the return

So the real routine does something the chain depends on, and it is not in any register: the chain restores those. Running the chain with the real routine and comparing the stack afterwards shows what it is. Three qwords above the chain's saved registers have changed.

slot pushed by the construct written by the routine what is there
first 0x3FEB276 0x2335316 ret
second 0x40F51A4 0x416FDBF ret
third 0x25842E17 0x26D01BE3 mov dword ptr [rsp+58h], 8, then more of the game function

The three addresses the construct pushes are decoys. The routine overwrites all three before it returns. The chain's own ret then goes to a ret, which goes to another ret, which goes to the third address, and that one is the next piece of the game function.

This holds for every one of the 730. The slots are always the three above the register save: at 0x118 + 8 ร— registers saved from the routine's own entry rsp, eight more when the alignment step pushed 0x18 instead of 0x10. The first two always hold the address of a ret, in one of two spellings, C3 or lea rsp,[rsp+8] ; jmp [rsp-8]. The third is the continuation.

So a routine in game code is not called on the way to somewhere. On its success path it is the way: the place where the function continues exists only as three writes inside the routine, and nothing in the calling construct names it. A disassembler that resolves every idiom perfectly, and then follows the constants it found, walks into a decoy. So does a patch that removes the routine or makes it return early.

It also puts the failed check in a different light. A guard that fails does not need a separate mechanism to send the program somewhere wrong. It only has to write something else into slots it was going to write anyway.

Fifty-three bytes

Since those three writes are everything the calling code needs, a routine can be replaced by a function that performs them and nothing else.

lea  rdx, [rsp+8]            ; the caller's frame, as the routine addresses it
mov  rax, [rdx+8]            ; the alignment push: 10h or 18h
shr  rax, 3
add  rax, idx                ; first slot, in qwords
lea  rcx, [rip+T2] ; mov [rdx+rax*8+10h], rcx
lea  rcx, [rip+T1] ; mov [rdx+rax*8+8],  rcx
lea  rcx, [rip+T0] ; mov [rdx+rax*8],    rcx
ret

It is 53 bytes, position independent, and fits in the routine's own first instructions. The three addresses are read out of one emulated run of each routine, by watching what it writes to the stack above its frame.

The order of the three stores is not free. Some chains save only twelve registers, and in those rax, rcx and rdx come back to the game holding whatever the routine last put in them: a slot index, the address of a ret, a stack address. To be indistinguishable from the routine, the replacement has to leave the same three leftovers, and it does only when it writes the slots in this order. 52 routines also leave a loop counter in r8, and their replacement ends with one more mov.

Each of the 730 chains was then run twice in the emulator, from the instruction that calls the routine to the continuation: once with the real routine, once with the 53 bytes. The comparison covers rip, rsp, all sixteen general registers, the flags, and the live stack. All 730 pairs end in the same state.

Values the guards leave behind

The second thing the program needs from the routines is state. A guard publishes its digest into a slot in code memory before it compares, and code elsewhere reads such slots later.

Searching both code sections for instructions that read anything a routine publishes, and discarding the instructions that the routines themselves execute, leaves very little: 55 short sequences, all of one family.

sub  rsp, 8
mov  ecx, [P]            ; a published value
add  ecx, [A]
xor  ecx, [B]
add  rsp, rcx            ; zero when P is what a clean run leaves there
add  rsp, [rsp+8]
pop  rcx

The variants end in a conditional jump or in a cmov between two addresses instead of the add rsp. All of them compute one number from a published value and two constants, and all of them are harmless only when that number is zero. They read 40 distinct values: 16 digest slots and 24 other words in code memory.

The value each one needs follows from its own constants, since (P + A) ^ B = 0 gives P = B - A. That makes a useful cross-check. For 25 of the 40 values the publisher was found and run in the emulator, either a guard or the start-up decryptor, and in 25 of 25 what it writes is exactly the value the arithmetic asks for. For the other 15 no routine that publishes them was reached, and the arithmetic is the only source.

So the published state can be stored in the file. Forty dwords, 160 bytes, written where the guards would have written them; five of them already hold the right value in the shipped image.

With those in place every input of every check is a constant, and a check with constant inputs has one outcome. Each of the 55 was emulated on the image with the values stored, from two random states, to the point where the stack is back where it began. All 55 come out the same way both times, and each is replaced by a jmp to that point.

Folding a nest

An image with 730 replacement functions in it runs without the protection, but it does not look like it. Every chain is still there, saving and restoring up to fourteen registers and sixteen XMM registers around 53 bytes that write three constants.

Those 53 bytes are simple enough to reason about without running them. The layout tool's symbolic stack already resolves push R ; push G ; ret. Give it one more rule, "this routine stores these three addresses in these three slots", and it can evaluate a whole construct from its first instruction: the nested pushes, the chain, the three writes, the chain's ret into a ret, into another ret, into the continuation. For the construct shown earlier the result is short.

; shipped
07013EBC  push 25842E17 ; push 27FEF75C ; ret      ; and everything after it

; exported
07013EBC  jmp  26D01BE3
26D01BE3  mov  dword ptr [rsp+58h], 8
26D01BEB  mov  dword ptr [rsp+44h], 0FFFFFFF8h

Three wrapped calls, a context save, a routine and a context restore fold into one direct jump to the next piece of the game function, with the stack where it started.

Often the continuation of one routine is the first instruction of another construct, and the evaluation simply carries on through it. The 731 chains in game code (one more than the routine census counted: it sits in spare room at the end of .rdata, a place the next section comes back to) group into 311 such nests, each reached at its outermost push from the game's own code. A nest runs between one and five routines before it lets the function go on: 127 run one, 85 run two, and 60 run five in a row. 309 of the nests become a single jmp. The other two are entered one level in, with one or two decoys already on the stack, and become lea rsp,[rsp+8k] ; jmp T.

A jump is not quite the same thing as the nest it replaces, and the difference has to be shown harmless before the fold is allowed.

  • Registers. The routine leaves a slot index, the address of a ret and a stack address in rax, rcx and rdx, and a chain that does not save those three hands them to the game. After a fold they hold whatever they held before. That is the same only if nothing reads them before writing them. So from each fold target the code is followed on every path until each such register is written or read. A direct call on the way does not settle it either way: the callee is entered, because a function that overwrites rcx before using it does not care what was in it. One apparent reader turned out to be nop dword ptr [rax+rax], a filler instruction whose operand is never accessed.
  • Flags. A chain that does not save the flags leaves the ones its alignment arithmetic produced. The same walk is done for each status flag.

All 311 nests pass both tests.

Then each fold was checked against the real routine, not against the 53 bytes. The emulator runs the shipped construct from its first instruction, with the protection's routine executing in full, until it reaches the fold's target. The exported image only has to execute one jmp to get there. The two are compared on rip, rsp and every register that is live at the target. The final export has 309 of the folds (two nests go back to their shipped form, for a reason a later section gives). All 309 end equal.

They did not all get there in one pass. In the first, 260 were equal and 49 gave nothing to compare: the real routine ended in an illegal instruction, a breakpoint or a bad read before it reached the target, or was still running after ninety seconds. An illegal instruction and a breakpoint are two of the six debugger probes, and the timestamp decides which probe a routine runs. Run again from a new random state with a different pinned timestamp, 47 of the 49 reached the target at the first try. The last two only needed time: one takes 167 seconds of emulation to get through its routines, the other 87.

Straightening the jumps

The three idioms that had to be resolved to read the entry point are everywhere, and for an exported image they have to be resolved and written back.

That needs a definition of where code is. The walk that supplies it starts from everything the file itself calls an entry: the 127,967 records of the exception directory, 56,756 relocated pointers in the data sections that point into code, the entry point, the six TLS callbacks, the 203 exports, the unwind handlers and __except filters. From there it follows every direct branch, resolves every idiom into the branch it stands for, and follows that too.

Two things nearly hid a large part of the code from it.

The first is that code is not only in the code sections. 143 branches from walked code land in the last pages of .rdata, between the end of the data and the end of the section, on instructions that look like everything else the protection writes. There is a little more after the end of the exception table in .pdata. Those pages are walked and rewritten like the rest.

The second is the compiler's switch. MSVC dispatches a dense switch through a table of offsets:

lea  rdx, [__ImageBase]
mov  ecx, [rdx+rax*4+table]
add  rcx, rdx
jmp  rcx

A walker recognises this and reads the table to find the cases. In this build the last instruction is not jmp rcx. It is

mov  [rsp-8], rcx
lea  rsp, [rsp-8]
lea  rsp, [rsp+8]
jmp  [rsp-8]

which pushes rcx, pops nothing, and jumps to what it pushed. A walk that treats jmp [rsp-8] as an unknown destination stops there and never sees a single case of the switch. Reading those four instructions as jmp rcx brought 4,520 jump tables and every block behind them into the walk, about 25,000 idioms that had been invisible.

In the code the walk reaches there are 184,254 disguised branches: 106,468 conditional, 77,685 unconditional, 99 calls and the 2 partial nests. Each is replaced at its first instruction by what it means.

idiom replacement bytes
jmp X jmp X 5
jcc B, else A jcc B ; jmp A 11
call G, return to R call G ; jmp R 10

The tail of the entry point is the smallest example. Twenty-nine bytes in six instructions become five bytes in one:

; shipped
28DDA0BA  lea  rsp, [rsp-8]
28DDA0BF  mov  [rsp], rbp
28DDA0C3  lea  rbp, [rip-21D0101Ah]      ; 070D90B0
28DDA0CA  xchg [rsp], rbp
28DDA0CE  lea  rsp, [rsp+8]
28DDA0D3  jmp  [rsp-8]

; exported
28DDA0BA  jmp  27854BC6

The exported target is not 0x70D90B0, because 0x70D90B0 is itself only a jmp: the protection moved the body of __scrt_common_main_seh into its own section and left a jump behind. Every rewritten branch is followed through such joining jumps to the first instruction that does something.

The replacement has to fit where the idiom was, and an idiom is rarely in one place. Its instructions are spread over several chunks joined by jmp rel32, and the first chunk is often a single instruction and its joining jump: ten bytes, one short of a conditional branch and its fall-through. In 5,983 cases the first chunk gets a plain jmp to a longer chunk of the same idiom, and the real branch is written there.

It also has to be safe to overwrite. A chunk may be rewritten only if nothing else enters it: no branch from live code into its interior, no lea or movabs of an address inside it, and no exception record that starts in the middle of it. A branch to the idiom's first byte is fine, since whoever arrives there gets the replacement. 62 idioms fail this test and 7 have no chunk with eleven free bytes. Those 69 stay as they are. They still work, because nothing they need is removed.

Whether a conditional idiom can become a jcc at its first instruction depends on the flags surviving from there to the cmov that used to read them. They do. Everything the idiom executes in between is push, mov, lea, movabs or xchg, and none of those writes a flag.

One piece of bookkeeping is easy to miss. Every movabs in a conditional idiom carried a 64-bit address, so every one has an entry in the relocation table. If the instruction goes and its entry stays, the loader adds the load offset to eight bytes in the middle of whatever is there now. So each rewrite also deletes the relocation entries under it: 164,289 of the 422,110 the file started with.

The proof is the same kind as before. A rewritten idiom is run in the emulator from its first instruction to its target, in the decrypted image and in the patched one, from random register states, both ways for a conditional. Idioms that are byte-for-byte the same shape share one proof, so the runs cover one idiom of every shape and a random sample of the rest: 1,605 shapes, 4,585 idioms, 42,717 runs. All end in the same state.

One instruction, written as two

With the branches rewritten, jmp [rsp-8] should have disappeared from live code. Nearly 7,000 were still there, and grouping them by the instructions in front showed why. They are not branches. They are compiler epilogues in which every stack instruction has been written as a pair.

written as means in live code
lea rsp,[rsp-8] ; mov [rsp],r or mov [rsp-8],r ; lea rsp,[rsp-8] push r 52,085
mov r,[rsp] ; lea rsp,[rsp+8] or lea rsp,[rsp+8] ; mov r,[rsp-8] pop r 54,751
lea rsp,[rsp+8] ; jmp [rsp-8] ret 6,755
push r, then the ret pair jmp r 100

The two halves of a pair are often in different chunks, with a joining jump between them:

; shipped                                  ; exported
0041AA1F  lea  rsp, [rsp-8]                0041AA1F  push rdi
0041AA24  jmp  290B0D5F                    0041AA20  jmp  290B0D63
290B0D5F  mov  [rsp], rdi
290B0D63  ...                              290B0D63  ...

The one-instruction form is written over the first half, the joining jump is moved up behind it and pointed past the second half, and the freed bytes become filler. A pair is only taken when both halves are instructions the walk reached, nothing else enters the second half or the bytes between, and neither half belongs to an idiom. 18 pairs fail that and are left.

The proof runs the shipped pair and its replacement from the same random state and compares everything afterwards: one pair of every distinct byte shape and a random sample of the rest, 24,610 in all, with no difference.

None of these change what the program does, and they are not the protection's logic. But they are the protection's handwriting, and close to 114,000 of them are most of the reason a function in this build is hard to read.

Where the walk ends

Every plan so far rests on one definition: code is what the walk reaches. An inventory of the game's .text after the rewrite shows where that definition runs out. 6,996,602 bytes there are neither reached by the walk nor touched by a plan, and 3,645 jmp [rsp-8] sequences are among them. Decoded from the right offsets, part of it is ordinary code.

Grouping the 3,645 by the exception record around them gives the reason. 2,980 lie in 27 records that each have a jmp through a register among their walked instructions, and 1,912 of those are in a single record of 2.6 MB. The file has eight exception records larger than 1.8 MB, and the largest covers 8,034,120 bytes. These belong to the game's anti-cheat, which carries an obfuscation of its own: its blocks end in a register jump whose destination is computed at run time. A walk follows direct branches, idioms and jump tables. It does not follow a computed jump, and resolving those is outside the scope of this post. So the walk enters such a function, takes the blocks it can name, and stops.

Arxan did not stop there. It treated this code like any other. Its idioms run all through it, and pieces of it were moved into the protection's section and joined to the rest with the usual jmp rel32. That is why the edge matters for removal:

  • "Not reached" cannot be read as "dead". A wipe of everything the walk missed in the protection's section would take pieces of these functions with it.
  • A rewrite is safe only when every way into the rewritten bytes is known. Here some of the ways in cannot be seen.

So the code behind the computed jumps has to be found without walking to it, and the file's layout offers a way. A compiler emits blocks back to back, so the byte after an instruction that never falls through (jmp, ret, int3) is where the next block would begin. Every such byte that the walk did not reach, inside an exception record whose first instruction is live, is a candidate. One block is decoded from it, up to its terminator, and accepted when two things hold.

  • Every instruction is one a compiler writes for user-mode code: no in or out, no far return, no 32-bit stack pointer, no segment override, no operand that points outside the image.
  • The block ends at a terminator inside the unwalked run, or exactly on the start of an instruction the walk already has.

An accepted block ends somewhere, and the byte after its end is a new candidate, so the sweep repeats until a round adds nothing. That took 39 rounds. 944,961 candidate blocks were decoded and 345,249 accepted: 264,600 run onto an instruction the walk already had, and 80,649 end at a terminator. Of the gaps still left at the end, 370,555 decode across the boundary of a walked instruction, 191,896 are padding, 83,079 do not decode, and 57,354 contain an in or an out.

Passing those tests makes a block plausible. It does not make it code, and it says nothing about who jumps into its middle. So accepted blocks are not rewritten. They become the roots of a second walk with a different rule, keep: everything it reaches stays byte for byte.

  • No patch is planned in it.
  • Nothing it executes, reads or branches to is wiped.
  • A patch that was already planned over a byte it walks is taken back.
  • Where it calls one of the protection's routines, the routine keeps its 53-byte replacement, since the code around the call still depends on the three writes.

The keep walk covers 8,869,443 bytes and 1,491,036 instructions: 2,272,981 bytes in the game's .text and the rest in the protection's section. 797 planned patches gave way to it, which returned 641 disguised branches, 101 stack pairs and two of the 311 nests to their shipped form. So the export has 309 folded nests and 183,544 rewritten branches.

One more check closes the gap between "accepted" and "everything". The sweep rejects a block that does not end cleanly even when all its instructions pass, and such a block could still be code. So after the plans are final, every block still unwalked in a live record that passes the instruction test is scanned for a branch or a RIP-relative reference that lands on a byte about to be wiped. 202,704 blocks were scanned and 120,376 pass the test. Where one of them pointed into a wipe, its target was kept and the plans made again, until none did. 43 such targets do not decode as instructions at all, and each of those keeps the fifteen bytes an instruction there could occupy.

The price is stated in the keep walk's own numbers. Inside it, exactly as shipped, are 60,869 disguised branches, 59,790 stack pairs and 344 routine call sites. The protection's handwriting stays in the code the walk could not prove it understood.

The exported file

A plan changes bytes inside sections. The file around them has to follow, and the exporter does that part itself after the last plan is applied.

  • Relocations. An entry whose eight bytes were patched or wiped is turned into a padding entry, which the loader skips. An entry whose bytes no longer hold an address inside the image goes the same way. What is left is checked: every remaining entry still points at a value inside the image.
  • The exception directory. A record whose whole range was wiped is removed and the table closed up. A record that begins in the middle of something rewritten but still covers live code is left alone. The shipped table is not clean to begin with: 433 of its 127,967 records begin inside an instruction or inside one of the protection's own sequences, and about 20,000 more begin on one of its chunks. The protection laid its code over space that still had function records and never tidied the table.
  • Imports. The protection has an import descriptor of its own, a second KERNEL32.DLL with two functions, AddVectoredExceptionHandler and RemoveVectoredExceptionHandler. Its debugger probes use them and nothing else does. The descriptor is removed once no instruction left in the file loads either slot. In this export that condition is not met, for a reason the last section gives, and the descriptor stays.
  • Signature and checksum. The certificate table is cleared, since the signature cannot match any more, and the PE checksum is recomputed.

Section protections are a separate question. The first start-up routine used to make every section writable and executable, and it is gone. An option of the export writes the same thing into the section headers instead. Whether anything left in the image still needs it is not something an emulator can answer, because an emulator has no page protections unless they are modelled, so the option exists and the comparison below does not depend on it.

Checking the whole

Each kind of rewrite was proven on its own, in isolation. That leaves the question of whether the pieces fit: whether a function in the exported image, run from its entry, does what the same function does in the protected one.

The comparison needs a reference that still has its protection, running. That is the decrypted image in the emulator with every routine executing, the start-up state as a cold start leaves it, the second import table filled, and each checksum guard held on its success path by the method of the main article: the expected digest is substituted for the computed one at the moment of publication. The candidate is the exported file, run as it is.

What a function does, as far as the rest of the world can tell, is the sequence of calls it makes to Windows and the state it leaves. So both sides are stopped at every import call and the function, its four register arguments, the stack pointer and the eight non-volatile registers are recorded. Calls the reference makes while one of the protection's routines is on its stack are left out, because the candidate has no routines. The two sequences must be equal. When both runs end the same way, the return value, the non-volatile registers, every changed page of every data section, the argument buffers and the heap must be equal too.

Four details of the reference turned out to say something about the protection.

  • A path that starts in the middle of the program's life meets checks before guards. A check adds (P + A) ^ B to the stack pointer. If the guard that publishes P has not run on this path, P still has its at-rest value and the reference walks off into an address like 0xE094DA97CC. In the real program the guard ran long before. So the reference gets the same 40 published values the export has.
  • A routine has returned when its chain's return address executes, not when the stack says so. The game can be in a deeper frame than the routine's was by the time it next calls Windows.
  • An exception record is not always a function. Some records begin three bytes into a mov, or at the third instruction of a disguised jump. Entered there, the shipped code and the export differ, and nothing can enter there. Only records whose first byte the walk reached as the start of an instruction count as entries.
  • A probe's random number has to be pinned where it is made. The same function, run alone in the reference six times, returned three times and stopped at an int 2Dh probe the other three, with every 0F 31 in the image pinned. Two instruction traces of it are identical for 568 instructions and differ at the next one, which is the probe bundle assembling its rdtsc:
  25854E37  lea  rdx, [rip+11D1F23h]       ; 26A26D61
  25854E3E  mov  eax, [rip-23C3D778h]
  25854E44  xor  eax, [rip-23CE1C47h]      ; eax = 310F9090
  25854E4A  mov  [rdx], eax
  25854E4C  jmp  26A26D61
  26A26D61  nop ; nop ; rdtsc              ; at rest: lea rdx, [rsp]
  26A26D65  jmp  273F0874
  273F0874  mov  [rbp+130h], eax

In the file those four bytes are a harmless lea, so a scan of the image for the opcode does not find them, and the timestamp that picks the probe came from the host. The reference now watches writes into code for the opcode and pins those as well. Two of the six probes raise an exception that this emulator does not deliver. A function whose reference ends at one of them is run again with the next of a fixed list of timestamp values, on both sides.

Pinning them had one more consequence. The game has a timer base in .data, set by the first caller from an rdtsc of its own. Once the protection's reads moved the same counter, two functions ended with a different word there: the reference's routines had used up one or two ticks before the game looked, and the export has no routines. So reads made while a routine is on the stack draw from a counter of their own.

One function shows what the filter on routine calls hides. At 0x5FB33E0 both sides make one call of their own, GetLastError. The reference makes seven more while routines are on its stack:

LoadLibraryA  GetProcAddress  GetCurrentProcess  NtQueryInformationProcess
FreeLibrary   AddVectoredExceptionHandler        CloseHandle

That is one of the debugger-probe bundles, running in the middle of a game function. The export makes none of those calls and ends in the same state.

The results on the final export:

functions run how many equal no verdict different
the entry path 1 1 0 0
every function that reaches a routine call site, a folded nest or a folded check 170 161 9 0
a random sample of function entries 3,000 2,987 13 0
a second sample, with arguments full of pointers 3,000 2,940 60 0

Every "no verdict" is the reference running out of time, 20 seconds for the first group and 6 for the samples: a routine in the middle of hashing megabytes of code is slow in an emulator. In the 170 targeted functions the reference ran 498 routine calls that the export does without, and seven of those functions needed a second timestamp value to get past a probe. 1,111 of the 6,089 equal runs went all the way to the function's return. The rest stopped at the same instruction in the same state on both sides, usually at a pointer the invented arguments could not satisfy.

That last sentence is the limit of the whole comparison. An emulator with invented arguments walks the first stretch of a function and seldom its depths, and it never follows a computed jump the way the running game would. What the table says is that no path it could take tells the two images apart.

What is left

The exported image is not free of the protection's bytes, and the numbers say how far it is.

72,268,708 bytes are filled with int3, in 236,561 ranges. The relocation table goes from 422,110 entries to 208,359. The protection's section is 103,949,312 bytes, and its entropy tells the story in three numbers: 7.96 bits per byte as shipped, 6.71 decrypted, 2.48 exported. 32,063,205 of its bytes still hold something. What those 32 MB are, by the first reason that keeps each byte:

kept because bytes
the walk reaches it as code 16,905,826
the keep walk reaches it 6,613,731
it is a rewritten instruction 5,835,709
a live instruction reads it as data 1,503,125
it is the relocation table, which the protection keeps in its own section 941,946
only exception records that begin on protection code reach it 114,493
a routine writes there 109,001
an unwalked block that looks like code points at it 38,788
other 586

The first row is the largest and the least certain. Part of it is game code that the protection moved, like the body of __scrt_common_main_seh. But a walk that follows every direct branch also follows the ones that are never taken, and some of what it reaches cannot be code. Among 27 million instruction starts in the walked set, 31,765 have a RIP-relative operand that points outside the image, 5,019 branch directly into bytes that are not code, and 87,683 overlap another instruction. Walking again and refusing to pass any instruction of the first two kinds loses 941,177 bytes of that first row, 5.6%. Refusing overlapping starts as well loses 8.0%. The rest shows none of the three symptoms, which is not proof that it is real.

The second row has a similar caveat from the other side. The direct-flow closure of the 734 routine entries is 3.7 MB, and 45% of what the keep walk holds in the protection's section lies inside it. So the keep walk does not only hold the anti-cheat's blocks. It also holds routine bodies that those blocks, or the bytes taken for them, lead into, and it cannot tell which of the two it is looking at.

What a reader of the file will still meet:

in code the walk reaches in the whole file
routine call sites 1 426
jmp [rsp-8] 598 55,304
instructions that load the protection's two import slots 10 1,308
4 KB code pages above 7.2 bits per byte 97

The one call site in walked code, 0x28630C77, hangs on an exception record at 0x708AE0D whose first instructions are the protection's own. Most of the 598 are tails of the branches the keep rule returned to their shipped form. Nearly all of the rest of the right-hand column is in code the keep walk holds.

The third row decides one thing about the file. Because 1,308 instructions still load AddVectoredExceptionHandler or RemoveVectoredExceptionHandler through the protection's second KERNEL32.DLL descriptor, the descriptor stays. Those instructions are the debugger probes. Whether any path the game takes still reaches one of them is a question about computed jumps, and the walk has no answer.

Three assumptions are not proven by anything here.

  • Data extents. A byte range is kept as data when a live instruction refers to it. A read with a stated operand size keeps that many bytes. An address that is taken keeps up to the next address taken, the next code byte, or 64 KB. About 8.3 MB of the protection's section is wiped on the strength of that rule and would have been kept by a looser one.
  • Targets that are not instructions. 43 direct branches go to bytes that do not decode, 41 of them from walked code. Fifteen bytes are kept at each, on the reading that such a branch is never taken.
  • Page protections. The emulator has none. 378 instructions in walked code store to an address inside a code section. Some are plainly misdecoded bytes, but I did not establish that for all of them, and unless the export marks them writable those sections are read-only in a real process.
๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.