Enter Sandbox – part 15: rE[mn]u[mn]eration games

November 24, 2017 in Reversing, Sandboxing

Observing a malware is one thing. Observing the very same malware in a rich context is another.

The traditional approach to sandboxes focuses on scoring the sample’s badness, extracting IOCs, and not focusing that much on the in-depth analysis. It’s understandable, because in-depth analysis are not the ultimate goal. It’s actually getting better – the competition is slowly changing the landscape and newer sandboxes support memory dumping, PE file rebuilding, show nice process / thread trees, various graphs, etc… and place more and more hooks in place. Still, even if they intercept the most popular APIs, inline functions, or even intercept virtual tables, it may still not be enough.

I thought, what would happen if I intercepted not only the most popular APIs that are used by malware, but also these that are less-frequently looked at – and in particular, these that may help to understand a flow of events in a better context – enriching the data that sandbox presents and making the in-depth analysis easier.

What are these APIs?

Let me show you an example…

Imagine you intercept the function CreateToolhelp32Snapshot to take a note of the fact that the malware is enumerating processes. This may add to the ‘badness’ weight, but on its own is not a malicious feature per se. Lots of ‘clean’ processes do it.

What if we not only did that, but also intercepted Process32First and Process32Next?

This could be the result (output is simplified to demo the idea):

Process32First: [System Process]
Process32Next: System
Process32Next: smss.exe
Process32Next: csrss.exe
Process32Next: winlogon.exe
Process32Next: services.exe
Process32Next: lsass.exe
Process32Next: svchost.exe
Process32Next: svchost.exe
Process32Next: svchost.exe
Process32Next: svchost.exe
Process32Next: svchost.exe
Process32Next: spoolsv.exe
Process32Next: explorer.exe
Opens Process: %WINDOWS%\explorer.exe
VirtualAllocEx: %WINDOWS%\explorer.exe
NtWriteVirtualMemory: %WINDOWS%\explorer.exe
VirtualAllocEx: %WINDOWS%\explorer.exe
NtWriteVirtualMemory: %WINDOWS%\explorer.exe
VirtualAllocEx: %WINDOWS%\explorer.exe
NtWriteVirtualMemory: %WINDOWS%\explorer.exe
VirtualAllocEx: %WINDOWS%\explorer.exe
NtWriteVirtualMemory: %WINDOWS%\explorer.exe
VirtualAllocEx: %WINDOWS%\explorer.exe
NtWriteVirtualMemory: %WINDOWS%\explorer.exe
CreateRemoteThread: %WINDOWS%\explorer.exe
NtResumeThread: %WINDOWS%\explorer.exe

Analysing a log like this tells you straight away that the malware is enumerating processes and when it finds explorer.exe, it injects a bunch of buffers into it (possibly mapping sections of the PE payload?), and then creates a remote thread. As a result, the explorer.exe process now is hosting malicious payload.

While the code injection into explorer.exe can be deducted from manual dynamic analysis, or may be even obviously apparent when we are evaluating the process tree generated by a sandbox, there is a subtle difference. The context these 2 additional intercepted APIs provide allows to be quite certain that the malware is actually quite specifically looking for the explorer.exe, and not for the other process. It also tells us HOW the process is found.

And mind you, this is actually not a trivial question if you are doing in-depth malware analysis.

There are cases where this determination is very important and having an ability to quickly determine if we are missing some target process on the test system can save us a lot of time spent on mundane manual analysis. This is actually one of the first questions your customer will ask you, especially when it comes to targeted attacks. And if you miss it, you may actually bring the whole analysis down. This is a very responsible job to deliver the results and not to miss stuff! When you look at malware that is highly targeted, f.ex. malware that is targeting Point of Sale systems running it through the sandbox may _not_ give you any results, because you either won’t see the process enumeration at all, or may miss the name of the process that the malware is looking for. The malware will look ‘broken’ to us. I can’t count how many times I wasted time on manual analysis and even incorrectly concluded that this is the case while looking at heavily obfuscated, or bloatwarish malware samples. It is really helpful to be able to cheat a bit.

For the case of the process enumeration one can not only intercept the Process32First and Process32Next functions, but also enhance the results with the interception of string comparison functions.

If we get lucky, the result could look like this:

Process32First: [System Process]
lstrcmpiA ([System Process], explorer.exe)
Process32Next: System
lstrcmpiA (System, explorer.exe)
Process32Next: smss.exe
lstrcmpiA (smss.exe, explorer.exe)
Process32Next: csrss.exe
lstrcmpiA (csrss.exe, explorer.exe)
Process32Next: winlogon.exe
lstrcmpiA (winlogon.exe, explorer.exe)
Process32Next: services.exe
lstrcmpiA (services.exe, explorer.exe)
Process32Next: lsass.exe
lstrcmpiA (lsass.exe, explorer.exe)
Process32Next: vmacthlp.exe
lstrcmpiA (vmacthlp.exe, explorer.exe)
Process32Next: svchost.exe
lstrcmpiA (svchost.exe, explorer.exe)
Process32Next: svchost.exe
lstrcmpiA (svchost.exe, explorer.exe)
Process32Next: svchost.exe
lstrcmpiA (svchost.exe, explorer.exe)
Process32Next: svchost.exe
lstrcmpiA (svchost.exe, explorer.exe)
Process32Next: svchost.exe
lstrcmpiA (svchost.exe, explorer.exe)
Process32Next: spoolsv.exe
lstrcmpiA (spoolsv.exe, explorer.exe)
Process32Next: PERSFW.exe
lstrcmpiA (PERSFW.exe, explorer.exe)
Process32Next: explorer.exe
lstrcmpiA (explorer.exe, explorer.exe)

In-depth malware analysis is supereasy, isn’t?

I think there is a potential market for supporting in-depth malware analysis with sandbox technology. Make the interception configurable (offer a list of APIs to monitor, allow time to run to be selected manually, rebuild files, perhaps give access to the analysis box, etc.).

Reverse Yks is the limit.

And while I do commercial in-depth analysis and I may be shooting myself in a foot here, I can’t stress enough how important ROI is for both you and the customer.

Reusigned Binaries – Living off the signed land

November 10, 2017 in Anti-*, Anti-Forensics, Compromise Detection, Forensic Analysis, Incident Response, Living off the land, Reusigned Binaries

Lots of research that concentrates on living off the land techniques focuses on finding legitimate OS binaries (both EXE and DLLs) that allow to:

  • load unsigned DLLs by the signed EXE files,
  • load code in an unexpected, unconventional way using phantom DLLs, sideloaded DLLs,
  • use native OS tools and abuse their functionality to download and upload files, maintain persistence, convert data, etc.,
  • break the process tree, and
  • many more.

Here, I propose to take it to a possible next, or at least parallel level.

If you are familiar with the ROP gadgets you know that it relies on re-using pieces of code belonging to loaded libraries already present in memory. These are used to chain together code blocks that may execute code of attackers’ choice. By its sole nature ROP is a complex beast and while it can be, and is now fully automated, it most of the time relies on the fact that the final piece of code is just a regular payload that the ROP chain transfer the control to…

I was wondering if it would be possible to re-use the ROP idea on a file-system level and build a library of high-level gadget-like signed executables and DLLs that could deliver the payload-like functionality, or at least its core building blocks. That would not only reduce the need to write the actual payload code – it would basically transfer the responsibility for the core functionality required by the attackers to signed libraries!

If it sounds weird, or complicated, let’s think for a second about existing installers. They implement and provide functionality that every single piece of malware needs: spawn processes, read file, write files, copying, downloading, uploading, same with the Registry operations, and more.

The installers have been abused by malware for a very long time, so it’s just a trivial example. I was thinking of something a little bit more refined and stealthy. Consider an example like this: a malicious document executes a macro; the macro drops a clean, signed executable produced by a well-known company – a file that not a single security solution can detect as malicious. It then instruments that signed executable to do all the dirty work. The chances are high that it would possibly bypass antivirus solutions, EDR, sandboxes and who knows, maybe even the Holy Grail – the whitelisting solutions.

Now that I formulated the idea in my head it was time to do some legwork…

I kicked off a number of searches within my files repository. After some poking around, eyeballing some code, a number of failed attempts I finally got lucky and hit the jackpot. To my surprise, I found a number of really interesting potentials!

The first interesting reusigned binary I came across is described below.

The nvuhda.exe and nvuhda6.exe are NVIDIA Uninstallers for 32- and 64-bit. When you execute them from a command line you will see the following screen:

The list of commands is shown below:

  • AddUninstall, Call, CheckPath, CheckRAID, ClassSweep, Copy, CopyV, CreateDevice, CreateShortcut, Del, DelBoot, DelBootQuiet, DelIniIfMatched, DelOemInfs, DelReg, DelRegE, DirAndApply, Echo, EnumDevices, EnumRegCmd, EnumRegNamesCmd, Eval, FindOEMInf, GetDrivePort, GetFolderPath, GetInfGUID, GetReg, Help, If, InstallDriver, InstallDriverEx, KillApp, RemoveDevice, Run, RunOnce, SendMessage, Set, SetEnv, SetReg, Sleep, Splash, StartLogging, StopLogging, SysCallAndWait, System, UnifyUninst, Uninstall, UnInstallEx, UninstallGUI, UninstallService, WaitOnRegDel

Hmm some of them look really interesting.

Using the ‘Help’ command we can retrieve more information about the commands:


We can run a few tests:

  • nvuhda6.exe System calc.exe
    • spawns the Calculator
  • nvuhda6.exe Copy test.txt,test-2.txt
    • copies ‘test.txt’ to ‘test-2.txt’
  • nvuhda6.exe SetReg HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\malware=malware.exe
    • adds a persistence key
  • nvuhda6.exe CreateShortcut test.lnk,"Test","c:\windows\system32\calc.exe","","c:\windows\system32"
    • creates a shortcut file ‘test.lnk’ pointing to calculator
  • nvuhda6.exe KillApp calculator.exe
    • kills the instances of ‘calculator.exe’ process
  • and so on and and so forth, and finally
  • nvuhda6.exe Run foo
    • will run commands from the file ‘foo’ (where commands are from the list above; it’s basically an install script)

It’s pretty much a Swiss-Army tool for doing a lot of legitimate operations on the system, but it could be certainly abused. The only issue is the UAC, because the file required Admin privileges in its manifest.

And… last, but not least – here’s the full list of commands:

  • Help
    Command Name
    If <Command Name> is provided displayes syntax and description of that command otherwise displays all the avilable commands
  • System
    Executes the given system command (returns immidiately)
  • SysCallAndWait
    Exact path to App + arguments
    call and wait untill app is done.
  • Set
    Defines the variable if not defined and Sets the its value to the given value.
  • Call
    Section Name
    runs all the commands in that section and returnd and continues executing commands after that line
  • Run
    Path to an NVU File
    Executes all the commands in that file and returns
  • RunOnce
    Path to an NVU File
    Run all the commands in this file and delete the file
  • DirAndApply
    A dir will be applied to the given path and for each file found it sets variable {current file} to that file and calls the given command.
  • If
    [!]Exp1}[=%]{Exp2} then {Command}
    Executes command if Exp1 is the same as Exp2 for = or Exp1 has Exp2 for % if ! is added to the beging of Exp1 it will negate the result
  • Eval
    reEvaluates the given command and executes it
  • StartLogging
    Opens the given log files ad Logs all the commands in the given file
  • StopLogging
    Stops logging close the file
  • Sleep
    Waits for a number of miliseconds passed before executing the next command
  • Splash
    {milisconds}, {BitmapPath}
    Shows the given bitmap for the given time number on the screen
  • WaitOnRegDel
    Allows waiting for a specific registry key or value to be deleted
  • FindOEMInf
    {Variable} , INF name
    Looks under the windows INF directory for additional NVIDIA display driver infs (oem*.inf). Returns TRUE if found.
  • CheckPath
    {Variable} = Local Path
    Returns TRUE if path exists.
  • Uninstall
    {NVU File}, {Uninstall Reg key}
    Runs the given file and deletes it. It also removes the given key from Add/Remove Program list
  • UnInstallEx
    Uninstall Display Reg key
    Uninstalls the given product from add remove programs. If it detects uninstall as its nvu it uses internal uninstall command otherwise calls the appropriate uninstall command.
  • AddUninstall
    {Uninstall File} , {Display Name}
    Adds Display name as the title to in Add/Remove programs list and copies uninstall binary and script file to windows system directory
  • DelBoot
    Path to files to be deleted on reboot
    Put the given file for delete in the next reboot. If the file exists it will ask user for the reboot when program ends.
  • Del
    Path to file to be deleted
    Deletes the given file if it exists, It also deletes a directory if it is empty. If the file is locked it will set the system to delete the file upon reboot
  • DelBootQuiet
    Path to files to be deleted on reboot without reboot request
    Put the given file for delete in the next reboot. If the file exists it will ask user for the reboot when program ends.
  • Copy
    Copies a file from the given source to given dest
  • CopyV
    Copies a file from the given source to given dest only if source is a higher version.
  • DelReg
    Registry pattern matching string
    Deletes regkey(s) matching the given registry key
  • DelRegE
    Registry pattern matching string
    Only deletes regkey(s) matching the given registry key if they have no subkeys or values
  • SetReg
    Registry pattern matching string\ame[=value]
    For all the matching registry paths, sets values if [=value] is present, creates subkeys otherwise
  • GetReg
    {Variable} = {regkeypath\name}
    If it finds name under regkeypath copies its value to the given variable, othewise does nothing.
  • UninstallService
    Service Name
    uninstalls the given service name
  • RemoveDevice
    {Enum Type} , {Hardware ID}, {Device type}
    Remove any device matched with the given description from the system using setupdi calls.
    Enum can be (PCI, EISA, etc), HWID usually is VEN_10DE and device type can be DISPLAY,HDC,MEDIA,NET,SYSTEM
  • InstallDriverEx
    {Hardware ID}, {InfFullPath}
    Installs the given driver for any device matched with the given device ID from the system using setupdi calls.
  • InstallDriver
    {Hardware ID}, {InfFullPath}
    Installs the given driver for any device matched using UpdateDriverForPlugAndPlayDevices for Win200 and above and InstallDriverEx for Win95 and Win98
  • CreateDevice
    {Hardware ID}, {InfFullPath}
    This function first creates a device Installs the driver for this device using given inf. This function should work for all versions of Windows
  • GetInfGUID
    Variable Name = Full Path to Inf
    Sets the given variable to a string representing the inf’s GUID
  • DelOemInfs
    {WildCard} , {Section} , {Name} , {Value} , {[…]
    it searches in all inf files under sysdir\\inf\\[Wildcard and OEM*.inf] and if it finds a match with given parameters it deletes it on reboot
  • DelIniIfMatched
    Inffile} , {Section} , {Name} , {Value} , {[,…]
    it searches in all inf files under sysdir\\inf\\OEM*.inf and if it finds a match with given parameters it deletes it on reboot
  • ClassSweep
    Pass in the GUID of the inf and the string patterns of the reg names to be deleted. It will remove all the reg names corresponding to the str pattern under the GUID 0001….. except in Properties)
  • EnumRegNamesCmd
    RegPathToEnumatrate} , {Command
    Enumerates all keys matching the given regpath and when matched enumarates all names under that key then calls the given command {Current Reg name} and {Current Reg value} are set when the given command is executed
  • EnumRegCmd
    {RegPathToEnumatrate} , {Command}
    Enumerates all keys matching the given regpath and when matched calls the given command {Current Reg Key} is set then the given command is executed
  • UnifyUninst
    This is a legacy command to maintain backward compatibility.
  • SetEnv
    Adds the given name to environment variables and sets its value
  • UninstallGUI
    Displays the GUI to uninstall whatever user chooses
  • KillApp
    Given an appname enumerates all the running app and kills its process if it is running
  • SendMessage
    {AppName}, {Message}
    Given an appname, sends its window a message
  • CreateShortcut
    Creates a shell link (shortcut)
  • GetDrivePort
    {Variable} = {path}
    It uses the first char of the path as drive letter and assigns the port number of that to the given variable name.
  • EnumDevices
    It enumerats all the devices present on the system if any device has {DeviceID} and is from the given {Class} then variable {Current Device} is set to that device ID and the given command gets executed.
  • GetFolderPath
    Variable Name = FolderCode
    Sets the given variable to the path of a special folder, identified by its CSIDL (check MSDN SHGetSpecialFolderPath Function)
  • CheckRAID
    Returns TRUE if RAID exists.