Friday, September 1, 2017

0patching the RSRC Arbitrary NULL Write Vulnerability in LabVIEW (CVE-2017-2779)

Whether Vendors Patch Their Products or Not, We Have Your Back

by Mitja Kolsek, the 0patch Team

Three days ago, Cisco Talos published a post about a code execution vulnerability in LabVIEW, whereby opening a malformed VI file with LabVIEW results in writing NULL bytes at chosen memory locations. This can most likely be used for executing arbitrary code by carefully placing NULLs in various data structures or stack. Nothing unusual so far. 

According to Talos' post, the producer of LabVIEW, National Instruments, initially* refused to patch this vulnerability, stating that "National Instruments does not consider that this issue constitutes a vulnerability in their product, since any .exe like file format can be modified to replace legitimate content with malicious."

(* Subsequently, National Instruments stated that they would produce a patch.)

A VI file is not a Windows executable that would run on any Windows computer. However, if you have LabVIEW installed, a VI file will get opened by it, and can be made to automatically run its embedded code. This code is very powerful and by design has ability to access your file system and launch native executables. So a malicious VI file, say, received via email or found on the Internet, could attack your computer if opened in LabVIEW - even without the vulnerability described here.

This is not entirely different from, say, a Microsoft Word document, which is also not an executable file, but can contain powerful damaging macros. (Although Word does warn you about macros and you have to explicitly allow their execution.) 

National Instruments provides Security Best Practices stating that you should exercise the same precautions with a VI file as you would with a EXE or DLL file. This makes sense - if an attacker can get you to open his malicious VI file, he can simply put malicious VI code in it that will attack you, just as if he could get you to open a malicious EXE. Importantly, he does not gain any additional benefit from a memory corruption issue described here, as he would still need you to open his VI file - and in contrast to Word and macros, LabVIEW does not ask your permission to execute VI code.  

However, the Security Best Practices document further states that if you want to safely inspect a suspect VI before running it, you should add that VI as a sub-VI to a blank VI, and inspect its code before running it.

In this case, however, there is a difference between a legitimately-formatted VI with malicious VI code (which does not get executed as a sub-VI) and a malformed VI causing memory corruption when loaded (which executes malicious code even if loaded as a sub-VI).

This vulnerability therefore allows an attacker to mount an attack with a malicious VI file against a user following National Instruments' Security Best Practices. Since the vendor initially stated that they would not issue a fix (it's still not available at the time of this writing), we decided to make one ourselves.


In order to fix this vulnerability, we needed to first understand it. We started with a sample VI file.

A .VI file (example shown above) is a data file in a publicly undocumented format. It gets opened with labview.exe, which, among other things, parses the file's RSRC segments into in-memory RSRC data structures. You can see one RSRC segment at the beginning of the file above, but there can be others further down in a file.

Talos' detailed vulnerability report provided useful details on where their malformed .VI file caused a crash. Apparently, a method called ClearAllDataHdls (yes, the affected DLL comes with some symbols) walks through an array of what we can assume are "data handles". Each data handle has an offset to its own array of some 20-byte objects, and the count of these objects. The code simply walks through all objects of all handles, and writes a NULL to each one of them. Manipulating the said offset allows for writing one or more NULLs at arbitrarily chosen locations in memory.

It was trivial to create a malformed .VI file from a sample file based on this information. And, as expected, it crashed LabVIEW with an access violation. However, it did not crash it in ClearAllDataHdls, but in a method called StandardizeAndSanityChkRsrcMap (actually in a small helper function called by it). What happened? Was our POC different, did we find another bug?

It turned out we were using LabVIEW 2017, while Talos did their testing on version 2016. It appears that in version 2017, LabVIEW added some RSRC sanitization code, and in fact looking at this method revealed some sanity checks are being done on the RSRC data, whereby a .VI file is rejected if these checks fail. Unfortunately, these checks are not for the malformed data in question; in fact, StandardizeAndSanityChkRsrcMap also performs initialization of above-mentioned 20-byte objects by reversing their byte order to little-endian format, and this very action is what resulted in our crash due to accessing an invalid memory address.

It was time to take a closer look at StandardizeAndSanityChkRsrcMap and understand the RSRC data structure. The following image shows the most important part of StandardizeAndSanityChkRsrcMap, where the outer loop walks through all the handles, and the inner loop walks through all objects of a given handle and byte-reverses them.

Now let's look at a sample RSRC structure in the memory, after all the values have been byte-reversed.

52 53 52 43 0d 0a 03 00 4c 56 49 4e 4c 42 56 57  RSRC....LVINLBVW
c4 28 00 00 50 03 00 00 20 00 00 00 a4 28 00 00  .(..P... ....(..
00 00 00 00 00 00 00 00 20 00 00 00 34 00 00 00  ........ ...4...

38 03 00 00 17 00 00 00 4c 56 53 52 00 00 00 00  8.......LVSR....
24 01 00 00 52 54 53 47 00 00 00 00 38 01 00 00  $...RTSG....8...
76 65 72 73 00 00 00 00 4c 01 00 00 43 4f 4e 50  vers....L...CONP
00 00 00 00 60 01 00 00 4c 49 76 69 00 00 00 00  ....`...LIvi....
74 01 00 00 42 44 50 57 00 00 00 00 88 01 00 00  t...BDPW........
49 43 4f 4e 00 00 00 00 9c 01 00 00 69 63 6c 38  ICON........icl8
00 00 00 00 b0 01 00 00 54 49 54 4c 00 00 00 00  ........TITL....
c4 01 00 00 43 50 43 32 00 00 00 00 d8 01 00 00  ....CPC2........
4c 49 66 70 00 00 00 00 ec 01 00 00 46 50 48 62  LIfp........FPHb
00 00 00 00 00 02 00 00 46 50 53 45 00 00 00 00  ........FPSE....
14 02 00 00 56 50 44 50 00 00 00 00 28 02 00 00  ....VPDP....(...
4c 49 62 64 00 00 00 00 3c 02 00 00 42 44 48 62  LIbd....<...BDHb
00 00 00 00 50 02 00 00 42 44 53 45 00 00 00 00  ....P...BDSE....
64 02 00 00 56 49 54 53 00 00 00 00 78 02 00 00  d...VITS....x...
44 54 48 50 00 00 00 00 8c 02 00 00 4d 55 49 44  DTHP........MUID
00 00 00 00 a0 02 00 00 48 49 53 54 00 00 00 00  ........HIST....
b4 02 00 00 50 52 54 20 00 00 00 00 c8 02 00 00  ....PRT ........
56 43 54 50 00 00 00 00 dc 02 00 00 46 54 41 42  VCTP........FTAB
00 00 00 00 f0 02 00 00
00 00 00 00 00 00 00 00  ................
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
ff ff ff ff 00 00 00 00 a4 00 00 00 00 00 00 00  ................
04 00 00 00 ff ff ff ff 00 00 00 00 b8 00 00 00  ................
00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00  ................
c8 00 00 00 00 00 00 00 00 00 00 00 ff ff ff ff  ................
00 00 00 00 d0 00 00 00 00 00 00 00 00 00 00 00  ................
ff ff ff ff 00 00 00 00 84 01 00 00 00 00 00 00  ................
00 00 00 00 ff ff ff ff 00 00 00 00 b8 01 00 00  ................
00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00  ................
3c 02 00 00 00 00 00 00 00 00 00 00 ff ff ff ff  <...............
00 00 00 00 40 06 00 00 00 00 00 00 00 00 00 00  ....@...........
ff ff ff ff 00 00 00 00 5c 06 00 00 00 00 00 00  ........\.......
00 00 00 00 ff ff ff ff 00 00 00 00 64 06 00 00  ............d...
00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00  ................
74 06 00 00 00 00 00 00 00 00 00 00 ff ff ff ff  t...............
00 00 00 00 50 09 00 00 00 00 00 00 00 00 00 00  ....P...........
ff ff ff ff 00 00 00 00 58 09 00 00 00 00 00 00  ........X.......
00 00 00 00 ff ff ff ff 00 00 00 00 60 09 00 00  ............`...
00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00  ................
84 0a 00 00 00 00 00 00 00 00 00 00 ff ff ff ff  ................
00 00 00 00 08 24 00 00 00 00 00 00 00 00 00 00  .....$..........
ff ff ff ff 00 00 00 00 10 24 00 00 00 00 00 00  .........$......
00 00 00 00 ff ff ff ff 00 00 00 00 9c 24 00 00  .............$..
00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00  ................
a4 24 00 00 00 00 00 00 00 00 00 00 ff ff ff ff  .$..............
00 00 00 00 ac 24 00 00 00 00 00 00 00 00 00 00  .....$..........
ff ff ff ff 00 00 00 00 d8 24 00 00 00 00 00 00  .........$......
00 00 00 00 ff ff ff ff 00 00 00 00 5c 25 00 00  ............\%..
00 00 00 00 80 00 00 00 ff ff ff ff 00 00 00 00  ................
38 28 00 00 00 00 00 00                          8(......

The structure begins with a 30h-byte header (purple), followed by a DWORD structure length (blue), which is the size of the entire structure as shown - in our case 338h. After that, a DWORD handle count (green), 17h, tells us that there are 23 handles in the handle array that follows (red). Each handle consists of three DWORDs: some seemingly user-readable keyword, count of handle's objects (subtracted by 1, so 0 means 1 object), and the offset of its first object; the offset is meant from the handle count (green). Finally, the rest of the structure is object data area (black). Each object takes 20 bytes, and if a handle has n objects, they take n * 20 consecutive bytes at the specified offset.

Clearly, a valid RSRC structure would have all handles' objects located neatly inside the object data area. But a malformed RSRC structure can specify an arbitrary offset, and thus tamper with chosen memory locations.


Our goal at this point was to add the missing sanity check to the original code: we should not allow accessing any object data outside the object data area.

We needed to find a good location for injecting the patch, and we chose one right after a handle's offset is obtained, at which point we had all information available to implement the sanitiy check. The following image shows the location of our patch.


We have the following information available at the patch injection point:
  1. esi holds the offset of the current handle's first object
  2. dword [ebp+10h] holds the number of objects for this handle (reduced by 1)
  3. dword [ebp-4] holds the address of the handle count value, which is right next to the structure length value in memory.
The existing sanitization code exits the function with return value 6 (in eax) when the existing sanity checks fail, indicating to the caller that the structure is invalid. When this happens, LabVIEW tells the user that the file is invalid. We decided to do the same in our sanity check. 

In pseudo-code, this is what we needed to do:

  1. if offset of the current handle is negative or ridiculously large, we return with error 6
  2. if the number of objects for the current handle is negative or ridiculously large, we return with error 6
  3. multiply the number of objects with 20 to get the size of the object array 
  4. add offset to the size of object array to get the offset immediately after the array
  5. calculate the maximum allowed offset by subtracting 34h (offset of handle count) from the structure length
  6. if the last byte of object array is beyond the maximum allowed offset, return with error 6 
  7. Otherwise continue

This is the source code of the actual patch:

MODULE_PATH "C:\Program Files (x86)\National Instruments\LabVIEW 2017\resource\mgcore_SH_17_0.dll"
VULN_ID 2892



 PIT mgcore_SH_17_0!0x30c09


    ; esi is offset of the handle's object data
    test esi, 0FFF00000h   ; is offset negative or too huge?
    jnz error             ; if so, exit with error

    mov eax, dword [ebp+10h] ; eax = number of objects in this handle (-1)
    inc eax                  ; eax = actual number of objects in this handle
    test eax, 0FFF00000h     ; is number of objects negative or too huge?
    jnz error

    imul eax, 14h         ; size of object data for this handle

                          ; (1 object is 14h bytes)
    add eax, esi          ; eax = offset right after this handle's 

                          ; last object

    mov edx, dword [ebp-4] ; stored address of handles_num
    mov edx, [edx-4]      ; structure length is stored right before

                          ; handles_num
    sub edx, 34h          ; edx is the maximum allowed offset
    cmp eax, edx          ; are we out of bounds?
    jg error              ; if so, exit with error

    jmp continue

    call PIT_ExploitBlocked
    jmp PIT_0x30c09       ; jmp to epilogue with error code 6



Our micropatch has been published and distributed to all installed 0patch Agents yesterday (two days after Talos published vulnerability details), and you can see it in action in this video.

The benefits of micropatching

This story is a common one: a software vendor creates a product, many users use it, then someone finds a vulnerability. The vendor is notified but it's expensive for them to create and distribute a patch outside their schedule. Even with an updating mechanism in place, the so-called "fat updates" (updates that replace huge chunks of the product) are risky; many things can go wrong and expensive full-blown testing has to be done. And then the update has to be delivered to users, who have to waste their precious time with updating. And all that just for a single vulnerability? Understandably, vendors are inclined to try postponing such unwanted updates and bundle them with scheduled ones, often buying their time by downplaying the issue. When that happens, the security community likes to drop the details ("hey, if the vendor says it's not an issue, there's no harm in publishing"), and that usually pushes the vendor to issue a fix after all. They do it under pressure, and the risk of error is higher than usual. Finally, since un-updating is not really a thing, a botched fix could mean a nightmare for users to just get back to the vulnerable functional state.

In contrast, in-memory micropatching can fix a vulnerability with minimal and extremely controlled code modification (usually a dozen or so machine instructions) with no unwanted side effects. In addition, a micropatch can be applied to a product instantly, while the product is running, and just as instantly removed if suspected to be causing problems. All this allows the testing to be less rigorous, and only focused on the modified code - therefore cheaper.

Now imagine National Instruments had micropatching integrated in LabVIEW. It would be inexpensive to create and distribute a highly reliable micropatch for a vulnerability like this - especially with their intimate knowledge of the product -, and they could stay on their original release schedule while users would get their LabVIEW installations micropatched without even knowing it. No PR mess, no unhappy users, and very little disruption of business. What's not to like?

Software vendors are welcome to approach us about saving money, grief, and their users' time with micropatching.

If you have 0patch Agent installed (it's free!), this micropatch is already on your computer and is getting automatically applied whenever you launch LabVIEW 2017. 


Thursday, August 24, 2017

0patching Foxit Reader's saveAs "0day" (CVE-2017-10952)

3rd-Party Patching a Logical Bug

By Mitja Kolsek, the 0patch team

A bit of introduction: last week we could all witness a familiar "It's a vuln - no it's not" dance, this time featuring Zero Day Initiative and Foxit Software. In short, ZDI reported to Foxit two security issues in its Reader and PhantomPDF products discovered by Steven Seeley and Ariele Caltabiano. Foxit said they would not fix these issues as their exploitation requires the user to disable Secure Mode and thus allow unsafe JavaScript code to execute. ZDI then moved to publish proof-of-concept details, which resulted in Foxit deciding to address these issues anyway. Finally,

Foxit stated that they would "add an additional guard in PhantomPDF/Reader code where when opening a PDF document contains these powerful ( and thus potentially insecure) JavaScript functions, the software will check if the document is digitally signed by a verifiable/trustworthy person of entity. Only certified documents can run these powerful JS functions even when “Safe Reading Mode” is turned off."

They also announced their plan to "release a Reader/PhantomPDF 8.3.2 patch update this week (ETA Aug 25th) with additional guard against misuse of powerful (potentially insecure) JavaScript functions — this will make Foxit software equivalent to what Adobe does."

We at 0patch like a challenge as much as the next guy. While we're usually patching memory corruption bugs (most critical remotely exploitable vulns are of that sort), we're happy to demonstrate that in-memory micrpatching can just as well be used for fixing logical bugs - at least temporarily, until the official vendor fix is applied.

So we set upon creating a micropatch for CVE-2017-10952, allowing a script inside a PDF document to use the saveAs function to save itself to an arbitrarily chosen location on user's computer, using an arbitrarily chosen file extension. For example, a PDF document containing a <html> block with some script anywhere in it could simply save itself as an HTA file (locally executable HTML file) in user's StartUp folder like this:

this.saveAs("/c/Users/”+ identity.loginName + ”/AppData/Roaming/Microsoft/Windows/STARTM~1/Programs/Startup/si.hta");

As a result, when the user logged in to Windows the next time, this HTA file would get executed.

Reproducing the issue

Reproducing the issue was simple: we downloaded and installed the latest version of Foxit Reader ( and put the above code into a sample PDF file to get our POC.

Opening the POC in Foxit Reader with default/recommended configuration resulted in the Safe Reading Mode warning. Pressing "OK" was enough to disable Safe Reading Mode and get our code executed. Indeed, si.hta got created in the StartUp folder.


It's generally not trivial to find code that implements a JavaScript function, especially if the result of the POC is not a crash. However, in this case the saveAs function writes a file to disk so it can be intercepted at a call to one of the disk-writing Windows API functions. While the ZDI article mentions the WriteFile function, putting a breakpoint on it resulted in way too many hits. So we went with CreateFile.

However, CreateFile also got called constantly with some BMP file that Foxit Reader seems to be loading all the time for some reason. Making the breakpoint conditional did the trick by simply checking two letters of the file path and not breaking if they matched the said BMP file path:

bp kernel32!CreateFileW "j poi(poi(esp+4)+6)!=0x00730055 ''; 'gc'"

Bingo! The first break occurred right in our saveAs call, confirmed by our HTA path being passed to CreateFile. The call stack tail looked like this:

0030eba8 01703c5e kernel32!CreateFileW
0030ebdc 016f7d4f FOXITREADER+0x823c5e
0030ebfc 011c5a22 FOXITREADER+0x817d4f
0030efac 010bd155 FOXITREADER+0x2e5a22
0030f068 0238ad23 FOXITREADER+0x1dd155
0030f230 02377492 FOXITREADER+0x14aad23

0030f2e4 012f17c7 FOXITREADER+0x1497492
0030f31c 0217568e FOXITREADER+0x4117c7

Time for IDA. As FOXITREADER.EXE is a 54MB beast, it took IDA quite a while to sort it all out. After that, looking at the functions in the call stack revealed that the one containing address FOXITREADER+0x14aad23 holds the bulk of saveAs implementation. There are references to all saveAs arguments there (cPath, cConvID, cFS, bCopy and bPromptToOverwrite), and one can see the logic of  bPromptToOverwrite value, which, if true, calls PathFileExistsW and sets a local variable we called allowed_to_save_file to 0 if the user declines the overwrite.

The image below shows the place where allowed_to_save_file is set to 0, and a bit further down where allowed_to_save_file is checked, whereby a bunch of code is bypassed if it is 0. The bypassed code includes the green block where the execution proceeds towards the CreateFile call.


It would be very difficult for us to do exactly what Foxit is about to do to address this issue (only allowing properly signed documents to use dangerous functions like saveAs) because digging down deeper to find a way to the data on document signatures could easily take us days. So we decided to simplify the fix in a way to still allow saveAs, but not in a RCE-style dangerous way.  

We noticed (and tested) that in contrast to Adobe's products, Foxit Reader's saveAs function doesn't seem to support document conversion. Consequently, it makes no sense to allow a document to save itself with any other extension than ".pdf". So our logic would be to check the file name passed to saveAs, and only allow files with a ".pdf" extension to proceed, while silently blocking all other extensions.

Having this patching logic in place, we already knew how to get the file path in the function shown above, so we only needed a way to sabotage the file creation for disallowed extensions without causing any unwanted side effects.

The implementation of bPromptToOverwrite logic came in handy as we saw that when the user doesn't allow overwriting, the execution simply bypasses a code block that otherwise leads to CreateFile, and that surely has no unwanted side effects.

So we did a similar thing: We decided to inject our patch code at the beginning of the green block and do the following there:

1) Get the address of the last "." in cPath_string (if any).
2) If no dot, jump out of the block
3) Make a case-insensitive _wcsicmp with ".pdf"
4) If we don't have a match, jump out of the block 

5) Otherwise continue

IDA was really helpful in identifying implementations of _wcsrchr and _wcsicmp inside FOXITREADER.EXE for us so we didn't have to implement them in the patch.

Furthermore, we decided to identify any attempt to save a file with some other file extension as an exploit attempt, which results in an "Exploit Attempt Blocked" popup.

This is the micropatch that came out of this:

; target: Foxit Reader
MODULE_PATH "C:\Program Files (x86)\Foxit Software\Foxit Reader\FoxitReader.exe"
VULN_ID 2891


PIT FoxitReader.exe!0x5CA2A1,FoxitReader.exe!0x5C9A22,FoxitReader.exe!0x14AAD23



    mov edx, dword [ebp-1A0h]
    push '.'
    push edx
    call PIT_0x5CA2A1           ; (_wcsrchr) find the last dot in cPath
    add esp, 8                  ; restore esp
    test eax, eax               ; was a dot found?
    jz Abort                    ; no dot found, we don't allow that
    call GetLocalPdfString      ; a trick to get the address of a local
                                ; string on stack
    dw __utf16__(".pdf"),0

    GetLocalPdfString:          ; at this point, the address of string
                                ; ".pdf" is on the stack
    push eax                    ; eax points to the found dot in cPath
    call PIT_0x5C9A22           ; (_wcsicmp) compare the two strings,
                                ; case insensitive
    add esp, 8                  ; restore esp
    test eax, eax               ; do strings match?
    jz Continue                 ; they do match, we allow saveAs to continue
    call PIT_ExploitBlocked     ; show the "Exploit Blocked" popup
    jmp PIT_0x14AAD23           ; jmp out of the block, sabotaging saveAs


Micropatch in Action

We made a video to quickly show you how 0patch Agent applies this micropatch to a running Foxit Reader, effectively patching it without disturbing the user.

Closing Remarks

We made this micropatch to show how logical vulnerabilities can also be patched, and to demonstrate the amount of effort required for creating a micropatch. It took us 6 man-hours from installing the vulnerable Foxit Reader to having a working micropatch. Mind you, the majority of time was spent on analyzing the vulnerability and Reader's code, and deciding on a good way to patch. The original product developers already know the product inside out and would skip most of this process.

We believe that with Foxit's intimate knowledge of their product, and our knowledge of micropatching, a high-quality micropatch could be made in less than an hour. With our distribution system, it would be on everyone's computer within another hour, and applied automatically. Even users using Foxit Reader at that time would not notice anything - Reader would instantly get from "vulnerable" to "fixed" while they would scroll the pages of some document. And that's how we believe most software vulnerabilities should (and could) be fixed.

If you have 0patch Agent installed (it's free!), this micropatch is already on your computer and is getting automatically applied when you launch the vulnerable Foxit Reader. You can use this POC to play with it. Have fun, write some micropatches and if you're a software vendor interested in equipping your products with self-micropatching ability, ping us at


Update 8/29/2017: The latest Foxit Reader ( fixes CVE-2017-10951, CVE-2017-10952, and both vulnerabilities reported by

Monday, July 10, 2017

0patching the Quick Brown Fox of CVE-2017-0283

By Luka Treiber, 0patch Team.

Among many other things, last Patch Tuesday brought a fix for an RCE vulnerability named "Windows Uniscribe font processing heap-based memory corruption in USP10!MergeLigRecords".  A couple of days later Mateusz Jurczyk of Google Project Zero published a report with PoC attached. Out of the eight vulnerabilities reported at the same time in that Windows library I chose to patch this one for being the most severe.


Opening font files from the package in Windows Font Viewer displayed the "quick brown fox text" in weird constellations but without a crash. With no exact PoC instructions given this was the procedure that worked for me on Windows 7 x64:
  1. unpack the PoC
  2. install signal_sigsegv_313372b5_210_42111ccffd2e10aba8b5e6ba45289ef3.ttf (or any other TTF from the package) on the system
  3. run Notepad
  4. select Format->Font...>[Font] 4000 Tall and [Script] Arabic
immediately a crash occurs at

(1410.378): Unknown exception - code c000041d (!!! second chance !!!)
000007fe`fd651444 8a040a          mov     al,byte ptr [rdx+rcx] ds:00000000`025230e8=??

The callstack: it matches the one from report


Analysis of the PoC

It is usually worth to take a look at PoC and try to understand its payload first before diving into debugging, and thus save a lot of time by knowing what data patterns to look for in the application's memory. So I searched the Internet for the original TTF file the PoC was derived from. I quickly found one and started diffing the two files in order to locate malformed font attributes. Comparison showed a common structure of the files. However, it became clear that an automatic fuzzer was used and too many attributes were polluted with suspicious values to sift through by hand. That task was definitely not a time-saver so I had to give it up.

Analysis of the official patch

Extracting and analyzing the official patch is the next reasonable thing to do after a Patch Tuesday. So let's see how this goes.

The vulnerable version 1.626.7601.23688 of usp10.dll got replaced by the patched 1.626.7601.23807. The files are both of approximately the same size (788KB) and when compared using BinDiff a match of 733 functions is found. Among those are also the ones from the crash call stack above. It makes sense to check differences in those functions first as the patch is often a sanity check on input data inserted before a vulnerable call. The first one - USP10!MergeLigRecords from the immediate crash context - is identical but the next one - USP10!LoadTTOArabicShapeTables - shows some interesting changes in the function graph. Left is the old (vulnerable) and right is the new (patched) version of usp10.dll

We can see that the vulnerable call MergeLigRecords is enclosed in a loop.

Within that loop the only significant change in the patched version is the gray cmp-jnz block that has been added to the patched DLL version. Could this be the patch? With limited analysis done so far it is hard to say what the data in comparison (rsp+var_9C) means, but it is clear that by introduction of that block the criteria to reach the problematic call is more refined than in the old version. This is also a behavior I would expect of a patch.

The only way to make sure is to debug. So we start WinDbg and attach it to notepad.exe on a vulnerable system. We set three breakpoints. One at the vulnerable MergeLigRecords, one before the call to ttoGetTableInfo, and one after. The ttoGetTableInfo call is interesting because it takes two struct parameters - TTOOutput and TTOInput. The gray if block that follows right after, checks if one of the TTOOutput attributes (rsp+var_9C) is 4 and in case of a mismatch exits the loop. So what we're interested in is where/if rsp+var_9C changes inside ttoGetTableInfo and how it is related to the crash inside MergeLigRecords. Before we hit [F5] in WinDbg and click-through the PoC we also need to locate a match for the rsp+var_9C attribute from the patched version in the vulnerable code.

We see that, conveniently, a reference to the same attribute can be found in the old LoadTTOArabicShapeTables named as rsp+var_A4 (it resolves to @rsp+34 in the snippets below).

Now we can observe our checkpoints in WinDbg

0:002> bu0 @!"usp10"+1e32f "dw @rsp+34 L1";
0:002> bu1 @!"usp10"+1e334 "dw @rsp+34 L1";
0:002> bu2 @!"usp10"+1e3f3;
0:002> g

In the first two passes, the value of var_A4 is 0004 and does not change. Also the USP10!MergeLigRecords call executes without a crash.

000007fe`fd59e32f e8bcfd0000      call    USP10!ttoGetTableInfo (000007fe`fd5ae0f0)
0:000> g
00000000`001edd14  0004
000007fe`fd59e334 85c0            test    eax,eax
0:000> g
Breakpoint 2 hit
000007fe`fd59e3f3 e8b8010000      call    USP10!MergeLigRecords (000007fe`fd59e5b0)
0:000> g
00000000`001edd14  0004
000007fe`fd59e32f e8bcfd0000      call    USP10!ttoGetTableInfo (000007fe`fd5ae0f0)
0:000> g
00000000`001edd14  0004
000007fe`fd59e334 85c0            test    eax,eax
0:000> g
Breakpoint 2 hit
000007fe`fd59e3f3 e8b8010000      call    USP10!MergeLigRecords (000007fe`fd59e5b0)
0:000> g

In the third pass, var_A4 gets changed by the ttoGetTableInfo call from 0004 to 0001 and MergeLigRecords crashes the app.

00000000`001edd14  0004
000007fe`fd59e32f e8bcfd0000      call    USP10!ttoGetTableInfo (000007fe`fd5ae0f0)
0:000> g
00000000`001edd14  0001
000007fe`fd59e334 85c0            test    eax,eax
0:000> g

Breakpoint 2 hit
000007fe`fd59e3f3 e8b8010000      call    USP10!MergeLigRecords (000007fe`fd59e5b0)
0:000> p
(14a8.189c): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
000007fe`fd651444 8a040a          mov     al,byte ptr [rdx+rcx] ds:00000000`03bf5018=??

At this point we can conclude that the gray cmp-jnz block would've prevented the crash so we found a patch candidate and can make a 0patch of it.


So far we've assembled all required pieces to build one - it's all in the gray block in above diff. And below is the resulting .0pp file I made.

MODULE_PATH "C:\Windows\System32\usp10.dll"
VULN_ID 2536

PIT USP10!0x2e0f0      ; import USP10!ttoGetTableInfo

  call PIT_0x2e0f0     ; call USP10!ttoGetTableInfo
  cmp word[rsp+34h], 4 ; var_A4
  je skip              ; inverse condition from original patch
  or eax, 01h          ; set piggyback condition

When turning the official patch into a 0patch I used a "jump condition piggy-backing" technique already described in a previous post (only this time It is the quick brown fox I'm piggy-backing). Conveniently the official patch is right next to a jump (jnz) that exits the problematic loop so this is also the location for our 0patch. I placed it before the original jnz. Due to lack of space (jnz is only 2 bytes long while we always need 5 to jump to our patch code) I had to place it before the ttoGetTableInfo call that 0patch Agent will substitute with the 5 byte jump. The first instruction in the patch is therefore the substituted original call to ttoGetTableInfo. What follows it is the check from the official patch. First var_A4 is compared to 4 to check if the loop can continue, otherwise eax that holds the result of ttoGetTableInfo, is set to 1 so the test eax,eax instruction from original code that follows the patch will set a jump flag (zf=0) for the jnz that will exit the loop.

After compiling this .0pp file with 0patch Builder, the patch gets applied and the PoC crashes no more. Our team tested it also against the other TTF files from the package and all of them seem to be disarmed. It is worth noting, however, that this patch only covers the execution route discovered in the Reproduction section above. In the diff of LoadTTOArabicShapeTablesthere there is one more cmp-jnz gray block added to the patched usp10.dll that exits a similar loop to the one covered above. But since there is no public PoC available that would trigger that branch of execution we won't include it in a 0patch. The only safe way for 0patch to work is to cover testable execution paths.

Now, if you haven't so far, install 0patch Agent  and check the PoC to test it for yourself. Next time you see a quick brown fox jumping, make sure that you have 0patch Agent enabled.

Monday, June 19, 2017

A Quick Analysis of Microsoft's ESTEEMAUDIT Patch

And why CVE-2017-0176 and CVE-2017-9073 are probably not the same thing

By Mitja Kolsek, 0patch Team

As you may know, we at 0patch wrote a micropatch for Equation Group's ESTEEMAUDIT exploit last month. It took us quite a while to reproduce the issue until we figured out that the attack only works against computers joined in a Windows domain, but after that, writing a patch was fairly simple. The image below shows its source code and the "Exploit Attempt Blocked" dialog that gets shown when ESTEEMAUDIT attack is detected and blocked.

Our patch is really simple: we check whether the data received from the remote smart card (imitated by ESTEEMAUDIT) is larger than 80h, which is the size of the destination buffer in gpkcsp.dll. If the received data is larger - and with ESTEEMAUDIT it is - we first alert our locally running 0patch agent (which pops up the alert) and then reduce the size of received data to 80h to prevent buffer overflow. This effectively blocks the attack without disrupting legitimate functionality by introducing just 4 machine instructions into the original code.


About a month later, Microsoft published their official update for ESTEEMAUDIT and several other vulnerabilities despite originally indicating that they would only provide these updates to customers with extended support. This is good: official vendor updates are the preferred way to fix vulnerabilities, and 0patch aims to provide most value when fixing issues that have no official fixes, or to provide protection from critical vulnerabilities to organizations in their security update gap.

Naturally, we were interested in how Microsoft fixed this vulnerability and compare their fix to ours. Enter IDA Pro and BinDiff; after a few minutes, we could compare the two side-by-side.

With fixed code on the left, and vulnerable code on the right, it's not-surprisingly obvious that Microsoft's patch also introduces the same check we did, at the exact same location. The main difference between our fixes is that while we just cut the received data to valid length, they spawn an error if the data is too long, and abandon the connection.

This makes sense: an official patch should provide troubleshooting info, wile a micropatch should just close the hole with minimum code.

But surprise: BinDiff shows another change.

Elsewhere in the code, Microsoft added another similar check, also checking for the received data length exceeding 80h - and responding with an error if so.

They obviously reviewed their code and noticed that a similar bug exists after another DoSCardTransmit call, and fixed it as well. Note that this second bug is not exploited by ESTEEMAUDIT, but would likely be found by interested parties based on the first one. Microsoft and other decent software vendors routinely search their code for vulnerabilities similar to those they learn about (either internally or externally), and proactively fix them.

This second bug, however, begs the question: Are there any other similar bugs there?

There are 66 calls to DoSCardTransmit in gpkcsp.dll, and we briefly looked at them. We were interested in cases where the received buffer would be copied to some other buffer. There actually was one such case, apart from those patched by Microsoft, as shown on the image below.

Again, the latest gpkcsp.dll is on the left side, and apparently no data length check was added to it. The code is suspiciously similar to the vulnerable code, but it really all depends on the size of the destination buffer at ds:[edx+ebx]. We had no time to look further into this but we hope Microsoft did and found it to be non-exploitable.

By the way, the ESTEEMAUDIT vulnerability was assigned CVE-2017-9073 but Microsoft associates its fix with CVE-2017-0176. This causes some confusion and makes people wonder whether the two CVEs are duplicates. Based on the above analysis of Microsoft's fix, it seems most accurate to say that CVE-2017-9073 is a subset of CVE-2017-0176, the former being only the ESTEEMAUDIT vulnerability and the latter also including the second similar issue that Microsoft also patched.


Monday, May 15, 2017

0patching the "Worst Windows Remote Code Execution Bug in Recent Memory" CVE-2017-0290

Building up our Skills and Speed for the Future WannaCry Attacks

By Mitja Kolsek, 0patch Team

Like many other stories of the past week, mine begins with this tweet.

Natalie Silvanovich and Tavis Ormandy of Google Project Zero found a pretty nasty bug in Microsoft Malware Protection Engine, allowing an attacker to execute arbitrary code as LocalSystem on any Windows computer running any Microsoft anti-malware product such as Security Essentials or Windows Defender by simply having that computer access a malicious file. Attack vectors were abundant, from emailing the file or sending it via any other channel like Skype or Messenger, to having it hosted on a malicious web site or uploading it to an IIS web server.

Unlike many other stories of the past week, mine is not about how Natalie and Tavis found this bug, how they reported it to Microsoft or how the fact that they found and reported it was made known to the public. Rather, it is about the bug itself, its root cause, and - of course - about writing a micropatch for it.

But first: why would we want to write a micropatch for a vulnerability that would quickly get automatically fixed on all Windows computers anyway? As you may know, Microsoft was super fast in fixing this bug and made an update available literally over the weekend. Furthermore, the Malware Protection Engine is implemented as a dynamic-load library mpengine.dll, and Microsoft designed their anti-malware products smartly enough to not require a computer restart - the old DLL is simply unloaded, and the new one loaded.

So why write a micropatch? Well, not every computer gets updated automatically: while automatic application of updates is configured by default, admins can change that if they want to control what gets applied when. And enterprise admins like to have such control, allowing them to test new code before deploying it to computers throughout their organization. Just imagine the updated mpengine.dll having a flaw that prevented users from accessing legitimate files.

Another reason for writing this micropatch was to learn, as we haven't patched a security product before - and one can expect to stumble upon something new here (and stumble I did, as you will see). The final reason was to teach, to share some knowledge with those of you who want to analyze vulnerabilities yourselves and learn how to write micropatches.

Reproducing CVE-2017-0290

The first step in analyzing a vulnerability is to reproduce its exploitation. The Project Zero report provides a downloadable proof-of-concept file, which has a .zip extension, but is really an HTML-lookalike file that comprises a tiny exploit bit and a lot of random HTML content that makes sure the engine processes the file.

Reproducing on 64-bit Windows 8.1 was trivial - just downloading and saving the file was enough to make the Windows Defender service crash, instantly turning from this:

 to this:

After the crash, the Application Event Log contained an Error event about this crash, revealing the crashing module being mpengine.dll, and the crash location being at offset 0x21745a. (You will find a different crash address in Google's report because they were working on a 32-bit computer.)

Note that I was using mpengine.dll version 1.1.13701.0, which is the last vulnerable version before the fixed 1.1.13704.0. It is always good to do your analysis on the last vulnerable version in order to minimize the difference with the fixed version - you will thank yourself when diffing these versions.

Analyzing CVE-2017-0290

With the bug successfully reproduced, the path was clear towards analysis. Here, the Google report was a great start, as Natalie and Tavis have clearly gained substantial understanding of what goes on in the crash case. The most important detail for me was that it was a type confusion error, specifically with some function expecting a string object but getting a number object (which resulted in calling a string vtable function where there really was no vtable).

This was important because when a bug is a type confusion error, a typical fix is to add the missing check for the correct type. And such a fix is usually easy to recognize when observing the difference between vulnerable and fixed code.

Which brings us to IDA. The image below shows the function that crashed - the exact access violation location was the mov rax, [rcx] instruction (see the red box) at address 0x75A31745A, which is at offset  0x21745a from mpengine.dll's default base address.

When a vendor patch is available, diffing the vulnerable and the patched version usually provides useful information and allows you to understand the bug, and the patch, better. Diffing can be a time-consuming operation though first for the computer and then for you, and with large binaries (mpengine.dll is 12MB) you can get a lot of matched functions, and finding where the code logic is different - as opposed to where the code is different - can be somewhat frustrating.

So I went on to diff the two versions of mpengine.dll, the vulnerable 1.1.13701.0 and the patched 1.1.13704.0. There were 38440 matched functions, which, in scientific terms, is an awful lot. What I could do with these results was compare the above crashing function between the two versions. If I was lucky, the patch would be there and I could go home early.

Nope. Both functions are logically identical, which means that the flaw (and the patch) is somewhere higher on the call stack. At this point one could diff all functions that call this function, but there are about 50 of them - and if all of those turned out to be identical as well, such approach could turn into an exponential mission impossible. (Not to mention that IDA may not see all callers.)
Now about the call stack: you will notice that I haven't used a debugger up to this point, and the reason is that Windows Defender is a protected service and as such tries very hard to protect itself from tampering. You cannot attach a debugger to a protected process, even if you're a local administrator. And it's not easy to un-protect a protected service either: while its protected status is defined by the LaunchProtected registry value (in our case under HKLM\SYSTEM\CurrentControlSet\Services\WinDefend), you cannot change that value for Windows Defender while Windows Defender is running as it prevents you from "attacking" it.

Fortunately, we have a way to stop Windows Defender - by crashing it with the PoC. So what I did was crash Windows Defender, rename its LaunchProtected registry value, restarted the computer (the protected status of services is read only at system startup), then configured Windows Error Reporting to generate dump files for crashing processes. (I only created the LocalDumps key and the DumpFolder value containing "C:\dumps" in it.)

After crashing Windows Defender again, I got its mini dump file in C:\dumps, and it contained a full call stack for the access violation. I was only interested in locations from mpengine.dll:


The top one we already know - it's the access violation location in the crashing function that we diffed just moments ago. So I proceeded with the second address, FreeSigFiles+0x12046f, and located it in IDA. It was, as expected, after a call to the crashing function. I then took the address of the function containing that address, and viewed the diff with its patched version.

Now we're talking! This looks like a typical added check that exits a function if something is not right. (The patched version is on the left.) The upper red block is added code that takes rdi (the object) and passes it to a call to some function, and if the result of that function is 4, the execution continues as before, otherwise the return value (al) is set to 0 in the lower red block, and the function exits. The function that gets called from the upper red block seems to determine the type of the object and returns its type code. Reviewing other calls to this function I found a very obvious implementation of JavaScript's typeof operator, which confirmed that type code for string is actually 4.

This is clearly the patch I was looking for. It was simple, it did exactly what I was expecting it to do, and it was in the code path of our crash.

Micropatching CVE-2017-0290

My goal at this point was to create a micropatch that would inject the same patch logic into the vulnerable version of mpengine.dll. In a perfect world, I could use literally the same code that I found in the patched version, and inject it in the same place - but in this world a compiler likes to use different registers and different implementation of the same logic in two subsequent builds. So I had to re-implement the patch logic from the original patch.

Let's look at the vulnerable function in IDA.

The above image shows the vulnerable function and a good location for injecting our code. The location is selected so that it allows us to jump from our patchlet code directly to the function epilogue (the lowest block of code).

Here is the patch code for 64-bit mpengine.dll version 1.1.13701.0:

;0patch for CVE-2017-0290 in 64-bit mpengine.dll version 1.1.13701.0

MODULE_PATH "C:\Analysis\CVE-2017-0290\mpengine.dll_64bit_1.1.13701.0\mpengine.dll"
VULN_ID 2436


 ; We'll need the GetTypeOf function and the location of function epilogue
 PIT mpengine.dll!0x218940,mpengine.dll!0x218E9A

 ; Note that GetTypeOf taints the following registers:
 ; rdx - always
 ; rcx - only in case of an exception
 ; rax - expected, this is the return value

  push rcx          ; We need to preserve rcx, as it's still used after our patchlet code
                    ; while GetTypeOf taints rdx, we don't need to preserve it
  mov rcx, r9       ; r9 points to the object
  call PIT_0x218940 ; GetTypeOf object
  pop rcx           ; restore rcx
  cmp eax, 4        ; is the object of type string?
  jz OK             ; It is? Very well, continue...

  xor al, al        ; It isn't? Exit this function without doing anything, return 0
  call PIT_ExploitBlocked ; Show "Exploit attempt blocked"
  jmp PIT_0x218E9A  ; Jump to function epilogue


What this single-patchlet patch, inserted at the shown point in code, does is - just as the original patch - call GetTypeOf on the object (whose address is in register r9) and see if its type code is 4 (string). If it is, it continues execution of original code where it was injected . Otherwise, it sets the return code (register al) to 0 and jumps to function epilogue.

Note that in order to avoid any negative side effects, I had to (1) review the GetTypeOf function to see which registers it may taint and whether that could impact the code after our injected patch (it taints rdx and rcx, but rdx holds nothing valuable at our injection point), and then (2) store rcx on the stack before calling GetTypeOf function because rcx holds some value that is still being used after our injected patch.

I also wrote the same patch for the last vulnerable 32-bit version of mpengine.dll. If you have 0patch Agent installed, patches ZP-271 and ZP-272 should already be downloaded to your computer, waiting for any occurrence of the vulnerable mpengine.dll getting loaded.

The Irony of Protected Services

To restore the original system configuration, I turned Windows Defender back to a protected service, and... shoot, the patch stopped getting applied. It quickly became clear that we can't inject our loader into the protected Windows Defender because only binaries signed by Microsoft are allowed to get loaded. (It's a bit more complex than that but close enough.) This is Windows Defender protecting itself against local malware - even with admin privileges - trying to compromise it.

The irony is that a Windows anti-malware protection prevents our security product from fixing a vulnerability in Windows Defender, while the exploit for the same vulnerability can freely execute arbitrary code in Windows Defender. (Hmm, perhaps we should leverage this exploit to get our code running inside Windows Defender and thereby fix it.) 

So while we're exploring options for extending our reach towards patching protected services, patches ZP-271 and ZP-272 for Malware Protection Engine will only get applied on Windows 7 and Windows Vista, which don't have protected services.  

Experimenting with Micropatches for CVE-2017-0290

If you want to experiment with these micropatches, you'll need two things:
  1. A 32-bit or 64-bit Windows 7 computer running Windows Defender. While you could also do the testing on newer Windows versions, you would have to un-protect the Windows Defender service in order to proceed. 
  2. Vulnerable mpengine.dll. If your Windows Defender doesn't happen to have this exact version (unlikely, due to automatic updates), you can get it here:
    1. 32-bit mpengine.dll version 1.1.13701.0 for 32-bit Windows
    2. 64-bit mpengine.dll version 1.1.13701.0 for 64-bit Windows
First of all, stop the Windows Defender service via elevated Services console.

Then browse to C:\ProgramData\Microsoft\Windows Defender (folder permissions don't originally allow you to open it so Windows will ask you for elevation, after which it will add your account to the folder ACL). Open folder Definition Updates, and notice one or more subfolders with GUID-like names starting with curly braces. Open each of these folders to find the one containing mpengine.dll. Rename the existing mpengine.dll into something else, then save the vulnerable mpengine.dll there.

Start the Windows Defender service.

Download the proof-of-concept file and store it in some empty temporary folder.

Launch the Windows Defender console via the Control Panel, and Custom-Scan the above folder. Notice that Windows Defender service crashes.

Now install 0patch Agent on the computer. If you don't already have it, download a free copy and register it with your free 0patch account.

Finally, restart the Windows Defender service and re-scan the temporary folder. This time, you'll see an "Exploit Attempt Blocked" popup instead of Windows Defender crashing.

If you want to build our patches yourself, you can download their source code and build them using 0patch Agent for Developers.

While this vulnerability has already been automatically fixed on most computers, it turned out to be an interesting learning experience to micropatch it. I hope this post will help future micropatchers jump-start their research.

While I was writing this post, the world got pierced by the WannaCry ransomware worm exploiting a known vulnerability that had an official patch available for Windows operating systems which Microsoft supported at the time. Many hospitals and other critical infrastructure components were taken offline, partly also because they were stuck with unsupported OSs such as Windows XP. They have very rational and complex reasons for being on such outdated systems in 2017, and undoubtedly they will have similar reasons next year and the year after. One of our goals with 0patch is to provide protection for such end-of-support systems while users scramble to update them (and have the same problem almost immediately afterwards). Defending against modern attackers will require rapid response, and this exercise with CVE-2017-0290 - although likely of low value to users - was an example of building up skills and speed. The world will need a lot of 3rd-party patch developers though, so all existing and prospective security researchers are warmly welcome to join us.