RE a piece of ransomware

Came across some malware -> here is the reverse engineering process, have fun ma G.

VM setup

firstly VM setup for those interested. It's just plain QEMU on Arch with a windows 10 VM and REMnux. They're on a private network using INetSim to fake the internet.

I'm really paranoid, so I don't have shared folders, the way I load samples in is a bit schitzo but it works for me. I have a script that converts the sample into an ISO that I can then mount as a CD drive. If I wanna get something out of the VM (rare) I get it through type file > COM1, a fake serial port.

Basic info

Opening it with DIE we see straight out the gate the file is packed with UPX, its a PE32 i386 binary of 7.5KB.

I unpacked the file with UPX and we get:

A 13 KB file, no CRT or compiler signature, which would fit out Xorist assumption, which is small and usually hand written in ASM.

Strings and imports

I ran floss on it to see what strings I can find in the binary. Here we got a lovely indicator that this binary is malicous as fuck clear as day:

Lovely, we can assume that this comes from a message box where you can put in your password to decrypt your files after you pay the guy, along with some nice stuff like pussylicker(which I highly doubt) and 0p3nSOurc3 X0r157, motherfucker!

We also see some nice windows API imports:

We got everything here, CryptCreateHash, CryptDestoryHash, ShellExecute a and RegSetValueExA for persistence.

There is also (not in the screenshot) stuff like CopyFileA CreateFileA and FindResourceA and FreeResource. This makes me think that there is probably some blob in the .rsrc section that hides something, possibly some keys.

IDA: the hidden config

Let's open the file in IDA to see what we can find.

The first function called right in start uses the FindResourceA API call we talked about:

It looks inside it's own .rsrc table for type 2 RT_BITMAP ID 14.

We can see it gets a handle hResData to the binary data in the resource. Makes a copy of the pointer and moves 16-bytes into a global variable I assume is the key -> moves 16 bytes forward to the rest of the data, I assume this is some config the malware needs and is hiding it.

Then it calls a function I named decrypt_config based on what it does. Which is simple enough:

Simple xor decrypt, initializes a repeating key XOR: plain[i] = enc[i] ^ key[i % 16]

We can dump the bitmap using ResourceHacker and decrypt it with some slop python:

The output we get out:

It's the ransom note and some file extentions and some other fields.

Looking back in IDA:

We see it uses RtlMoveMemory for this data:

It contains:

  • an extention list (.bak, .db, .dbf) with a count of 102, idk yet if it's the files it targets or skips.
  • a encrypted file extention .locks
  • some 16 byte random blob
  • a flags filed 01 01 01 01 00
  • and some IDs mainly: oVRGpPL614g4PEi, OPBILKBUWSSDZCF
  • and four numbers:

start

Lets look at start:

GetTempPathA stores the temp folder path in Buffer and then the guy copies it into String. GetModuleFileNameA stores the malwars own full path in Filename sub_4017B4(cfg_key) and sub_402472 are callled with no checks, we donno what these do yet.

lstrcatA(String, key_str_1) and lstrcatA(String, aExe) build %TEMP%\oVRGpPL614g4PEi plus aExe which is '.exe'

So the malware installs a copy of itself (CopyFileA(Filename, String, 1)) to TEMP, fails if destination already exists.

and moves on to some code that calls CreateWindowExA, so if it's clicked again it opens some window, assuming some sort of window where it prompts you to put in your password to decrypt.

If it does pass, it does some timestamp trick that's weak and boring and not in scope of this writeup. (For the record: sub_402472 reads the timestamps of C:\Windows\explorer.exe and the dropped copy gets stamped with them, so it looks as old as a system file in a folder listing.)

Persistence

The interesting fn is sub_402422: which is run-key persistence. (sub_402422 is really just a generic "write a string into the registry" helper, I renamed it reg_set_string. The persistence comes from the arguments it gets called with.) The call in main is:

if (flags5 == 1)
    reg_set_string(HKEY_LOCAL_MACHINE,
                   "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
                   "Alcmeter",
                   "%TEMP%\\oVRGpPL614g4PEi.exe");

It creates or opens HKLM\SOFWARE\Microsoft\\Windows\\CurrentVersion\\Run (sic, SOFTWARE) it sets a value named Alcmeter to the path of the dropped copy, and windows runs everything under that key every logon so the ransomware reruns on every boot and login.

Interestingly, HKLM requires admin, RegCreateKeyExA will fail silently so the code doesn't check for the failure.

It also depends on that flags5 swich, for this sample it's 01 so it's on, but it seems to be on a sample2sample basis.

After it also sets up that each time you click a .locks file it also reruns the TEMP\<random_shit.exe>

After some digging

After some digging, I found this: This coupled with the number 32 which is in that config we found -> we can assume this is TEA: MONEYYYYY


The .locks file association

Back in start, sub_402342 (I named it register_locks_assoc) calls the same registry helper four times, this time under HKEY_CLASSES_ROOT. The strings it uses are ., \DefaultIcon, ,0, \shell\open\command and CRYPTED!, and the empty string means "the key's default value". The result:

  • HKCR\.locks: OPBILKBUWSSDZCF
  • HKCR\OPBILKBUWSSDZCF: CRYPTED!
  • HKCR\OPBILKBUWSSDZCF\DefaultIcon: %TEMP%\oVRGpPL614g4PEi.exe,0
  • HKCR\OPBILKBUWSSDZCF\shell\open\command: %TEMP%\oVRGpPL614g4PEi.exe

So every encrypted file shows up as type CRYPTED! and double-clicking one starts the dropped exe.

Since it already exists, the loop fails and instead opens the window which is the password prompt.

The drive loop

After the persistence stuff start does GetLogicalDrives(), which returns a bitmask (bit 0 = A:, bit 2 = C:, ...). It loops from Z: down to A:, and for every drive that exists it builds the mask X:\*.* and calls sub_4013A8.

That is the function that does the damage. I named it crypt_dir, because it walks the directory tree and encrypts (or decrypts) every file it likes.

crypt_dir

This is the main encryption function -> it works like this:

  • FindFirstFileA / FindNextFileA list the folder.
  • If an entry is a directory (and not . or ..) it appends \*.* and calls itself. So it is a recursive walk of the whole drive.
  • If it is a file, it first skips a few names: HOW TO DECRYPT FI... (the ransom note, so it doesn't encrypt its own note) and two other strings I'm too lazy to look at.
  • Then comes the extension list from the config. For every one of the 102 patterns it calls PathMatchSpecA. If one matches, the file is processed, if none matches it is skipped. So the list is a target list: *.bak, *.db, *.dbf and so on are what it goes after. That answers the "target or skip?" question from earlier.
  • If byte_40752A == 1 it also does something in every folder (sub_40103A). It's just the ransom note dropper.

The same function is used for decrypting. A mode byte (byte_406550) switches it:

  • 0: encrypt (set by start) — name.ext + .locks
  • 1: decrypt — extension stripped (Probably)

The key

The key is cfg_key, the same 16 bytes that decrypted the config. start passes it to sub_4017B4 (I named it setup_cypher_key):

It reads the key as four 32-bit words and flips the byte order of each one (_byteswap_ulong), and stores them at 0x406595. That's all.

(Remember the number 32 that sat right after these four words in memory, we'll get back to it.)

Then for every file, crypt_dir makes a small per-file key out of it:

c = first_char_of_filename;
for (i = 0; i < 16; i++) {
    file_key[i] = stored_key[i] ^ c;
    c = rol8(c, 1);                 // rotate the byte left by 1
}

So the key for report.db is slightly different from the key for notes.db, but the only thing that changes is the first letter of the file name.

TEA

Next the file is opened, and this is what happens to it:

  1. SetFilePointer(78): jump to offset 78. The first 78 bytes are never touched.
  2. ReadFile(..., 1909150): read up to ~1.9 MB from there (both numbers came out of the config).
  3. Encrypt what was read.
  4. Seek back to 78, write it back over the same spot, restore the file's old timestamps, rename to .locks.

Step 3 is two layers, a manager and a worker:

  • encrypt_buffer (sub_40177A) is the manager. It cuts the buffer into 8-byte blocks and calls encrypt_block on each one. If the size isn't a multiple of 8, the last few bytes are left alone.
  • encrypt_block (sub_4017EC) is the worker: TEA aka the tiny encryption algorithm, on one 8-byte block with the per-file key.

We know it's TEA due to the reason mentioned above but it's even confirmed, just look at the reference on wikipedia.

  • The round function matches the reference one: ((v1<<4)+k0) ^ (v1+sum) ^ ((v1>>5)+k1).
  • The loop runs until sum == delta * dword_4065A5, and that config number is 0x20. So dword_4065A5 is the round count, 32. That's the number from the config that looked random earlier.
  • decrypt_block / decrypt_buffer are the mirrored (same loop, sum going backwards).

There is also a third function, sub_401748 (xor_buffer_fallback): a plain repeating XOR with cfg_key. It runs when the fourth flag in the config is 0. In our sample that flag is 1, so TEA is used. It's another example of the builder picking options per sample so I guess this malware is targeted for specific victims?

So what ends up encrypted in a file:

bytes 0 .. 77                     untouched
bytes 78 .. 78+1.9MB              TEA, 8-byte blocks, each block alone
   (last n mod 8 bytes of that range: untouched)
everything after ~1.9MB           untouched

This also means that files smaller than 8 bytes are ignored, which is I guess on purpose, that shit aint valuable to the person anyway ig.

The window from earlier (sub_401AB9, window procedure) is a real password prompt: a text box, a main button, a small "?" button and Exit. If the third flag is set it also pops the ransom note in a message box. On the main button it:

  1. checks an attempts counter (dword_407525, starts at 5, one of the four config numbers; when it runs out some unread code runs -> probably some shit trying to scare you.
  2. hashes the typed password 5 times in a row with `sub_401F15'
  3. compares the result with the "random" 16-byte blob from the config. So that blob is just the expected password hash,
  4. match -> sub_401216 (presumably decrypt + cleanup, unread).
  5. No match -> "Password is incorrect".

so know we know what the four config numbers are: 5 = password attempts, 32 = TEA rounds, 78 = offset where encryption starts, 1,909,150 = max bytes per file.

same with the five flag bytes 01 01 01 01 00 (at 0x407529):

  • 0: HKLM Run-key persistence
  • 1: per-folder action in crypt_dir (probably drops the note)
  • 2: show the ransom note in a message box when the window opens
  • 3: TEA (1) or plain XOR (0)
  • 4: alternate window captions (0 = the default set, the one in the screenshot below)

Lets run it

Let's run the .exe to confirm the suspicions listed above. I made some .db test files filled with random shit. Took a regshot before and ran the malware.

First thing that happens is the ransom note popping up and the screen going blue, takes a while for the desktop to show up again.

Then the Regshot comparison. The .locks association from earlier, all five keys:

And the Run key, pointing at the dropped copy in the user's temp folder:

Two details here: the %TEMP% path got expanded to the real folder (C:\Users\mal\AppData\Local\Temp\oVRGpPL614g4PEi.exe), and the key landed under WOW6432Node. That's the sample being a 32-bit process on 64-bit Windows, Windows redirects its HKLM\SOFTWARE writes there. The association keys show up under HKLM\SOFTWARE\Classes, the machine-wide half of HKCR.

The password window:

Since we can see the guts of the thing, we can write a decryptor for this particular piece of malware, we know the key and we know it's TEA and the number of rounds.

  1. Take the first 16 bytes of the config resource, K (I dumped it with Resource Hacker as Bitmap14.bin).
  2. Reverse the byte order inside each 4-byte group (that's what setup_cypher_key did).
  3. For each file, XOR in the rotating first letter of the original file name (the loop above). The result is the 16-byte TEA key, read as four little-endian words.
  4. Skip 78 bytes, then TEA-decrypt in 8-byte blocks. The two halves of each block are read as big-endian, 32 rounds, sum starting at delta * 32.
  5. Write it back, remove the .locks.

The mix of big- and little-endian is the part that is kinda fucked and takes some tries, and googling (ppl wrote this decryptor before me as well -> https://www.emsisoft.com/en/ransomware-decryption/xorist/ . Here it is:

import sys, os, struct
M, D, R = 0xFFFFFFFF, 0x9E3779B9, 32

rsrc, src, dst = sys.argv[1:4]
K = open(rsrc, 'rb').read()[:16]
st = bytes(K[i // 4 * 4 + 3 - i % 4] for i in range(16))
c = ord(os.path.basename(src)[0])
fk = []
for i in range(16):
    fk.append(st[i] ^ c)
    c = ((c << 1) | (c >> 7)) & 255
k = struct.unpack('<4I', bytes(fk))

d = open(src, 'rb').read()
body = bytearray(d[78:78 + 1909150])
for i in range(0, len(body) // 8 * 8, 8):
    a, b = struct.unpack('>2I', body[i:i + 8])
    s = D * R & M
    for _ in range(R):
        b = b - (((a << 4) + k[2]) ^ (a + s) ^ ((a >> 5) + k[3])) & M
        a = a - (((b << 4) + k[0]) ^ (b + s) ^ ((b >> 5) + k[1])) & M
        s = s - D & M
    body[i:i + 8] = struct.pack('>2I', a, b)
open(dst, 'wb').write(d[:78] + body + d[78 + 1909150:])

what the sample did to Report.db:

The first 78 bytes are in plaintext, you can read two full lines and Report line 3 lorem ipsu (exactly 24 characters into line 3, byte 78), then it turns to garbage.

And after running the script on it, the original is back:

IOCs

  • Dropped file: %TEMP%\oVRGpPL614g4PEi.exe
  • Run key: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run → Alcmeter (under WOW6432Node for the 32-bit sample on 64-bit Windows)
  • File association: HKCR\.locks → OPBILKBUWSSDZCF (CRYPTED!)
  • Extension: .locks
  • Ransom: US$1500, doubling every 48 hours
  • BTC: 1Mc9xe3mjaMLz99CUjao88s65X3ydVEZbX
  • Email: frankhans@tuta.io
  • Ransom note: HOW TO DECRYPT FI... (full name not checked yet) E-mail is being tracked: https://ddanchev.blogspot.com/2022/03/profiling-currently-active-high-profile.html

():))(:::)::))))::((())::::)) GLORY TO YETTUK the y2k daemon!