All Posts

4 posts

MS11-077: From Patch to Proof-of-Concept

Abstract:

In the October 2011 Patch Tuesday, Microsoft released update MS11-077 to fix a null pointer de-reference vulnerability (CVE-2011-1985). In this paper, we will reverse engineer the patch for MS11-077 (CVE-2011-1985) to get a better understanding of the vulnerability fixed by this patch.

Sample:

Unpatched File: win32k.sys (version: 5.1.2600.6119)
Patched File: win32k.sys (version: 5.1.2600.6149)

Patch Analysis:

  1. Using binary diff, we can see the changes that were made to the vulnerable file win32k.sys. Figure 1 below shows the TurboDiff results.


    Figure 1: TurboDiff Results

    As you can see in  Figure 1 above,  while most of the functions are identical, there are a couple of functions that look ‘suspicious’ and some others that are ‘changed’. The large number of changes is not a surprise because Microsoft has fixed four different vulnerabilities with this patch.

  2. Taking a closer look at all the functions that were changed, you will see that the changes made to functions ‘NtUserfnINLBOXSTRING’, ‘NtUserfnSENTDDEMSG’ and ‘NtUserfnINCBOXSTRING’ are all the same. Figure 2, below shows the changes made.


    Figure 2: Binary Diff for function NtUserfnINLBOXSTRING(x,x,x,x,x).

  3. Looking at the binary difference, it is  clear that the patch is checking that the arg_0 (first argument passed to the function) is 0xFFFFFFFF and if it is 0xFFFFFFFF, call _UserSetLastError() with  0x578 and return from the function.
  4. This gives us two pointers to exploit the vulnerability. The first is that the arg_0 has to be 0xFFFFFFFF. The second pointer is that the patched function bails out setting system error code to 0x578. This is the system error code for ERROR_INVALID_WINDOW_HANDLE, thus hinting us that the argument is of type HWND.

Quest:

Everything until now is pretty simple and it looks easy to exploit this vulnerability. However, the really challenge here is finding a user mode function that will call the vulnerable function. It turns out this isn’t very straightforward, and we will need to understand the Windows GUI subsystem.

Win32 GDI Subsystem:


Figure 3: Win32 interfaces and their relation to the kernel components

The GDI (Graphics Device Interface) APIs are implemented in the GDI32.DLL and include all the low-level graphics services such as drawing lines, displaying BMPs etc. The GDI APIs make system calls into the WIN32k.sys to implement most APIs. The User APIs are implemented in USER32.DLL module and include all higher-level GUI-related services such as window management, menus, dialog boxes, user controls etc. USER heavily relies on GDI to do its work.

One of the most important means of communication in Windows is Messages. Windows-based applications are event-driven and act upon messages sent to them. The way you program in Windows is by responding to events. These events are called Messages. Messages can signal many events, caused by the user, the operating system, or another program. Each window, owned by a thread, has a window procedure (function) for processing input messages and dispatching them to the operating system. If a thread accesses any of the user interface or GDI system calls (handled by win32k.sys), the kernel creates a THREADINFO structure which holds three message queues used to process input. These are the input queue, the post queue, and the send queue. The input queue is primarily used for mouse and keyboard messages, while the send and post queues are used for synchronous (send) and asynchronous (post) window messages respectively.

Asynchronous messages are used in one-way communication between window threads and are typically used to notify a window to perform a specific task. Asynchronous messages are handled by the PostMessage APIs and are sent to the post queue of the receiving thread. The sender does not wait for the processing to complete in the receiving thread and thus returns immediately.

Synchronous messages differ from asynchronous messages as the sender typically waits for a response to be provided or a timeout to occur before continuing execution. Thus, they require mechanisms to ensure that the threads are properly synchronized and in the expected state. Synchronous messages use the SendMessage APIs which in turn directs execution to the NtUserMessageCall system call in win32k.sys.

This information is enough for us to take our analysis further.

Hitting the vulnerable function:

As described above, the message mechanism plays an integral role in the user interface component of the Windows operating system.  There are many different types of message codes and those less than 0x400 are reserved by operating system. Depending upon the type of message code, NtUserMessageCall() calls a particular function to handle the message. Let’s take a closer look at how NtUserMessageCall, calls the appropriate functions to handle different message types.


Figure 4: Assembly code for NtUserMessageCall()

As seen in the above figure, the function first checks if the Msg code is less than 0x400(EAX has the Msg code) to check if it’s a system message code. Each Message code denotes an index in the win32k!MessageTable byte array. This byte value is than logically AND to 0x3F, since the last 6bits of the byte obtained from win32k!MessageTable determines the function that will handle the Message code.  _gapfnMessageCall is a function table that stores address of all the functions that can handle different messages. See Figures below to see how _gapfnMessageCall table looks.


Figure 5: _gapfnMessageCall function table

Thus if we can get the index of our vulnerable function in _gapfnMessageCall, we can easily compute how we can call the vulnerable function. The index of our vulnerable functions are 29(0x1D), 27(0x27) and 43(0x2B) for NtUserfnINLBOXSTRING(),NtUserfnINCBOXSTRING() and NtUserfnSENTDDEMSG() respectively.

Following is the pseudo code to compute Msg codes for hitting the vulnerable function:

for i in range[0x00 to 0x400]
    if MessageTable[i] & 0x3F == 0x1D //NtUserfnINLBOXSTRING() Hit!
    if MessageTable[i] & 0x3F == 0x1B //NtUserfnINCBOXSTRING() Hit!
    if MessageTable[i] & 0x3F == 0x2B //NtUserfnSENTDDEMSG() Hit!

Proof of Concept:

#include <windows.h>

int main(){

    SendNotifyMessageA((HWND)0xFFFF,0x143,0,0);

}

OR

#include <windows.h>

int main(){

    SendMessageCallbackA((HWND)0xFFFF,0x143,0,0);

}

Other Possible Msg codes for hitting vulnerable functions are:

0x143, 0x14A, 0x14C, 0x14D, 0x158, 0x180, 0x181, 0x18C, 0x18F, 0x1A2, 0x1AA, 0x1AB, 0x1AC, 0x1AD, 0x3E2, 0x3E3, 0x3E5, 0x3E6, 0x3E7, 0x3E8

Conclusion:

As we’ve seen above, it is pretty easy to trigger this vulnerability. We would recommend our customers to scan their environment for QID 90746 and apply this security update as soon as possible.

References:

http://www.codeproject.com/KB/dialog/messagehandling.aspx

http://c0decstuff.blogspot.com/2011/03/desynchronization-issues-in-windows.html

http://en.wikipedia.org/wiki/Reversing:_Secrets_of_Reverse_Engineering

http://doxygen.reactos.org/d3/d69/include_2reactos_2win32k_2ntuser_8h_a14fd6fae7992b1218ed08fbaec9396b8.html

http://uninformed.org/index.cgi?v=10&a=2#MSFT:2

Patch Analysis for MS11-058

In the Patch Tuesday for August 2011, Microsoft released Security Bulletin MS11-058 (CVE-2011-1966) to fix a unauthenticated remote code execution vulnerability in DNS servers. According to the security advisory, a remote code execution vulnerability exists because the Windows DNS Server improperly handles a specially crafted NAPTR query string in memory. An attacker who successfully exploited this vulnerability could run arbitrary code in the context of the system.

We reverse engineered the patch to get a better understanding of the mechanism of the vulnerability and found this vulnerability can be triggered with a few easy steps. While the proof of concept described below demonstrates a denial of service, attackers with malicious intent may be able to get reliable code execution.

QualysGuard detects this vulnerability with QID: 90726 – Microsoft Windows DNS Server Remote Code Execution Vulnerability (MS11-058). Because of the possibility of a code execution attack, Qualys recommends all our customers to scan their environment for QID 90726 and apply this security update as soon as possible.

Sample

Unpatched File: dns.exe (version: 6.0.6002.18005)
Patched File: dns.exe (version: 6.0.6002.18486)

Patch Analysis

  1. We start the analysis by binary-diffing the unpatched and the patched version of the files that were made available by the MS11-058 security update. This helps us understand the changes that were made in order to fix the vulnerabilities by this patch. To perform binary diffing we use TurboDiff, which is a plugin for IDA pro. TurboDiff shows us a list of all the functions that are identical, changed, unmatched and those that look suspicious. Suspicious functions have unchanged function graphs but changed checksums, which indicates a small code change was made. While most of the functions look identical, TurboDiff lists some of these functions as suspicious (Fig. 1).


    Figure 1: Diffing results by TurboDiff.

  2. As seen in figure 1, TurboDiff lists four of these functions as suspicious. The vulnerability we are investigating is related to CVE-2011-1966, which is related to Name Authority Pointer (NAPTR) DNS resource record. From the names of the four functions marked as suspicious, it is pretty clear the ‘NaptrWireRead(x,x,x,x)’ has something to do with the NAPTR DNS record and this should be the first function to analyze further.
  3. Taking a closer look at the diffing results for the function NaptrWireRead(x,x,x,x) reveals there is only one change made to the entire function (Figure 2, indicated with green box).
  4. The signed extended instruction “movsx edi, byte ptr[ebx]” is replaced with zero extended instruction “movzx edi, byte ptr[ebx]”. This value is then further used as the number of bytes to copy from the source buffer to the destination buffer for memcpy().
  5. The signed extended move instruction is a trouble maker here. If the byte pointed by “byte ptr[ebx]” is greater than 127(0x7F), the resulting value in  the edi register will be a very large number. For example if byte pointed by [ebx] is 128, the resulting value in register edi will be 0xFFFFFF80. The next instruction “LEA EAX, DWORD PTR DS:[EDI+1]” will load EAX with 0XFFFFFF81 which is used as a count for memcpy(). This example will try to copy the entire 4Gb of memory, leading the DNS service to crash.


    Figure 2: Binary Diff for function NaptrWireRead(x,x,x,x).

DOS Proof-of-Concept

  1. For the proof of concept, you need two DNS servers. Register the domain crasher.test.com on the first server and configure a NAPTR DNS record as shown in figure 3 below. The second DNS server will act as a forwarder DNS server. Of all the fields shown, the “Service String” and “Regular Expression” fields are the ones that can take input greater than 127 characters with no restrictions.
  2. To exploit this vulnerability we make any of the above mentioned fields have more than 128 characters. In this case we set the "regular expression" field to 128 characters.
  3. From the forwarder DNS, type the command “nslookup -type=all crasher.test.com. 127.0.0.1”. This command will crash the DNS server working as the forwarder.


    Figure 3: DNS NAPTR form.

  4. To see the vulnerability in action, attach your debugger to the DNS executable and set a break point at the NaptrWireRead(x,x,x,x) function and also set a breakpoint at the memcpy() function in that function.


    Figure 4: BreakPoint at memcpy() in NaptrWireRead().

  5. From Figure 4 (see the values passed on the stack when calling memcpy()), it is clear that setting the value greater than 128 has caused the count parameter for memcpy function to be a really large value causing an access violation and crashing the DNS server.
  6. The call Stack Trace for the above vulnerability can be seen in Figure 5 below.


    Figure 5: Call Stack Trace.

  7. To analyse the crash via windbg, you can start Windbg with the command “windbg -I” an register it as a default postmortem debugger. When you run the “nslookup -type=all crasher.test.com. 127.0.0.1” again, the DNS server crashes and windbg starts for analysis. Figure 6 shows the output of the !exploitable crasher analyzer.


    Figure 6: !exploitable plugin output.

Conclusion

As shown in the analysis above, this vulnerability can be triggered with a few easy steps. While this PoC demonstrates a denial of service, attackers with malicious intent may be able to get reliable code execution. Hence we recommend all our customers to scan their environment for QID 90726 and apply this security update as soon as possible.

Analysis: Malware Win32/Rimecud.B

Infections of Win32/Rimecud.B were first spotted in the wild in the second half of 2010, but customers are still calling us due to difficulties in removing it even in the presence of anti-virus software. So we decided to analyze it and on the way also describe some interesting anti-debugging techniques that are used by it. We also analyze the malware’s behavior once a system is infected.

Sample

File:       ctfmon.exe
MD5:        f5f4ec6d780715d713b7e085fd24447c
SHA1:       f4507f91806aef7bdbbab1047b5ce4d5d6033e6c
File Type:  MS Windows Portable Executable file

Malware Analysis

  1. Before starting the analysis, open the malware in PEiD to see if the malware was packed using any known available packers. PEid indicates that the malware is packed using UPX packer (fig.1). For further analysis the malware is unpacked using the Ultimate Packer for executable.

    Figure 1: PEid output for malware sample.
  2. Once the unpacked malware executable is opened in a debugger, we will see that the malware does a lot of calls to Windows API “CopyFileA”, trying to copy some random files to random location and this is done multiple times in a very big loop. This is junk code used to probably frustrate the reverse engineer (Fig.2).

    Figure 2: Random Calls to “CopyFileA” API.
  3. Inside this junk code, the malware implements a very powerful anti-debugging technique. The malware calls the “kerne32.CloseHandle” API with random values of “hObject” (Fig 3.). If a process being debugged tries to close an invalid handle, it generates a STATUS_INVALID_HANDLE (0xC0000008) exception. The only proper way of bypassing this anti-debugging technique is to modify the syscall data from ring3, before it is called or setup a kernel hook. To bypass this anti-debugging technique we will replace all such random values by NULL and this will allow us to debug our malware smoothly.

    Figure 3: CloseHandle Anti-debugging technique.
  4. However, even after bypassing this anti-debugging technique, if you allow the malware to run, it will get executed and terminate with exit code 0 without doing anything or will stop with “Access Violation” exception, depending upon the time elapsed since the program is executed. This is because of the anti-debugging technique implemented by malware using the ‘kernel32.GetTickCount’API (Fig.4).

    Figure 4: kernel32.GetTickCount Anti-debugging technique.

    The instruction at 0x00330126 will call kernel32.GetTickCount and PUSH that value on stack. It again makes the same call, subtracts that value from the one obtained previously and tests if it is zero. It continues this in loop until it gets the subtraction of these two values as zero. On every time this loop is executed, the value of kernel32.GetTickCount is pushed on the stack. After coming out of this loop, CALL 00330151 is made. This function make CALL DWORD PTR SS:[ESP+C], which should ideally be kernel32.GetProcAdddress. However if you are debugging the malware, the stack might have values that were pushed on stack because of the previous ‘GetTickCount’ loop and hence trigger an Access Violation. To bypass this debugging technique you need to adjust the ESP value so that [ESP+C] points to kernel32.GetProcAddress.

  5. The malware under analysis is created using a CrimeWare Kit that is available in the underground market called CRUM Cryptor Polymorphic by Sunzer Flint (Fig 5). This is a program that is used by malware authors to encrypt malware through a random key of 256 bytes and also subject it to polymorphism.

    Figure 5: CRUM Cryptor Polymorphic.
  6. The last two anti-debugging techniques that are implemented by malware before it decrypts itself, is done by accessing the Process Environment Block (PEB) of the current process. The first technique is checking if the byte at offset 0x02(IsDebugged) in the PEB is set or not. If a program is being debugged, this byte is set to 1 else it is 0. The other anti-debugging technique is to check for the NtGlobalFlags at offset 0x68 in the PEB. If the process is debugged, some flags controlling the heap manipulation routines in ntdll will be set. This anti-debug can be bypassed by resetting the NtGlobalFlags field (Fig. 6).

    Figure 6: PEB Anti-debugging Technique.
  7. Once we have bypassed all these anti-debugging technique, the malware will start importing the different library it requires using the kernel32.LoadLibraryA API.
  8. The malware then tries to find if the process “explorer.exe” is running on the system and gets handle to this process via the kernel32.OpenProcess API(Fig. 7).

    Figure 7: Malware trying to find the “explorer.exe” process.
  9. The malware then reserves a region of memory within the virtual address space of the “explorer.exe” process using kernel32.VirutalAllocEx API and creates a thread in the explorer.exe process via the kernel32.CreateRemoteThread API (Fig. 8). Once the remote thread is created in the “explorer.exe” process, the malware terminates itself with exit code 0.

    Figure 8: Malware Creates a Remote Thread in explorer.exe.
  10. Once this new thread is created in the explorer process, the original malware file is copied to “%USERPROFILE%\\ctfmon.exe” location (Fig. 9) and sets file attributes to system, read-only and hidden.

    Figure 9: Explorer Thread making a copy of itself as “ctfmon.exe”.
  11. After creating the executable, the malware creates the key “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Taskman”: “%USERPROFILE%\ctfmon.exe” (Fig. 10). This key ensures that every time explorer.exe process is created, the malware gets executed.

    Figure 10: Explorer Thread creating the “TaskMan” registry.
  12. The malware creates a NamedPipe which can be later used for inter-process communication (Fig. 11).

    Figure 11: Explorer Thread creating a NamedPipe.
  13. The malware then tries to communicate to its masters at “tinaivanovic.sexy-serbain-girls.info” (Fig. 12).

    Figure 12: Malware trying to communicate on Internet.
  14. The malware is known to spread via USB drives. On connecting a USB stick to an infected host, the malware drops a copy of itself in the “[RemovableDrive]\\nemoj\\meni.exe” and creates an autorun.inf file (Fig. 13).

    Figure 13: Malware trying to spread via removable drive.

Removal Instructions

  1. Open “Regedit” and locate the above mentioned registry key. Delete this registry key.
  2. Open “Task Manager” and find explorer.exe in the “Processes” tab. Right click on explorer.exe and select “Kill Process”. If you are comfortable using command line, use the following steps to kill explorer.exe:        
    • tasklist | find /i "explorer"
      This command will give you the process id of explorer.exe process.
    • taskkill /PID 12345 /f
      (12345 to be substituted with the process id of explorer.exe obtained from the above step)
  3. Upon doing this you will notice that another process named “ctfmon.exe” appears in the process list. Kill “ctfmon.exe” as well, same way as we killed explorer.exe.
  4. Browse to the %UserProfile% directory using a command line. Use “dir /ah” command to list all the files in that directory. You should be able to see “ctfmon.exe” file in that directory. This file has “SHR” attribute. Remove these attributes of the file so that you can delete this file. Use the following commands to do this:
    • attrib –S –H –R ctfmon.exe
    • del ctfmon.exe

Attachments

Malware Win32:Riimecud.B 682.9 K

Analysis: Adobe Flash Player Zero Day CVE-2011-0611

Adobe recently released an advisory warning about a zero day vulnerability affecting Adobe Flash Player 10.2.153.1 being exploited in the wild. The attack uses a flash .swf file embedded inside a seemingly innocuous .doc file. The embedded .swf file uses ActionScript to perform a heap spray and then loads another malicious swf files created via the loadBytes() function.

(Click figure below for full resolution image).

fig1

Sample

File:      Disentangling Industrial Policy and Competition Policy.doc

MD5:       96cf54e6d7e228a2c6418aba93d6bd49

SHA1:      820699d9999ea3ba07e7f0d0c7f08fe10eae1d2d

CVE:        CVE-2011-0611

File Type:  MS Word.doc file with embedded flash .swf file

Analysis of the Malware:

  1. On opening the .doc file, the vulnerability in flash player is exploited and it creates “scvhost.exe” and “AAAA” files in the %temp% directory. The “scvhost.exe” is the malware dropper and file “AAAA” is a dummy word file that will be shown to the user after the exploited is completed.fig2
  2. Once scvhost.exe is created, this file is then executed using the command “cmd /c “%temp%\\scvhost.exe””.fig3
  3. The malware then replaces the original .doc malicious file with the innocuous “AAAA” file it created and then opens it. It also kills “hwp.exe” process. It does this by executing the following command:
    cmd.exe /c     "dir /s %windir%\system32\*.sys&&taskkill /im hwp.exe /f &       
    dir  /a  /s %windir%\system32\*.msc &&     copy %temp%\\AAAA   "C:\Documents 
    and Settings\Rodrigo\Desktop\Disentangling Industrial Policy and Competition 
    Policy.doc " /y && "C:\Documents and Settings\Rodrigo\Desktop\Disentangling 
    Industrial Policy and Competition Policy.doc"
  4. The scvhost.exe process on startup stops the “WmdmPmSN” service. The scvhost.exe process now copies the “SFC_OS.dll” to a temp file.fig4
  5. Copies the windows %system32%\\mspmsnsv.dll to %programfiles%\\commonfiles\\bak.dll. The system32%\\mspmsnsv.dll file is then moved to %temp% dir and set to delete on restart.
  6. Svchost.exe then creates the malicious %system32%\\mspmsnsv.dll and msimage.dat.fig5
  7. Svchost.exe then copies this %system32%\\mspmsnsv.dll to %system32%\\dllchace\\mspmsnsv.dllfig6
  8. Svchost.exe is then moved to a %temp%\\[tempfilename] and is then set to delete on reboot and starts the “WmdmPmSN” service. Thus leaving no trace of any malicious executable on system.
    fig7
  9. Once the service restarts it tries to connect to its masters at liciayee.dyndns-free.com.

Files Created and MD5:

fig8

Conclusion

As a best practice, avoid opening unexpected e-mails or attachments and do no click on links from un-trusted sources. Adobe has released a critical security advisory APSA11-02 and is in the process of finalizing a fix for Adobe Flash Player 10.2.x, Adobe Acrobat X (10.0.2) and earlier 10.x and 9.x versions for Windows and Macintosh, Adobe Reader X (10.0.1) for Macintosh, and Adobe Reader 9.4.3 and earlier 9.x versions for Windows and Macintosh.Google Chrome users can update to Chrome version 10.0.648.205. Verify the version of Google Chrome installed on your system. QualysGuard customers can scan for QID: 119144 for Adobe Flash and QID: 119145 for Adobe Reader/Acrobat for detecting this vulnerability in their network.