Wednesday, May 30, 2018

0patching Foxit Reader Buffer... Oops... Integer Overflow (CVE-2017-17557)

by Luka Treiber, 0patch Team


https://0patch.com


In April, Steven Seeley of Source Incite published a report  of a vulnerability in Foxit Reader and PhantomPDF versions up to 9.0.1 that could allow for remote code execution on a target system. Public release of this report was coordinated with an official vendor fix included in the April's Foxit Reader and PhantomPDF 9.1. release.

According to our analysis the PoC attached to the report triggers a heap-based buffer overflow in a Bitmap image data copy operation inside ConvertToPDF_x86.dll module using an overlong biWidth attribute.

When dropping SRC-2018-0009.bmp into Foxit Reader we immediately got a crash and inspected it by hooking WinDbg with Page Heap enabled.


(3250.3480): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
*** ERROR: Symbol file could not be found.  Defaulted to export symbols for C:\Program Files (x86)\Foxit Software\Foxit Reader\Plugins\Creator\x86\ConvertToPDF_x86.dll -
eax=00000004 ebx=00000000 ecx=00000008 edx=15db5ef8 esi=15db9f38 edi=15dc2000
eip=5f5f9d17 esp=1866f904 ebp=1866f920 iopl=0         nv up ei pl nz na po cy
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010203
ConvertToPDF_x86!CreateFXPDFConvertor+0x1f42e7:
5f5f9d17 8807            mov     byte ptr [edi],al          ds:002b:15dc2000=??



It first looked like a typical buffer overflow, where a missing boundary check allows data to be written over the edge of destination buffer addressed by edi. (Note: the crash offset is marked in red.)






But the loop of the copy operation is constrained by checking biWidth (at esi+54h) which is read from Bitmap image header. So why is there an access violation despite this check?

When inspecting that buffer's properties something stuck out: an unusually small buffer size was reported by !heap to have been allocated, specifically just 4 bytes (UserSize in the WinDbg output below).


0:012> !heap -p -a edi
    address 15dc2000 found in
    _DPH_HEAP_ROOT @ 157e1000
    in busy allocation ( DPH_HEAP_BLOCK:  UserAddr  UserSize -  VirtAddr  VirtSize)
                               15ce264c:  15dc1ff8         4 -  15dc1000      2000
    65688e89 verifier!AVrfDebugPageHeapAllocate+0x00000229
    7748103e ntdll!RtlDebugAllocateHeap+0x00000030
    7743abe2 ntdll!RtlpAllocateHeap+0x000000c4
    773e34a1 ntdll!RtlAllocateHeap+0x0000023a
    5f564b50 ConvertToPDF_x86!CreateFXPDFConvertor+0x0015f120
    5f6de073 ConvertToPDF_x86!CreateFXPDFConvertor+0x002d8643
    5f6ddead ConvertToPDF_x86!CreateFXPDFConvertor+0x002d847d
    5f6de124 ConvertToPDF_x86!CreateFXPDFConvertor+0x002d86f4
   *5f5f9975 ConvertToPDF_x86!CreateFXPDFConvertor+0x001f3f45
    5f5d8598 ConvertToPDF_x86!CreateFXPDFConvertor+0x001d2b68



Inspecting SRC-2018-0009.bmp in a hex editor revealed that biWidth is set to a huge value of 40000001h - a remotely controllable attribute in case the image used in conversion to PDF was obtained from the attacker. So if biWidth was used in calculation of destination buffer size before buffer allocation, that calculation was probably prone to integer overflow in order to result in so much lower a value (4).

Besides heap block properties, !heap also printed out the buffer allocation call stack. We inspected that and indeed we found an overflow-prone buffer size calculation right before the orange-marked return address in the above call stack. The code graph below shows only a part of the vulnerable execution path, but the omitted code is very similar so it suffices for our explanation. There are three code blocks; edi represents biWidth read from image data in the first block, in the third block eax is the destination buffer size to be allocated, ecx represents biBitCount (number of bits per pixel).





There are 3 instructions that can overflow in the last code block:

  1. imul eax, ecx - in case of SRC-2018-0009.bmp, eax=40000001h and ecx=4 so this is the operation that overflows (result is 00000001`00000004h but eax can only hold the lower DWORD - 00000004h)
  2. add eax,ebx - addition of 1Fh to a potentially huge number held by eax could overflow in case previous multiplication didn't overflow
  3. add eax,edx - addition of up to 1Fh (edx is and-ed to 1Fh beforehand) to a potentially huge number held by eax could overflow

As already said, this is not the only vulnerable code block before the destination buffer allocation. Depending on biBitCount value that can hold at most 20h two other similar buffer size calculations can occur. In order to fix all of them, many checks would have to be inserted so we decided for a more compact solution. Given that all constraints to the buffer size calculation are known - buffer size can not theoretically exceed 0xffffffff, biBitCount can be at most 20h and two potentially added values are at most 1Fh -, the maximum valid biWidth could be calculated beforehand as follows:

(0xffffffff-0x1f-0x1f)/0x20 = 0x07fffffe

However, one of the vulnerable blocks does not properly handle signed values so this also needs to be taken into account by halving the maximum buffer size to 0xffffffff/2 = 0x7fffffff. Once we do that, the add eax,edx instruction can't overflow because edx is the sign extension (mind the cdq instruction) and will always be 0. So the final constraint calculation goes like this:

(0x7fffffff-0x1f)/0x20 = 0x03ffffff

Knowing this, a single check can be placed right before biWidth is first used - at the first block of the code graph above - that makes sure only biWidth values lower than 0x03ffffff can pass. If this condition is not met, we can set biWidth to 0 so the subsequent jle would raise a handled exception and abort further processing of a malformed image. Here is the patch code that does this:


; CVE-2017-17557 patch for Foxit Reader 9.0.1 
MODULE_PATH "C:\0patch\Patches\CVE-2017-17557\ConvertToPDF_x86.dll"
PATCH_ID 1000031
PATCH_FORMAT_VER 2
VULN_ID 3556
PLATFORM win32

patchlet_start
PATCHLET_ID 1
PATCHLET_TYPE 2
PATCHLET_OFFSET 0x2098d9
JUMPOVERBYTES 3
N_ORIGINALBYTES 2

code_start
    mov edi, [esi+54h]      ; original instruction replaced by jump to this
                              patchlet
    cmp edi, 03ffffffh      ; is edi<(7fffffffh-1fh)/20h?
    jb skip                 ; if so, everything's okay 
    call PIT_ExploitBlocked ; otherwise, we had an integer overflow - 
                              show the popup
    xor edi,edi             ; and annulate biWidth so the subsequent logic 
                              will throw a handled exception
    skip:
    ;test    edi, edi       ; original instruction displaced to the trampoline
code_end
patchlet_end


When this patch is applied to Foxit Reader's memory, the first two instructions from the top code block above (mov edi, [esi+54h] and test edi, edi, making up exactly 5 bytes) are replaced by a 5-byte jump to the patch code, forcing us to repeat the first instruction (mov edi, [esi+54h]) at the beginning of our patch code if we want to inject our code between the two instructions. The second instruction (test edi, edi) is automatically placed after the patch code by 0patch Loader because JUMPOVERBYTES 3 directs it to only omit the first instruction (3 bytes) while keeping the remaining 2-byte instruction.

This video shows our micropatch in action.




This micropatch has already been published and distributed to all installed 0patch Agents. If you're using Foxit Reader or Foxit PhantomPDF version 9.0.1.1049, you can download our free 0patch Agent, create a free 0patch account and register the agent to that account to immediately receive this micropatch and have it applied to your Foxit software.

If you're using some other version of Foxit Reader and would like to have micropatches for it, please contact us at support@0patch.com.


Tuesday, May 15, 2018

Windows Updates Broke Your Networking? Free Micropatches To The Rescue (CVE-2018-8174)

A Single-Instruction Micropatch For a Critical Remote Execution Issue

by Mitja Kolsek, 0patch Team

Last week, Microsoft issued an update resolving (among others) a critical remote code execution issue in VBScript Engine named CVE-2018-8174, exploit for which has previously been detected in the wild.

Unfortunately, Microsoft's update breaks networking on some computers (details below), prompting users to avoid their application. Windows updates are "all or nothing" these days, so users can't just remove a defective KB and enjoy the protection provided by other KBs issued on the same Patch Tuesday. Fortunately, micropatching provided by 0patch is the exact opposite of that, addressing each vulnerability individually. Let's start with the exploit and the underlying vulnerability.   

It appears the exploit has been caught by at least two security firms, Kaspersky and 360, and they both issued detailed analyses of the infection chain and, more importantly for us, the vulnerability itself [Kaspersky's analysis, 360's analysis]

The vulnerability is triggered by this simple proof-of-concept provided by Kaspersky:


Dim ArrA(1)
Dim ArrB(1)

Class ClassVuln
    Private Sub Class_Terminate()
        Set ArrB(0) = ArrA(0)
        ArrA(0) = 31337
    End Sub
End Class

Sub TriggerVuln
    Set ArrA(0) = New ClassVuln
    Erase ArrA
    Erase ArrB
End Sub

TriggerVuln


By simply saving the above code to poc.vbs and double-clicking it on a Windows computer without May 2018 updates installed, we trigger the vulnerability and get wscript.exe to crash in oleaut32.dll's VariantClear function .


Access Violation in OLEAUT32.DLL's VariantClear due to accessing an unallocated memory address

 

Let's see what goes on here. We create two fixed-size arrays ArrA and ArrB with one element each.
A ClassVuln object is created and assigned to the first element of the ArrA array, then the ArrA array is erased. There is just one element in the array, namely the ClassVuln object, and Erase sets ArrA(0) to Nothing, which removes all references to the object and triggers its destruction.

Our object has a weird method called Class_Terminate. This is a class event that's not officially supported in VBScript anymore but apparently still works and gets called upon object's destruction. (If you're wondering why unsupported functionality still works it's probably because removing it would break an unknown number of production scripts that are using it, and cause much more headache than keeping it and removing it from documentation.)

In our Class_Terminate, the first element of ArrB is set to ArrA(0) - but wait, ArrA(0) is the very object being destroyed, and you can imagine where this is heading. This assignment increases the reference ("lock") count for the object, but the following instruction (ArrA(0) = 31337) decreases the same reference count, which will lead to the object being actually destroyed.

However, after being destroyed, there will still be a reference to this object in ArrB(0), which is called a "dangling pointer," i.e., a pointer to a memory block that has already been freed. In this case the object was allocated on the heap, so now ArrB(0) has a reference to some location on the heap, and those versed in exploiting "use after free" issues have a nice starting point to make use of this reference.

We're not interested in exploiting this issue, however, but in patching it. To do that, we first need to understand the vulnerability.

Kaspersky researchers pointed their fingers at the VBScriptClass::Release function, which only checks the object reference count before calling VBScriptClass::TerminateClass (this executes our Class_Terminate code), and doesn't account for the case where Class_Terminate would increase the object reference count. So even though the reference count was increased (by Set ArrB(0) = ArrA(0)), the object still gets destroyed.

We're not sure that this is the (entire) root cause, although we would probably try to fix the issue using this avenue if we didn't have Microsoft's official patch that contains information on how they fixed it.

After applying the May 2018 Windows updates, executing the PoC has a different result:


Patched Windows show a runtime error

The error states: "Object required: 'ArrA(...)'" in line 6, indicating that the assignment of ArrA(0) is not possible as ArrA is not an object (anymore).

First we decided to compare code execution between the patched and the unpatched version using WinDbg's wt (trace and watch data) command. Fortunately symbols are available for oleaut32.dll so the traces looked fairly identical up to the point where the patched version "derailed" from the unpatched version's path towards crashing. It turned out the fork happened in function vbscript!AssignVar, executed as a result of assigning ArrA(0) to ArrB(0). In this function (which hasn't been modified by the patch), a test is being made on the vt (variant type) member of a VARIANT structure, which in our case denotes the ArrA(0) element. And it turns out on the unpatched computer, vt is 9 (VT_DISPATCH) while on the patched computer, it is 0 (VT_EMPTY).

This means someone must have changed the value of vt from 9 to 0 along the way. In order to find out who did that, we placed an access breakpoint to the address of vt sometime earlier in the execution where it was still 9 on the patched computer.

Bingo! We found a "mov word [rdi], bp" instruction in our old friend, the VariantClear function, which sets our vt to 0. (rdi points to the VARIANT structure, and ebp is 0 throughout the function.)

It was time for BinDiff. We compared the patched and the last unpatched version of oleaut32.dll (which is where the crash occurs), and looked at the modified functions. Unsurprisingly, VariantClear was slightly modified in several places (orange blocks on the image below). Three of these blocks set the vt (variant type) member of a VARIANT structure to 0, which means VT_EMPTY, or an empty object.



Left: unpatched code; Right: patched code





Our PoC executes the middle orange block, and that block contains - in its patched version - the instruction that sets vt to 0.

So we created a micropatch that injects a logically identical instruction to the vulnerable code. Since the vulnerable code uses rbx as the pointer to the VARIANT, this is what we needed to inject:

mov word [rbx], 0

And this is the source code for our micropatch:


; Patch for CVE-2018-8174 in oleaut32.dll version 6.1.7601.23775 64bit
MODULE_PATH "c:\windows\system32\oleaut32.dll"
PATCH_ID 321
PATCH_FORMAT_VER 2
VULN_ID 3568
PLATFORM win64

patchlet_start
 PATCHLET_ID 1
 PATCHLET_TYPE 2
 PATCHLET_OFFSET 0x000011bf

 code_start

  mov word [rbx], 0 ; Set VARIANT's vt to 0 (VT_EMPTY)

 code_end

patchlet_end


Sure enough, applying this micropatch stopped the wscript.exe from crashing and made its behavior identical to the officially patched version:

The old version with our micropatch has an identical reaction to our PoC as the new version.


Our micropatches for this vulnerability have been labeled ZP-320 and ZP-321 for 32-bit and 64-bit version of oleaut32.dll respectively, and are applicable on Windows 7 and Windows 2008 Server updated up to April 2018 Windows updates. Why only these versions? Well, updates KB4103718 and KB4103712 are reportedly causing networking problems on some computers, which prompts users to delay their application - remaining vulnerable to the issue we have micropatched here. We have reports of Windows 7 and Windows 2008 Servers being affected, but if you or someone you know is experiencing this issue on other Windows versions, just ping us and we'll quickly port these micropatches.

As always, if you have 0patch Agent installed, the above-mentioned micropatches should already be present and applied on your system. If not, you can download a free copy of 0patch Agent to protect your system from CVE-2018-8174 at least until Microsoft resolves the functional problems with their updates.
 

Cheers!

@mkolsek
@0patch