DEV Community

odindev
odindev

Posted on AI-assisted

Inside Arxan, Appendix A: the file on disk, in full

This is Appendix A 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 gives the shape of the file and of its two layers. This article is the whole account, question by question, in the order the questions came up: how a file whose code is ciphertext starts at all, the cipher and its list, what the protection did to the entry point, the functions that stay encrypted after start-up, and the strings.

The file on disk

Everything above describes a process that is already running. The file that produces that process is a different object. It is 297 MB on disk against 693 MB mapped, and almost none of its code can be read.

This article starts from the shipped file and works out how it becomes the running image the main article describes, without ever running it. The method is the same as before, with one more step at the end:

  1. look at the bytes and ask the smallest question they raise;
  2. answer it by running Arxan's own code in the emulator;
  3. replace the emulation with a plain re-implementation, and check that against the memory dump.

The last step is what turns an observation into a tool. Each section below is one question, in the order the questions came up.

Two images of one build

The first step is the obvious one. Map the shipped modernwarfare.exe and the memory dump by RVA and compare them section by section.

section size entropy on disk equal to the running image
.text (game) 120.1 MB 7.991 3.67%
.rdata 5.3 MB 5.936 99.7%
.data 460.8 MB (mostly zero-fill) 0.260 n/a, written at run time
.pdata 1.5 MB 7.198 100.0%
.rsrc, .reloc, _RDATA 1.8 MB 5.5 to 7.5 100%
.text (protection) 103.9 MB 7.959 11.08%

Eight bits per byte is what random data measures. Both code sections are ciphertext, and nothing else is.

That second half of the sentence matters as much as the first. The headers, the import directory, the relocation table, the TLS directory, the exception directory and the resources are all in the clear. Windows can map this file, relocate it, bind its imports, register its unwind data and call its TLS callbacks with no help from the protection. Only the code is locked, and the loader never needs to read code.

What has to be readable

A file whose code is entirely ciphertext cannot start. So the next question is: what is the first instruction the process executes, and is it readable?

The loader calls TLS callbacks first, then the entry point. On disk the entry point is nine plaintext bytes followed by noise:

070D9224  48 83 EC 28        sub  rsp, 28h
070D9228  E8 9E ED A2 FA     call 01B07FCB
070D922D  ...                ; ciphertext
Enter fullscreen mode Exit fullscreen mode

The TLS directory lists six callbacks. Five of them begin with bytes that decode to nothing. The first begins with a jump:

00A80D10  E9 E2 67 FA 00     jmp  01A274F7
Enter fullscreen mode Exit fullscreen mode

Both of those targets are readable, and they contain the same thing: fourteen register pushes, sixteen XMM saves, a stack alignment, and then the call stub every routine is entered through. The code that unlocks the file is not special. It is ordinary Arxan routines, reached through the ordinary stub, stored in plaintext.

To see how much plaintext there is, compare the two images byte by byte and look for long runs that already agree. In the game's .text there are 233 runs of 256 bytes or more, 901 KB in total. In the protection's section there are two large islands: 4.4 MB at 0x25A8CA90, and a 4.8 MB tail from 0x290FB97A that holds, among other things, the relocation table.

How do you relocate ciphertext?

The image is built for address 0x140000000 and is loaded somewhere else. The loader fixes that by adding the difference to every address stored in the image. The relocation table lists 422,110 such places. 34,282 are inside the game's code and 251,874 are inside the protection's.

That is a problem for an encrypted file. The loader adds a number to eight bytes of ciphertext, before any decryption has run. Decrypting afterwards would give garbage at every one of those places.

Looking at the sites directly settles it. At each relocation site inside the code sections, the eight bytes on disk are a readable link-time pointer, and the bytes on either side are noise. The encryption steps around every relocation. So whatever decrypts this file must have a list of what to skip, and that list has at least 286,000 holes in it.

The count for the protection's own section is worth a second look. A quarter of a million absolute addresses is a lot for code that is otherwise position-independent. Once the code is readable the reason is plain: 99.3% of those sites are the 64-bit immediate of a movabs, the instruction one of the protection's jump idioms uses to name its targets. It appears further down this article.

Cold-starting the file

With two readable entry stubs, the file can be started in the emulator the way the loader would start it.

  • Map the disk file at its preferred base, section by section.
  • Point every import at a stub that logs the call and returns something plausible.
  • Call TLS callback 0 with the loader's arguments: the image base, DLL_PROCESS_ATTACH, and zero.

The first thing it does is ask Windows for access. GetSystemInfo once, then a VirtualQuery and a VirtualProtect for the headers and for each of the nine sections, ten pairs in all. Every one of them asks for PAGE_EXECUTE_READWRITE. That is 21 API calls, and there are no others for the rest of the callback.

Then the bytes start changing, front to back, at about 13 MB per minute of emulation. Sampling the instruction pointer shows the emulator in two small loops: a byte-by-byte copy at 0x2905BDAE, and a longer loop at 0x28584D29.

The cipher

The loop at 0x28584D29 is plaintext on disk, so it can simply be read.

mov eax,[rbp+1Ch] ; shl eax,4
mov edx,[rbp+1Ch] ; shr edx,5 ; xor eax,edx ; add eax,[rbp+1Ch]     ; ((v1<<4) ^ (v1>>5)) + v1
mov edx,[rbp+20h] ; and edx,3 ; mov rcx,[rbp] ; mov edx,[rcx+rdx*4] ; key[sum & 3]
add edx,[rbp+20h] ; xor eax,edx ; add eax,[rbp+18h] ; mov [rbp+18h],eax  ; v0 += ...
mov eax,[rbp+14h] ; add eax,[rbp+20h] ; mov [rbp+20h],eax           ; sum += delta
...                                    shr edx,0Bh ; and edx,3      ; key[(sum>>11) & 3]
add dword [rbp+24h],1 ; cmp [rbp+24h],[rbp+10h] ; jb loop           ; rounds
Enter fullscreen mode Exit fullscreen mode

Two shifts by 4 and 5, a key word chosen by the low two bits of a running sum, then the same again with bits 11 and 12. This is the XTEA block function, in the encipher direction. The round count and the constant added to the sum are arguments, and the key is behind a pointer.

Knowing the block function is not knowing the cipher. The question that decides everything is what goes into the block function and what happens to what comes out. A hook at the head of the loop and another at its tail, logging the frame for the first 600 blocks, answers it.

parameter value where it is stored
key 7B7006CF 0F833A93 A21A3354 13F7BA9F RVA 0x23BF3897, plaintext
sum increment 0x9E3779B9 immediate
rounds 64 immediate
first input block E8B9C3BC A0A8028D RVA 0x26D860DC, plaintext

The round count is twice the usual 32. The constant is the standard one.

The inputs are the surprise. Every block's input is the previous block's output. No block ever takes its input from the image. And each byte that the copy loop stores is the byte that was already at that address, XORed with the next byte of the block outputs taken in order.

So the cipher never touches the code. It enciphers its own 8-byte state over and over, and the successive states are a keystream that is XORed into the image:

S(0)   = the stored block
S(i+1) = XTEA(S(i))
plaintext = ciphertext XOR (S(1) || S(2) || S(3) || ...)
Enter fullscreen mode Exit fullscreen mode

That is output-feedback mode, and it has three consequences.

  • Encryption and decryption are the same operation. The build tool that encrypted the file and the routine that decrypts it can be the same code.
  • It is strictly sequential. Block n cannot be computed without the n − 1 before it. There is no seeking to the middle and no splitting the work across threads.
  • Position is everything. The keystream carries no trace of where it is being applied. Feed it the wrong list of addresses, or the right list in the wrong order, and every byte after the first mistake is wrong.

The first 312 bytes stored by the copy loop all followed the rule, and all 312 matched the running image.

The list

The keystream ran straight across the boundary between two separate destination ranges without restarting. So the one thing still missing is the list of ranges, in order.

The store log gives its first few entries: 16 bytes at 0x1000, then 28 at 0x7004, 28 at 0xD014, 28 at 0x13024. Those are exactly the gaps between the plaintext islands found earlier.

A checksum guard describes what it hashes as a stream of LEB128 (gap, length) pairs. If the bootstrap uses the same encoding, its list begins with 80 20 10 (gap 0x1000, length 16) followed by F4 BF 01 1C (gap 0x5FF4, length 28) repeated. Searching the file for those bytes gives one hit, at RVA 0x25A8CA90: the first byte of the 4.4 MB plaintext island in the protection's section.

Decoded from there, the list is:

  • 2,774,020 bytes long;
  • 1,324,188 ranges;
  • 208,856,213 bytes covered. That is 96.69% of the game's code section, 89.15% of the protection's, and under 22,000 bytes spread across the data sections.

It ends with a gap that moves a 32-bit cursor from the end of the last range to exactly 0xFFFFFFFF.

The most common gap is 8 bytes. Of 23,166 eight-byte gaps sampled, 21,997 sit exactly on a relocation site. That is the answer to the relocation question: every relocated pointer is a hole in the list. The list also steps over the plaintext islands, the key, the starting block, and itself.

More than a million ranges for two sections sounds excessive until the holes are counted. The code is not encrypted as a block with exceptions. It is encrypted as 1.3 million fragments that fit between the things the loader has to touch.

Decrypting without running anything

Key, starting block, round count and list are all plaintext in the file. Nothing is derived from the machine, the time, or the process. So the layer can be removed by a program that never executes a byte of the game.

That program is mwdec. It maps the file by RVA, decodes the list, and runs one XTEA keystream across all 1.3 million ranges in order: 26,107,027 blocks, in 4.1 seconds. The emulator needs about fifteen minutes for the same work.

Then comes the check: rebase the result to the dump's load address through the relocation table, and compare.

section entropy before entropy after equal to the running image before after
.text (game) 7.991 6.916 3.67% 99.05%
.text (protection) 7.959 6.743 11.08% 96.25%

Because the keystream is positional, this result is stronger than the percentages suggest. One wrong range anywhere in the list would have turned everything after it into noise. Agreement at the far end of the second section means all 1.3 million ranges are right.

What a memory dump gets wrong

That leaves 5.0 MB of code that differs, in 75,253 separate places. It is tempting to call that "still encrypted". Comparing the entropy of the two sides of each difference shows four different things instead.

  1. Zero in the dump, code in the static image. Whole pages, such as 64 KB at 0x3C0000. The static side is ordinary x64. The dumping tool could not read those pages, and the static image has them.
  2. Code in the static image, noise in the dump. For example 4,222 bytes at 0x5192A0: a normal function prologue statically, entropy 7.9 in the dump. The running process encrypted that function after start-up.
  3. Noise on both sides, but different noise. 3.2 MB in 53 runs, the largest 2.16 MB at 0x23D66DC2.
  4. Small edits. About 70,000 runs of 8 to 64 bytes, 1.3 MB in total, with code on both sides.

In the first two cases the static result is the better image of the two. A dump is a photograph of one moment in a program that keeps rewriting itself. The file, once the bootstrap layer is off, is the state every run starts from.

The last two cases are the writer routines, seen from the other side. The next sections take them in turn, after the entry point.

How the entry point is built

With the code decrypted, the entry paths can be read instead of emulated. Reading them still takes a tool, because no path is contiguous. Each one is a trail of one or two instructions at a time, scattered across both code sections and joined by jumps, and the jumps themselves are disguised.

Three idioms

Three patterns have to be undone before a path becomes a listing.

; "jmp X"
lea rsp,[rsp-8] ; mov [rsp],rbp ; lea rbp,[rip+X] ; xchg [rsp],rbp
lea rsp,[rsp+8] ; jmp [rsp-8]

; "jne B", falling through to A
push rbp ; movabs rbp,A ; xchg [rsp],rbp          ; push A
push rcx ; push rdx
mov rcx,[rsp+10h] ; movabs rdx,B ; cmovne rcx,rdx ; mov [rsp+10h],rcx
pop rdx ; pop rcx ; ret

; "call G", returning to R
push R ; push G ; ret                              ; each push built as above
Enter fullscreen mode Exit fullscreen mode

The first hides the target of a jump from anything that looks for E9 or FF 25. The second replaces a conditional branch with a conditional move between two absolute addresses, followed by a ret. A disassembler following control flow sees no branch at all.

The second idiom is also where the quarter of a million relocations come from. movabs rbp, A holds a full 64-bit address, so the loader has to fix it up, so it needs a relocation entry, so the bootstrap's range list has to step around it. Of the 251,874 relocation sites in the protection's section, 250,178 are movabs immediates.

A small layout tool starts at each TLS callback and at the entry point, follows every jump, tracks a small symbolic stack to resolve these three idioms, and folds each block of register saves or restores into one line.

The entry point is the compiler's

Here is the entry point, laid out:

070D9224  sub  rsp, 28h
070D9228  call 01B07FCB
070D922D  nop
28DDA0B6  add  rsp, 28h
28DDA0D3  jmp  070D90B0
Enter fullscreen mode Exit fullscreen mode

Anyone who has looked at an MSVC binary will recognise the shape. This is mainCRTStartup:

sub  rsp, 28h
call __security_init_cookie
add  rsp, 28h
jmp  __scrt_common_main_seh
Enter fullscreen mode Exit fullscreen mode

0x70D90B0 begins mov ecx,1 ; call … ; test al,al and then reads the CRT's startup-state global. It is __scrt_common_main_seh. So the tail of the entry point is untouched, apart from being moved into the protection's section and having its jmp rewritten in the first idiom.

The call is where the protection got in. It no longer goes to __security_init_cookie. It goes to a thunk:

01B07FCB  ; save context: 14 registers, 16 XMM
          ; align stack
031206B6  call 0043907D
          ; restore context
          ; save context, align stack
27714CFC  call 258DC3DA
          ; restore context
          ; save context, align stack
27850B16  call 285C23FC
          ; restore context
2863455F  jmp  070DD5F0
Enter fullscreen mode Exit fullscreen mode

0x70DD5F0 loads a global and compares it with 0x2B992DDFA232. That constant is MSVC's default stack cookie, and the function is __security_init_cookie, the one the call originally named.

So the protection did not write an entry point. It took the compiler's, and redirected its first call through a thunk that runs three routines and then tail-jumps to the original callee. Everything else about process start-up is stock.

This also explains the nine plaintext bytes. sub rsp,28h and the call are the only two instructions of the entry point that can execute before decryption, so they are the only two left in the clear.

The same three calls, at every way in

TLS callback 0, laid out the same way, begins with the same three calls, each in its own save and restore, and then continues into the callback's own first instruction, mov [rsp+8], rbx. Nothing tests the loader's reason code before them. The three routines are entered every time Windows calls the callback: at process attach, for every thread that starts, for every thread that ends, and at process detach. After the first time they have nothing left to do, and each returns at once without a call or a write.

The other five callbacks have nothing prefixed, and none of the six is the protection's own. An unprotected build made from nearly the same source two weeks before 1.20 has 1.20's three callbacks in the same order, sharing their constants almost one for one (136 of 139 in the first, all 17 in the third). They belong to the game and its anti-cheat: the first reads a fresh copy of ntdll.dll from disk, the others register DLL-load notifications or query memory when the process attaches, and return immediately for any other reason. What the protection did to them is what it does to any function it covers. Between 45% and 90% of each callback's instructions have been moved into the appended section (the fifth callback of 1.51.2, 43 instructions of plain compiled code, is the one left alone), their conditional jumps are written as constructs, their ret is lea rsp,[rsp+8] ; jmp [rsp-8], and the bytes the moved blocks left behind are used again for pieces of other functions: routines, call chains, debugger probes, the stores that publish a guard's value. A scan of a callback's address range finds all of those. A walk of the callback's own paths reaches none of them, and an emulated run of every callback for every reason enters no routine except the three at the front.

The loader runs TLS callbacks before the entry point, so in a normal start the callback does the work. The entry point's copy is the fallback, for a process whose first executed instruction is the entry point.

Those are not the only two copies. The executable exports 204 symbols: the NGX SDK's entry points, the C runtime's printf and scanf families that a static library brought along, and one variable, NvOptimusEnablement. Each of the 203 exported functions begins with a jump to its own copy of the three calls. With the entry point and the callback that makes 205 entries and 615 call chains, 205 for each routine. Whichever door into the image is used first, the code behind it has been decrypted by the time it runs.

Running the three routines one at a time in the emulator, on the statically decrypted image, shows what each one is.

routine API calls what it does to memory
0x43907D GetSystemInfo, then VirtualQuery and VirtualProtect for the headers and each section reads one byte and writes it back at the start of every 4 KB page: 169,353 pages
0x258DC3DA none the XTEA pass over 1,324,188 ranges
0x285C23FC none copies 667 pointers from .idata to the start of .rdata

Unlock. The first routine makes the whole image readable, writable and executable, then touches every page. Reading a byte and writing the same byte back changes nothing, but it forces each page to become a private, committed copy before the decryptor starts writing. Nothing in the start-up path puts the protections back. From here on every Arxan routine simply writes to code, which is why no writer routine ever calls VirtualProtect.

Decrypt. The second is the cipher described above.

Connect the imports. The third is the one a static decryptor would miss.

Two import tables

The file has two import address tables. The PE import directory describes one in .idata, a section the protection added. That is the table the Windows loader fills in. The original table is still at the very start of .rdata, but no directory entry mentions it and the loader never touches it.

Counting the indirect calls in the decrypted code shows that both are in use.

in the game's code through .idata (loader's) through .rdata (original)
call [rip+d] 10,015 1,226
jmp [rip+d] 338 21
distinct slots used 600 183

Nine call sites in ten were rewritten to use the new table. The rest still go through the old one. Left alone, each of those 1,226 calls would jump through a slot that holds whatever the linker put there, which is not an address.

The third routine is what keeps them working. It walks two range lists in step, one at 0x26D045AE and one at 0x23B163B3, in the same LEB128 encoding as everything else. The first list is 33 runs in .idata. The second is 32 runs of the same sizes in .rdata. Run by run, it copies the loader's pointers across: 667 of them, one run per imported DLL.

The odd run out is the protection's own. The import directory has 33 descriptors, and the last is a second KERNEL32.DLL with exactly two functions, AddVectoredExceptionHandler and RemoveVectoredExceptionHandler. The game does not import them. The debugger probes need them. They have no copy in the old table.

The protection's own section never calls an import directly. It has 3,960 places that load a pointer from .idata into a register, and none that touch the old table.

For a static image, the consequence is practical. A disassembler shown the decrypted file names the imports in .idata and leaves 1,226 call sites pointing into a table of anonymous numbers. A tool that rebuilds imports from a memory dump finds two tables holding the same pointers and has to guess which one is real. Both are. The decryptor decodes the two lists and writes out every slot of both tables with its DLL and function name.

Flags in the padding

If both the callback and the entry point call the same three routines, the second caller must not decrypt again. XORing the keystream in twice would re-encrypt the image.

Each routine keeps a flag, and keeps it somewhere that looks like nothing: CC bytes between functions. The unlock routine's flag is four CC bytes at 0x1BF4DAF, which it sets to zero when it finishes. The import routine reads one CC byte at 0x41B988 on entry and writes zero to it on the way out. A flag that is still CC means "not yet".

The emulator confirms the rest. Comparing the memory left by a complete emulated run of the callback with the output of mwdec, the two code sections differ in 25 bytes out of 224,083,968.

RVA static after the real routines what it is
0x41B988 CC 00 import routine's flag
0x1BF4DAF CC CC CC CC 00 00 00 00 unlock routine's flag
0xA8C97F, 0x1C176AE two dwords two different dwords state written by the decryptor
0x23BF3897 CF 06 70 7B 92 78 77 22 first word of the XTEA key
0x26D860DC BC C3 B9 E8 8D 02 A8 A0 18 77 80 CB 6C AA FD EF the keystream state

With those 25 bytes in place, calling each of the three routines again returns in a fraction of a second, with no API call and no write to code.

The last two rows are worth a moment. The decryptor enciphers its state in place, so when it finishes, the starting block has been replaced by the final one. mwdec ends on the same value, CB807718 EFFDAA6C, which is a second, independent check on 26 million blocks. And the decryptor overwrites the first word of its own key on the way out.

A memory dump of the running game therefore holds neither the key nor the starting block. Everything needed to decrypt the file is in the file, and after start-up it is nowhere else.

Functions that stay encrypted

After the bootstrap, 251 of the game's 29,329 code pages are still noise. They belong to 59 functions, the largest of them 454 KB. These are the functions that are decrypted on demand, and the obvious question is where their key is.

Following one dword backwards

The way to find a key is to take one decrypted value and walk back to where it came from. So: run a writer that is known to produce the function at 0x387DEC0, log every read and write, and look at the instruction that produced the first four bytes of code, 55 48 8B EC.

2583A98F  mov rax, [rbp+68h]        ; a pointer that starts at 0x2500ACF2
2583A993  mov eax, [rax]            ; e = 0x17A80096
2583A995  xor eax, [rip+...]        ; K = the dword at 0x415D1D = 0xFB2348C3
2583A99F  mov [rdx], eax            ; -> a 4-byte buffer, then memcpy to the function
2583A9A1  add qword ptr [rbp+68h], 4
Enter fullscreen mode Exit fullscreen mode

0x17A80096 ^ 0xFB2348C3 = 0xEC8B4855. That is the code.

What is missing from this listing is more interesting than what is in it. The writer never reads the function. The pointer walks through a block of data in the protection's own section, half a gigabyte of address space away from the function it is producing.

So this is not decryption in the usual sense. The noise that fills the function at rest is not transformed into code. It is thrown away. Each writer carries its own encoded copy of the bytes it will write, a stash, and overwrites the target with the decoded copy. One experiment confirms it: fill every target range with random bytes before running the writers, and the result is identical.

Four encodings

Scanning both code sections for the shape of that decode block finds every variant of it. There are four.

variant decode step notes
xor p = e ^ K 66 sites
subtract p = K - e 51 sites
autokey p = e ^ k ; k += p 45 sites; k starts as K
multiply-rotate a = rol(a, b & 31) ; p = e - a*b ; b = ~p ^ b 34 sites; a starts as K, b as K & 31

In every case e is the next dword of the stash, p is the next four bytes of output, and K is a single dword. K is not stored anywhere that looks like data. It sits in the filler bytes between two fragments of scattered code, for example D9 0F 56 2A between one jmp and the next instruction.

Where the output goes is given by a range list, in the same LEB128 encoding as the guards and the bootstrap.

So a writer is completely described by four addresses and a variant: range list, stash, key, and which of the four steps to use. None of the four depends on anything at run time.

Layers

Run one at a time, some writers still produce noise. The model is right and the key is right, and the output is not code.

The function at 0x471CCF0 shows why. Two writers are involved. The first, a subtract writer, does not write code at all. It writes 8,000 bytes into the protection's own section, at 0x25673181. The second, an autokey writer, uses exactly that address as its stash. Run the second alone and it decodes a stash that has not been prepared. Run them in order and the function appears:

0471CCF0  mov  dword ptr [rsp+8], ecx
0471CCF4  sub  rsp, 608h
0471CCFB  movsxd rax, dword ptr [rsp+610h]
0471CD03  lea  rcx, [rip+1A3C0BAEh]
0471CD0A  mov  rax, [rcx+rax*8]
Enter fullscreen mode Exit fullscreen mode

Some writers exist only to prepare another writer's stash. One of them prepares the stashes of four others at once. Working from the memory dump, the order is ten stash writers, then seventy-four code writers.

One more level, visible only from the file

Applying those 84 writers to the statically decrypted file produced 43 of the 59 functions. The other 16 stayed noise, and all 16 depend on two stashes: 2.16 MB at 0x23D66DC2 and 234 KB at 0x267730C9.

Those addresses had appeared before. They are two of the "noise on both sides, but different noise" regions left over after the bootstrap. The stash in the shipped file is not the stash in the dump.

That is a statement about time. By the moment the dump was taken, something had already rewritten those two stashes. Seen from the dump they need no preparation, and seen from the file they do. The search for what rewrote them is mechanical: take every writer on record, including the ones filed as writing noise, decode each from the static image, and keep any whose target overlaps the stash and whose output equals what the dump holds there. Exactly one writer qualifies for each stash, and both are autokey writers.

With those two run first, the count is 86 writers: 12 that prepare stashes and 74 that produce code. Up to three steps now separate the file from a function.

  1. The bootstrap keystream decrypts the feeder's stash.
  2. The feeder decodes that into the writer's stash.
  3. The writer decodes that into code.

Every step is a function of bytes in the file.

Every range has two writers

Those 86 are not all the writers there are. A function that is produced on demand is also taken away again: for every on-demand range a second routine exists, with the same range list and a stash of its own, whose output is noise. It is the same mechanism pointed the other way. Hiding a function is one more overwrite from an encoded copy, and the copy happens to be ciphertext.

So the writers come in pairs, and a memory dump shows each range in whichever state the last of the two left it. For a 454 KB function it is obvious which writer produces code. For 259 bytes scattered over seven fragments, "does this decode?" is a weak question.

The at-rest file allows a stronger one. Run every one of the 730 routines once on the statically decrypted image. For each, take the bytes it writes that differ from what the image already holds, leaving out its bookkeeping words, and measure two entropies over them: of what the routine writes, and of what is there.

the routine writes the image holds routines bytes what they are
about 8.0 bits per byte 5.6 to 6.7 75 1,101,492 re-encryptors: they turn code the image already has into noise
4.4 to 5.9 7.2 to 8.0 15 17,717 decryptors whose output the image does not have yet
7.6 to 7.8 7.5 to 7.8 7 4,928 re-encryptors of the ranges in the row above

Every other routine either writes nothing of this kind or writes what is already there. The table sorts itself: the first row is to be left alone for ever, the third row pairs off with seven of the second by range list, and the second row is fifteen writers still to apply.

A guard's list is not its writer's list

One of the fifteen is the writer of 0x387DEC0, the function whose first dword was followed backwards above. Its stash and key are known. Its range list looked known as well: nine ranges, 84,761 bytes, which is to the byte what the checksum guard for that function hashes.

Lay the decoded stash over those nine ranges and seven of them come out as code. The last two do not:

247A940F   2E 78 68 61 73 68 00 00 63 6F 6C 6C 69 73 69 6F   .xhash..collisio
25FC7169   61 69 6D 00 70 61 73 73 74 68 72 6F 75 67 68 2D   aim.passthrough-
Enter fullscreen mode Exit fullscreen mode

Text, in two places where the real routine, run in the emulator, leaves a function prologue and a register-restoring thunk. Plain text is not what a wrong key looks like. The stream is right and it is landing in the wrong place, which means a range is missing in front of it.

The protection encodes a list as LEB128 (gap, length) pairs, so a guess at the missing range can be encoded and searched for. The image holds three lists that begin with the same seven ranges. One has nine entries. The other two have ten, and the extra one sits eighth: 10,760 bytes at 0x72DAEB0, in .rdata.

With the ten-range list the last two ranges become the prologue and the thunk, and the block in .rdata becomes 619 strings: collisiontile, passthrough-if/else, j_shoulder_le, tag_ik_target_left. They are the names of animation states, and at rest they are stored as noise.

So a writer can carry data along with its function, and the guard that watches the function hashes the writer's list with the data left out. Two lists that start the same way are not copies of each other.

Reading a writer's parameters from one run

For seven of the fifteen, the only writer on record with their range list was the twin that re-encrypts, and its stash decodes to noise. Their own stash, key and variant had to come from somewhere.

They come from watching one run. Hook every read and every write of the image while the routine executes, and then:

  • the longest unbroken run of image bytes it read is the stash, whatever the access size;
  • of the dwords it read anywhere else, exactly one turns that stash into the bytes it wrote under one of the four decode steps. That dword is K, the address it was read from is where K lives, and the step that worked is the variant;
  • the ranges it wrote, encoded as a list, are found in the image by search.

Nothing here requires understanding the routine, and nothing about it is specific to this build. Pointed at a writer whose four parameters were already known, it returns the same four. For the seven: five multiply-rotate, one autokey, one xor.

Fourteen entries that are not there

Apart from the string block, what the fifteen writers produce is small: 6,957 bytes. Seventy of those bytes are the interesting ones. They are fourteen five-byte patches that sit close together in the game's code, between 0xAF8E10 and 0xAFB4A0.

At rest each of those fourteen places holds five bytes of noise. Decrypted, the five bytes are a jmp into the protection's section, and everything else the writer produces is what the jump leads to: a call chain, its return thunk, its ret gadgets, and a few instructions of game code that end in a return. Each is the entry of a small subroutine, between 258 and 892 bytes with its chain included, whose body is not in the game's code section at all and which has no record in the exception directory.

They belong to a larger family. Writers target 76 such five-byte entries in that neighbourhood, and after the bootstrap layer only 7 of them are readable. The 86 writers account for most of the rest; these fourteen need the fifteen.

The chain in front of each of the fourteen bodies runs a re-encryptor, and what it hides is not the subroutine it stands in. It hides the entry and the chain of another member of the family. Running one of them makes a different one unreadable, in all fourteen cases.

That is the most thorough hiding in the image. The entry is noise in the file, the body lives in the protection's section, nothing in the PE headers says a function is there, and the running process keeps closing the family behind itself as it goes.

With the fifteen added the table has 100 writers: 12 that prepare stashes and 88 that produce code, one of which also produces strings.

Checking it

There are two independent routes to the same 59 functions. One starts from the shipped file and uses only mwdec. The other starts from the memory dump, applies the writers there, and was itself checked against the emulated output of each writer. They agree on 883,737 of 883,737 bytes.

The fifteen writers of the last three sections have a check of their own, because the dump cannot provide one. The real routines, run in the emulator on the at-rest image, write 17,717 bytes that the image did not hold. The static model writes the same 17,717, with none missing and none extra.

Counting pages of the game's code that still measure above 7.2 bits per byte:

image noisy pages, of 29,329
shipped file 29,094
after the bootstrap layer 251
after the writers 6
memory dump of the running game 254

The static image ends with 248 fewer unreadable pages than a dump of the game that was actually running. The six that remain look the same in the dump, and no writer that was found targets them.

The 88 code writers write 3.8 MB in all, in 151,337 ranges. Less than a quarter of that is the 59 functions. The rest is small change: the tails of scattered fragments and five-byte jump patches, in the game's code and in the protection's own. That is the population of "small edits" from the comparison with the dump.

Two practical consequences follow from the stash model.

  • A byte changed inside one of these functions is not detected by its writer and does not corrupt anything. It is simply overwritten the next time the writer runs.
  • There is nothing to gain from attacking the noise in the function body. Nothing reads it.

Strings

Text is hidden in this executable in three ways. Two of them are Arxan's.

The protection's own: two pads

Arxan needs two names at run time, ntdll.dll and NtQueryInformationProcess, for the debugger probe described earlier. It stores neither.

Each place that needs a name carries two byte arrays of the same length and a length dword, all three inside a code section. The name is the XOR of the two arrays.

lea  r, [rip + padA]   ; mov [frame], r
lea  r, [rip + padB]   ; mov [frame], r
mov  r32, [rip + len]
...                    ; out[i] = padA[i] ^ padB[i]
Enter fullscreen mode Exit fullscreen mode

There are 544 pairs: 276 decode to ntdll.dll and 268 to NtQueryInformationProcess. Every site has its own pair of pads, so no two sites share a single byte even though they produce the same nine or twenty-five characters. A search for the bytes of one finds none of the others.

The pads are inside the bootstrap's ranges, so in the shipped file they are under the keystream as well. After the first layer they are plain data, and finding them is a matter of following the scattered instructions above from each candidate lea. A scan of the decrypted image does exactly that.

A table that travels with a function

The second is the block met in the previous section: 619 animation-state names, 10,760 bytes at 0x72DAEB0 in .rdata. The writer that produces the function at 0x387DEC0 produces the table in the same pass, and the routine that hides the function hides the table with it.

It is the only data the writers handle. Of everything the 88 code writers write, this block is the one range that is not code: the rest of what they put outside the two code sections is 694 bytes of the protection's own fragments, which spill into the tail of .rdata and the last page of .pdata.

The engine's: keyed blobs

The game engine has its own scheme, and it is much larger: 17,205 strings in .data.

+0x0   8 bytes   key
+0x8   3 bytes   length
+0xB   1 byte    1 = encrypted, 0 = decrypted
+0xC   length    text, each byte XORed with key[i & 7]
       1 byte    a plain zero
Enter fullscreen mode Exit fullscreen mode

Each string has an inlined getter. The first time the string is wanted, the getter XORs it in place and clears the byte at +0xB. After that it is an ordinary C string with a twelve-byte header.

Because the key travels with the blob, the shipped file alone is enough. mwdec scans .data on 8-byte boundaries for the header shape, requires the terminating zero and readable text, and counts the code that refers to each blob as a cross-check. The decryptor writes the plaintext and clears the flag, which leaves every blob in exactly the state the game itself would leave it in.

The cross-check has a pleasing detail. With only the bootstrap layer removed, about 440 of the blobs have no reference from code at all. With the writers applied, every one of the 17,205 does. The difference is 402 strings that are used only from inside the on-demand functions of the previous section: dw_match_id, noShowReport, teamsValidated, totalGameCount, winningTeamIndex. In a memory dump those strings look unused, because the code that uses them is noise. They also say something about what was thought worth the extra layer.

The dump gives a direct check here too. By the time it was taken the game had already decrypted 9,144 of these strings, and all 9,144 match the static result byte for byte. The remaining eight thousand had never been used in that run. They exist in readable form only in the static image.

Some of what turns up: armadillo initialization faillure, tact_client_create_error, Crash Report in progress..., HARDWARE\DESCRIPTION\System\CentralProcessor\0.

What is not there

Two searches came back empty, which is worth recording. There are no stack strings: 1,765 runs of immediate stores to the stack contain control-flow state values, not text. And there are no single-byte XOR loops over text among 87,070 candidate loops.

Console-variable names are a separate matter. The build replaces each name with a ten-letter code that spells a 32-bit number, and the original names are not in the file in any form. That is hashing, not encryption, and there is nothing to decrypt.

Top comments (0)