Now Reading
Raspberry Robin’s Roshtyak: A Little Lesson in Trickery

Raspberry Robin’s Roshtyak: A Little Lesson in Trickery

2023-12-05 13:42:12

There are numerous methods malware authors use to make malware analysts’ jobs harder. These methods embrace obfuscation methods to complicate reverse engineering, anti-sandbox methods to evade sandboxes, packing to bypass static detection, and extra. Numerous misleading methods utilized by numerous malware strains in-the-wild have been documented over time. Nonetheless, few of those methods are applied in a typical piece of malware, regardless of the numerous obtainable methods. 

The topic of this weblog publish, a backdoor we dubbed Roshtyak, isn’t your typical piece of malware. Roshtyak is stuffed with methods. Some are well-known, and a few we now have by no means seen earlier than. From a technical perspective, the lengths Roshtyak takes to guard itself are extraordinarily attention-grabbing. Roshtyak belongs to one of many best-protected malware strains we now have ever seen. We hope by publishing our analysis and evaluation of the malware and its safety methods we’ll assist fellow researchers acknowledge and reply to comparable methods, and harden their evaluation environments, making them extra proof against the evasion methods described.

Roshtyak is the DLL backdoor utilized by Raspberry Robin, a worm spreading via contaminated detachable drives. Raspberry Robin is extraordinarily prevalent. We protected over 550K of our customers from the worm this yr. Because of its excessive prevalence, it must be no shock that we aren’t the one ones paying attention to Raspberry Robin. 

Pink Canary’s researchers revealed the first analysis of Raspberry Robin in Could 2022. In June, Symantec revealed a report describing a mining/clipboard hijacking operation, which reportedly made the cybercriminals at the very least $1.7 million. Symantec didn’t hyperlink the malicious operation to Raspberry Robin. However, we assess with excessive confidence that what they analyzed was Raspberry Robin. This evaluation is predicated on C&C overlaps, sturdy malware similarity, and coinfections noticed in our telemetry. Cybereason, Microsoft, and Cisco revealed additional stories in July/August 2022. Microsoft reported that Raspberry Robin infections led to DEV-0243 (a.ok.a Evil Corp) pre-ransomware conduct. We couldn’t affirm this connection utilizing our telemetry. Nonetheless, we discover it cheap to imagine that the miner payload isn’t the one method Raspberry Robin infections are being monetized. Different recent reports additionally trace at a doable connection between Raspberry Robin and Evil Corp.

A map displaying the variety of customers Avast shielded from Raspberry Robin

There are various unknowns about Raspberry Robin, regardless of so many revealed stories. What are the last word aims behind the malware? Who’s liable for Raspberry Robin? How did it change into so prevalent? Sadly, we do not need solutions to all these questions. Nonetheless, we will reply an vital query we noticed requested a number of occasions: What performance is hidden contained in the closely obfuscated DLL (or Roshtyak as we name it)? To reply this query, we absolutely reverse engineered a Roshtyak sample, and current our evaluation outcomes on this weblog publish.

Overview

Roshtyak is packed in as many as 14 protecting layers, every closely obfuscated and serving a particular function. Some artifacts counsel the layers have been initially PE information however have been reworked into customized encrypted constructions that solely the earlier layers know methods to decrypt and cargo. Quite a few anti-debugger, anti-sandbox, anti-VM, and anti-emulator checks are sprinkled all through the layers. If one in all these checks efficiently detects an evaluation surroundings, one in all 4 actions are taken. 

  1. The malware calls TerminateProcess on itself to keep away from exhibiting any additional malicious conduct and to maintain the following layers encrypted.
  2. Roshtyak crashes on function. This has the identical impact as terminating itself, however it may not be instantly clear if the crash was intentional or due to a bug because of Roshtyak’s obfuscated nature.
  3. The malware enters an infinite loop on function. Because the loop itself is situated in obfuscated code and spans hundreds of directions, it is likely to be laborious to find out if the loop is doing one thing helpful or not.
  4. Essentially the most attention-grabbing case is when the malware reacts to a profitable test by unpacking and loading a faux payload. This occurs within the eighth layer, which is loaded with dozens of anti-analysis checks. The results of every of those checks is used to change the worth of a worldwide variable. There are two payloads encrypted within the information part of the eighth layer: the actual ninth layer and a faux payload. The true ninth layer will get decrypted provided that the worldwide variable matches the anticipated worth after all of the checks have been carried out. If at the very least one test succeeded in detecting an evaluation surroundings, the worldwide variable’s worth will differ from the anticipated worth, inflicting Roshtyak to unpack and execute the faux payload as a substitute. 
Roshtyak’s obfuscation causes even comparatively easy features to develop into giant proportions. This necessitates some customized deobfuscation tooling if one needs to reverse engineer it inside an affordable timeframe.

The faux payload is a BroAssist (a.ok.a BrowserAssistant) adware sample. We imagine this faux payload was meant to mislead malware analysts into pondering the pattern is much less attention-grabbing than it truly is. When a reverse engineer focuses on shortly unpacking a pattern, it would appear to be the entire pattern is “simply” an obfuscated piece of adware (and a really previous one at that), which may trigger the analyst to lose curiosity in digging deeper. And certainly, it seems that these faux payload shenanigans could be very efficient. As could be seen on the screenshot beneath, it fooled at the very least one researcher, who misattributed the Raspberry Robin worm, due to the faux BrowserAssistant payload.

A safety researcher misattributing Raspberry Robin due to the faux payload. This isn’t to choose on anybody, we simply wish to present how simple it’s to make a mistake like this given Roshtyak’s trickery and complexity.

The Bag of Methods

For the sake of holding this weblog publish (form of) brief and to the purpose, let’s get straight into detailing among the extra attention-grabbing evasion methods employed by Roshtyak.

Section registers

Early within the execution, Roshtyak prefers to make use of checks that don’t require calling any imported features. If one in all these checks is profitable, the pattern can quietly exit with out producing any suspicious API calls. Beneath is an instance the place Roshtyak checks the conduct of the gs section register. The test is designed to be stealthy and the encompassing rubbish directions make it simple to miss.

A stealthy detection of single-stepping. Solely the underscored directions are helpful.

The primary thought behind this test is to detect single-stepping. Earlier than the above snippet, the worth of cx was initialized to 2. After the pop ecx instruction, Roshtyak checks if cx remains to be equal to 2. This could be the anticipated conduct as a result of this worth ought to propagate via the stack and the gs register below regular circumstances. Nonetheless, a single step occasion would reset the worth of the gs selector, which might end in a special worth getting popped into ecx on the finish.

However there’s extra to this test. As a facet impact of the 2 push/pop pairs above, the worth of gs is briefly modified to 2. After this test, Roshtyak enters a loop, counting the variety of iterations till the worth of gs is not 2. The gs selector can also be reset after a thread context swap, so the loop primarily counts the variety of iterations till a context swap occurs. Roshtyak repeats this process a number of occasions, averages out the outcome, and checks that it belongs to a wise vary for a naked metallic execution surroundings. If the pattern runs below a hypervisor or in an emulator, the typical variety of iterations would possibly fall outdoors of this vary, which permits Roshtyak to detect undesirable execution environments.

Roshtyak additionally checks that the worth of the cs section register is both 0x1b or 0x23. Right here, 0x1b is the anticipated worth when operating on native x86 Home windows, whereas 0x23 is the anticipated worth below WoW64.

APC injection via a random ntdll gadget

Roshtyak performs a few of its performance from separate processes. For instance, when it communicates with its C&C server, it spawns a brand new innocent-looking course of like regsvr32.exe. Utilizing shared sections, it injects its comms module into the handle house of the brand new course of. The injected module is executed through APC injection, utilizing NtQueueApcThreadEx.

Apparently, the ApcRoutine argument (which marks the goal routine to be scheduled for execution) doesn’t level to the entry level of the injected module. As an alternative, it factors to a seemingly random handle inside ntdll. Taking a better look, we see this handle was not chosen randomly however that Roshtyak scanned the code part of ntdll for pop r32; ret devices (excluding pop esp, as a result of pivoting the stack could be undesirable) and picked one at random to make use of because the ApcRoutine

A random pop r32; ret gadget used because the entry level for APC injection

Wanting on the calling conference for the ApcRoutine reveals what’s happening. The pop instruction makes the stack pointer level to the SystemArgument1 parameter of NtQueueApcThreadEx and so the ret instruction successfully jumps to wherever SystemArgument1 is pointing. Which means by abusing this gadget, Roshtyak can deal with SystemArgument1 because the entry level for the aim of APC injection. This obfuscates the management circulation and makes the NtQueueApcThreadEx name look extra reputable. If somebody hooks this operate and inspects the ApcRoutine argument, the truth that it’s pointing into the ntdll code part is likely to be sufficient to persuade them that the decision isn’t malicious.

Checking learn/write efficiency on write-combined reminiscence

On this subsequent test, Roshtyak allocates a big reminiscence buffer with the PAGE_WRITECOMBINE flag. This flag is meant to change cache conduct to optimize sequential write efficiency (on the expense of learn efficiency and probably reminiscence ordering). Roshtyak makes use of this to detect if it’s operating on a bodily machine. It conducts an experiment the place it first writes to the allotted buffer after which reads from the allotted buffer, all whereas measuring the learn/write efficiency utilizing a separate thread as a counter. This experiment is repeated 32 occasions and the test is handed provided that write efficiency was at the very least six occasions greater than learn efficiency a lot of the occasions. If the test fails, Roshtyak deliberately selects a unsuitable RC4 key, which leads to failing to correctly decrypt the subsequent layer.

Hiding shellcode from plain sight

The injected shellcode is apparently hidden, too. When Roshtyak prepares for code injection, it first creates a big part and maps it into the present course of as PAGE_READWRITE. Then, it fills the part with random information and locations the shellcode at a random offset inside the random information. Because the shellcode is only a comparatively small loader adopted by random-looking packed information, the entire part seems to be like random information. 

A histogram of the bytes contained in the shared part. Observe that it seems to be nearly random, probably the most suspicious signal is the slight overrepresentation of null bytes.

The part is then unmapped from the present course of and mapped into the goal course of, the place it’s executed utilizing the above-described APC injection method. The random information was added in an try to hide the existence of the shellcode. Judging solely from the reminiscence dump of the goal course of, it would appear to be the part is stuffed with random information and doesn’t include any legitimate executable code. Even when one suspects precise legitimate code someplace in the course of the part, it won’t be simple to seek out its precise location. 

The beginning of the shellcode inside the shared part. It is likely to be laborious to pinpoint the precise begin handle as a result of it unconventionally begins on an odd bt instruction.

Ret2Kernel32

Roshtyak makes some extent of cleansing up after itself. Each time a sure string or piece of reminiscence is not wanted, Roshtyak wipes and/or frees it in an try to destroy as a lot proof as doable. The identical holds for Roshtyak’s layers. Each time one layer finishes its job, it frees itself earlier than passing execution onto the subsequent layer. Nonetheless, the layer can’t simply merely free itself straight. The entire course of would crash if it referred to as VirtualFree on the area of reminiscence it’s at the moment executing from.

Roshtyak, due to this fact, frees the layer via a ROP chain executed throughout layer transitions to keep away from this downside. When a layer is about to exit, it constructs a ROP chain on the stack and returns into it. An instance of such a ROP chain could be seen beneath. This chain begins by returning into VirtualFree and UnmapViewOfFile to launch the earlier layer’s reminiscence. Then, it returns into the subsequent layer. The return handle from the subsequent layer is about to RtlExitUserThread, to safeguard execution.

A easy ROP chain consisting of VirtualFree -> UnmapViewOfFile -> subsequent layer -> RtlExitUserThread

MulDiv bug

MulDiv is a operate exported by kernel32.dll, which takes three signed 32-bit integers as arguments. It multiplies the primary two arguments, divides the multiplication outcome by the third argument, and returns the ultimate outcome rounded to the closest integer. Whereas this would possibly appear to be a easy sufficient operate, there’s an historical signal extension bug in Microsoft’s implementation. This bug is form of thought of a function now and would possibly by no means get fastened.

Roshtyak is conscious of the bug and checks for its presence by calling MulDiv(1, 0x80000000, 0x80000000). On actual Home windows machines, this triggers the bug and MulDiv erroneously returns 2, though the proper return worth must be 1, as a result of (1 * -2147483648) / -2147483648 = 1. This enables Roshtyak to detect emulators that don’t replicate the bug. For instance, this efficiently detects Wine, which, funnily sufficient, accommodates a special bug, which makes the above name return 0.

Tampering with return addresses saved on the stack

There are additionally methods designed to obfuscate operate calls. As proven within the earlier part, Roshtyak likes to name features utilizing the ret instruction. This subsequent trick is analogous in that it additionally manipulates the stack so a ret instruction can be utilized to leap to the specified handle. 

To attain this, Roshtyak scans the present thread’s stack for pointers into the code part of one of many earlier layers (not like the opposite layers, this one was not freed utilizing the ROP chain method). It replaces all these pointers with the handle it needs to name. Then it lets the code return a number of occasions till a ret instruction encounters one of many hijacked pointers, redirecting the execution to the specified handle.

Exception-based checks

Moreover, Roshtyak accommodates checks that arrange a customized vectored exception handler and deliberately set off numerous exceptions to make sure all of them get dealt with as anticipated.

Roshtyak units up a vectored exception handler utilizing RtlAddVectoredExceptionHandler. This handler accommodates customized handlers for chosen exception codes. A top-level exception handler can also be registered utilizing SetUnhandledExceptionFilter. This handler shouldn’t be referred to as within the focused execution environments (not one of the deliberately triggered exceptions ought to fall via the vectored exception handler). So this top-level handler simply accommodates a single name to TerminateProcess. Apparently, Roshtyak additionally makes use of ZwSetInformationProcess to set SEM_FAILCRITICALERRORS utilizing the ProcessDefaultHardErrorMode class. This ensures that even when the exception one way or the other is handed all the best way to the default exception handler, Home windows wouldn’t present the usual error message field, which may alert the sufferer that one thing suspicious is occurring.

When every little thing is about up, Roshtyak begins producing exceptions. The primary exception is generated by a popf instruction, straight adopted by a cpuid instruction (proven beneath). The worth popped by the popf instruction was crafted to set the entice flag, which ought to, in flip, elevate a single-step exception. On a bodily machine, the exception would set off proper after the cpuid instruction. Then, the customized vectored exception handler would take over and transfer the instruction pointer away from the C7 B2 opcodes, which mark an invalid instruction. Nonetheless, below many hypervisors, the single-step exception wouldn’t be raised. It is because the cpuid instruction forces a VM exit, which could delay the impact of the entice flag. If that’s the case, the processor will elevate an unlawful instruction exception when making an attempt to execute the invalid opcodes. If the vectored exception handler encounters such an exception, it is aware of that it’s operating below a hypervisor. A variation of this method is described completely in a blog post by Palo Alto Networks. Please confer with it for extra particulars. 

The exception-based test utilizing popf and cpuid to detect hypervisors

One other exception is generated utilizing the two-byte int 3 instruction (CD 03). This instruction is adopted by rubbish opcodes. The int 3 right here raises a breakpoint exception, which is dealt with by the vectored exception handler. The vectored exception handler doesn’t actually do something to deal with the exception, which is attention-grabbing. It is because by default, when Home windows handles the two-byte int 3 instruction, it can go away the instruction pointer in between the 2 instruction bytes, pointing to the 03 byte. When disassembled from this 03 byte, the rubbish opcodes all of the sudden begin making sense. We imagine it is a test towards some overeager debuggers, which may “repair” the instruction pointer to level after the 03 byte.

Furthermore, the vectored exception handler checks the thread’s CONTEXT and makes certain that registers Dr0 via Dr3 are empty. If they don’t seem to be, the method is being debugged utilizing {hardware} breakpoints. Whereas this test is comparatively frequent in malware, the CONTEXT is normally obtained utilizing a name to a operate like GetThreadContext. Right here, the malware authors took benefit of CONTEXT being handed as an argument to the exception handler, so they didn’t must name any extra API features.

Giant executable mappings

This subsequent test is attention-grabbing principally as a result of we aren’t certain what it’s actually imagined to test (in different phrases, we’d be comfortable to listen to your theories!). It begins with Roshtyak creating a big PAGE_EXECUTE_READWRITE mapping of dimension 0x386F000. Then it maps this mapping 9 occasions into its personal handle house. After this, it memsets the mapping to 0x42 (opcode for inc edx), apart from the final six bytes, that are crammed with 4 inc ecx directions and jmp dword ptr [ecx] (see beneath). Subsequent, it places the 9 base addresses of the mapped views into an array, adopted by an handle of a single ret instruction. Lastly, it factors ecx into this array and calls the primary mapped view, which leads to all of the mapped views being referred to as sequentially till the ultimate ret instruction. After the return, Roshtyak validates that edx obtained incremented precisely 0x1FBE6FCA occasions (9 * (0x386F000 - 6)).

The tip of the massive mapped part. The jmp dword ptr [ecx] instruction is meant to leap to the beginning of the subsequent mapped view.

Our greatest guess is that that is yet one more anti-emulator test. For instance, in some emulators, mapped sections may not be absolutely applied, so the directions written into one occasion of the mapped view may not propagate to the opposite eight situations. One other idea is the test may very well be performed to request giant quantities of reminiscence that emulators would possibly fail to supply. In spite of everything, the mixed dimension of all of the views is nearly half of the usual 32-bit person mode handle house.

Detecting course of suspension

This trick abuses an undocumented thread creation flag in NtCreateThreadEx to detect when Roshtyak’s principal course of will get externally suspended (which may imply {that a} debugger obtained connected). This flag primarily permits a thread to maintain operating even when PsSuspendProcess will get referred to as. That is coupled with one other trick abusing the truth that the thread droop counter is a signed 8-bit worth, which signifies that it maxes out at 127. Roshtyak spawns two threads, one in all which retains suspending the opposite one till the droop counter restrict is reached. After this, the primary thread retains periodically suspending the opposite one and checking if the decision to NtSuspendThread retains failing with STATUS_SUSPEND_COUNT_EXCEEDED. If it doesn’t, the thread will need to have been externally suspended and resumed (which would depart the droop counter at 126, so the subsequent name to NtSuspendThread would succeed). Not getting this error code could be suspicious sufficient for Roshtyak to give up utilizing TerminateProcess. This complete method is described in additional element in a blog post by Secret Membership. We imagine that’s the place the authors of Roshtyak obtained this trick from. It’s additionally price mentioning Roshtyak makes use of this method solely on Home windows builds 18323 (19H1) and later as a result of the undocumented thread creation flag was not applied on prior builds.

Oblique registry writes

Roshtyak performs many suspicious registry operations, for instance, establishing the RunOnce key for persistence. Since modifications to such keys are more likely to be monitored, Roshtyak makes an attempt to avoid the monitoring. It first generates a random registry key identify and briefly renames the RunOnce key to the random identify utilizing ZwRenameKey. As soon as renamed, Roshtyak provides a brand new persistence entry to the non permanent key earlier than lastly renaming it again to RunOnce. This methodology of writing to the registry could be simply detected, however it would possibly bypass some easy hooking-based monitoring strategies.

Equally, there are a number of strategies Roshtyak makes use of to delete information. Except for the obvious name to NtDeleteFile, Roshtyak is ready to successfully delete a file by setting FileDispositionInformation or FileRenameInformation in a name to ZwSetInformationFile. Nonetheless, not like the registry modification methodology, this doesn’t appear to be applied to be able to evade detection. As an alternative, Roshtyak will attempt these various strategies if the preliminary name to NtDelete file fails. 

Checking VBAWarnings

The VBAWarnings registry worth controls how Microsoft Workplace behaves when a person opens a doc containing embedded VBA macros. If this worth is 1 (that means “Allow all macros”), macros are executed by default, even with out the necessity for any person interplay. This can be a frequent setting for sandboxes, that are designed to detonate maldocs robotically. Then again, this setting is unusual for normal customers, who usually don’t go round altering random settings to make themselves extra weak (at the very least most of them don’t). Roshtyak due to this fact makes use of this test to distinguish between sandboxes and common customers and refuses to run additional if the worth of VBAWarnings is 1. Apparently, which means customers, who for no matter cause have lowered their safety this manner, are proof against Roshtyak.

Command line wiping

Roshtyak’s core is executed with very suspicious command strains, resembling RUNDLL32.EXE SHELL32.DLL,ShellExec_RunDLL REGSVR32.EXE -U /s "C:Customers<REDACTED>AppDataLocalTempdpcw.etl.". These command strains don’t look significantly reputable, so Roshtyak makes an attempt to cover them throughout execution. It does this by wiping command line data collected from numerous sources. It begins by calling GetCommandLineA and GetCommandLineW and wiping each of the returned strings. Then it makes an attempt to wipe the string pointed to by PEB->ProcessParameters->CommandLine (even when this factors to a string that has already been wiped). Since Roshtyak is commonly operating below WoW64, it additionally calls NtWow64QueryInformationProcess64 to acquire a pointer to PEB64 to wipe ProcessParameters->CommandLine obtained by traversing this “second” PEB. Whereas the wiping of the command strains was most likely meant to make Roshtyak look extra reputable, the whole absence of any command line can also be extremely uncommon. This was observed by the Pink Canary researchers of their blog post, the place they proposed a detection methodology primarily based on these suspiciously empty command strains.

Roshtyak’s core course of, as proven by Course of Explorer. Observe the suspiciously empty command line.

Further methods

Except for the methods described up to now, Roshtyak makes use of many much less subtle methods which might be generally present in different malware as effectively. These embrace:

  • Hiding threads utilizing ThreadHideFromDebugger (and verifying that the threads actually obtained hidden utilizing NtQueryInformationThread)
  • Patching DbgBreakPoint in ntdll
  • Detecting person inactivity utilizing GetLastInputInfo
  • Checking fields from PEB (BeingDebugged, NtGlobalFlag)
  • Checking fields from KUSER_SHARED_DATA (KdDebuggerEnabled, ActiveProcessorCount, NumberOfPhysicalPages)
  • Checking the names of all operating processes (some are in contrast by hash, some by patterns, and a few by character distribution)
  • Hashing the names of all loaded modules and checking them towards a hardcoded blacklist
  • Verifying the primary course of identify isn’t too lengthy and doesn’t match recognized names utilized in sandboxes
  • Utilizing the cpuid instruction to test hypervisor data and the processor model
  • Utilizing poorly documented COM interfaces
  • Checking the username and computername towards a hardcoded blacklist
  • Checking for the presence of recognized sandbox decoy information
  • Checking MAC addresses of personal adapters towards a hardcoded blacklist
  • Checking MAC addresses from the ARP desk (utilizing GetBestRoute to populate it and GetIpNetTable to examine it)
  • Calling ZwQueryInformationProcess with ProcessDebugObjectHandle, ProcessDebugFlags, and ProcessDebugPort
  • Checking DeviceId of show gadgets (utilizing EnumDisplayDevices)
  • Checking ProductId of .PhysicalDrive0 (utilizing IOCTL_STORAGE_QUERY_PROPERTY)
  • Checking for digital laborious disks (utilizing NtQuerySystemInformation with SystemVhdBootInformation)
  • Checking the uncooked SMBIOS firmware desk (utilizing NtQuerySystemInformation with SystemFirmwareTableInformation)
  • Establishing Defender exclusions (each for paths and processes)
  • Eradicating IFEO registry keys associated to course of names utilized by the malware

Obfuscation

We’ve proven many anti-analysis methods which might be designed to stop Roshtyak from detonating in undesirable execution environments. These methods alone could be simple to patch or bypass. What makes analyzing Roshtyak particularly deadly is the mix of all these methods with heavy obfuscation and a number of layers of packing. This makes it very troublesome to review the anti-analysis methods statically and determine methods to cross all of the checks to be able to get Roshtyak to unpack itself. Moreover, even the primary payload obtained the identical obfuscation, which signifies that statically analyzing Roshtyak’s core performance additionally requires an excessive amount of deobfuscation. 

In the remainder of this part, we’ll undergo the primary obfuscation methods utilized by Roshtyak.

A random code snippet from Roshtyak. As could be seen, the obfuscation makes the uncooked output of the Hex-Rays decompiler virtually incomprehensible.

Management circulation flattening

Management circulation flattening is among the most noticeable obfuscation methods employed by Roshtyak. It’s applied in an uncommon method, giving the management circulation graphs of Roshtyak’s features a novel look (see beneath). The objective of management circulation flattening is to obscure management circulation relations between particular person code blocks. 

Management circulation is directed by a 32-bit management variable, which tracks the execution state, figuring out the code block to be executed. This management variable is initialized firstly of every operate to confer with the beginning code block (which is regularly a nop block). The management variable is then modified on the finish of every code block to determine the subsequent code block that must be executed. The modification is carried out utilizing some arithmetic directions, resembling add, sub, or xor.

There’s a dispatcher utilizing the management variable to route execution into the proper code block. This dispatcher is made up of if/else blocks which might be circularly linked right into a loop. Every dispatcher block takes the management variable and masks it utilizing arithmetic directions to test if it ought to route execution into the code block that it’s guarding. What’s attention-grabbing right here is there are a number of factors of entry from the code blocks into the dispatcher loop, giving the management circulation graphs the jagged “sawblade” look in IDA. 

Branching is carried out utilizing a particular code block containing an imul instruction. It depends on the earlier block to compute a department flag. This department flag is multiplied utilizing the imul instruction with a random fixed, and the result’s added, subbed, or xored to the brand new management variable. Which means after the department block, the management variable will determine one of many two doable succeeding code blocks, relying on the worth that was computed for the department flag.

Management circulation graph of a operate obfuscated utilizing management circulation flattening

Operate activation keys

Roshtyak’s obfuscated features anticipate an additional argument, which we name an activation key. This activation secret is used to decrypt all native constants, strings, variables, and so on. If a operate is known as with a unsuitable activation key, the decryption ends in rubbish plaintext, which is able to most probably trigger Roshtyak to get caught in an infinite loop contained in the management circulation dispatcher. It is because all constants utilized by the dispatcher (the preliminary worth of the management variable, the masks utilized by the dispatcher guards, and the constants used to leap to the subsequent code block) are encrypted with the activation key. With out the proper activation key, the dispatcher merely doesn’t know methods to dispatch.

Reverse engineering a operate is virtually inconceivable with out understanding the proper activation key. All strings, buffers, and native variables/constants stay encrypted, all cross-references are misplaced, and worse, there isn’t any management circulation data. Solely particular person code blocks stay, with no option to understand how they relate to one another.

Every obfuscated operate must be referred to as from someplace, which implies the code calling the operate has to provide the proper activation key. Nonetheless, acquiring the activation key isn’t that simple. First, name targets are additionally encrypted with activation keys, so it’s inconceivable to seek out the place a operate is known as from with out understanding the best activation keys. Second, even the equipped activation secret is encrypted with the activation key of the calling operate. And that activation key obtained encrypted with the activation key of the subsequent calling operate. And so forth, recursively, all the best way till the entry level operate.

This brings us to methods to deobfuscate the mess. The activation key of the entry level operate should be there in plaintext. Utilizing this activation key, it’s doable to decrypt the decision targets and activation keys of features which might be referred to as straight from this entry level operate. Making use of this methodology recursively permits us to reconstruct the complete name graph together with the activation keys of all of the features. The one exceptions could be features that have been by no means referred to as and have been left in by the compiler. These features will most likely stay a thriller, however because the pattern doesn’t use them, they don’t seem to be that vital from a malware analyst’s perspective.

Variable masking

Some variables should not saved in plaintext kind however are masked utilizing a number of arithmetic directions. Which means if Roshtyak isn’t actively utilizing a variable, it retains the variable’s worth in an obfuscated kind. Each time Roshtyak wants to make use of the variable, it has to first unmask it earlier than it may use it. Conversely, after Roshtyak makes use of the variable, it converts it again into the masked kind. This masking-based obfuscation methodology barely complicates monitoring variables throughout debugging and makes it tougher to go looking reminiscence for a recognized variable worth.

Loop transformations

Roshtyak is inventive with some loop circumstances. As an alternative of writing a loop like for (int i = 0; i < 1690; i++), it transforms the loop into e.g. for (int32_t i = 0x06AB91EE; i != 0x70826068; i = i * -0x509FFFF + 0xEC891BB1). Whereas each loops will execute precisely 1690 occasions, the second is far tougher to learn. At first look, it’s not clear what number of iterations the second loop executes (and if it even terminates). Monitoring the variety of loop iterations throughout debugging can also be a lot tougher within the second case.

Packing

As talked about, Roshtyak’s core is hidden behind a number of layers of packing. Whereas all of the layers appear to be they have been initially compiled into PE information, all however the strictly vital information (entry level, sections, imports, and relocations) have been stripped away. Moreover, Roshtyak helps two customized codecs for storing the stripped PE file data, and the layers take activates what format they use. Moreover, elements of the customized codecs are encrypted, typically utilizing keys generated primarily based on the outcomes of varied anti-analysis checks.

This makes it troublesome to unpack Roshtyak’s layers statically right into a standalone PE file. First, one must reverse engineer the customized codecs and determine methods to decrypt the encrypted elements. Then, one must reconstruct the PE header, the sections, the part headers, and the import desk (the relocation desk doesn’t must be reconstructed since relocations can simply be turned off). Whereas that is all completely doable (and could be simplified utilizing libraries like LIEF), it would take a major period of time. Including to this that the layers are typically interdependent, it is likely to be simpler to only analyze Roshtyak dynamically in reminiscence.

A bit header in one of many customized PE-like file codecs: raw_size corresponds to SizeOfRawData, raw_size + virtual_padding_size is successfully VirtualSize. There is no such thing as a VirtualAddress or PointerToRawData equal as a result of the sections are loaded sequentially.

Different obfuscation methods

Along with the above-described methods, Roshtyak additionally makes use of different obfuscation methods, together with:

  • Junk instruction insertion
  • Import hashing
  • Frequent reminiscence wiping
  • Combined boolean-arithmetic obfuscation
  • Redundant threading
  • Heavy polymorphism

Core Performance

Now that we’ve described how Roshtyak protects itself, it is likely to be attention-grabbing to additionally go over what it really does. Roshtyak’s DLL is comparatively giant, over a megabyte, however its performance is surprisingly easy when you get rid of all of the obfuscation. Its principal function is to obtain additional payloads to execute. As well as, it does the same old evil malware stuff, specifically establishing persistence, escalating privileges, lateral motion, and exfiltrating details about the sufferer.

Persistence

Roshtyak first generates a random file identify in %SystemRootpercentTemp and strikes its DLL picture there. The generated file identify consists of two to eight random lowercase characters concatenated with a random extension chosen from a hardcoded checklist. The PRNG used to generate this file identify is seeded with the quantity serial variety of C:. The pattern we analyzed hardcoded seven extensions (.log, .tmp, .loc, .dmp, .out, .ttf, and .etl). We noticed different extensions being utilized in different samples, suggesting this checklist is considerably dynamic. With a small chance, Roshtyak may even use a randomly generated extension. As soon as absolutely constructed, the complete path to the Roshtyak DLL would possibly appear to be e.g. C:WindowsTempwcdp.etl.

After the DLL picture is moved to the brand new filesystem path, Roshtyak stomps its Modified timestamp to the present system time. It then proceeds to arrange a RunOnce(Ex) registry key to truly set up persistence. The registry entry is created utilizing the beforehand described indirect registry write method. The command inserted into the important thing would possibly look as follows:

RUNDLL32.EXE SHELL32.DLL,ShellExec_RunDLL REGSVR32.EXE -U /s "C:WindowsTempwcdp.etl."

There are a few issues to notice right here. First, regsvr32 doesn’t care concerning the extensions of the DLLs it masses, permitting Roshtyak to cover below an innocent-looking extension resembling .log. Second, the /s parameter places regsvr32 into silent mode. With out it, regsvr32 would complain that it didn’t discover an export named DllUnregisterServer. Lastly, discover the trailing interval character on the finish of the trail. This era is removed throughout path normalization, so it virtually has no impact on the command. We aren’t precisely certain what the creator’s unique intention behind together with this era character is. It seems to be prefer it may have been designed to trick some anti-malware software program into not with the ability to join the persistence entry with the payload on the filesystem.

See Also

By default, Roshtyak makes use of the HKCUSOFTWAREMicrosoftWindowsCurrentVersionRunOnce key for persistence. Nonetheless, below some circumstances (resembling when it detects that Kaspersky is operating by checking for a course of named avp.exe) the important thing HKLMSOFTWAREMicrosoftWindowsCurrentVersionRunOnceEx will likely be used as a substitute. The RunOnceEx secret is able to loading a DLL, so when utilizing this key, Roshtyak specifies shell32.dll straight, omitting the use rundll32.

A RunOnceEx persistence entry established by Roshtyak

Privilege escalation

Roshtyak makes use of each UAC bypasses and common EoP exploits in an try to elevate its privileges. In contrast to many different items of malware, which simply blindly execute no matter UAC bypasses/exploits the authors may discover, Roshtyak makes efforts to determine if the privilege escalation methodology is even possible to achieve success. This was most likely applied to decrease the possibilities of detection as a result of pointless utilization of incompatible bypasses/exploits. For UAC bypasses, this includes checking the ConsentPromptBehaviorAdmin and ConsentPromptBehaviorUser registry keys. For EoP exploits, that is about checking the Home windows construct quantity and patch degree.

In addition to checking the ConsentPromptBehavior(Admin|Person) keys, Roshtyak performs different sanity checks to make sure that it ought to proceed with the UAC bypass. Specifically, it checks for admin privileges utilizing CheckTokenMembership with the SID S-1-5-32-544 (DOMAIN_ALIAS_RID_ADMINS). It additionally inspects the worth of the DbgElevationEnabled flag in KUSER_SHARED_DATA.SharedDataFlags. That is an undocumented flag that’s set if UAC is enabled. Lastly, there are AV checks for BitDefender (detected by the module atcuf32.dll), Kaspersky (course of avp.exe), and our personal Avast/AVG (module aswhook.dll). If one in all these AVs is detected, Roshtyak avoids chosen UAC bypass methods, presumably those that may end in detection.

As for the precise UAC bypasses, there are two principal strategies applied. The primary is an implementation of the aptly named ucmDccwCOM methodology from UACMe. Apparently when this methodology is executed, Roshtyak briefly masquerades its course of as explorer.exe by overwriting FullDllName and BaseDllName within the _LDR_MODULE construction similar to the primary executable module. The payload launched by this methodology is a randomly named LNK file, dropped into %TEMP% utilizing the IShellLink COM interface. This LNK file is designed to relaunch the Roshtyak DLL, via LOLBins resembling advpack or register-cimprovider.

The second methodology is extra of a UAC bypass framework than a particular bypass methodology, as a result of a number of UAC bypass strategies observe the identical easy sample: first registering some particular shell open command after which executing an autoelevating Home windows binary (which internally triggers the shell open command). As an illustration, a UAC bypass is likely to be completed by writing a payload command to HKCUSoftwareClassesms-settingsshellopencommand after which executing fodhelper.exe from %windirpercentsystem32. Mainly, the identical bypass could be achieved by substituting the pair ms-settings/fodhelper.exe with different pairs, resembling mscfile/eventvwr.exe. Roshtyak makes use of the next six pairs to bypass UAC:

Class Executable
mscfile eventvwr.exe
mscfile compmgmtlauncher.exe
ms-settings fodhelper.exe
ms-settings computerdefaults.exe
Folder sdclt.exe
Launcher.SystemSettings slui.exe

Let’s now take a look at the kernel exploits (CVE-2020-1054 and CVE-2021-1732) Roshtyak makes use of to escalate privileges. As is commonly the case in Roshtyak, these exploits are saved encrypted and are solely decrypted on demand. Apparently, as soon as decrypted, the exploits grow to be common PE information with fully legitimate headers (not like the opposite layers in Roshtyak, that are both in shellcode kind or saved in a customized stripped PE format). Furthermore, the exploits lack the obfuscation given to the remainder of Roshtyak, so their code is straight away decompilable, and just some fundamental string encryption is used. We don’t know why the attackers left these exploits so uncovered, however it is likely to be as a result of distinction in bitness. Whereas Roshtyak itself is x86 code (more often than not operating below WoW64), the exploits are x64 (which is sensible contemplating they exploit vulnerabilities in 64-bit code). It may very well be that the obfuscation instruments utilized by Roshtyak’s authors have been designed to work on x86 and should not transportable to x64.

Snippet from Roshtyak’s exploit for CVE-2020-1054, scanning via IsMenu to seek out the offset to HMValidateHandle.

To execute the exploits, Roshtyak spawns (the AMD64 model of) winver.exe and will get the exploit code to run there utilizing the KernelCallbackTable injection method. Roshtyak’s implementation of this injection methodology primarily matches a public PoC, with the most important distinction being the utilization of barely totally different API features as a result of want for cross-subsystem injection (e.g. NtWow64QueryInformationProcess64 as a substitute of NtQueryInformationProcess or NtWow64ReadVirtualMemory64 as a substitute of ReadProcessMemory). The code injected into winver.exe isn’t the exploit PE itself however reasonably a barely obfuscated shellcode, designed to load the exploit PE into reminiscence.

The kernel exploits goal sure unpatched variations of Home windows. Particularly, CVE-2020-1054 is simply used on Home windows 7 methods the place the revision quantity isn’t greater than 24552. Then again, the exploit for CVE-2021-1732 runs on Home windows 10, with the focused construct quantity vary being from 16353 to 19042. Earlier than exploiting CVE-2021-1732, Roshtyak additionally scans via put in replace packages to see if a patch for the vulnerability is put in. It does this by enumerating the registry keys below HKLMSOFTWAREMicrosoftWindowsCurrentVersionComponent Based mostly ServicingPackages and checking if the bundle for KB4601319 (or greater) is current.

Lateral motion

On the subject of lateral motion, Roshtyak merely makes use of the tried and examined PsExec device. Earlier than executing PsExec, Roshtyak ensures it is sensible to run it by checking for a SID matching the “well-knownWinAccountDomainAdminsSid group. If area admin rights should not detected, Roshtyak skips its lateral motion section solely.

Roshtyak makes an attempt to get round detection by setting Defender exclusions, as PsExec is commonly flagged as a hacktool (for good causes). It units a path exclusion for %TEMP% (the place it can drop PsExec and different information used for lateral motion). Later, it units up a course of exclusion for the precise path from which PsExec will likely be executed. 

Whereas we might anticipate PsExec to be bundled inside Roshtyak, it seems Roshtyak downloads it on demand from https://obtain.sysinternals[.]com/information/PSTools.zip. The downloaded zip archive is dropped into %TEMP% below a random identify with the .zip extension. PsExec is then unzipped from this archive utilizing the Home windows Shell COM interface (IShellDispatch) right into a randomly named .exe file in %TEMP%.

The payload to be executed by PsExec is a self-extracting bundle created by a device referred to as IExpress. That is an archaic installer that’s a part of Home windows, which might be why it’s used, since Roshtyak can depend on it already being on the sufferer machine. The installer technology is configured by a textual content file utilizing the Self Extraction Directive (SED) syntax. 

Roshtyak’s IExpress configuration template

Roshtyak makes use of a SED configuration template with three placeholders (%1, %2, and %3) that it substitutes with actual values at runtime. As seen above, the configuration template was written in mixed-case, which is regularly utilized in Raspberry Robin typically. As soon as the SED configuration is ready, it’s written right into a randomly named .txt file in %TEMP%. Then, iexpress is invoked to generate the payload utilizing a command resembling C:Windowsiexpress.exe /n /q <path_to_sed_config>. The generated payload is dumped right into a randomly named .exe file in %TEMP%, as configured by the TargetName directive (placeholder %1).

As soon as the payload is generated, Roshtyak proceeds to truly run PsExec. There are two methods Roshtyak can execute PsExec. The primary one makes use of the command <path_to_psexec> * -accepteula -c -d -s <path_to_payload>. Right here, the * wildcard instructs PsExec to run the payload on all computer systems within the present area. Alternatively, Roshtyak would possibly run the command <path_to_psexec> @<path_to_target_file> -accepteula -c -d -s <path_to_payload>. Right here, the target_file is a textual content file containing a particular checklist of computer systems to run the payload on. Roshtyak builds this checklist by enumerating Lively Listing objects utilizing API features exported from activeds.dll.

Profiling the sufferer

USB worms are inclined to have a lifetime of their very own. Since their worming conduct is normally fully automated, the menace actor who initially deployed the worm doesn’t essentially have full management over the place it spreads. Because of this it’s vital for menace actors to have the worm beacon again to their C&C servers. With a beaconing mechanism in place, the menace actor could be knowledgeable about all of the machines below their management and might use this information to handle the worm as an entire.

The outgoing beaconing messages usually include some details about the contaminated machine. This helps financially-motivated cybercriminals resolve on methods to greatest monetize the an infection. Roshtyak is not any exception to this, and it collects a variety of details about every contaminated sufferer. Roshtyak concatenates all of the collected data into a big string, utilizing semicolons as delimiters. This huge string is then exfiltrated to one in all Roshtyak’s C&C servers. The exfiltrated items of data are listed beneath, so as of concatenation.

  • Exterior IP handle (obtained throughout a Tor connectivity test)
  • A string hardcoded into Roshtyak’s code, e.g. AFF123 (we will’t ensure what’s the that means behind this, however it seems to be like an affiliate ID)
  • A 16-bit hash of the DLL’s PE header (with some fields zeroed out) xored with the decrease 16 bits of its TimeDateStamp. The TimeDateStamp seems to be specifically crafted in order that the xor ends in a recognized worth. This might operate as a tamper test or a watermark.
  • Creation timestamp of the System Quantity Info folder on the system drive
  • The quantity serial variety of the system drive
  • Processor rely (GetActiveProcessorCount)
  • IsWow64Process (_PROCESS_EXTENDED_BASIC_INFORMATION.Flags & 2)
  • Home windows model (KUSER_SHARED_DATA.Nt(Main|Minor)Model)
  • Home windows product sort (KUSER_SHARED_DATA.NtProductType)
  • Home windows construct quantity (PEB.OSBuildNumber)
  • Native administrative privileges (ZwQueryInformationToken(TokenGroups)/CheckTokenMembership, test for DOMAIN_ALIAS_RID_ADMINS)
  • Area administrative privileges (test for WinAccountDomainAdminsSid/WinAccountDomainUsersSid)
  • System time (KUSER_SHARED_DATA.SystemTime)
  • Time zone (KUSER_SHARED_DATA.TimeZoneBias)
  • System locale (NtQueryDefaultLocale(0))
  • Person locale (NtQueryDefaultLocale(1))
  • Setting variables (username, computername, userdomain, userdnsdomain, and logonserver)
  • Java model (GetFileVersionInfo("javaw.exe") -> VerQueryValue)
  • Processor data (cpuid to acquire the Processor Model String)
  • Path to the picture of the primary executable module (NtQueryVirtualMemory(MemorySectionName))
  • Product ID and serial variety of the primary bodily drive (DeviceIoControl(IOCTL_STORAGE_QUERY_PROPERTY, StorageDeviceProperty))
  • MAC handle of the default gateway (GetBestRoute -> GetIpNetTable)
  • MAC addresses of all community adapters (GetAdaptersInfo)
  • Put in antivirus software program (rootsecuritycenter2 -> SELECT * FROM AntiVirusProduct)
  • Show machine data (DeviceId, DeviceString, dmPelsWidth, dmPelsHeight, dmDisplayFrequency) (EnumDisplayDevices -> EnumDisplaySettings)
  • Lively processes (NtQuerySystemInformation(SystemProcessInformation))
  • Screenshot encoded in base64 (gdi32 methodology)

Beaconing

As soon as collected, Roshtyak sends the sufferer profile to one in all its C&C servers. The profile is distributed over the Tor network, utilizing a customized comms module Roshtyak injects right into a newly spawned course of. The C&C server processes the exfiltrated profile and would possibly reply with a shellcode payload for the core module to execute.

Let’s now take a better take a look at this entire course of. It’s price mentioning that earlier than producing any malicious visitors, Roshtyak first performs a Tor connectivity test. That is performed by contacting 28 reputable and well-known .onion addresses in random order and checking if at the very least one in all them responds. If none of them reply, Roshtyak doesn’t even try to contact its C&C, as it will most probably not get via to it anyway.

As for the precise C&C communication, Roshtyak accommodates 35 hardcoded V2 onion addresses (e.g. ip2djbz3xidmkmkw:53148, see our IoC repository for the complete checklist). Like throughout the connectivity test, Roshtyak iterates via them in random order and makes an attempt to contact every of them till one responds. Observe that whereas V2 onion addresses are officially deprecated in favor of V3 addresses (and the Tor Browser not helps them in its newest model) they nonetheless look like useful sufficient for Roshtyak’s nefarious functions.

Roshtyak’s hardcoded C&C addresses

The sufferer profile is distributed within the URL path, appended to the V2 onion handle, together with the / character. Because the uncooked profile would possibly include characters forbidden to be used in URLs, the profile is wrapped in a customized construction and encoded utilizing Base64. The very first 0x10 bytes of the customized construction function an encryption key, with the remainder of the construction being encrypted. The customized construction additionally accommodates a 64-bit hash of the sufferer profile, which presumably serves as an integrity test. Apparently, the customized construction would possibly get its finish padded with random bytes. Observe that the complete path may very well be fairly giant, because it accommodates a doubly Base64-encoded screenshot. The authors of Roshtyak have been most likely conscious that the URL path isn’t appropriate for sending giant quantities of information and determined to cap the size of the sufferer profile at 0x20000 bytes. If the screenshot makes the exfiltrated profile bigger than this restrict, it isn’t included.

When the complete onion URL is constructed, Roshtyak goes forward to launch its Tor comms module. It first spawns a dummy course of to host the comms module. This dummy course of is randomly chosen and could be one in all dllhost.exe, regsvr32.exe, or rundll32.exe. The comms module is injected into the newly spawned course of utilizing a shared part, obfuscated via the beforehand described shellcode hiding method. The comms module is then executed through NtQueueApcThreadEx, utilizing the already mentioned ntdll gadget trick. The injected comms module is a customized construct of an open-source Tor library packed in three extra protecting shellcode layers.

The core module communicates with the comms module utilizing shared sections as an IPC mechanism. Each modules synchronously use the identical PRNG with the identical seed (KUSER_SHARED_DATA.Cookie) to generate the identical part identify. Each then map this named part into their respective handle areas and talk with one another by studying/writing to it. The info learn/written into the part is encrypted with RC4 (the important thing additionally generated utilizing the synchronized PRNGs).

The communication between the core module and the comms module follows a easy request/response sample. The core module writes an encrypted onion URL (together with the URL path to exfiltrate) into the shared part. The comms module then decrypts the URL and makes an HTTP request over Tor to it. The core module waits for the comms module to jot down the encrypted HTTP response again to the shared part. As soon as it’s there, the core module decrypts it and unwraps it from a customized format (which incorporates decrypting it but once more and computing a hash to test the payload’s integrity). The decrypted payload would possibly embrace a shellcode for the core module to execute. If the shellcode is current, the core module allocates an enormous chunk of reminiscence, hides the shellcode there utilizing the shellcode hiding method, and executes it in a brand new thread. This new thread is hidden utilizing the NtSetInformationThread -> ThreadHideFromDebugger method (together with a follow-up anti-hooking test utilizing NtGetInformationThread to substantiate that the NtSetInformationThread name did certainly succeed).

Conclusion

On this weblog publish, we took a technical deep dive into Roshtyak, the backdoor payload related to Raspberry Robin. The primary focus was to explain methods to cope with Roshtyak’s safety mechanisms. We confirmed some never-before-seen anti-debugger/anti-sandbox/anti-VM methods and mentioned Roshtyak’s heavy obfuscation. We additionally described Roshtyak’s core performance. Particularly, we detailed the way it establishes persistence, escalates privileges, strikes laterally, and makes use of Tor to obtain additional payloads.

Now we have to confess that reverse engineering Roshtyak was definitely no simple process. The mix of heavy obfuscation and quite a few superior anti-analysis methods made it a substantial problem. Nick Harbour, when you’re in search of one thing to repurpose for subsequent yr’s ultimate Flare-On problem, this is likely to be it.

Indicators of Compromise (IoCs)

IoCs can be found at https://github.com/avast/ioc/tree/master/RaspberryRobin.



Source Link

What's Your Reaction?
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0
View Comments (0)

Leave a Reply

Your email address will not be published.

2022 Blinking Robots.
WordPress by Doejo

Scroll To Top