Showing posts with label analysis. Show all posts
Showing posts with label analysis. Show all posts

Thursday, March 20, 2014

The Mystery of Anti-Debug by HeapAlloc

first of all, a big thank you to my friend moti who actually provided the final hints to solve that mystery and saved me A LOT of time googling heap structures. i wish everyone of you would have a moti when getting stuck in RE questions :)

to the story: meanwhile, in a zeus trojan. last week i peeked into a zeus just to really quickly 
stumble over an anti-debug trick. SURPRISE! kidding. 

that anti-debug is really easy to pass by, but wasn’t that trivial to explain; or at least that is what it seems like because i couldn’t find any suitable documentation. and this while the interwebz is full of malware reverser’s write ups.. kidding again.

so here we go...


in a nutshell: the malware would allocate heap memory and use the header of the heap entry as an indicator for an attached debugger. simple, after all. is that frequently used? i don’t know.

but, lets start at the end. the debugger would crash with an access violation when executing invalid arguments. those invalid arguments were produced by an unpacking routine, and it took some runs for brute forcing with IDA Stealth to find a possible root cause: NtGlobalFlag. well known you might think now, and indeed i had some people smiling at me with a yes my dear, thats not tricky at all. but i went on to at least spot the check for this flag, which as for example Mr. Yason described very nicely https://www.blackhat.com/presentations/bh-usa-07/Yason/Whitepaper/bh-usa-07-yason-WP.pdf indicates an attached debugger. guess what, didn’t find that check. 
 

in the first illustration you see the call that causes the exception: EnumWindows, that should call into a handler function, which actually is the unpacked code and turned out to be invalid when NtGlobalFlag is set.


Exception happening in EnumWindows handler function
so i held on to that exception and discovered that by turning IDA Stealth on and off the decryption key in the unpacking routine would change. gotcha, challenge accepted. so, investigating that key i eventually ended up in a piece of memory that preceded an allocated heap block. i provided my walkway up the unpacking routine in a screenshot doku, for people who like pictures just as much as me.


in the unpacking loop: bl being used to XOR the future code


up: ebx initialized with key_init


up: modifying key_init with esi


up: tweaking esi


up: grabbing esi initially from allocated_heap-8


root of all evil: HeapAlloc

so i ended up clueless inside of the RtlAllocateHeap function of ntdll.dll. in fact the value that the malware would grab from memory was initialized by RtlAllocateHeap and i admit it took some staring at the memory to accept the fact that it must be part of the header of the allocated heap block. the memory happened to always be allocated at 9A0688h; the value requested in the code therefor was 9A0680h. i could wonderfully watch the value at this offset turn from 03 to 01 when turning IDA Stealth, specifically NtGlobalFlag protection on or off. and this very value was the cause of crash.


Value in Question in the Memory Block Header

here is where moti jumped in and pointed me to the _HEAP_ENTRY structure, which assigns names to the values preceding my heap block:


The Memory Block Header

with data_offset-8 one hits exactly the size variable of that structure, which actually contains the size divided by 4 PLUS.. size of management information - like the header for example, which would explain a +1. or additional debug information, which could explain a +3. overall, the allocated buffer size in that particular case is always 14000h (it is dedicated to contain unpacked code later). the size value in _HEAP_ENTRY therefor is 2803h when a debugger is attached, or 2801h without a debugger or IDA Stealth activated.


Magic happened - Value changed!
so finalizing, when NtGlobalFlag indicates an attached debugger the heap manager understands this as a higher need for debug information so the allocated heap blocks are slightly bigger than without that flag set. this fact is used by the malware, as it uses the lower byte of the size value for calculation of the unpacking XOR key. 

for more information on heap structures check out this article which i found very informative
http://www.informit.com/articles/article.aspx?p=1081496
OR ask your own moti!

Saturday, February 22, 2014

Dissection Is My Hobby: Upatre Insights

i found the biggest problem to face with actual all my projects is not necessarily that i lack the idea of what i want to do, but that i lack documentation on how to do it and then go and have to figure out myself. would that be nice if someone had just mounted a page like.. malware reverser's frequently asked questions, arrrr well never happened.

now im not going to start a FAQ page, but in order to help that situation i produced detailed documentation of my latest reversing project

if you read this because you want to know about malware you will be a bit disappointed probably. mainly because the purpose of that malware itself is not so exciting at all. it just downloads.. stuff. but also because i myself focused not directly on the final executable but on the stony path it takes to get there. it is just awkwardly fascinating to watch malware shift bytes around in memory and trying to escape. i would recommend everyone just slightly interested to try it out himself, the according sample hashes for identification are listed in the write up doc.

for the records, the malware is detected as TrojanDownloader.Win32.Upatre, the full report can be downloaded at https://drive.google.com/file/d/0B9Mrr-en8FX4MS1HdjBjNEhYWk0/edit?usp=sharing, on a summary i will try now here. could get dirty though.

FUNCTIONALITY 

the analyzed sample is a malicious downloader with the sole purpose to connect to a remote C&C when invoked and to download and execute additional malware. it communicates via HTTPS to one of two hardcoded domains, which are believed to be legitimate websites on compromised web servers. malware execution can be parted in a protection layer, an unpacking layer with different stages and the final payload. For an initial infection the malware just copies its own image to the systems %TEMP% directory and executes that copy.

PROTECTION LAYER

the malware possesses a neat collection of anti-analysis tricks, none of them highly-sophisticated but very nice for learning purposes. 

anti-simulation
 
the first one is an anti-simulation trick targetting anti-virus simulation engines by the use of a multimedia API as seen in the picture. acmMetrics is an API call present in the msacm32.dll library. usually it is used for retrieving metrics for ACM objects (Audio Compression Manager). during the startup procedure of a malware sample it is highly likely that this was not the initial intention when placing that call. acmMetrics is part of the multimedia library since at least Microsoft Windows 2000 (according to Microsoft documentation) and in this special case called to trick AV simulation engines.

in our case acmMetrics is expected to deliver an error message for an invalid handle, which is not surprising given that the handle parameter is not initialized beforehand. in case the return value is not MMSYSERR_INVALIDHANDLE, code 5, execution continues to access the memory referenced by edx, which at this point always results in a memory access violation. edx is not initialized thus set to zero. 

the point of this check is, on a normal operating system like Windows 2000 or newer this function returns 5 in any case. Simulator engines usually don’t support media APIs due to overhead, therefor either crash on the call or later on the access violation.

implicit breakpoint detection

the protection layer performs minor decryption of a part of its own code, which results in implicit breakpoint detection. the decryption consists in subtracting a key from every opcode of a given section. the simple decryption routine iterates code on the position 40100Fh, where execution continues later on. If a software breakpoint is placed in the section to be decrypted the routine produces invalid opcodes and the malware crashes later on.

window confusion

At the end of what could be classified as protection layer stage one the malware invokes CreateWindowExA with a provided WndClass Structure. This structure defines the handler function of the dummy window, which will execute the second part of the protection layer. The created window has no graphical representation, thus can’t be seen so just only serves for executing said handler function. If the analyst does not recognize the switch of execution to the handler function and places according breakpoints control of the debugger will be lost.  


broken timing defence

interesting in the next section of the protection layer is a rdtsc-triggered timing defense. malware can utilize the system time to verify if a debugger, including a human analyst, is attached to the running process. windows offers various mechanisms to request the system time, most commonly used are rdtsc or the GetTickCount system call.  for detecting an attached debugger/human malware wants to know the time difference between two time stamps, namely if the delta is too big as if the CPU would execute without interruption.

the malware at hand issues two rdtsc instructions, wrapped around the decryption loop. the delta is calculated immediately afterwards, but never checked against any threshold. instead it is kept in eax until the next system call overwrites it with its return value. no other verification could be found, this anti-debugging trick is either broken or the first timestamp servers a different purpose that could not be identified. 



more multimedia disturbance

the windows media library is used a second time as a means of protection from analysis. the malware issues a call to mciSendStringA with the command “set waveaudio door open”. it is not perfectly clear what purpose the command “set waveaudio door open” usually fulfills, but without doubt the aim of the malware at hand is not to interfere with multimedia devices. an effect of mciSendStringA is that it starts up two additional threads for interaction with devices – the analyst could lose control of the debugger when inappropriately configured. a solution is to configure the debugger to stop on the start-up of a new thread, step back to the original code and continue execution until it returns to the malware code. 

UNPACKING LAYER

after bypassing all the protection mechanisms the unpacker executes without problems. unpacking can be parted in three steps: 
  • one that compresses and decrypts the packed payload data
  • second one that decompresses the same data using RtlDecompressBuffer
  • third one which performs checks on the unpacked binary, patches function call offsets and reconstructs the import address table (IAT). 
details on the unpacking routine, including the IAT reconstruction, can be found in the report mentioned above. any critics on that analysis are welcome :) ou.. how did that sample actually catch my attention? it was part of a mean malware spam wave, that has been ongoing in austria for at least since november. samples are all the same size and have very similar protection/unpacking mechanisms. so some future research would be to look at the other ~100 related malwares that i have and correlate similarities on binary level. maybe..

future shines bright, you know?