3S Labs Banner

Friday, September 7, 2012

Unpacking ASPack-2.29 using Dynamic Analysis

ASPack is a Win32 executable file compressor which also protects the executable against basic Reverse Engineering. Although there are automated tools like IDA Pro's Universal Malware Unpacker or can probably be unpacked using techniques defined in BitBlaze Renovo, we analyzed ASPack protected executables using Dynamic Analysis particularly as an exercise for our upcoming training on Reverse Engineering and Malware Analysis at Nullcon 2012 Delhi.

Following analysis is based on Free version of ASPack 2.29.

ASPack-2.29 Generated Executable Overview

ASPack compresses each section of the input executable along with adding two of its own section: .aspack and .asdata - the former containing the decoder and loader code however it is currently not clear about the purpose of the later as it seem to be empty (SizeOfRawData = 0).

Section List for Original Executable

Section List for Packed Executable

Comparing the Section Listing of the original and packed executable above, following assumptions can be made:

  • ASPack keeps the original sections intact including the section RVA however it sets the section mapping permission to RWX instead of the original R_X.
  • ASPack adds two news sections - .aspack and .adata among which the purpose of .adata is unknown as it is empty.
  • As understandable, the original entry-point is redirected to point somewhere within .aspack section.

Analysis Approach

The approach was conventional - start with Static Analysis to have a basic idea of the decoder logic and look for possible anti-debug or anti-diassambly technique and acquire enough knowledge to proceed with Dynamic Analysis. We needed to identify important code blocks like decoder loop, section mapping, control transfer to Original Entry Point (OEP) etc before we can proceed with automated unpacking.

Static Analysis


The entry point code in .aspack section in the packed executable uses a bunch of fake long and short jump op-codes (0xe9, 0xeb) to break the disassembler (Note: IDA 6.3 can detect such obfuscation technique and disassemble correctly without manual intervention). After little manual fix-up the code can be analyzed and IDA 5.0 (free) can build the Flow Graph correctly as shown below.



Three APIs as shown below in the disassembly were found to be resolved early in the loader code. Based on this logic, we made an assumption that those APIs will be used in order to decode and map sections and hence are perfect analysis points during Dynamic Analysis.


Dynamic Analysis

Phase1

We needed to verify that the decoded code is executed from its original location (as mapped by the PE Loader). Since our test executable was a GUI application (calc.exe) which inevitably calls GetMessageW, we set a breakpoint on the API and on breakpoint hit we could verify that the original code was decoded and execute from its original location only.

Phase2

Once it is verified that ASPack decoder decodes and execute original code in-place, we wanted to discover the decoder code block. For this we set a break-on-write (ba w4 addr-range in WinDBG) at the base address of the mapping containing the packed code.

Phase3

During Phase1 we noticed that the memory mapping of the decoded .text section is changed to R_X before execution from its original RWX permission as seen in the packed executable. From this we inferred that VirtualProtect must have been used before control is transferred to OEP.

Using this logic we were able to determine the exact point where ASPack loader transfers control to the OEP in the decoded .text section as shown below:




Little trial and error proved that ASPack loader does not seem to have any random or metamorphic component and hence this particular code above is always at an offset 0x420 from the base of .aspack section. The 0x00 above is patched with the computed OEP address at runtime.

Workflow for Automatic Unpacking

  • Set breakpoint on entry point
  • On breakpoint hit
    • Set breakpoint on OEP Caller address (push)
    • On breakpoint-hit
      • Dump the PE
      • Update entry point in PE Optional Header
      • TODO: Re-construct IAT

The Tool

The tool is written using the wonderful Metasm Framework, without it a LOT of work would have been required. The core logic is as below:


The full code is available here.

Closing Note: ASPack is not really meant for executable protection as such, it is more of a compression system similar to UPX. For serious requirement, appropriate tools like ASProtect, Themida, VMProtect etc. should be considered.

Advertising:

We will be conducting a 2-days workshop on Reverse Engineering and Malware Analysis at Nullcon 2012 Delhi which includes topic as described above along with other interesting topics like Dynamic Binary Instrumentation, Binary Patch Analysis etc. If you are new to Reverse Engineering, we will try our best to equip you with the basics of x86 ASM and Win32 platform components so that you can benefit from open information available on the internet. Do check out if you are interested.



Reference

http://www.aspack.com/
http://metasm.cr0.org/
http://bitblaze.cs.berkeley.edu/

Sunday, September 2, 2012

Keystroke Logging within the Browser

During a recent PenTest, we had to exploit a typical Cross Site Scripting vulnerability in a Rich Internet Application which was making heavy use of Javascript and Ajax to present an almost Desktop like UI. The objective was to prove the severity of XSS vulnerabilities, as the client was not satisfied with a mere /XSS/ popup - even though so many examples exist on the open web.

The result of our effort was to show the client an almost real time keystroke logging by exploiting a Cross Site Scripting vulnerability in his application's console. Although there is a fairly stable Javascript Keylogger available here, we wrote our own as our requirement was quite specific, something as below:


The log transfer code is intentionally removed however it is trivial to transfer the data to any predefined location by injecting iframe or img tag or perhaps even with Ajax and CORS.

Although it is perhaps trivial to write a JavaScript Key Logger and in most cases probably it is unnecessary to use such payload as using an XSS bug a target user's session can itself be hijacked, however it might be useful in certain unconventional cases.

  • Consider the case of Rich Internet Applications where the entire UX is Javascript driven and the page is never refreshed or re-loaded. Considering various near real-time use-cases like Chat, Message Ticker, Notification Message etc in the web console, it is sometime desirable to sniff user's activities which otherwise is not recorded by the application. In such a case, it might be useful to have a JS Keylogger payload handy for use with an XSS bug.
  • Major browser plugins are written in Javascript and hence one cannot rule out the possibility of infecting plugins with malicious code. Perhaps this is particularly desirable for various banking trojans as a stealth alternative.
  • Conventionally a keylogger for Win32 platform is written using the SetWindowsHookEx API. A defensive application such as an AV or an HIPS can reliably detect keyloggers at runtime by inspecting SetWindowsHookEx API. However if the objective is to log keystrokes on the browser only then it might be possible to use Form Grabbing like technique to inject malicious JS code by using eval like APIs.



Wednesday, August 8, 2012

Remote DLL Loader

Sometimes it is required to somehow force a remote process to load an arbitrary DLL via LoadLibrary. The loaded DLL once executed from within the address space of the target process can then perform a wide variety of operation. This can be achieved using AppInit_DLLs registry option for applications which are linked with user32.dll.

However we want a bit more generic solution and that too without modifying anything in the system. The idea is quite simple and perhaps widely used:
  • Find or execute the target process and obtain its handle
  • Allocate memory in the target process using VirtualAllocEx
  • Write a shellcode that performs LoadLibrary("C:\\Our.dll") using WriteProcessMemory
  • Execute the shellcode using CreateRemoteThread

Thanks to the excellent Metasm library, building and testing the tool was a matter of less than an hour. The tool can be found here.

Note: The loader shellcode will look for exported function named Init in the DLL and will call it if found after LoadLibrary(..) This allows performing operations which otherwise should not be performed from the DllMain.

The usage is pretty simple:


Wednesday, July 11, 2012

Analyzing Password Protected Word Documents


Recently we were tasked to analyze a malicious word (doc) document. On opening the document in Sandboxie, it was noticed that the document successfully exploited some vulnerability in Microsoft Word (Microsoft Office 2007 was used for testing) and dropped an executable as the payload.

The exploit package was found to be working across a wide configuration of Windows and Office products. Due to the reliable nature of the exploit, we were greatly intrigued to analyze the vulnerability it was exploiting.

Usually it is not very challenging to have a rough idea of the vulnerability being exploited by a doc file as we have various internal scripts which can dump various section of a doc file. However in this case, this particular sample was encrypted and a password is to be provided before the vulnerability is triggered. Since we were already provided the password, our job was only to analyze the vulnerability that is being exploited by the sample.

Using Ruby OLE, the Document Structure was found to be as below:



Initially we were hoping to find off-the-shelf tools which can decrypt or remove the password from a given word document. Failed to find anything usable, we wen't ahead trying to write a tool to decrypt the Word document for conventional analysis.

As per MSDN:
  • In a file that is password protected by using Office binary document RC4 CryptoAPI encryption as specified in [MS-OFFCRYPTO] section 2.3.5, FibBase.fEncrypted MUST be 1 and FibBase.fObfuscation MUST be 0.
  • The EncryptionHeader as specified in [MS-OFFCRYPTO] section 2.3.5.1 MUST be written in unencrypted form in the first FibBase.lKey bytes of the Table stream. The remainder of the Table stream, the WordDocument stream beyond the initial 68 bytes, and the entire Data stream MUST be encrypted.
  • These three streams of data MUST be encrypted in 512-byte blocks. The block number MUST be set to zero at the beginning of the stream and MUST be incremented at each 512 byte boundary. The encryption algorithm MUST be carried out at the beginning of the Table stream and the WordDocument stream even though some of the bytes are written in unencrypted form.
  • If fDocProps is set in the EncryptionHeader.Flags, the Encryption stream MUST be present, the Summary Information stream MUST NOT be present, and a placeholder Document Summary Information stream MUST be present as specified in [MS-OFFCRYPTO] section 2.3.5.4.
After a couple of hours of effort, it was realized that it really is not worth the effort to write a decryption engine for Word documents based on scarcely available documentation. Some half baked scripts for dumping various encryption related structure that we wrote is available here. In turn we turned to our swiss army knife, not really "a knife" but a "knives" really .. it was time to give up the current approach and turn towards Dynamic Analysis.

Finally we struck an idea to identify the shellcode execution in memory and set a break point in appropriate code where the shellcode is executed. The idea was quite simple: Since most Windows shellcode starts with a stub that attempts to resolve the base address of kernel32.dll by walking the loaded module list based on which LoadLibrary and GetProcAddress is resolved. We set a break-on-read on PEB loaded module list's head pointer.

Once the shellcode was interception, we took a minidump fo the word process which had the decrypted doc file in memory. Some effort will be required to recreate an unencrypted doc file from the memory dump but that was more or less enough the study and analyze the exploited vulnerability.